diff --git a/AGENTS.md b/AGENTS.md index 4046f6e..a1fa6e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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.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`. | diff --git a/bridge.mjs b/bridge.mjs index 8b55edc..e6ef37c 100644 --- a/bridge.mjs +++ b/bridge.mjs @@ -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' @@ -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) @@ -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). @@ -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)) @@ -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) => { @@ -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`) @@ -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(() => ({})) @@ -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 @@ -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) }) } diff --git a/browser/browser.test.mjs b/browser/browser.test.mjs index 709f1b0..cf81ea9 100644 --- a/browser/browser.test.mjs +++ b/browser/browser.test.mjs @@ -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\(/) +}) diff --git a/browser/handoff.mjs b/browser/handoff.mjs index 25872a3..b1bc3a7 100644 --- a/browser/handoff.mjs +++ b/browser/handoff.mjs @@ -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 +} diff --git a/browser/manager.mjs b/browser/manager.mjs index 861bedb..02d8876 100644 --- a/browser/manager.mjs +++ b/browser/manager.mjs @@ -21,6 +21,8 @@ import { cdpMouse, cdpWheel, coalesce, parseInput, MODIFIERS } from './input.mjs export { readOnlyRequestDecision, findChromium } const CONTEXT_IDLE_MS = 30 * 60_000 +// The longest a hold (a handoff waiting on the owner) keeps a context open. +const HOLD_MAX_MS = 24 * 60 * 60_000 const BROWSER_IDLE_MS = 10 * 60_000 const DEFAULT_TIMEOUT = 15_000 const MAX_TIMEOUT = 60_000 @@ -82,7 +84,7 @@ export function normalizeUrl(raw) { } export function createBrowserManager({ - log = () => {}, onFrame = () => {}, executablePath = findChromium(), loadPlaywright = () => import('playwright-core'), + log = () => {}, onFrame = () => {}, onClose = () => {}, executablePath = findChromium(), loadPlaywright = () => import('playwright-core'), headed = false, contextIdleMs = CONTEXT_IDLE_MS, browserIdleMs = BROWSER_IDLE_MS, releaseTimeoutMs = RELEASE_TIMEOUT_MS, } = {}) { let browserPromise = null @@ -101,7 +103,9 @@ export function createBrowserManager({ b.on('disconnected', () => { browserPromise = null for (const s of sessions.values()) endViewers(s, 'closed') + const keys = [...sessions.keys()] sessions.clear() + for (const key of keys) onClose(key) }) userAgent = await ownUserAgent(b) log(`browser: started ${executablePath}${headed ? ' (headed)' : ''}`) @@ -140,15 +144,41 @@ export function createBrowserManager({ function touch(s, key) { s.lastUsed = Date.now() if (s.timer) clearTimeout(s.timer) + s.timer = null + if (s.holds) return s.timer = setTimeout(() => closeSession(key), contextIdleMs) s.timer.unref?.() } + /** + * Keep a chat's context open while something in it waits on the owner (a + * browser handoff he may come back to hours later): its idle timer starts again + * once every hold is released, or a hold reaches `maxMs`. Returns the release. + */ + function keepOpen(key, { maxMs = HOLD_MAX_MS } = {}) { + const s = sessions.get(key) + if (!s) return () => {} + s.holds = (s.holds || 0) + 1 + if (s.timer) { clearTimeout(s.timer); s.timer = null } + let released = false + const cap = setTimeout(() => release(), maxMs) + cap.unref?.() + function release() { + if (released) return + released = true + clearTimeout(cap) + s.holds-- + if (sessions.get(key) === s) touch(s, key) + } + return release + } + async function closeSession(key) { const s = sessions.get(key) if (!s) return sessions.delete(key) if (s.timer) clearTimeout(s.timer) + onClose(key) endViewers(s, 'closed') await stopCast(s) await s.context.close().catch(() => {}) @@ -197,7 +227,8 @@ export function createBrowserManager({ // CDP's Page.startScreencast on the current tab while at least one viewer // watches, stopped when the last one leaves, the tab changes or the context // closes. Watching never opens a browser or a context, and never keeps one - // alive: only the agent's actions and the owner's input touch the idle timer. + // alive: only the agent's actions and the owner's input touch the idle timer + // (and keepOpen, while a handoff waits on him). async function cdpFor(s, tab) { if (!tab.cdp) { @@ -887,7 +918,7 @@ export function createBrowserManager({ executablePath, status, open, navigate, resize, setColorScheme, snapshot, click, type, press, scroll, evaluate, waitFor, look, watch, latestFrame, input, release, - renderPage, readPage, storageState, closeSession, closeAll, + renderPage, readPage, storageState, closeSession, closeAll, keepOpen, sessionKeys: () => [...sessions.keys()], } } diff --git a/browser/stream.test.mjs b/browser/stream.test.mjs index 95dca30..e155c90 100644 --- a/browser/stream.test.mjs +++ b/browser/stream.test.mjs @@ -198,6 +198,28 @@ test('the idle timers end the stream, close the context, then the browser', asyn await until(() => fake.seen.browserClosed === 1, 1000) }) +test('a hold keeps the context open past its idle time; releasing it starts the timer again', async () => { + const fake = fakePlaywright() + const closed = [] + const manager = createBrowserManager({ executablePath: '/bin/true', loadPlaywright: fake.loadPlaywright, contextIdleMs: 60, browserIdleMs: 40, onClose: (key) => closed.push(key) }) + try { + await manager.open('t', { url: 'https://example.com' }) + const release = manager.keepOpen('t') + await new Promise((r) => setTimeout(r, 200)) + assert.deepEqual(manager.sessionKeys(), ['t'], 'held: still open well past the idle time') + release() + release() + await until(() => manager.sessionKeys().length === 0, 1000) + assert.equal(manager.keepOpen('gone')(), undefined, 'holding a chat with no browser is a no-op') + await manager.open('u', { url: 'https://example.com' }) + manager.keepOpen('u', { maxMs: 50 }) + await until(() => manager.sessionKeys().length === 0, 1000) + assert.deepEqual(closed, ['t', 'u'], 'every close is reported, so a handoff in it can end') + } finally { + await manager.closeAll() + } +}) + test('owner input reaches the page in order, as CDP mouse events and keyboard keys', async () => { const fake = fakePlaywright() const manager = createBrowserManager({ executablePath: '/bin/true', loadPlaywright: fake.loadPlaywright }) diff --git a/docs/chat.md b/docs/chat.md index 11c9c5a..2b2dcc8 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -744,6 +744,28 @@ the CLI drops the call. Then the banner stays, and Done sends "I'm done in the b as his next message. Any new message settles a leftover handoff. Totems with the browser switch don't get the tool, since nobody is watching their runs. +While a handoff waits, the chat's browser stays open past its 30-minute idle close, for a +day at most (`keepOpen` in `browser/manager.mjs`, `holdHandoff`/`dropHandoff` in +`bridge.mjs`), so the page is still there when he comes back hours later. A browser that +closes anyway (past that day, the chat deleted, Chromium gone) ends its handoff, and a call +still waiting is told he skipped it (`onClose` on the manager). + +A handoff waiting on him shows outside the panel too, so a chat held on him for hours never +looks like one still working. The chat list's summaries carry it while its browser is open +(`handoff` on `GET /api/threads?view=summary`, `withHandoff` in `browser/handoff.mjs`; it +lives in memory beside the browser, never in the thread), and the stores keep it in `handoffs`: a chat this +device follows a run for keeps what its stream said, and a list sent before this device +learned of one, or one it answered, cannot undo it (`takeHandoffs` in `web/src/chat/store.ts`). +Its row in the chats list says "Your turn", the running-chats panel says "Your turn in the +browser: …" and counts it as waiting on him rather than running, and the chat shows a row over +the composer with Open / Skip / Done while the panel is shut (the panel's banner has its own +Done / Skip; `HandoffBar.tsx`). +Opening a chat that is waiting opens its browser panel. One helper decides what a chat waits +on him for and the words for it, questions first, then a tool approval, then the browser, +then an inbox proposal (`web/src/chat/attention.ts`, copied to `mobile/src/lib/chat/`). The +iPhone app has no browser to drive: it shows the same badge and row, and Done or Skip from +there answers it. + The sessions live in memory: a bridge restart closes every chat's browser, and the next `preview_open` starts a fresh one. diff --git a/mobile/src/features/chat/ChatScreen.tsx b/mobile/src/features/chat/ChatScreen.tsx index 8d3276c..e6274f5 100644 --- a/mobile/src/features/chat/ChatScreen.tsx +++ b/mobile/src/features/chat/ChatScreen.tsx @@ -36,6 +36,7 @@ import Composer, { type ComposerHandle, type FollowUpPayload } from './Composer' import QueuedMessages from './QueuedMessages' import { UserMessage, AssistantMessage } from './Message' import { useQuestionFlow } from './QuestionsPanel' +import HandoffBar from './HandoffBar' import { pendingQuestions } from '../../lib/chat/questions' import { DECLINE_PLACEHOLDER, pendingApproval } from '../../lib/chat/approvals' import { ModelChip } from './ModelPicker' @@ -685,7 +686,7 @@ export default function ChatScreen() { ) : null} - {questionFlow ? questionFlow.panel : <>{parkedEl}{pendingHandoff}} + {questionFlow ? questionFlow.panel : <>{parkedEl}{pendingHandoff}} {empty && !project && !temporary && !questionFlow && startInProjects.length ? ( Start in diff --git a/mobile/src/features/chat/ChatsNav.tsx b/mobile/src/features/chat/ChatsNav.tsx index fab495e..8b675e4 100644 --- a/mobile/src/features/chat/ChatsNav.tsx +++ b/mobile/src/features/chat/ChatsNav.tsx @@ -15,8 +15,7 @@ import { MenuView } from '@react-native-menu/menu' import ReanimatedSwipeable, { type SwipeableMethods } from 'react-native-gesture-handler/ReanimatedSwipeable' import Animated, { useAnimatedStyle, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated' import { useChat, openProject, createProject, foldersOf, threadTitle } from '../../lib/chat/store' -import { pendingQuestions } from '../../lib/chat/questions' -import { pendingApproval } from '../../lib/chat/approvals' +import { attentionOf, attentionBadge, attentionTitle } from '../../lib/chat/attention' import { shelve, wokeAt, countdown, ago, settledAt, isSnoozed, snoozePresets, offersSettle, keptOpenId, type Shelf, } from '../../lib/chat/settle' @@ -76,9 +75,9 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now }: { const title = threadTitle(t) const woke = shelf === 'active' && !!wokeAt(t, now) && !active const waiting = (t.needsReply && !live) || woke - // Questions from the agent outrank everything else on the row, as in T3. - const asking = !!pendingQuestions(t) - const approving = !asking && !!pendingApproval(t) + // What the chat waits on him for outranks everything else on the row, as in T3 (attention.ts). + const handoff = useChat((s) => s.handoffs[t.id]) + const needs = attentionOf(t, handoff) const menu = threadMenu(t, shelf, live) const swipe = useRef(null) // Every swipe action is one of the menu's own ids, so both run the same code. @@ -106,8 +105,7 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now }: { > {title} - {asking ? Awaiting input - : approving ? Awaiting approval + {needs ? {attentionBadge(needs)} : live ? : woke ? Woke : t.needsReply && !offersSettle(t, shelf, live) ? : null} diff --git a/mobile/src/features/chat/HandoffBar.tsx b/mobile/src/features/chat/HandoffBar.tsx new file mode 100644 index 0000000..b6288a8 --- /dev/null +++ b/mobile/src/features/chat/HandoffBar.tsx @@ -0,0 +1,39 @@ +import React from 'react' +import { StyleSheet, View } from 'react-native' +import { useChat, answerHandoff } from '../../lib/chat/store' +import { T } from '../../ui/Text' +import { Press } from '../../ui/kit' +import { tap } from '../../ui/haptics' +import { TI, vc } from './ui' +import { IconHandClick } from './icons' + +// The web's HandoffBar: the chat's agent handed its browser to the owner +// (preview_handoff) and is waiting on him, so a chat that looks like it is still +// running says why. The app has no browser to drive, so it says where the page +// is; Done (he did it on the web) and Skip answer it from here. +const BLUE = '#7aa2ff' + +export default function HandoffBar({ threadId }: { threadId: string | null }) { + const handoff = useChat((s) => (threadId ? s.handoffs[threadId] || null : null)) + if (!threadId || !handoff) return null + return ( + + + + Your turn in the browser + {handoff.reason} · do it in this chat on the web + + { tap(); void answerHandoff(threadId, 'skip') }} accessibilityRole="button" accessibilityLabel="Skip">Skip + { tap(); void answerHandoff(threadId, 'done') }} accessibilityRole="button" accessibilityLabel="Done">Done + + ) +} + +const st = StyleSheet.create({ + bar: { + flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 6, paddingVertical: 6, paddingLeft: 12, paddingRight: 6, + borderRadius: 12, borderWidth: 1, borderColor: 'rgba(122,162,255,0.45)', backgroundColor: 'rgba(122,162,255,0.12)', + }, + ghost: { height: 36, paddingHorizontal: 10, borderRadius: 999, alignItems: 'center', justifyContent: 'center' }, + done: { height: 36, paddingHorizontal: 14, borderRadius: 999, alignItems: 'center', justifyContent: 'center', backgroundColor: BLUE }, +}) diff --git a/mobile/src/features/chat/RunningChats.tsx b/mobile/src/features/chat/RunningChats.tsx index 6013cb7..e73cf1b 100644 --- a/mobile/src/features/chat/RunningChats.tsx +++ b/mobile/src/features/chat/RunningChats.tsx @@ -18,9 +18,7 @@ import { useChat, getState, setActive, stop, settleThread, snoozeThread, markRea import { useOnScreen, getOnScreen } from '../../lib/chat/onScreen' import { isSnoozed, ago, snoozePresets } from '../../lib/chat/settle' import type { ChatThread, Project } from '../../lib/chat/types' -import { pendingQuestions } from '../../lib/chat/questions' -import { pendingApproval } from '../../lib/chat/approvals' -import { pendingInboxCards } from '../../lib/chat/inboxCards' +import { attentionOf, attentionStatus } from '../../lib/chat/attention' import { pushToast } from '../../lib/toast' import { colors } from '../../theme' import { T } from '../../ui/Text' @@ -73,12 +71,9 @@ function Row({ t, run, now, onOpen }: { t: ChatThread; run?: RunState; now: numb const title = threadTitle(t) const failed = !run && failedReply(t) const when = ago(t.updatedAt, now) - const asking = pendingQuestions(t) - const approving = !asking && pendingApproval(t) - const proposals = !asking && !approving ? pendingInboxCards(t) : [] - const status = asking ? (asking.part.questions.length === 1 ? 'A question for you' : `${asking.part.questions.length} questions for you`) - : approving ? 'Waiting for your approval' - : proposals.length ? `Waiting on your approval: ${proposals.length === 1 ? proposals[0].title : `${proposals.length} proposals`}` + const handoff = useChat((s) => s.handoffs[t.id]) + const needs = attentionOf(t, handoff) + const status = needs ? attentionStatus(needs) : run ? `${elapsed(now - run.startedAt)} · ${run.activity?.split('\n')[0] || 'Working'}` : failed ? `Failed ${when !== 'now' ? `${when} ago` : 'just now'}` : when !== 'now' ? `Done ${when} ago` : 'Done just now' @@ -91,7 +86,7 @@ function Row({ t, run, now, onOpen }: { t: ChatThread; run?: RunState; now: numb {title} {run ? : null} - {status} + {status} @@ -128,6 +123,7 @@ export default function RunningChats({ onOpenChat }: { onOpenChat?: (id: string) const threads = useChat((s) => s.threads) const runs = useChat((s) => s.runs) const projects = useChat((s) => s.projects) + const handoffs = useChat((s) => s.handoffs) const onScreen = useOnScreen() const { height } = useWindowDimensions() const [collapsed, setCollapsed] = useState(true) @@ -165,9 +161,9 @@ export default function RunningChats({ onOpenChat }: { onOpenChat?: (id: string) }, [runs, open]) const candidates = useMemo(() => threads.filter((t) => ( - !t.totemId && (runs[t.id] || pendingQuestions(t) || pendingInboxCards(t).length || t.needsReply) && !onScreen.open.has(t.id) + !t.totemId && (runs[t.id] || attentionOf(t, handoffs[t.id]) || t.needsReply) && !onScreen.open.has(t.id) && !isSnoozed(t, now) && t.settledOverride !== 'settled' - )), [threads, runs, onScreen, now]) + )), [threads, runs, handoffs, onScreen, now]) // Leaving is immediate; joining waits a moment. const [shown, setShown] = useState([]) @@ -196,8 +192,9 @@ export default function RunningChats({ onOpenChat }: { onOpenChat?: (id: string) }, [visible, projects]) if (!visible.length) return null - const running = visible.filter((t) => runs[t.id]).length - const waiting = visible.filter((t) => !runs[t.id] && pendingInboxCards(t).length).length + // A run held on him is waiting, not running: the pill must not say "running" for hours. + const waiting = visible.filter((t) => attentionOf(t, handoffs[t.id])).length + const running = visible.filter((t) => runs[t.id] && !attentionOf(t, handoffs[t.id])).length const done = visible.length - running - waiting const summary = [running && `${running} running`, waiting && `${waiting} waiting on you`, done && `${done} unread`].filter(Boolean).join(' · ') @@ -205,7 +202,7 @@ export default function RunningChats({ onOpenChat }: { onOpenChat?: (id: string) return ( { tap(); setCollapsed(false) }} accessibilityLabel={`Other chats: ${summary}. Show them`}> - {running > 0 ? : } + {running > 0 ? : waiting > 0 ? : } {summary} diff --git a/mobile/src/features/chat/history.shared.test.mjs b/mobile/src/features/chat/history.shared.test.mjs index 320ba4f..6c2a8b1 100644 --- a/mobile/src/features/chat/history.shared.test.mjs +++ b/mobile/src/features/chat/history.shared.test.mjs @@ -1,7 +1,8 @@ -// A chat's history (summaries, windows, "Load earlier") is one copy shared with -// the web: web/src/chat/history.ts, tested there (history.test.ts) and mirrored -// byte for byte to mobile/src/lib/chat/history.ts. This checks the copy has not -// drifted. Run with `node --test mobile/src/features/chat/*.test.mjs`. +// Chat files shared with the web, mirrored byte for byte into mobile/src/lib/chat/: +// a chat's history (summaries, windows, "Load earlier"; web/src/chat/history.ts, +// tested by history.test.ts) and what a chat waits on the owner for +// (web/src/chat/attention.ts, tested by attention.test.ts). This checks the copies +// have not drifted. Run with `node --test mobile/src/features/chat/*.test.mjs`. import test from 'node:test' import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' @@ -14,3 +15,7 @@ const read = (path) => readFileSync(join(repo, path), 'utf8') test('the chat history file is the web’s, byte for byte', () => { assert.equal(read('mobile/src/lib/chat/history.ts'), read('web/src/chat/history.ts'), 'mobile/src/lib/chat/history.ts has drifted from web/src/chat/history.ts') }) + +test('what a chat waits on the owner for is the web’s, byte for byte', () => { + assert.equal(read('mobile/src/lib/chat/attention.ts'), read('web/src/chat/attention.ts'), 'mobile/src/lib/chat/attention.ts has drifted from web/src/chat/attention.ts') +}) diff --git a/mobile/src/lib/chat/attention.ts b/mobile/src/lib/chat/attention.ts new file mode 100644 index 0000000..ddef4e2 --- /dev/null +++ b/mobile/src/lib/chat/attention.ts @@ -0,0 +1,56 @@ +// What a chat is waiting on the owner for, if anything, in the words its row in +// the chats list, the running-chats panel and the chat itself use. A run held on +// him still counts as running, so without this a chat waiting for hours on a +// sign-in looks like one still working. As in T3 Code, questions come first, +// then a tool approval, then the browser, then an inbox proposal. +import type { BrowserHandoff, ChatThread } from './types' +import { pendingQuestions } from './questions' +import { pendingApproval } from './approvals' +import { pendingInboxCards } from './inboxCards' + +export type Attention = + | { kind: 'questions'; count: number } + | { kind: 'approval' } + | { kind: 'browser'; reason: string } + | { kind: 'proposal'; titles: string[] } + +/** The one thing a chat waits on him for. `handoff` is the store's `handoffs[t.id]`. */ +export function attentionOf(t: Pick | null | undefined, handoff?: BrowserHandoff | null): Attention | null { + if (!t) return null + const asking = pendingQuestions(t) + if (asking) return { kind: 'questions', count: asking.part.questions.length } + if (pendingApproval(t)) return { kind: 'approval' } + if (handoff) return { kind: 'browser', reason: handoff.reason } + const proposals = pendingInboxCards(t) + if (proposals.length) return { kind: 'proposal', titles: proposals.map((p) => p.title) } + return null +} + +/** The badge on its row: a couple of words. */ +export function attentionBadge(a: Attention): string { + switch (a.kind) { + case 'questions': return 'Awaiting input' + case 'approval': case 'proposal': return 'Awaiting approval' + case 'browser': return 'Your turn' + } +} + +/** The badge's tooltip, and its words for a screen reader. */ +export function attentionTitle(a: Attention): string { + switch (a.kind) { + case 'questions': return a.count === 1 ? 'Totem asked you a question' : `Totem asked you ${a.count} questions` + case 'approval': return 'A tool call is waiting for your approval' + case 'browser': return `Your turn in the browser: ${a.reason}` + case 'proposal': return a.titles.length === 1 ? `Waiting on your approval: ${a.titles[0]}` : `Waiting on your approval:\n${a.titles.join('\n')}` + } +} + +/** The running-chats panel's status line, which has a little more room. */ +export function attentionStatus(a: Attention): string { + switch (a.kind) { + case 'questions': return a.count === 1 ? 'A question for you' : `${a.count} questions for you` + case 'approval': return 'Waiting for your approval' + case 'browser': return `Your turn in the browser: ${a.reason}` + case 'proposal': return `Waiting on your approval: ${a.titles.length === 1 ? a.titles[0] : `${a.titles.length} proposals`}` + } +} diff --git a/mobile/src/lib/chat/icons.ts b/mobile/src/lib/chat/icons.ts index 4b57532..1122c90 100644 --- a/mobile/src/lib/chat/icons.ts +++ b/mobile/src/lib/chat/icons.ts @@ -23,6 +23,7 @@ export { default as IconX } from '@tabler/icons-react-native/dist/esm/icons/Icon export { default as IconLoader2 } from '@tabler/icons-react-native/dist/esm/icons/IconLoader2.mjs' export { default as IconTerminal2 } from '@tabler/icons-react-native/dist/esm/icons/IconTerminal2.mjs' export { default as IconWorld } from '@tabler/icons-react-native/dist/esm/icons/IconWorld.mjs' +export { default as IconHandClick } from '@tabler/icons-react-native/dist/esm/icons/IconHandClick.mjs' export { default as IconDeviceDesktop } from '@tabler/icons-react-native/dist/esm/icons/IconDeviceDesktop.mjs' export { default as IconChecklist } from '@tabler/icons-react-native/dist/esm/icons/IconChecklist.mjs' export { default as IconTarget } from '@tabler/icons-react-native/dist/esm/icons/IconTarget.mjs' diff --git a/mobile/src/lib/chat/store.ts b/mobile/src/lib/chat/store.ts index 00fd04c..e431d12 100644 --- a/mobile/src/lib/chat/store.ts +++ b/mobile/src/lib/chat/store.ts @@ -18,7 +18,7 @@ import { } from './api' import type { QueueAction } from './api' import { defaultSettingsFor, fromPreset, normalizeModelSettings, parseModelSpec, visibleModels, wireModel } from './models' -import type { ApprovalDecision, Attachment, BrowserFrame, ChatCapabilities, ChatMessage, ChatMode, ChatThread, ModelRow, ModelSettings, Project, ProviderRow, QueuedMessage, StreamEvent } from './types' +import type { ApprovalDecision, Attachment, BrowserFrame, BrowserHandoff, ChatCapabilities, ChatMessage, ChatMode, ChatThread, ModelRow, ModelSettings, Project, ProviderRow, QueuedMessage, StreamEvent } from './types' import { isLoaded, mergeEarlier, mergeLatest, mergeSummary, summarize, type ThreadPage } from './history' import { OPENED_KEY, markOpened, readJson } from './recents' import { activeAt, wokeAt, settledAt, settleFieldsOf, settleChange, unsettleChange, snoozeChange, wakeChange, wakeDescription, type SettleFields } from './settle' @@ -61,6 +61,8 @@ export interface ChatState { browser: Record /** The browser panel is open beside the active chat. */ browserOpen: boolean + /** Chats whose agent has handed the browser to the owner and is waiting (the web's; this app has no browser to hand over). */ + handoffs: Record /** The Agents panel (AgentsPanel.tsx) is open beside the active chat. */ agentsOpen: boolean /** The sub-agent it has open: the id of the tool card that started it. */ @@ -113,6 +115,7 @@ let state: ChatState = { artifact: null, browser: {}, browserOpen: false, + handoffs: {}, agentsOpen: false, agentFocus: null, retitling: {}, @@ -387,7 +390,7 @@ export function setActive(id: string | null) { const scope = t ? (t.projectId && state.projects.some((p) => p.id === t.projectId) ? t.projectId : null) : state.projectId const openedSettled = t && settledAt(t, now(), state.prefs.autoSettleDays ?? 3, !!state.runs[t.id]) ? t.id : null set({ activeId: id, openedSettled, artifact: null, browserOpen: false, agentsOpen: false, agentFocus: null, projectId: scope }) - if (id && !state.browser[id]) loadBrowser(id) + if (id && (!state.browser[id] || state.handoffs[id])) loadBrowser(id) if (id) { // Overview's Recent chats and the cache both go by when a chat was last opened here. try { localStorage.setItem(OPENED_KEY, JSON.stringify(markOpened(readJson(localStorage, OPENED_KEY, {}), id, now()))) } catch {} @@ -713,12 +716,77 @@ export async function moveThread(threadId: string, projectId: string | null) { const browserDismissed = new Set() async function loadBrowser(threadId: string) { + const sentAt = handoffClock try { - const r = await api<{ open: boolean; frame: BrowserFrame | null }>(`/api/chat/browser?threadId=${encodeURIComponent(threadId)}`) + const r = await api<{ open: boolean; frame: BrowserFrame | null; handoff?: BrowserHandoff | null }>(`/api/chat/browser?threadId=${encodeURIComponent(threadId)}`) if (r.frame && !state.browser[threadId]) set((s) => ({ browser: { ...s.browser, [threadId]: { ...r.frame!, live: !!s.runs[threadId] } } })) + if (r.handoff && !answeredHandoffs.has(r.handoff.id)) onHandoff(threadId, r.handoff) + // Answered elsewhere, or the browser closed: only one this device saw before asking. + else if (!r.handoff && state.handoffs[threadId] && (handoffSeen.get(threadId) || 0) <= sentAt) onHandoff(threadId, null) } catch {} } +// When this device last learned of each chat's handoff (a count, not a clock), +// and the ones it answered: a list or browser read sent before then cannot take +// one back, and none brings back one answered here. +let handoffClock = 0 +const handoffSeen = new Map() +const answeredHandoffs = new Set() + +/** + * The handoffs a chat list names (`handoff` on a summary, the bridge's + * withHandoff), taken off the threads. A chat whose run this device follows keeps + * what its stream said; for the rest the list is the word, except that it cannot + * undo what this device learned after asking, or bring back one it answered. + */ +function takeHandoffs(threads: ChatThread[], sentAt: number) { + const named = new Map() + for (const t of threads) { + const h = (t as ChatThread & { handoff?: BrowserHandoff }).handoff + if (h && !answeredHandoffs.has(h.id)) named.set(t.id, h) + delete (t as { handoff?: unknown }).handoff + } + return (s: ChatState) => { + const out: Record = {} + for (const [id, h] of Object.entries(s.handoffs)) { + if (s.runs[id] || named.has(id) || (handoffSeen.get(id) || 0) > sentAt) out[id] = h + } + for (const [id, h] of named) if (!s.runs[id] && out[id]?.id !== h.id) { out[id] = h; handoffSeen.set(id, ++handoffClock) } + return out + } +} + +// The app has no browser to drive: a handoff shows as the chat's row over the +// composer (HandoffBar.tsx) and on its row in the drawer, with Done and Skip. +function onHandoff(threadId: string, handoff: BrowserHandoff | null) { + handoffSeen.set(threadId, ++handoffClock) + set((s) => { + const handoffs = { ...s.handoffs } + if (handoff) handoffs[threadId] = handoff + else delete handoffs[threadId] + return { handoffs } + }) +} + +/** Done or Skip on a handoff. Past the agent's wait, it goes as his next message. */ +export async function answerHandoff(threadId: string, action: 'done' | 'skip') { + const handoff = state.handoffs[threadId] + if (!handoff) return + answeredHandoffs.add(handoff.id) + onHandoff(threadId, null) + try { + const r = await api<{ live: boolean; message: string | null }>('/api/chat/browser/handoff', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ threadId, id: handoff.id, action }) }) + if (!r.live && r.message) send({ threadId, text: r.message }) + } catch (e: any) { + // A 404: it was already over (answered elsewhere, or the browser closed). + if ((e as { status?: number })?.status === 404) return + // Not taken: it is still waiting on him. + answeredHandoffs.delete(handoff.id) + if (!state.handoffs[threadId]) onHandoff(threadId, handoff) + if (!fail(e)) pushError(`Couldn't answer the browser handoff: ${e?.message || 'Totem is out of reach'}`) + } +} + function onBrowserFrame(threadId: string, frame: BrowserFrame) { set((s) => ({ browser: { ...s.browser, [threadId]: { ...frame, live: true } } })) if (state.activeId === threadId && !state.browserOpen && !browserDismissed.has(threadId) && !narrowScreen()) { @@ -781,9 +849,11 @@ export async function syncThreads() { } catch {} localStorage.setItem(MIGRATED, '1') } + const sentAt = handoffClock const { threads } = await getThreadSummaries() // A newer sync went out while this one was waiting: its answer is the one to take. if (mine !== syncSeq) return + const listed = takeHandoffs(threads as ChatThread[], sentAt) const stale: string[] = [] set((s) => { const byId = new Map(s.threads.map((t) => [t.id, t])) @@ -808,7 +878,7 @@ export async function syncThreads() { const out = withOutbox(merged, new Set(Object.keys(s.runs))) // A thread created here a moment ago may not have reached the bridge yet. for (const t of s.threads) if ((s.runs[t.id] || threadReads.has(t.id)) && !out.some((m) => m.id === t.id)) out.push(t) - return { threads: sortThreads(out), loaded: true } + return { threads: sortThreads(out), loaded: true, handoffs: listed(s) } }) // The open chat moved on the bridge (another device, a totem, a queued reply): read it again. const open = state.activeId @@ -1023,6 +1093,9 @@ function handleEvent(threadId: string, e: StreamEvent) { case 'browser': onBrowserFrame(threadId, { tabId: e.tabId, url: e.url, title: e.title, image: e.image, at: e.at }) break + case 'handoff': + onHandoff(threadId, e.handoff) + break case 'title': patchThread(threadId, (t) => ({ ...t, title: e.title, ...(e.icon ? { icon: e.icon } : {}) })) break diff --git a/mobile/src/lib/chat/types.ts b/mobile/src/lib/chat/types.ts index c76aeb5..0ec84c8 100644 --- a/mobile/src/lib/chat/types.ts +++ b/mobile/src/lib/chat/types.ts @@ -14,6 +14,8 @@ export interface Attachment { export interface TextPart { type: 'text'; text: string } /** What the chat's browser is showing (bridge `browser` events). `image` is a JPEG data URL. */ export interface BrowserFrame { tabId: string; url: string; title: string; image: string; at: number } +/** The agent handing the browser to the owner (preview_handoff): what it needs done. */ +export interface BrowserHandoff { id: string; reason: string; at: number } export interface ImagePart { type: 'image'; uploadId: string; alt?: string; url?: string } export interface ToolPart { @@ -436,6 +438,7 @@ export type StreamEvent = | { type: 'agent'; toolId: string; agent?: Partial; step?: AgentStep; seq: number } | { type: 'image'; uploadId: string; alt?: string; url?: string; seq: number } | ({ type: 'browser'; seq: number } & BrowserFrame) + | { type: 'handoff'; handoff: BrowserHandoff | null; seq: number } | { type: 'file'; file: FilePart; seq: number } | { type: 'steer'; steer: Omit; seq: number } | { type: 'questions'; questions: Partial & { id: string }; seq: number } diff --git a/web/src/chat/HandoffBar.tsx b/web/src/chat/HandoffBar.tsx new file mode 100644 index 0000000..43b2e6c --- /dev/null +++ b/web/src/chat/HandoffBar.tsx @@ -0,0 +1,24 @@ +import React from 'react' +import { useChat, answerHandoff, showBrowser } from './store' +import { TI } from './ui' +import { IconHandClick } from './icons' + +// The chat's own word that its agent handed the browser over (preview_handoff) +// and is waiting on him: a row over the composer for as long as it waits, so a +// chat that looks like it is still running says why. While the browser panel +// shows, its own banner has Done and Skip, so this row steps aside. +export default function HandoffBar({ threadId }: { threadId: string | null }) { + const handoff = useChat((s) => (threadId ? s.handoffs[threadId] || null : null)) + const frame = useChat((s) => !!(threadId && s.browser[threadId])) + const panelOpen = useChat((s) => s.browserOpen) + if (!threadId || !handoff || (panelOpen && frame)) return null + return ( +
+ + Your turn in the browserYour turn {handoff.reason} + {frame && } + + +
+ ) +} diff --git a/web/src/chat/RunningChats.tsx b/web/src/chat/RunningChats.tsx index 6893a8f..2779146 100644 --- a/web/src/chat/RunningChats.tsx +++ b/web/src/chat/RunningChats.tsx @@ -10,9 +10,7 @@ import SnoozeMenu from './SnoozeMenu' import { TI } from './ui' import { IconPlayerStopFilled, IconClock, IconCheck, IconMailOpened, IconChevronDown, IconHome } from './icons' import type { ChatThread, Project } from './types' -import { pendingQuestions } from './questions' -import { pendingApproval } from './approvals' -import { pendingInboxCards } from './inboxCards' +import { attentionOf, attentionStatus, attentionTitle } from './attention' // The running-chats panel, bottom-right on every screen. It lists the chats that // are answering and the finished ones he hasn't read yet (`needsReply`), that he @@ -74,15 +72,10 @@ function Row({ t, run, now, onOpen, onSnooze }: { }) { const title = threadTitle(t) const failed = !run && failedReply(t) - const asking = pendingQuestions(t) - const approving = !asking && pendingApproval(t) - const proposals = !asking && !approving ? pendingInboxCards(t) : [] - const status = asking - ? {asking.part.questions.length === 1 ? 'A question for you' : `${asking.part.questions.length} questions for you`} - : approving - ? Waiting for your approval - : proposals.length - ? p.title).join('\n')}>Waiting on your approval: {proposals.length === 1 ? proposals[0].title : `${proposals.length} proposals`} + const handoff = useChat((s) => s.handoffs[t.id]) + const needs = attentionOf(t, handoff) + const status = needs + ? {attentionStatus(needs)} : run ? <>{elapsed(now - run.startedAt)} · {run.activity || 'Working'} : failed @@ -121,6 +114,7 @@ export default function RunningChats({ onOpenChat, onShowPanel, narrow }: { onOp const threads = useChat((s) => s.threads) const runs = useChat((s) => s.runs) const projects = useChat((s) => s.projects) + const handoffs = useChat((s) => s.handoffs) const onScreen = useOnScreen() const [collapsed, setCollapsed] = useState(true) const [snoozing, setSnoozing] = useState(null) @@ -162,9 +156,9 @@ export default function RunningChats({ onOpenChat, onShowPanel, narrow }: { onOp }, [runs, open]) const candidates = useMemo(() => threads.filter((t) => ( - !t.totemId && (runs[t.id] || pendingQuestions(t) || pendingInboxCards(t).length || (t.needsReply && !onPlacePage)) && !onScreen.rows.has(t.id) && !onScreen.open.has(t.id) + !t.totemId && (runs[t.id] || attentionOf(t, handoffs[t.id]) || (t.needsReply && !onPlacePage)) && !onScreen.rows.has(t.id) && !onScreen.open.has(t.id) && !isSnoozed(t, now) && t.settledOverride !== 'settled' - )), [threads, runs, onScreen, now, onPlacePage]) + )), [threads, runs, handoffs, onScreen, now, onPlacePage]) // Leaving is immediate; joining waits a moment. const [shown, setShown] = useState([]) @@ -195,15 +189,16 @@ export default function RunningChats({ onOpenChat, onShowPanel, narrow }: { onOp const closeSnooze = useCallback(() => setSnoozing(null), []) if (!visible.length) return null - const running = visible.filter((t) => runs[t.id]).length - const waiting = visible.filter((t) => !runs[t.id] && pendingInboxCards(t).length).length + // A run held on him is waiting, not running: the pill must not say "running" for hours. + const waiting = visible.filter((t) => attentionOf(t, handoffs[t.id])).length + const running = visible.filter((t) => runs[t.id] && !attentionOf(t, handoffs[t.id])).length const done = visible.length - running - waiting const summary = [running && `${running} running`, waiting && `${waiting} waiting on you`, done && `${done} unread`].filter(Boolean).join(' · ') if (collapsed) { return ( ) diff --git a/web/src/chat/ThreadList.tsx b/web/src/chat/ThreadList.tsx index 9814ca0..b42d968 100644 --- a/web/src/chat/ThreadList.tsx +++ b/web/src/chat/ThreadList.tsx @@ -1,7 +1,6 @@ import React, { useCallback, useMemo, useRef, useState } from 'react' import { useChat, getState, linkTask, groupThreads, threadTitle, renameThread, setPinned, keepThread, removeThread, regenerateTitle, moveThread, markRead, markUnread, setProjectContext, settleThread, unsettleThread, snoozeThread, wakeThread } from './store' -import { pendingQuestions } from './questions' -import { pendingApproval } from './approvals' +import { attentionOf, attentionBadge, attentionTitle } from './attention' import type { ChatThread } from './types' import { TI, useDismiss } from './ui' import { IconDots, IconPinned, IconPencil, IconTrash, IconCheck, IconSparkles, IconFolder, IconFolderOff, IconMail, IconMailOpened, IconClock, IconAlarmOff, IconArrowBackUp, IconChevronUp, IconChevronDown, IconPlus, IconLink } from './icons' @@ -76,6 +75,7 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now = Da const closePicker = useCallback(() => setPicking(null), []) const autoDays = useChat((s) => s.prefs.autoSettleDays ?? 3) const retitling = useChat((s) => !!s.retitling[t.id]) + const handoff = useChat((s) => s.handoffs[t.id]) const [editing, setEditing] = useState(false) const [draft, setDraft] = useState('') const rowRef = useRowOnScreen(t.id) @@ -109,16 +109,14 @@ export function ThreadItem({ t, active, live, onOpen, shelf = 'active', now = Da : shelf === 'settled' ? {ago(settledAt(t, now, autoDays), now)} : null - // Questions from the agent outrank everything else on the row, as in T3. - const asking = !!pendingQuestions(t) - const approving = !asking && !!pendingApproval(t) + // What the chat waits on him for outranks everything else on the row, as in T3 (attention.ts). + const needs = attentionOf(t, handoff) return (
)} - {questionFlow ? questionFlow.panel : <>{parkedEl}{pendingHandoff}} + {questionFlow ? questionFlow.panel : <>{parkedEl}{pendingHandoff}} {composerEl}
)}