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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ open-ended work. The default provider and model come from Settings → Providers
| Context window and compaction | `chat/context.mjs`, `chat/compaction.mjs`, `web/src/chat/context.ts` (byte copy in `mobile/src/lib/chat/`), `web/src/chat/ContextMeter.tsx`, `web/src/chat/CompactionMark.tsx` | T3 Code's context meter and compaction rules. A bar in the composer (amber 80%, red 90%, a tick at Claude's compaction point) from the last request's usage: Claude's `assistant` events live, Codex's rollout `token_count` (tailed, since `exec --json` lacks it), OpenCode's last step; never the reply's summed `stats`. The CLIs compact themselves; Totem shows a divider where they did, runs `/compact` on a Claude session as a hidden turn (other accounts get T3's "does not support /compact"), and Settings → Chat › Compact idle threads (`compactIdle`: When you return = a Compact chip and `compactFirst`, which queues the message behind a `/compact`; Before the cache expires = an in-memory timer two minutes before Claude's prompt cache expires; Never) plus Auto-compact after (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`). A compaction turn is never replayed to another account and keeps the session's `through`. `docs/chat.md` → Context window and compaction. |
| Running chats | `web/src/chat/RunningChats.tsx`, `web/src/chat/onScreen.ts` | Bottom-right panel of chats answering, finished-but-unread (`needsReply`) or holding a pending approval card ("Waiting on your approval") out of sight, grouped by project and folder, with open, stop, snooze, settle and mark as read; finished replies also toast. "Out of sight" means not open and no row at least half on screen; a new list of chats should give its rows `useRowOnScreen`. `docs/chat.md` → Running chats panel. |
| Other chats, for agents | `chat/thread-tools.mjs`, `totem_threads_*` in `bridge.mjs` | `totem_threads_list`/`totem_threads_read` (`threads__*` in the gateway) let an agent list and read the owner's other chats (running, waiting, settled, by project or keyword). `totem_threads_create`/`totem_threads_projects` make a chat in a project or folder (creating the folder if needed), opening with the agent's message and optionally starting a run, deduplicated by `key` (`sourceKey` on the thread); this is how a totem opens a chat per new ticket. Every chat turn with the gateway on is told its own chat id and to use them only when the owner points at another chat or the turn truly needs one (`threadsRule`); keep that restraint in any change. `docs/chat.md` → Other chats. |
| Agent browser | `browser/`, `web/src/chat/BrowserPanel.tsx` | A headless Chrome or Chromium (`browser/pick.mjs`: `BROWSER_EXECUTABLE`, installed Chrome, Playwright's full Chromium, a system Chromium, the headless shell last; new headless mode, the user agent without "HeadlessChrome", a 1920×1080 screen; `BROWSER_HEADED=true` for a window on a host with a display) driven by `playwright-core` behind T3 Code's `preview_*` tool names, served to each chat run over a per-run loopback MCP endpoint (`/agent-mcp`). An open panel watches the chat's current tab live over `/api/chat/browser/ws` (`browser/socket.mjs`: CDP screencast while a viewer is there, never waiting on a slow viewer, which keeps only its newest frame; stopped when the last leaves; held input is per tab and per socket (owners), released on a tab switch or when its socket closes, each release bounded to a second; watching never opens or keeps alive a context), and the owner drives it with real input (mouse, drag, wheel, keys with modifiers, IME, paste; `browser/input.mjs`, `web/src/chat/browserInput.ts`), on the socket or `POST /api/chat/browser/input`. Driving is an approval route (low: a session or the approval code, never the bearer alone; the socket takes the code as a subprotocol); the iPhone app shows stills. That is how he signs in for the agent: the agent calls `preview_handoff`, the panel shows Done / Skip, and the call waits on him like `ask_questions` (`browser/handoff.mjs`). **Offered to every dashboard or app chat run** (not voice turns); the prompt has the agent use it only when a request needs it and ask first when unsure (`chat/reach.mjs`). Never give it, or computer use, to the phone path (`limitReach` in `runAgent` enforces it) or to jobs; a totem gets the browser only through its own `browser` switch. |
| Agent browser | `browser/`, `web/src/chat/BrowserPanel.tsx` | A headless Chrome or Chromium (`browser/pick.mjs`: `BROWSER_EXECUTABLE`, installed Chrome, Playwright's full Chromium, a system Chromium, the headless shell last; new headless mode, the user agent without "HeadlessChrome", a 1920×1080 screen; `BROWSER_HEADED=true` for a window on a host with a display) driven by `playwright-core` behind T3 Code's `preview_*` tool names, served to each chat run over a per-run loopback MCP endpoint (`/agent-mcp`). An open panel watches the chat's current tab live over `/api/chat/browser/ws` (`browser/socket.mjs`: CDP screencast while a viewer is there, never waiting on a slow viewer, which keeps only its newest frame; stopped when the last leaves; held input is per tab and per socket (owners), released on a tab switch or when its socket closes, each release bounded to a second; watching never opens or keeps alive a context), and the owner drives it with real input (mouse, drag, wheel, keys with modifiers, IME, paste; `browser/input.mjs`, `web/src/chat/browserInput.ts`), on the socket or `POST /api/chat/browser/input`. Driving is an approval route (low: a session or the approval code, never the bearer alone; the socket takes the code as a subprotocol); the iPhone app shows stills. That is how he signs in for the agent: the agent calls `preview_handoff`, the panel shows Done / Skip, and the call waits on him like `ask_questions` (`browser/handoff.mjs`). A handoff still waiting rides on the chat list's summaries (`withHandoff`), so the chat's row says "Your turn", the running-chats panel counts it as waiting rather than running, the chat shows a Done / Skip row over the composer (`HandoffBar.tsx`, web and app), and opening it opens the panel; `web/src/chat/attention.ts` (copied to the app) is the one place that decides what a chat waits on him for (docs/chat.md → Browser). **Offered to every dashboard or app chat run** (not voice turns); the prompt has the agent use it only when a request needs it and ask first when unsure (`chat/reach.mjs`). Never give it, or computer use, to the phone path (`limitReach` in `runAgent` enforces it) or to jobs; a totem gets the browser only through its own `browser` switch. |
| Gmail | `gmail/`, the "Gmail" blocks in `bridge.mjs`, Settings → Connections › Accounts | The owner's Gmail accounts over the Calendar OAuth client (`gmail.modify`; tokens in `data/gmail-tokens.json`, 0600). Agents get `totem_gmail_*`/`gmail__*`: search, read, labels, archive, trash, drafts. The same Google sign-in also connects the account's calendar (`addCalendarFromGmail`), unless that address already has one. No send tool: `propose_email` stages an `email` inbox item that only the dashboard sends or saves as a draft, and the card shows the email as it will arrive. Tools register only when the OAuth client exists. `docs/gmail.md`. |
| Google Drive | `drive/`, `google/accounts.mjs`, the "Google Drive" blocks in `bridge.mjs`, Settings → Connections › Accounts | The owner's Drive accounts over the Calendar OAuth client (full `drive` scope, its own sign-in; tokens in `data/drive-tokens.json`, 0600). Agents get `totem_drive_*`/`drive__*`: search, read (Docs as Markdown, Sheets as tabs and cells, other files downloaded), create, copy (`convert` turns an `.xlsx` into a Sheet), rename, move, trash, plus cell-level Sheets edits and Docs find-and-replace/append. No sharing tool and no permanent delete. `google/accounts.mjs` holds the sign-in, token and refresh code Gmail and Drive share. `docs/drive.md`. |
| LinkedIn | `linkedin/`, `browser/read-only.mjs` and `readPage` in `browser/manager.mjs`, the "LinkedIn" blocks in `bridge.mjs`, `LinkedinCard` in `web/src/components/InboxView.tsx` and `mobile/src/features/inbox/InboxScreen.tsx` | Read-only. The owner signs in in a chat's browser (`preview_open` + `preview_handoff`); `linkedin__sign_in` copies only LinkedIn's cookies into `data/linkedin-tokens.json` (0600, a `*-tokens.json` file, so under the same deny and change-flow rules). Each read is one page in a fresh context through `readPage`, whose policy (`readOnlyRequestDecision`) lets out only GET/HEAD over https to `linkedin.com`/`licdn.com`; sockets closed, no service workers, popups or downloads. At most 20 pages an hour (`LINKEDIN_MAX_PAGES_PER_HOUR`), one at a time with a pause, never in the background; each read is a `linkedin` source-health run, and a redirect to `/login`, `/authwall` or `/checkpoint` ends the sign-in. Agents get `totem_linkedin_*`/`linkedin__*` (registered only where the browser is): status, sign in/out, notifications, messages, one conversation, feed, a profile, `propose_action` and `list_proposals`. No tool acts on LinkedIn: `propose_action` stages a `linkedin` inbox card (link, excerpt, a draft; JSON in `inbox-prompts/P<n>.linkedin.json`), once per canonical target URL ever (open, done or denied), at most five open, and only when signed in. The card has Open on LinkedIn, Copy and an editable draft; Mark done (the accept) only records that he did it, is low risk at the approval gate (`LOW_RISK_KINDS`) and is taken only with `approvedVia === 'dashboard'`. The seeded agent totem `linkedin-networking` (off; `linkedin/totem.mjs`) runs Monday and Wednesday. `linkedin/linkedin.test.mjs` checks no tool mutates and the connector's source never clicks or types. `docs/linkedin.md`. |
Expand Down
39 changes: 31 additions & 8 deletions bridge.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ import { createBrowserManager } from './browser/manager.mjs'
import { attachBrowserSocket, panelOwner, BROWSER_WS_PATH } from './browser/socket.mjs'
import { callBrowserTool, browserToolDescriptors } from './browser/tools.mjs'
import { embedLocalImages } from './browser/shots.mjs'
import { HANDOFF_TOOL, HANDOFF_TOOL_DESCRIPTOR, HANDOFF_LATER, HANDOFF_GONE, normalizeReason, handoffDone, handoffSkipped, handoffMessage } from './browser/handoff.mjs'
import { HANDOFF_TOOL, HANDOFF_TOOL_DESCRIPTOR, HANDOFF_LATER, HANDOFF_GONE, normalizeReason, handoffDone, handoffSkipped, handoffMessage, withHandoff } from './browser/handoff.mjs'
import { createVoiceService, realtimeTools, VOICE_INSTRUCTIONS } from './chat/voice.mjs'
import { createJournalService } from './journal/service.mjs'
import { createJournalHttpHandler } from './journal/http.mjs'
Expand Down Expand Up @@ -8777,6 +8777,12 @@ const browserFrames = new Map() // threadId → the latest frame, for a viewer t
const browserManager = createBrowserManager({
log,
headed: BROWSER_HEADED,
// A chat's browser closed (idle past a hold's cap, the chat deleted, Chromium gone):
// a handoff waiting in it is over, and a call still waiting is told he skipped it.
onClose: (threadId) => {
const handoff = browserHandoffs.get(threadId)
if (handoff) { dropHandoff(threadId); handoffWaits.dismiss(handoff.id) }
},
onFrame: (threadId, f) => {
const frame = { tabId: f.tabId, url: f.url, title: f.title, image: `data:image/jpeg;base64,${f.jpeg.toString('base64')}`, at: Date.now() }
browserFrames.delete(threadId)
Expand Down Expand Up @@ -8873,6 +8879,19 @@ if (CHANGE_FLOW_ENABLED) {
// The browser handed to the owner (browser/handoff.mjs): the one waiting in each
// chat, for a viewer that arrives late, and the live calls waiting on Done.
const browserHandoffs = new Map() // threadId → { id, reason, at }
// While one waits, the chat's browser stays open (browserManager.keepOpen, a day at most):
// he may come back hours later, past the 30-minute idle close, to sign in.
const handoffHolds = new Map() // threadId → release
function holdHandoff(threadId, handoff) {
dropHandoff(threadId)
browserHandoffs.set(threadId, handoff)
handoffHolds.set(threadId, browserManager.keepOpen(threadId))
}
function dropHandoff(threadId) {
browserHandoffs.delete(threadId)
handoffHolds.get(threadId)?.()
handoffHolds.delete(threadId)
}
const handoffWaits = createQuestionWaits()

// Questions waiting on a live tool call, by part id (chat/questions.mjs).
Expand Down Expand Up @@ -9057,7 +9076,11 @@ const signQueue = (queue) => (queue || []).map((q) => (q.attachments ? { ...q, a
const signThread = (t) => (t ? { ...t, messages: (t.messages || []).map(signMessage), ...(t.queue ? { queue: signQueue(t.queue) } : {}) } : t)

const listThreads = async () => (await threadStore.list()).map(signThread)
const listThreadSummaries = async () => (await threadStore.summaries()).map(signThread)
// The list carries a browser handoff still waiting on the owner (browser/handoff.mjs).
const listThreadSummaries = async () => {
const open = new Set(browserManager.sessionKeys())
return (await threadStore.summaries()).map((t) => withHandoff(signThread(t), browserHandoffs, open))
}
const readThread = async (id) => signThread(await threadStore.get(id))
const readThreadPage = async (id, opts) => signThread(await threadStore.page(id, opts))
const writeThread = async (id, body) => signThread(await threadStore.put(id, body))
Expand Down Expand Up @@ -10010,7 +10033,7 @@ async function startChatTurn(body, { idle = null } = {}) {
const t0 = Date.now()
// A new message settles a browser handoff left waiting from an earlier reply.
const leftOver = browserHandoffs.get(threadId)
if (leftOver) { browserHandoffs.delete(threadId); handoffWaits.dismiss(leftOver.id) }
if (leftOver) { dropHandoff(threadId); handoffWaits.dismiss(leftOver.id); push({ type: 'handoff', handoff: null }) }
const assistant = { ...thread.messages[thread.messages.length - 1], parts: [] }
let pending = null
const save = (extra) => threadStore.update(threadId, (t) => {
Expand Down Expand Up @@ -10124,7 +10147,7 @@ async function startChatTurn(body, { idle = null } = {}) {
return { content: [{ type: 'text', text: `${HANDOFF_TOOL}: no page is open in this chat. Open the page with preview_open first.` }], isError: true }
}
const handoff = { id: randomUUID().slice(0, 12), reason: normalizeReason(input), at: Date.now() }
browserHandoffs.set(threadId, handoff)
holdHandoff(threadId, handoff)
push({ type: 'handoff', handoff })
await browserManager.look(threadId).catch(() => {})
log(`web chat [${provider}] handed the browser to the owner`)
Expand All @@ -10147,12 +10170,12 @@ async function startChatTurn(body, { idle = null } = {}) {
release()
}
if (r.gone) {
if (signal.aborted) { browserHandoffs.delete(threadId); return { content: [{ type: 'text', text: 'The reply was stopped.' }], isError: true } }
if (signal.aborted) { dropHandoff(threadId); push({ type: 'handoff', handoff: null }); return { content: [{ type: 'text', text: 'The reply was stopped.' }], isError: true } }
return codexWindow?.aborted && !gone.aborted
? { content: [{ type: 'text', text: HANDOFF_LATER }] }
: { content: [{ type: 'text', text: HANDOFF_GONE }], isError: true }
}
if (browserHandoffs.get(threadId)?.id === handoff.id) browserHandoffs.delete(threadId)
if (browserHandoffs.get(threadId)?.id === handoff.id) dropHandoff(threadId)
push({ type: 'handoff', handoff: null })
if (r.dismissed) return { content: [{ type: 'text', text: handoffSkipped(handoff.reason) }] }
const page = await browserManager.status(threadId).catch(() => ({}))
Expand Down Expand Up @@ -10843,7 +10866,7 @@ async function handleChatApi(req, res, path) {
await browserManager.closeSession(threadId)
browserFrames.delete(threadId)
const handoff = browserHandoffs.get(threadId)
if (handoff) { browserHandoffs.delete(threadId); handoffWaits.dismiss(handoff.id) }
if (handoff) { dropHandoff(threadId); handoffWaits.dismiss(handoff.id) }
return send(res, 200, { ok: true })
}
// Done or Skip on a browser handoff (browser/handoff.mjs). A call still waiting
Expand All @@ -10856,7 +10879,7 @@ async function handleChatApi(req, res, path) {
if (!handoff || handoff.id !== id) return send(res, 404, { error: 'that handoff is over' })
const done = action !== 'skip'
const live = done ? handoffWaits.answer(id, {}) : handoffWaits.dismiss(id)
browserHandoffs.delete(threadId)
dropHandoff(threadId)
return send(res, 200, { live, message: live ? null : handoffMessage(handoff.reason, done) })
}

Expand Down
23 changes: 23 additions & 0 deletions browser/browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,26 @@ test('the handoff tool reaches every CLI and is only promised when it is there',
assert.match(browserRules('x', { handoff: true }), /preview_handoff/)
assert.doesNotMatch(browserRules('x'), /preview_handoff/)
})

test('the chat list carries a handoff still waiting, and nothing else of it', async () => {
const { withHandoff } = await import('./handoff.mjs')
const handoffs = new Map([['a', { id: 'h1', reason: 'Sign in to Gmail', at: 5, extra: 'x' }]])
const open = new Set(['a', 'b'])
assert.deepEqual(withHandoff({ id: 'a', title: 'Mail' }, handoffs, open), { id: 'a', title: 'Mail', handoff: { id: 'h1', reason: 'Sign in to Gmail', at: 5 } })
const other = { id: 'b' }
assert.equal(withHandoff(other, handoffs, open), other)
assert.equal(withHandoff(null, handoffs, open), null)
const closed = { id: 'a', title: 'Mail' }
assert.equal(withHandoff(closed, handoffs, new Set()), closed, 'no badge for a browser that has closed')
})

test('the bridge sets and clears a handoff only through holdHandoff and dropHandoff', async () => {
// Those keep the chat's browser open while it waits; a bare set or delete would
// let it close after 30 idle minutes, or hold it open with nothing waiting.
const { readFileSync } = await import('node:fs')
const bridge = readFileSync(new URL('../bridge.mjs', import.meta.url), 'utf8')
assert.equal(bridge.match(/browserHandoffs\.set\(/g)?.length, 1)
assert.equal(bridge.match(/browserHandoffs\.delete\(/g)?.length, 1)
assert.match(bridge, /function holdHandoff\(threadId, handoff\) \{\n dropHandoff\(threadId\)\n browserHandoffs\.set\(/)
assert.match(bridge, /function dropHandoff\(threadId\) \{\n browserHandoffs\.delete\(/)
})
12 changes: 12 additions & 0 deletions browser/handoff.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,15 @@ export const HANDOFF_GONE =
/** The message sent for him when Done is pressed after the call stopped waiting. */
export const handoffMessage = (reason, done) =>
done ? `I'm done in the browser (${reason}). Carry on.` : `I skipped that in the browser (${reason}). Carry on without it.`

/**
* A chat as the list sends it, with the handoff still waiting on the owner. The
* handoff lives in memory beside the browser it needs (`handoffs`, thread id →
* handoff), never in the thread, so a chat he is not in, on any device, still
* says it is waiting on him there; only while that browser is open (`open`, the
* chats with a browser session), as GET /api/chat/browser does.
*/
export const withHandoff = (thread, handoffs, open) => {
const handoff = thread && open.has(thread.id) && handoffs.get(thread.id)
return handoff ? { ...thread, handoff: { id: handoff.id, reason: handoff.reason, at: handoff.at } } : thread
}
Loading
Loading