Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ SCREEN_ENABLED=false
# picture, which is a chat upload).
# CONNECTION_ICONS_FILE=data/connection-icons.json

# Chat uploads a saved draft in some browser still holds, kept past the daily orphan
# sweep for 30 days from the last time that browser named them.
# UPLOAD_HOLDS_FILE=data/upload-holds.json

# The chat project or folder each task is filed under (the chats panel's Tasks face).
# TASK_FOLDERS_FILE=data/task-folders.json
# Shared sheet rows the owner marked done or snoozed in Totem (never written to the sheet).
Expand Down
15 changes: 9 additions & 6 deletions AGENTS.md

Large diffs are not rendered by default.

177 changes: 124 additions & 53 deletions bridge.mjs

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions browser/browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,38 @@ test('a shared screenshot becomes an upload; any other path stays put', async ()
} finally { await rm(dir, { recursive: true, force: true }) }
})

test('a picture the agent opened is shown from the upload its tool made; one it did not stays text', async () => {
const { embedLocalImages } = await import('./shots.mjs')
const { writeFile, mkdir } = await import('node:fs/promises')
const dir = await mkdtemp(join(tmpdir(), 'vshots-'))
try {
await mkdir(join(dir, 'listing photos'))
const seen = join(dir, 'listing photos', 'back yard.jpg')
const other = join(dir, 'other.jpg')
await writeFile(seen, Buffer.from([0xff, 0xd8, 0xff, 1]))
await writeFile(other, Buffer.from([0xff, 0xd8, 0xff, 2]))
const saved = []
const save = async (f) => { saved.push(f); return { id: 'x', url: '/x' } }
const known = new Map([[seen, { id: 'read1', url: '/api/chat/uploads/read1?sig=s' }]])
// A path with spaces is written in angle brackets.
const out = await embedLocalImages(`![cover](<${seen}>)\n\n![nope](${other})`, { allowedDirs: [], seen: known, save })
assert.equal(saved.length, 0, 'the disk is not read again: the reply reuses what the agent saw')
assert.match(out.text, /!\[cover\]\(\/api\/chat\/uploads\/read1\?sig=s\)/)
assert.ok(out.text.includes(`![nope](${other})`))
// A literal % in a name is tried as written before any URL decoding.
const pct = join(dir, '100% cotton.png')
const shown = await embedLocalImages(`![shirt](<${pct}>)`, { allowedDirs: [], seen: new Map([[pct, { url: '/api/chat/uploads/pct1' }]]), save })
assert.match(shown.text, /!\[shirt\]\(\/api\/chat\/uploads\/pct1\)/)
} finally { await rm(dir, { recursive: true, force: true }) }
})

test('text uploads: the ids a reply\'s text shows are found for the sweep', async () => {
const { textUploadIds } = await import('../chat/uploads.mjs')
const id = 'a'.repeat(32)
assert.deepEqual(textUploadIds(`![x](/api/chat/uploads/${id}?sig=abc) and [f](/api/chat/uploads/bad!) ![y](/api/chat/uploads/${id}?sig=d)`), [id, id])
assert.deepEqual(textUploadIds(undefined), [])
})

test('browser calls read like what the agent did', async () => {
const { describeMcpCall } = await import('../chat/tools.mjs')
assert.equal(describeMcpCall({ name: 'mcp__totem-browser__preview_open', input: { url: 'https://www.example.com/x' } }).title, 'Opened example.com')
Expand Down
57 changes: 37 additions & 20 deletions browser/shots.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
// A model shows the owner a screenshot the way it would in T3 Code: it saves one
// (preview_snapshot save:true) and writes ![what it shows](/abs/path.png) in its
// reply. The browser in the chat can't load a path on the box, so when the turn
// ends each such image is copied into the chat's uploads and its path replaced
// with the upload's signed URL. Only files under `allowedDirs` are taken — a
// reply can't smuggle an arbitrary file off the disk by naming it.
// ends each such image becomes a chat upload and its path is replaced with the
// upload's signed URL. A file under `allowedDirs` is copied from disk. A picture
// a tool already returned this turn (`seen`: an image the agent read, by path)
// reuses that tool's upload, so the reply shows exactly the bytes the agent saw
// and the disk is not read again. Nothing else is taken — a reply can't smuggle
// an arbitrary file off the disk by naming it.

import { readFile, stat } from 'node:fs/promises'
import { basename, extname, resolve, sep } from 'node:path'

const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' }
// ![alt](path) or ![alt](<path with spaces>), optionally file://-prefixed.
const MD_IMAGE = /!\[([^\]\n]*)\]\(\s*<?((?:file:\/\/)?\/[^)\s>]+)>?\s*\)/g
const MD_IMAGE = /!\[([^\]\n]*)\]\(\s*(?:<((?:file:\/\/)?\/[^>\n]{1,4096})>|((?:file:\/\/)?\/[^)\s>]+))\s*\)/g

const inside = (file, dir) => {
const d = resolve(dir)
Expand All @@ -19,30 +22,44 @@ const inside = (file, dir) => {

/**
* Rewrite local screenshot images in `text`. `save({buffer, name, mime})`
* stores one and returns {id, url}. Returns {text, uploads}.
* stores one and returns {id, url}; `seen` maps a path to an upload already
* made from it ({url}). Returns {text, uploads} (`uploads`: the ones saved here).
*/
export async function embedLocalImages(text, { allowedDirs = [], save, maxBytes = 15 * 1024 * 1024 }) {
export async function embedLocalImages(text, { allowedDirs = [], seen = new Map(), save, maxBytes = 15 * 1024 * 1024 }) {
if (!text || !text.includes('![')) return { text, uploads: [] }
const known = new Map([...seen].map(([f, up]) => [resolve(f), up]))
const done = new Map()
const uploads = []
for (const m of text.matchAll(MD_IMAGE)) {
const raw = m[2].replace(/^file:\/\//, '')
const raw = (m[2] ?? m[3]).replace(/^file:\/\//, '')
if (done.has(raw)) continue
let file
try { file = resolve(decodeURIComponent(raw)) } catch { continue }
const mime = IMAGE_MIME[extname(file).toLowerCase()]
if (!mime || !allowedDirs.some((d) => inside(file, d))) continue
try {
const info = await stat(file)
if (!info.isFile() || info.size > maxBytes) continue
const up = await save({ buffer: await readFile(file), name: basename(file), mime })
done.set(raw, up.url)
uploads.push(up)
} catch {}
// The path as written first (a file may really be called "100% cotton.jpg"),
// then URL-decoded (%20 for a space).
const tries = [raw]
try { const d = decodeURIComponent(raw); if (d !== raw) tries.push(d) } catch {}
for (const t of tries) {
const file = resolve(t)
const mime = IMAGE_MIME[extname(file).toLowerCase()]
if (!mime) continue
// A file in the chat's own folders is read now, so an edit made after the
// agent looked at it shows; anything else only as the agent saw it.
if (!allowedDirs.some((d) => inside(file, d))) {
if (known.has(file)) { done.set(raw, known.get(file).url); break }
continue
}
const info = await stat(file).catch(() => null)
if (!info?.isFile() || info.size > maxBytes) continue
try {
const up = await save({ buffer: await readFile(file), name: basename(file), mime })
done.set(raw, up.url)
uploads.push(up)
} catch {}
break
}
}
if (!done.size) return { text, uploads }
const out = text.replace(MD_IMAGE, (whole, alt, p) => {
const url = done.get(p.replace(/^file:\/\//, ''))
const out = text.replace(MD_IMAGE, (whole, alt, angled, bare) => {
const url = done.get((angled ?? bare).replace(/^file:\/\//, ''))
return url ? `![${alt}](${url})` : whole
})
return { text: out, uploads }
Expand Down
44 changes: 43 additions & 1 deletion chat/chat.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createThreadStore } from './store.mjs'
import { createThreadStore, wakeOnOwnerMessage } from './store.mjs'
import { createUploadStore } from './uploads.mjs'
import { createChatRuns } from './runs.mjs'
import { planHistory, renderTranscript, attachmentBlock, applyEvent, finalizeMessage, fallbackTitle, failureText } from './turn.mjs'
Expand Down Expand Up @@ -159,6 +159,25 @@ test('applyEvent builds ordered text and tool parts, and settles tools', () => {
assert.equal(msg.status, 'stopped')
})

test('a picture a tool returned goes on its card, not in the reply, and survives a save', () => {
const msg = { role: 'assistant', content: '' }
applyEvent(msg, { type: 'tool', tool: { id: 'r1', phase: 'start', title: 'Read a file' } })
applyEvent(msg, { type: 'tool_image', uploadId: 'up1', toolId: 'r1' })
applyEvent(msg, { type: 'tool', tool: { id: 'r1', phase: 'end', status: 'done', output: '[image]' } })
// A call this reply never saw (another attempt's) drops its picture rather than showing it.
applyEvent(msg, { type: 'tool_image', uploadId: 'up2', toolId: 'gone' })
// An image the CLI made, with no call, still stands in the reply.
applyEvent(msg, { type: 'image', uploadId: 'up3' })
assert.deepEqual(msg.parts.map((p) => p.type), ['tool', 'image'])
assert.deepEqual(msg.parts[0].images, [{ uploadId: 'up1' }])
assert.equal(msg.parts[1].uploadId, 'up3')
const saved = normalizeMessage({ ...msg, id: 'm1' })
assert.deepEqual(saved.parts[0].images, [{ uploadId: 'up1' }])
// A bad id in a saved file is dropped.
const bad = normalizeMessage({ id: 'm2', role: 'assistant', content: '', parts: [{ type: 'tool', id: 't', images: [{ uploadId: '../x' }] }] })
assert.equal(bad.parts[0].images, undefined)
})

test('finalizeMessage records a final reply that never streamed', () => {
const msg = { role: 'assistant', content: '', parts: [] }
finalizeMessage(msg, { status: 'done', finalText: 'All set.' })
Expand Down Expand Up @@ -310,3 +329,26 @@ test('a tool part keeps its connector name and only an https logo', () => {
assert.equal(saved.parts[0].logo, 'https://claude.ai/m365.png')
assert.equal(saved.parts[1].logo, undefined)
})

const WOKEN_AT = 1_800_000_000_000
const woken = (t) => { wakeOnOwnerMessage(t, WOKEN_AT); return t }

test('writing in a settled chat brings it back to the top', () => {
assert.deepEqual(woken({ settledOverride: 'settled', settledAt: WOKEN_AT - 1000 }), { unsettledAt: WOKEN_AT })
})

test('writing in a snoozed chat wakes it and drops the timer', () => {
assert.deepEqual(woken({ snoozedUntil: WOKEN_AT + 3_600_000, snoozedAt: WOKEN_AT - 1000 }), { unsettledAt: WOKEN_AT })
})

test('writing in a chat that already woke clears the Woke mark and leaves its place', () => {
assert.deepEqual(woken({ snoozedUntil: WOKEN_AT - 1000, snoozedAt: WOKEN_AT - 5000, unsettledAt: WOKEN_AT - 9000 }), { unsettledAt: WOKEN_AT - 9000 })
})

test('writing in a chat taken off the shelf by hand hands it back to auto-settle', () => {
assert.deepEqual(woken({ settledOverride: 'active', unsettledAt: WOKEN_AT - 9000 }), { unsettledAt: WOKEN_AT - 9000 })
})

test('writing in a chat the agent marked done means it is not done', () => {
assert.deepEqual(woken({ doneAt: WOKEN_AT - 1000, settledOverride: 'active' }), {})
})
21 changes: 17 additions & 4 deletions chat/done.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,31 @@ export const DONE_TOOL_DESCRIPTOR = {
name: DONE_TOOL,
title: 'Mark this chat done',
description:
'Mark this chat as finished. Call it at the end of a reply that fully completes a one-off request (for example ' +
'"add a task for X" and the task is made) when nothing is left to discuss and you are not waiting on the owner. ' +
'Mark this chat as finished. Call it when this reply fully completes a one-off request (for example ' +
'"add a task for X" and the task is made) and nothing is left to discuss and you are not waiting on the owner. ' +
'Call it before you write your answer, then write the whole answer as your reply: the owner sees only your reply text, ' +
'never your thinking, and the reply is the text after your last tool call. ' +
'The owner gets a one-tap Settle on the chat, and it moves to the Settled shelf by itself once they have read your reply. ' +
'Do not call it when you asked a question, need anything from the owner, hit an error, or the conversation is ongoing. ' +
'It changes nothing else; still write your reply as usual.',
'It changes nothing else. Never mention in your reply that you marked the chat done.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { title: 'Mark this chat done', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
}

export const DONE_RESULT = 'Marked done. The chat will settle once the owner has read your reply. Finish your reply as usual.'
// Opus has been seen writing its whole answer as thinking, calling this, and then
// replying only "I've marked this chat as done." The owner never sees thinking,
// so the result says plainly what is still owed, harder when the reply has no
// text at all yet (`answered`, from the run's reply so far).
export function doneResult({ answered = true } = {}) {
return answered
? 'Marked done. The owner sees only your reply text, never your thinking. If your full answer is not already in your ' +
'reply text, write it now. Do not mention that you marked the chat done.'
: 'Marked done. The owner has not seen any answer yet: your thinking is never shown to them. Write your complete answer ' +
'to their request now, as your reply. Do not mention that you marked the chat done.'
}

export const DONE_RULES =
`ONE-OFF REQUESTS: When this reply fully completes a one-off request and nothing is left to discuss, call ${DONE_TOOL} ` +
'(in the totem-browser server, or browser__mark_chat_done through totem-gateway) once, so the chat settles after the owner reads it. ' +
'Call it before you write your answer, then write the answer in full as reply text; never answer only "marked done". ' +
'Never call it if you asked something, are waiting on the owner, something failed, or the conversation is still going.'
22 changes: 22 additions & 0 deletions chat/done.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { doneResult, DONE_TOOL_DESCRIPTOR, DONE_RULES } from './done.mjs'

test('mark_chat_done tells an agent with no reply text yet that the answer is still owed', () => {
const owed = doneResult({ answered: false })
assert.match(owed, /has not seen any answer/)
assert.match(owed, /thinking is never shown/)
assert.match(owed, /Write your complete answer/)
assert.match(owed, /Do not mention/)
const after = doneResult({ answered: true })
assert.match(after, /never your thinking/)
assert.doesNotMatch(after, /has not seen any answer/)
assert.equal(doneResult(), after)
})

test('mark_chat_done is called before the answer, never instead of it', () => {
assert.match(DONE_TOOL_DESCRIPTOR.description, /before you write your answer/)
assert.match(DONE_TOOL_DESCRIPTOR.description, /never your thinking/)
assert.match(DONE_RULES, /before you write your answer/)
assert.doesNotMatch(DONE_TOOL_DESCRIPTOR.description, /write your reply as usual/)
})
9 changes: 8 additions & 1 deletion chat/reach.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@ export const WORK_RULES =
'GETTING THINGS DONE: When the owner asks you to do something, treat it as a job to carry out end to end with your ' +
'tools (shell, files, the Totem app tools, connected services), not a question about how it could be done. Stop to ask ' +
'only when you are genuinely blocked or unsure what he wants. When you did real work, finish with a short summary: what ' +
'you did, what changed, and anything only he can do.'
'you did, what changed, and anything only he can do. He sees only the text of your reply, never your thinking, and the ' +
'reply is what you write after your last tool call: put the whole answer there, after any housekeeping (a memory note, ' +
'marking the chat done), never only in your thinking. Pictures you open with your tools (an image file you read, a ' +
'screenshot) are not shown to him either: they stay folded in your steps. To show him one, put ' +
'![what it shows](/absolute/path/to/image.png) in your reply (in <angle brackets> if the path has spaces), and only ' +
'the ones that help him, never the ones you only looked at along the way. The path must be in your outputs folder (copy ' +
'the picture there first), or, in Claude Code only, an image your Read tool opened this turn; any other path stays ' +
'plain text.'

/** The browser's how-to. Also the /agent-mcp server's `instructions`. */
export function browserRules(mcpName, { handoff = false } = {}) {
Expand Down
9 changes: 9 additions & 0 deletions chat/reach.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,12 @@ test('offering the browser costs nothing: Chromium starts on the first tool call
assert.ok(opened.isError)
assert.equal(launches, 1)
})

test('the work rules say thinking is never shown and the answer follows housekeeping', () => {
assert.match(WORK_RULES, /never your thinking/)
assert.match(WORK_RULES, /after your last tool call/)
// Pictures the agent looked at stay in its steps; it shows one by naming its path.
assert.match(WORK_RULES, /folded in your steps/)
assert.match(WORK_RULES, /!\[what it shows\]\(\/absolute\/path/)
assert.match(WORK_RULES, /outputs folder/) // the one place every backend's picture can be shown from
})
Loading
Loading