diff --git a/resources/mcp-bridge.js b/resources/mcp-bridge.js index 588ec0e3..eb8b8a52 100644 --- a/resources/mcp-bridge.js +++ b/resources/mcp-bridge.js @@ -92,8 +92,16 @@ function send(msg) { const CALL_TIMEOUT_MS = Number(process.env.HARNESS_CALL_TIMEOUT_MS) || 60_000 // Worktree creation legitimately blocks on git fetch / PR checkout. const WORKTREE_CREATE_TIMEOUT_MS = 300_000 +// edit_copy waits on a person, not on Ness, and a person may leave a draft +// open over lunch. Claude Code (2.1.301) aborts a stdio tool call after 30 min +// with no response *or progress notification* +// (CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT), and hard-caps it at MCP_TOOL_TIMEOUT, +// default 1e8 ms (~27.8 h). So the bridge sends a progress heartbeat while it +// waits, and its own limit sits just under Claude's cap. +const COPY_DRAFT_TIMEOUT_MS = 24 * 60 * 60 * 1000 +const COPY_DRAFT_HEARTBEAT_MS = Number(process.env.HARNESS_PROGRESS_HEARTBEAT_MS) || 60_000 -function callControl(method, path, body, timeoutMs) { +function callControl(method, path, body, timeoutMs, signal) { return new Promise((resolve, reject) => { const data = body ? JSON.stringify(body) : undefined const limit = timeoutMs || CALL_TIMEOUT_MS @@ -108,7 +116,8 @@ function callControl(method, path, body, timeoutMs) { 'Content-Type': 'application/json', 'X-Harness-Terminal-Id': TERMINAL_ID, ...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}) - } + }, + ...(signal ? { signal } : {}) }, (res) => { let chunks = '' @@ -903,6 +912,32 @@ const TOOLS = [ required: ['tab_id'] } }, + { + name: 'edit_copy', + description: + "Hand a draft of human-facing copy to the user so they can rewrite it themselves before you use it. Use this for prose where the user's voice matters more than yours: UI strings and microcopy, onboarding or empty-state text, marketing/landing-page copy, release notes, announcements, social posts, emails. Ness opens your draft in an editor next to this conversation and the call blocks until the user submits. The result is their final text — use it VERBATIM wherever the copy is going (don't polish, reformat, or 'fix' it), and treat any note they add as direction for related copy. If they dismiss the draft, don't ship it; read their note and either try again or ask. Send one coherent piece per call (a headline + subhead is fine together); for many unrelated strings, make separate calls so each can be judged on its own.", + inputSchema: { + type: 'object', + properties: { + draft: { + type: 'string', + description: + 'Your draft, exactly as it would appear to readers. Plain text; keep line breaks meaningful because the user edits it as-is.' + }, + title: { + type: 'string', + description: + 'Short label for what this copy is, shown as the editor heading (e.g. "Settings empty-state headline", "v2.4 release notes").' + }, + context: { + type: 'string', + description: + 'Optional: where the copy lands and any constraints the user should keep in mind while editing (length limits, tone, placeholders like {count} that must survive).' + } + }, + required: ['draft'] + } + }, { name: 'list_shells', description: @@ -1026,6 +1061,7 @@ async function getToolPerms() { // default — and matching the browser gates' permissive-on-failure // posture rather than hiding a feature the user has enabled. tabNaming: s.tabNaming || { enabled: true }, + copyEditing: s.copyEditing || { enabled: false }, reviews: s.reviews || { enabled: false } } } @@ -1047,6 +1083,7 @@ async function getRendersMarkdown() { function filterToolsByPerms(tools, perms) { return tools.filter((t) => { if (MESSAGING_TOOLS.has(t.name)) return perms.messaging.enabled + if (t.name === 'edit_copy') return perms.copyEditing.enabled if (t.name === 'set_tab_name') return perms.tabNaming.enabled !== false if (t.name === 'request_review') return perms.reviews.enabled === true const isView = VIEW_BROWSER_TOOLS.has(t.name) @@ -1080,7 +1117,48 @@ function stripForkAffordance(tools) { }) } -async function handleToolCall(name, args) { +function formatCopyDraftResult(original, r) { + const note = r.note ? '\n\nNote from the user: ' + r.note : '' + if (r.kind === 'dismissed') { + return { + content: [ + { + type: 'text', + text: 'The user dismissed the draft without approving it. Do not use it.' + note + } + ], + isError: true + } + } + const text = typeof r.text === 'string' ? r.text : '' + if (text === original) { + return 'The user approved the draft unchanged. Use it verbatim.' + note + } + return ( + 'The user edited the draft. Use this text verbatim (between the markers, exclusive):\n<<>>' + + note + ) +} + +/** Keep the client's idle timer from firing while a call waits on a human. + * Without a progressToken the client isn't listening for progress, so + * there's nothing to send. */ +function startHeartbeat(progressToken) { + if (progressToken === undefined || progressToken === null) return () => {} + let progress = 0 + const timer = setInterval(() => { + send({ + jsonrpc: '2.0', + method: 'notifications/progress', + params: { progressToken, progress: ++progress, message: 'waiting for the user to edit the draft' } + }) + }, COPY_DRAFT_HEARTBEAT_MS) + return () => clearInterval(timer) +} + +async function handleToolCall(name, args, signal, progressToken) { if (name === 'create_worktree') { const prNumber = args && args.prNumber if (!args || (!args.branchName && !prNumber)) { @@ -1605,6 +1683,24 @@ async function handleToolCall(name, args) { (r.viewport.deviceScaleFactor !== 1 ? ' @' + r.viewport.deviceScaleFactor + 'x' : '') ) } + if (name === 'edit_copy') { + if (!args || typeof args.draft !== 'string' || !args.draft.trim()) { + throw new Error('draft is required') + } + const stopHeartbeat = startHeartbeat(progressToken) + try { + const r = await callControl( + 'POST', + '/copy-drafts', + { draft: args.draft, title: args.title, context: args.context }, + COPY_DRAFT_TIMEOUT_MS, + signal + ) + return formatCopyDraftResult(args.draft, r) + } finally { + stopHeartbeat() + } + } if (name === 'list_shells') { const r = await callControl('GET', '/shells') return JSON.stringify((r && r.shells) || [], null, 2) @@ -1641,6 +1737,11 @@ async function handleToolCall(name, args) { throw new Error('unknown tool: ' + name) } +// In-flight tool calls by JSON-RPC id, so a `notifications/cancelled` from +// the client (turn interrupted) can hang up on Ness — which is what tells the +// control server to withdraw a pending edit_copy card. +const inflight = new Map() + async function handle(msg) { const { id, method, params } = msg try { @@ -1659,6 +1760,11 @@ async function handle(msg) { if (method === 'notifications/initialized' || method === 'initialized') { return null } + if (method === 'notifications/cancelled') { + const controller = params && inflight.get(params.requestId) + if (controller) controller.abort() + return null + } if (method === 'tools/list') { logErr('tools/list received') const perms = await getToolPerms() @@ -1669,10 +1775,19 @@ async function handle(msg) { } if (method === 'tools/call') { logErr('tools/call received name=' + (params && params.name)) - const result = await handleToolCall( - params && params.name, - (params && params.arguments) || {} - ) + const controller = new AbortController() + inflight.set(id, controller) + let result + try { + result = await handleToolCall( + params && params.name, + (params && params.arguments) || {}, + controller.signal, + params && params._meta ? params._meta.progressToken : undefined + ) + } finally { + inflight.delete(id) + } const content = result && typeof result === 'object' && Array.isArray(result.content) ? result.content @@ -1680,7 +1795,7 @@ async function handle(msg) { return { jsonrpc: '2.0', id, - result: { content } + result: { content, ...(result && result.isError ? { isError: true } : {}) } } } return { @@ -1691,6 +1806,8 @@ async function handle(msg) { } catch (err) { const message = (err && err.message) || String(err) logErr('error', method, message) + // The client cancelled this call; MCP says not to answer it. + if (method === 'tools/call' && err && err.name === 'AbortError') return null if (method === 'tools/call') { return { jsonrpc: '2.0', diff --git a/resources/mcp-bridge.test.js b/resources/mcp-bridge.test.js index 7c25d5f0..81e54afd 100644 --- a/resources/mcp-bridge.test.js +++ b/resources/mcp-bridge.test.js @@ -378,6 +378,150 @@ describe('mcp-bridge get_tab_dom', () => { }, 10_000) }) +describe('mcp-bridge edit_copy', () => { + let stub + let bridge + + afterEach(async () => { + if (bridge) await bridge.kill() + if (stub) await stub.close() + bridge = null + stub = null + }) + + async function callEditCopy(reply, args = { draft: 'Get started now!', title: 'Headline' }) { + stub = await startStub((req, body, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify(req.url === '/copy-drafts' ? reply : { scope: null })) + }) + bridge = spawnBridge(stub.port, 'tok') + bridge.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + await bridge.next() + bridge.send({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { name: 'edit_copy', arguments: args } + }) + return bridge.next() + } + + async function listedNames(copyEditing) { + stub = await startStub((req, body, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ scope: null, ...(copyEditing ? { copyEditing } : {}) })) + }) + bridge = spawnBridge(stub.port, 'tok') + bridge.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + await bridge.next() + bridge.send({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }) + const response = await bridge.next() + return response.result.tools.map((t) => t.name) + } + + it('is only advertised when copy editing is enabled', async () => { + expect(await listedNames(null)).not.toContain('edit_copy') + await bridge.kill() + await stub.close() + expect(await listedNames({ enabled: true })).toContain('edit_copy') + }) + + it('returns the edited text and forwards title + context', async () => { + const response = await callEditCopy( + { kind: 'submitted', text: 'Start here', note: 'less shouty' }, + { draft: 'Get started now!', title: 'Headline', context: 'max 20 chars' } + ) + expect(response.result.isError).toBeFalsy() + const text = response.result.content[0].text + expect(text).toContain('<<>>') + expect(text).toContain('less shouty') + const post = stub.captured.find((c) => c.url === '/copy-drafts') + expect(post.body).toEqual({ + draft: 'Get started now!', + title: 'Headline', + context: 'max 20 chars' + }) + }) + + it('says so when the user approved the draft unchanged', async () => { + const response = await callEditCopy({ kind: 'submitted', text: 'Get started now!' }) + expect(response.result.content[0].text).toMatch(/approved the draft unchanged/) + }) + + it('reports a dismissal as an error so the agent does not ship the draft', async () => { + const response = await callEditCopy({ kind: 'dismissed', note: 'wrong tone' }) + expect(response.result.isError).toBe(true) + expect(response.result.content[0].text).toMatch(/dismissed/) + expect(response.result.content[0].text).toContain('wrong tone') + }) + + it('sends progress heartbeats while the user is editing', async () => { + let answer + stub = await startStub((req, body, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }) + if (req.url !== '/copy-drafts') return res.end(JSON.stringify({ scope: null })) + answer = () => res.end(JSON.stringify({ kind: 'submitted', text: 'x' })) + }) + bridge = spawnBridge(stub.port, 'tok', { HARNESS_PROGRESS_HEARTBEAT_MS: '20' }) + bridge.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + await bridge.next() + bridge.send({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { name: 'edit_copy', arguments: { draft: 'x' }, _meta: { progressToken: 'p1' } } + }) + const first = await bridge.next() + const second = await bridge.next() + expect(first).toMatchObject({ + method: 'notifications/progress', + params: { progressToken: 'p1', progress: 1 } + }) + expect(second.params.progress).toBe(2) + answer() + let msg = await bridge.next() + while (msg.method === 'notifications/progress') msg = await bridge.next() + expect(msg.id).toBe(2) + }) + + it('hangs up on Ness when the client cancels the call', async () => { + let closed = false + stub = await startStub((req, body, res) => { + if (req.url !== '/copy-drafts') { + res.writeHead(200, { 'Content-Type': 'application/json' }) + return res.end(JSON.stringify({ scope: null })) + } + res.on('close', () => { + closed = true + }) + }) + bridge = spawnBridge(stub.port, 'tok') + bridge.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + await bridge.next() + bridge.send({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { name: 'edit_copy', arguments: { draft: 'x' } } + }) + for (let i = 0; i < 200 && !stub.captured.some((c) => c.url === '/copy-drafts'); i++) { + await new Promise((r) => setTimeout(r, 10)) + } + bridge.send({ + jsonrpc: '2.0', + method: 'notifications/cancelled', + params: { requestId: 2 } + }) + for (let i = 0; i < 200 && !closed; i++) { + await new Promise((r) => setTimeout(r, 10)) + } + expect(closed).toBe(true) + // MCP: a cancelled request gets no response. + bridge.send({ jsonrpc: '2.0', id: 3, method: 'tools/list', params: {} }) + expect((await bridge.next()).id).toBe(3) + }) +}) + describe('mcp-bridge eval_tab', () => { let stub let bridge diff --git a/src/main/approval-bridge-rules.test.ts b/src/main/approval-bridge-rules.test.ts index 9e67db5b..48944b8d 100644 --- a/src/main/approval-bridge-rules.test.ts +++ b/src/main/approval-bridge-rules.test.ts @@ -431,6 +431,21 @@ describe('ApprovalBridge — persistent allowlist', () => { }) expect(res).toBeNull() }) + + it('always allows edit_copy without a grant or a card', async () => { + // The tool itself is the human prompt; approving it first would ask twice. + const h = await harness([]) + const res = await h.send({ + id: 'req-7', + tool_name: 'mcp__ness-control__edit_copy', + input: { draft: 'hello' }, + tool_use_id: 'tu-7' + }) + expect(res).toMatchObject({ + result: { behavior: 'allow', updatedInput: { draft: 'hello' } } + }) + expect(h.store.getSnapshot().state.jsonClaude.pendingApprovals['req-7']).toBeUndefined() + }) }) describe('ApprovalBridge — abandoned tool calls', () => { diff --git a/src/main/build-initial-state.ts b/src/main/build-initial-state.ts index 42c671e0..2e289dbd 100644 --- a/src/main/build-initial-state.ts +++ b/src/main/build-initial-state.ts @@ -24,6 +24,7 @@ import { initialAssignedPRs } from '../shared/state/assigned-prs' import { initialConfigHealth, type ConfigLoadError } from '../shared/state/config-health' import { initialAliases } from '../shared/state/aliases' import { initialPermissions } from '../shared/state/permissions' +import { initialCopyDrafts } from '../shared/state/copy-drafts' import { initialSubscriptions, type WorktreeSubscription } from '../shared/state/subscriptions' import { initialOrigins, type WorktreeOrigin } from '../shared/state/origins' import { initialNotifications } from '../shared/state/notifications' @@ -267,6 +268,7 @@ export function buildInitialAppState( : initialPermissions.rules, approvedSetupCommands: sanitizeApprovedSetupCommands(config.approvedSetupCommands) }, + copyDrafts: initialCopyDrafts, reviews: config.reviews ? { byPath: sanitizeReviews(config.reviews) } : initialReviews, subscriptions: Array.isArray(config.worktreeSubscriptions) ? { list: config.worktreeSubscriptions.filter(isStoredSubscription) } @@ -338,6 +340,7 @@ export function buildInitialAppState( ? config.lochPromptDismissedRepos : [], lochRecordNewRepos: typeof config.lochRecordNewRepos === 'boolean' ? config.lochRecordNewRepos : null, + copyEditingEnabled: config.copyEditingEnabled === true, agentTabNamingEnabled: config.agentTabNamingEnabled !== false, defaultClaudeTabType: config.defaultClaudeTabType === 'json' ? 'json' : 'xterm', chatPromotionDismissed: config.chatPromotionDismissed === true, diff --git a/src/main/control-server.test.ts b/src/main/control-server.test.ts index d292a4a5..586f1581 100644 --- a/src/main/control-server.test.ts +++ b/src/main/control-server.test.ts @@ -9,6 +9,7 @@ import type { ChatDeliveryResult, TabDeliveryResult } from './chat-delivery' import type { ChatTabInfo } from '../shared/agent-tabs' import type { ReviewComment } from '../shared/state/reviews' import type { CaptureResult } from './browser-manager-types' +import type { CopyDraftInput, CopyDraftOutcome } from './copy-draft-broker' import { parseAutomatedMessage } from '../shared/state/json-claude' import { followedByCreatorNote } from './control-server' import { createNewProject } from './repo-create' @@ -192,6 +193,15 @@ let domResult: () => Promise = async () => null let browserMode: 'view' | 'full' = 'full' const evalTab = vi.fn(async () => null) +/** Drafts the fake broker is holding, keyed by id, so a test can answer + * one the way the renderer would. */ +const heldDrafts = new Map< + string, + { input: CopyDraftInput; answer: (o: CopyDraftOutcome) => void } +>() +const cancelDraft = vi.fn<(id: string) => void>() +let nextDraftId = 0 +let copyEditingEnabled = true /** Mutable so the add_repo / create_project tests can register roots; reset * after each of those so the rest of the file still sees one repo. */ let repoRoots = ['/repo'] @@ -279,6 +289,21 @@ const deps: ControlServerDeps = { getWorktreeDetail: async (path) => ({ worktreePath: path, branch: 'b' }), reviews, listChatTabs: (path) => tabsByWorktree[path] ?? [], + copyDrafts: { + isEnabled: () => copyEditingEnabled, + request: (input) => { + const id = `draft-${++nextDraftId}` + const result = new Promise((answer) => { + heldDrafts.set(id, { input, answer }) + }) + return { id, result } + }, + cancel: (id) => { + cancelDraft(id) + heldDrafts.get(id)?.answer({ kind: 'cancelled' }) + heldDrafts.delete(id) + } + }, renameBranch: (worktreePath, newBranch) => renameBranch(worktreePath, newBranch) } @@ -1268,6 +1293,93 @@ describe('control-server subscription endpoints', () => { }) }) +describe('control-server /copy-drafts endpoint', () => { + async function waitForDraft(): Promise { + for (let i = 0; i < 100 && heldDrafts.size === 0; i++) { + await new Promise((r) => setTimeout(r, 5)) + } + const [id] = heldDrafts.keys() + if (!id) throw new Error('draft never reached the broker') + return id + } + + it('holds the response until the human submits, then returns their text', async () => { + heldDrafts.clear() + const pending = call('POST', '/copy-drafts', { + draft: 'Get started now!', + title: 'Empty state', + context: ' ' + }) + const id = await waitForDraft() + expect(heldDrafts.get(id)?.input).toEqual({ + terminalId: CALLER_TERMINAL, + worktreePath: CALLER_WORKTREE, + draft: 'Get started now!', + title: 'Empty state', + context: undefined + }) + heldDrafts.get(id)?.answer({ kind: 'submitted', text: 'Start here', note: 'calmer' }) + heldDrafts.delete(id) + const r = await pending + expect(r.status).toBe(200) + expect(r.json).toEqual({ kind: 'submitted', text: 'Start here', note: 'calmer' }) + }) + + it('returns 409 when the draft is withdrawn', async () => { + heldDrafts.clear() + const pending = call('POST', '/copy-drafts', { draft: 'x' }) + const id = await waitForDraft() + heldDrafts.get(id)?.answer({ kind: 'cancelled' }) + heldDrafts.delete(id) + const r = await pending + expect(r.status).toBe(409) + }) + + it('withdraws the draft when the caller hangs up', async () => { + heldDrafts.clear() + cancelDraft.mockClear() + const controller = new AbortController() + const pending = fetch(`${baseUrl}/copy-drafts`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + 'X-Harness-Terminal-Id': CALLER_TERMINAL + }, + body: JSON.stringify({ draft: 'x' }), + signal: controller.signal + }).catch(() => null) + const id = await waitForDraft() + controller.abort() + await pending + for (let i = 0; i < 100 && cancelDraft.mock.calls.length === 0; i++) { + await new Promise((r) => setTimeout(r, 5)) + } + expect(cancelDraft).toHaveBeenCalledWith(id) + }) + + it('refuses when copy editing is disabled', async () => { + copyEditingEnabled = false + try { + const r = await call('POST', '/copy-drafts', { draft: 'x' }) + expect(r.status).toBe(403) + expect(heldDrafts.size).toBe(0) + } finally { + copyEditingEnabled = true + } + }) + + it('rejects an empty draft', async () => { + const r = await call('POST', '/copy-drafts', { draft: ' ' }) + expect(r.status).toBe(400) + }) + + it('rejects a caller with no worktree', async () => { + const r = await call('POST', '/copy-drafts', { draft: 'x' }, { terminalId: 'unknown' }) + expect(r.status).toBe(404) + }) +}) + describe('control-server POST /projects and POST /repos', () => { let tmp: string const savedEnv = { ...process.env } diff --git a/src/main/control-server.ts b/src/main/control-server.ts index ce67c135..1f51e8b1 100644 --- a/src/main/control-server.ts +++ b/src/main/control-server.ts @@ -22,6 +22,7 @@ import type { NotifyMode } from '../shared/state/subscriptions' import type { Subscriber } from '../shared/subscribers' import type { FanOutResult, SubscribeResult, UnsubscribeResult } from './worktree-subscriptions' import type { CaptureResult } from './browser-manager-types' +import type { CopyDraftInput, CopyDraftOutcome } from './copy-draft-broker' import type { TabEvalResult } from './browser-eval' import { wrapAutomatedMessage } from '../shared/state/json-claude' import { writeResultImage } from './json-claude-attachments' @@ -213,6 +214,14 @@ export interface ReviewQueries { ) => { ok: true; reviewerTabId: string; reused: boolean } | { ok: false; error: string } } +export interface CopyDraftQueries { + /** Whether the edit_copy setting is on. Re-read per request so a toggle + * takes effect without restarting the bridge. */ + isEnabled: () => boolean + request: (input: CopyDraftInput) => { id: string; result: Promise } + cancel: (id: string) => void +} + /** Scope derived from the caller's terminal id on every request. The * source of truth — env vars injected into the MCP bridge can go stale * (teleport sessions, deleted worktrees), so each tool call re-resolves. */ @@ -286,6 +295,7 @@ export interface ControlServerDeps { /** Chat tabs of a worktree, most recently active first — the only tabs * reviews and tab messages can be delivered to. */ listChatTabs: (worktreePath: string) => ChatTabInfo[] + copyDrafts: CopyDraftQueries /** Trim + 80-char clamp + dispatch. Matches the aliases:set IPC handler. * Empty-after-trim routes to clearAlias — never stores an empty alias. */ setAlias: (worktreePath: string, alias: string) => void @@ -1471,6 +1481,50 @@ async function handleRequest( } } + // edit_copy — hand a draft to the human and hold this response open until + // they submit or dismiss it. Closing the connection (bridge timeout, agent + // interrupt, process exit) withdraws the draft from the UI. + if (req.method === 'POST' && path === '/copy-drafts') { + if (!deps.copyDrafts.isEnabled()) { + return sendJson(res, 403, { + error: 'copy editing is disabled in Ness settings (Settings → Experimental → Copy editing)' + }) + } + const { scope, terminalId } = resolveScope(req, deps) + if (!terminalId) { + return sendJson(res, 400, { error: 'X-Harness-Terminal-Id header required' }) + } + if (!scope) { + return sendJson(res, 404, { + error: 'caller terminal is not associated with a worktree' + }) + } + const body = await readJson(req) + const draft = typeof body.draft === 'string' ? body.draft : '' + if (!draft.trim()) return sendJson(res, 400, { error: 'draft required' }) + const optional = (v: unknown): string | undefined => + typeof v === 'string' && v.trim() ? v.trim() : undefined + + const { id, result } = deps.copyDrafts.request({ + terminalId, + worktreePath: scope.worktreePath, + draft, + title: optional(body.title), + context: optional(body.context) + }) + const onClose = (): void => { + if (!res.writableEnded) deps.copyDrafts.cancel(id) + } + res.on('close', onClose) + const outcome = await result + res.off('close', onClose) + if (res.destroyed) return + if (outcome.kind === 'cancelled') { + return sendJson(res, 409, { error: 'the draft was withdrawn before the user answered' }) + } + return sendJson(res, 200, outcome) + } + // /scope — returns the caller's current scope. The MCP bridge calls this // once at startup so it can adapt tool descriptions (e.g. signalling // "create_worktree defaults to this repo" for feature callers) and filter @@ -1486,6 +1540,7 @@ async function handleRequest( conversationFork: { enabled: deps.getConversationForkEnabled() }, messaging: { enabled: deps.messaging.isEnabled() }, tabNaming: { enabled: deps.getAgentTabNamingEnabled() }, + copyEditing: { enabled: deps.copyDrafts.isEnabled() }, reviews: { enabled: deps.getAgentReviewsEnabled() } }) } diff --git a/src/main/copy-draft-broker.test.ts b/src/main/copy-draft-broker.test.ts new file mode 100644 index 00000000..3cd395bb --- /dev/null +++ b/src/main/copy-draft-broker.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('./debug', () => ({ + log: () => {} +})) + +import { Store } from './store' +import { CopyDraftBroker } from './copy-draft-broker' +import { initialState } from '../shared/state' + +function setup(chatSessions: string[] = []): { + store: Store + broker: CopyDraftBroker + openTabs: Set +} { + const store = new Store(initialState) + const openTabs = new Set(['term-1']) + const broker = new CopyDraftBroker( + store, + (id) => chatSessions.includes(id), + (id) => openTabs.has(id) + ) + broker.start() + return { store, broker, openTabs } +} + +const input = { terminalId: 'term-1', worktreePath: '/wt', draft: 'Get started now!', title: 'Headline' } + +describe('CopyDraftBroker', () => { + it('publishes the draft and settles the waiter with the human answer', async () => { + const { store, broker } = setup() + const { id, result } = broker.request(input) + expect(store.getSnapshot().state.copyDrafts.pending[id]).toMatchObject(input) + + expect(broker.resolve(id, { kind: 'submitted', text: 'Start here' })).toBe(true) + await expect(result).resolves.toEqual({ kind: 'submitted', text: 'Start here' }) + expect(store.getSnapshot().state.copyDrafts.pending[id]).toBeUndefined() + }) + + it('only the first answer wins', async () => { + const { broker } = setup() + const { id, result } = broker.request(input) + broker.cancel(id) + expect(broker.resolve(id, { kind: 'submitted', text: 'late' })).toBe(false) + await expect(result).resolves.toEqual({ kind: 'cancelled' }) + }) + + it('keeps an edited withdrawn draft until the user clears it', () => { + const { store, broker } = setup() + const { id } = broker.request(input) + broker.markEdited(id) + broker.cancel(id) + const drafts = (): typeof initialState.copyDrafts => store.getSnapshot().state.copyDrafts + expect(drafts().pending[id]).toBeUndefined() + expect(drafts().withdrawn[id]).toMatchObject(input) + + expect(broker.clearWithdrawn(id)).toBe(true) + expect(drafts().withdrawn[id]).toBeUndefined() + expect(broker.clearWithdrawn(id)).toBe(false) + }) + + it('drops the draft outright when its tab closed, since nobody would see the notice', () => { + const { store, broker, openTabs } = setup() + const { id } = broker.request(input) + broker.markEdited(id) + openTabs.delete('term-1') + broker.cancel(id) + expect(store.getSnapshot().state.copyDrafts.withdrawn[id]).toBeUndefined() + expect(store.getSnapshot().state.copyDrafts.pending[id]).toBeUndefined() + }) + + it('drops a withdrawn draft nobody edited instead of leaving a notice', () => { + const { store, broker } = setup() + const { id } = broker.request(input) + broker.cancel(id) + expect(store.getSnapshot().state.copyDrafts.withdrawn[id]).toBeUndefined() + expect(store.getSnapshot().state.copyDrafts.pending[id]).toBeUndefined() + }) + + it('clears a withdrawn draft once its tab is closed', () => { + const { store, broker, openTabs } = setup() + const { id } = broker.request(input) + broker.markEdited(id) + broker.cancel(id) + expect(store.getSnapshot().state.copyDrafts.withdrawn[id]).toBeDefined() + + openTabs.delete('term-1') + store.dispatch({ type: 'terminals/panesForWorktreeCleared', payload: '/wt' }) + expect(store.getSnapshot().state.copyDrafts.withdrawn[id]).toBeUndefined() + }) + + it('hands a Terminal tab back to waiting, not processing, when the agent stops waiting', () => { + // An Esc in the TUI ends the turn with no further hook event, so a + // processing dot would spin until the next prompt. + const { store, broker } = setup() + const { id } = broker.request(input) + broker.cancel(id) + expect(store.getSnapshot().state.terminals.statuses['term-1']).toBe('waiting') + }) + + it('flags a terminal tab as needs-approval until the human answers', () => { + const { store, broker } = setup() + const { id } = broker.request(input) + const terminals = (): typeof initialState.terminals => store.getSnapshot().state.terminals + expect(terminals().statuses['term-1']).toBe('needs-approval') + expect(terminals().pendingTools['term-1']?.name).toBe('edit_copy') + + broker.resolve(id, { kind: 'dismissed' }) + expect(terminals().statuses['term-1']).toBe('processing') + }) + + it('leaves Chat-tab status to the json-claude deriver', () => { + const { store, broker } = setup(['term-1']) + broker.request(input) + expect(store.getSnapshot().state.terminals.statuses['term-1']).toBeUndefined() + }) +}) diff --git a/src/main/copy-draft-broker.ts b/src/main/copy-draft-broker.ts new file mode 100644 index 00000000..961756aa --- /dev/null +++ b/src/main/copy-draft-broker.ts @@ -0,0 +1,140 @@ +// Holds the agent side of the `edit_copy` MCP tool. The control server's +// HTTP handler parks on `request()` until a human submits or dismisses the +// draft from whichever client is showing it; the slice entry is what every +// client renders, and the waiter map is what turns the human's click back +// into the HTTP response the agent is blocked on. +// +// Status dots: Chat tabs get needs-approval from JsonClaudeStatusDeriver, +// which reads the copyDrafts slice. Terminal tabs have no deriver — their +// status comes from Claude Code hooks, which only know a tool is running — +// so the broker sets needs-approval itself and hands back to processing once +// the human answers (the tool is still finishing; PostToolUse follows). A +// withdrawal goes to waiting instead: it's usually an Esc in the TUI, which +// ends the turn without another hook event to correct the dot. +// +// Withdrawn drafts only outlive their tab long enough to be noticed: a tab +// closing is itself a withdrawal (the bridge dies with it), and nothing would +// ever render that notice, so it's dropped on the spot or once panes change. +// A draft nobody edited is dropped too — usually the user pressed Stop on +// purpose. Clients report their first edit via markEdited, since only main +// sees every client and can tell "untouched here" from "untouched anywhere". + +import { randomUUID } from 'crypto' +import type { Store } from './store' +import type { CopyDraftRequest } from '../shared/state/copy-drafts' +import { log } from './debug' + +export type CopyDraftOutcome = + | { kind: 'submitted'; text: string; note?: string } + | { kind: 'dismissed'; note?: string } + | { kind: 'cancelled' } + +export type CopyDraftInput = Omit + +export class CopyDraftBroker { + private waiters = new Map void>() + private edited = new Set() + + private unsubscribe: (() => void) | null = null + + constructor( + private store: Store, + private isChatSession: (terminalId: string) => boolean, + private tabExists: (terminalId: string) => boolean + ) {} + + start(): void { + if (this.unsubscribe) return + this.unsubscribe = this.store.subscribe((event) => { + if (!event.type.startsWith('terminals/panes')) return + // Sweeping is fine here: withdrawn holds a handful of entries at most, + // and pane events are user-paced, not streaming. + for (const req of Object.values(this.store.getSnapshot().state.copyDrafts.withdrawn)) { + if (!this.tabExists(req.terminalId)) this.clearWithdrawn(req.id) + } + }) + } + + stop(): void { + this.unsubscribe?.() + this.unsubscribe = null + } + + request(input: CopyDraftInput): { id: string; result: Promise } { + const id = randomUUID() + const req: CopyDraftRequest = { ...input, id, timestamp: Date.now() } + const result = new Promise((resolve) => { + this.waiters.set(id, resolve) + }) + this.store.dispatch({ type: 'copyDrafts/requested', payload: req }) + if (!this.isChatSession(req.terminalId)) { + this.store.dispatch({ + type: 'terminals/statusChanged', + payload: { + id: req.terminalId, + status: 'needs-approval', + pendingTool: { name: 'edit_copy', input: { title: req.title, draft: req.draft } } + } + }) + } + log('copy-drafts', `requested id=${id} terminal=${req.terminalId}`) + return { id, result } + } + + /** Returns false when the draft is already gone — answered from another + * client, or the agent's call was abandoned. */ + resolve(id: string, outcome: Exclude): boolean { + return this.settle(id, outcome) + } + + /** The agent stopped waiting (call timed out, turn interrupted, process + * exited). The draft moves to `withdrawn` rather than vanishing, so a + * half-finished edit can still be copied out. */ + cancel(id: string): void { + this.settle(id, { kind: 'cancelled' }) + } + + markEdited(id: string): void { + if (this.waiters.has(id)) this.edited.add(id) + } + + clearWithdrawn(id: string): boolean { + const req = this.store.getSnapshot().state.copyDrafts.withdrawn[id] + if (!req) return false + this.store.dispatch({ + type: 'copyDrafts/withdrawnCleared', + payload: { id, terminalId: req.terminalId } + }) + return true + } + + private settle(id: string, outcome: CopyDraftOutcome): boolean { + const waiter = this.waiters.get(id) + const req = this.store.getSnapshot().state.copyDrafts.pending[id] + if (!waiter || !req) return false + this.waiters.delete(id) + const wasEdited = this.edited.delete(id) + const withdrawn = + outcome.kind === 'cancelled' && wasEdited && this.tabExists(req.terminalId) + this.store.dispatch({ + type: withdrawn ? 'copyDrafts/withdrawn' : 'copyDrafts/resolved', + payload: { id, terminalId: req.terminalId } + }) + if (!this.isChatSession(req.terminalId)) { + const current = this.store.getSnapshot().state.terminals.statuses[req.terminalId] + if (current === 'needs-approval') { + this.store.dispatch({ + type: 'terminals/statusChanged', + payload: { + id: req.terminalId, + status: outcome.kind === 'cancelled' ? 'waiting' : 'processing', + pendingTool: null + } + }) + } + } + log('copy-drafts', `settled id=${id} outcome=${outcome.kind}`) + waiter(outcome) + return true + } +} diff --git a/src/main/hooks.ts b/src/main/hooks.ts index 32f383e4..10b01598 100644 --- a/src/main/hooks.ts +++ b/src/main/hooks.ts @@ -13,6 +13,7 @@ import type { Store } from './store' import { log } from './debug' import { getAgent } from './agents' import { findTabById } from '../shared/state/terminals' +import { firstDraftForTerminal } from '../shared/state/copy-drafts' // This path is also the signature we use to recognize Ness-installed // hook entries when deduping at install time. If you change it, update @@ -261,7 +262,12 @@ export function tailLog(terminalId: string, store: Store): void { } emitStopIfRelevant(terminalId, ev) const update = deriveStatus(terminalId, ev) - if (update) { + // edit_copy's PreToolUse can land after the broker already flagged the + // tab as waiting on the human; don't let it paper over that. + const awaitingCopyEdit = + update?.status === 'processing' && + firstDraftForTerminal(store.getSnapshot().state.copyDrafts, terminalId) !== null + if (update && !awaitingCopyEdit) { store.dispatch({ type: 'terminals/statusChanged', payload: { diff --git a/src/main/index.ts b/src/main/index.ts index 43a91bf3..974b0dc2 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -42,6 +42,7 @@ import { writeAttachmentImage } from './json-claude-attachments' import { JsonClaudeStatusDeriver } from './json-claude-status-deriver' +import { CopyDraftBroker, type CopyDraftOutcome } from './copy-draft-broker' import { Store } from './store' import { WebSocketServerTransport } from './transport-websocket' import { CompoundServerTransport } from './transport-compound' @@ -516,6 +517,11 @@ const approvalBridge = new ApprovalBridge(store, { return store.getSnapshot().state.worktrees.repoRoots.includes(want) } }) +const copyDraftBroker = new CopyDraftBroker( + store, + (terminalId) => terminalId in store.getSnapshot().state.jsonClaude.sessions, + (terminalId) => findTabById(store.getSnapshot().state.terminals.panes, terminalId) !== null +) const composerVisibility = new ComposerVisibility() const jsonClaudeManager = new JsonClaudeManager(store, { getClaudeCommand: () => @@ -952,6 +958,7 @@ store.subscribe((event) => { // Lives in its own module — see src/main/json-claude-status-deriver.ts. const jsonClaudeStatusDeriver = new JsonClaudeStatusDeriver(store) jsonClaudeStatusDeriver.start() +copyDraftBroker.start() /** Resolve the GitHub login of whoever owns the configured token, and * dispatch it so the sidebar can route PRs they didn't author into the @@ -3576,6 +3583,20 @@ function registerIpcHandlers(): void { return true }) + transport.onRequest('config:setCopyEditingEnabled', (_ctx, enabled: boolean) => { + if (enabled) { + config.copyEditingEnabled = true + } else { + delete config.copyEditingEnabled + } + saveConfig(config) + store.dispatch({ + type: 'settings/copyEditingEnabledChanged', + payload: config.copyEditingEnabled === true + }) + return true + }) + transport.onRequest('config:setNameClaudeSessions', (_ctx, enabled: boolean) => { if (enabled) { config.nameClaudeSessions = true @@ -4572,6 +4593,35 @@ function registerIpcHandlers(): void { // The request surfaces in the store as jsonClaude/approvalRequested; the // renderer UI calls this handler once the user clicks Allow/Deny, which // writes the PermissionResult back out over the same socket. + transport.onRequest( + 'copyDrafts:resolve', + (_ctx, id: string, outcome: Exclude) => { + if (outcome?.kind === 'submitted' && typeof outcome.text === 'string') { + return copyDraftBroker.resolve(id, { + kind: 'submitted', + text: outcome.text, + note: outcome.note?.trim() || undefined + }) + } + if (outcome?.kind === 'dismissed') { + return copyDraftBroker.resolve(id, { + kind: 'dismissed', + note: outcome.note?.trim() || undefined + }) + } + return false + } + ) + + transport.onRequest('copyDrafts:clearWithdrawn', (_ctx, id: string) => + copyDraftBroker.clearWithdrawn(id) + ) + + transport.onRequest('copyDrafts:markEdited', (_ctx, id: string) => { + copyDraftBroker.markEdited(id) + return true + }) + transport.onRequest( 'jsonClaude:resolveApproval', ( @@ -6377,6 +6427,11 @@ async function runBoot(): Promise { if (result.ok && result.renamed) await worktreesFSM.refreshList() return result }, + copyDrafts: { + isEnabled: () => config.copyEditingEnabled === true, + request: (input) => copyDraftBroker.request(input), + cancel: (id) => copyDraftBroker.cancel(id) + }, messaging: { isEnabled: () => config.worktreeMessagingEnabled !== false, resolveTarget: (query) => diff --git a/src/main/json-claude-status-deriver.test.ts b/src/main/json-claude-status-deriver.test.ts index 049a0433..b62aeda8 100644 --- a/src/main/json-claude-status-deriver.test.ts +++ b/src/main/json-claude-status-deriver.test.ts @@ -282,4 +282,25 @@ describe('JsonClaudeStatusDeriver', () => { expect(events.removed).toEqual(['A']) expect(events.statusChanged).toHaveLength(0) }) + it('flags a pending edit_copy draft as needs-approval and clears it on resolve', () => { + const store = makeStore({ sessions: { A: makeSession('A', { busy: true }) }, pendingApprovals: {} }) + const { events } = startDeriverWithCapture(store) + const draft = { id: 'd1', terminalId: 'A', worktreePath: '/tmp/wt-A', draft: 'hi', timestamp: 1 } + + store.dispatch({ type: 'copyDrafts/requested', payload: draft }) + expect(events.statusChanged.at(-1)).toMatchObject({ id: 'A', status: 'needs-approval' }) + + store.dispatch({ type: 'copyDrafts/resolved', payload: { id: 'd1', terminalId: 'A' } }) + expect(events.statusChanged.at(-1)).toMatchObject({ id: 'A', status: 'processing' }) + }) + + it('ignores copy drafts from terminal tabs', () => { + const store = makeStore({ sessions: { A: makeSession('A') }, pendingApprovals: {} }) + const { events } = startDeriverWithCapture(store) + store.dispatch({ + type: 'copyDrafts/requested', + payload: { id: 'd1', terminalId: 'xterm-1', worktreePath: '/wt', draft: 'hi', timestamp: 1 } + }) + expect(events.statusChanged).toEqual([]) + }) }) diff --git a/src/main/json-claude-status-deriver.ts b/src/main/json-claude-status-deriver.ts index b95f5952..03dd953b 100644 --- a/src/main/json-claude-status-deriver.ts +++ b/src/main/json-claude-status-deriver.ts @@ -9,6 +9,7 @@ // exited → terminals/removed // pending approval → needs-approval (with PendingTool), unless the // auto-reviewer is still deciding +// pending edit_copy → needs-approval (the human owes the agent a draft) // busy → processing // otherwise → waiting // @@ -17,6 +18,7 @@ import type { Store } from './store' import type { StateEvent } from '../shared/state' import type { JsonClaudeState } from '../shared/state/json-claude' +import { firstDraftForTerminal, type CopyDraftsEvent } from '../shared/state/copy-drafts' import type { PtyStatus, PendingTool } from '../shared/state/terminals' import { log } from './debug' @@ -46,6 +48,14 @@ export class JsonClaudeStatusDeriver { } private onEvent(event: StateEvent): void { + if (event.type.startsWith('copyDrafts/')) { + const jc = this.store.getSnapshot().state.jsonClaude + const { terminalId } = (event as CopyDraftsEvent).payload + if (terminalId in jc.sessions) { + this.deriveSession(terminalId, jc) + } + return + } if (!event.type.startsWith('jsonClaude/')) return const jc = this.store.getSnapshot().state.jsonClaude // Re-derive only the session(s) the event touched, then dedup against @@ -107,10 +117,20 @@ export class JsonClaudeStatusDeriver { const approval = Object.values(jc.pendingApprovals).find( (a) => a.sessionId === sessionId && a.autoReview?.state !== 'pending' ) + const copyDraft = approval + ? null + : firstDraftForTerminal(this.store.getSnapshot().state.copyDrafts, sessionId) if (approval) { status = 'needs-approval' pendingTool = { name: approval.toolName, input: approval.input } fingerprint = `needs-approval:${approval.requestId}` + } else if (copyDraft) { + status = 'needs-approval' + pendingTool = { + name: 'edit_copy', + input: { title: copyDraft.title, draft: copyDraft.draft } + } + fingerprint = `needs-approval:${copyDraft.id}` } else if (session.busy) { status = 'processing' fingerprint = 'processing' diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 144be1a0..1350cfb8 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -295,6 +295,9 @@ export interface Config { // endpoint accepts calls, letting an agent write into another worktree's // chat. Default on (undefined treated as true). worktreeMessagingEnabled?: boolean + // When true, the edit_copy MCP tool is advertised and the /copy-drafts + // endpoint accepts calls. Default off (undefined treated as false). + copyEditingEnabled?: boolean /** loch blame gutter in the file viewer. Default ON, so only an explicit * `false` is written — absence means enabled. */ lochBlameEnabled?: boolean diff --git a/src/renderer/build-backend.ts b/src/renderer/build-backend.ts index 34f1bf2a..9a1a0d3a 100644 --- a/src/renderer/build-backend.ts +++ b/src/renderer/build-backend.ts @@ -322,6 +322,8 @@ export function buildBackend( refreshLochAvailability: () => req('loch:refreshAvailability'), setAgentTabNamingEnabled: (enabled: boolean) => reqConfig('config:setAgentTabNamingEnabled', enabled), + setCopyEditingEnabled: (enabled: boolean) => + reqConfig('config:setCopyEditingEnabled', enabled), setDefaultClaudeTabType: (value: 'xterm' | 'json') => reqConfig('config:setDefaultClaudeTabType', value), setChatPromotionDismissed: (value: boolean) => @@ -751,6 +753,12 @@ export function buildBackend( interrupt?: boolean } ) => req('jsonClaude:resolveApproval', requestId, result), + resolveCopyDraft: ( + id: string, + outcome: { kind: 'submitted'; text: string; note?: string } | { kind: 'dismissed'; note?: string } + ) => req('copyDrafts:resolve', id, outcome), + clearWithdrawnCopyDraft: (id: string) => req('copyDrafts:clearWithdrawn', id), + markCopyDraftEdited: (id: string) => req('copyDrafts:markEdited', id), rerunJsonClaudeAutoApprovalReview: (requestId: string) => req('jsonClaude:rerunAutoApprovalReview', requestId), startJsonClaude: (id: string, cwd: string) => req('jsonClaude:start', id, cwd), diff --git a/src/renderer/components/CopyDraftOverlay.tsx b/src/renderer/components/CopyDraftOverlay.tsx new file mode 100644 index 00000000..4fb0a073 --- /dev/null +++ b/src/renderer/components/CopyDraftOverlay.tsx @@ -0,0 +1,229 @@ +import { useState } from 'react' +import { ChevronDown, ChevronUp, PenLine } from 'lucide-react' +import type { CopyDraftRequest } from '../../shared/state/copy-drafts' +import { useCopyDraftForTerminal, useWithdrawnCopyDraftForTerminal } from '../store' +import { useBackend } from '../backend' + +/** What the user has typed, per draft id. Lives outside the component so + * nothing that remounts the editor — a mobile tab switch, the Chat card + * moving from the bottom of the log to its tool call, the draft being + * withdrawn — throws their rewrite away. Per-client, so not slice state. */ +const inProgress = new Map() +/** Drafts this client has already reported as edited to main. */ +const reportedEdited = new Set() + +/** Docked editor for an agent's `edit_copy` call, rendered over the bottom of + * a Terminal tab. Chat tabs render `CopyDraftCard` inline in the transcript + * instead, under the tool call it answers. */ +export function CopyDraftOverlay({ terminalId }: { terminalId: string }): JSX.Element | null { + const pending = useCopyDraftForTerminal(terminalId) + const withdrawn = useWithdrawnCopyDraftForTerminal(terminalId) + const draft = pending ?? withdrawn + if (!draft) return null + return +} + +export function CopyDraftCard({ + draft, + withdrawn = false +}: { + draft: CopyDraftRequest + withdrawn?: boolean +}): JSX.Element { + return +} + +function CopyDraftEditor({ + draft, + docked, + withdrawn +}: { + draft: CopyDraftRequest + docked: boolean + withdrawn: boolean +}): JSX.Element { + const backend = useBackend() + const saved = inProgress.get(draft.id) + const [text, setTextState] = useState(saved?.text ?? draft.draft) + const [note, setNoteState] = useState(saved?.note ?? '') + const [collapsed, setCollapsed] = useState(false) + const [sending, setSending] = useState(false) + const [copied, setCopied] = useState(false) + const edited = text !== draft.draft + + function remember(next: { text: string; note: string }): void { + inProgress.set(draft.id, next) + if (!withdrawn && !reportedEdited.has(draft.id)) { + reportedEdited.add(draft.id) + void backend.markCopyDraftEdited(draft.id) + } + } + function setText(value: string): void { + setTextState(value) + remember({ text: value, note }) + } + function setNote(value: string): void { + setNoteState(value) + remember({ text, note: value }) + } + + async function answer( + outcome: + | { kind: 'submitted'; text: string; note?: string } + | { kind: 'dismissed'; note?: string } + ): Promise { + setSending(true) + try { + if (await backend.resolveCopyDraft(draft.id, outcome)) inProgress.delete(draft.id) + } finally { + setSending(false) + } + } + + async function copyText(): Promise { + await navigator.clipboard.writeText(text) + setCopied(true) + } + + function close(): void { + inProgress.delete(draft.id) + void backend.clearWithdrawnCopyDraft(draft.id) + } + + const submit = (): Promise => answer({ kind: 'submitted', text, note }) + const dismiss = (): Promise => answer({ kind: 'dismissed', note }) + + const heading = ( + <> + + + Edit copy + + {draft.title && {draft.title}} + {withdrawn && · not sent} + + ) + + if (docked && collapsed) { + return ( +
+ +
+ ) + } + + return ( +
+
+ {heading} + {docked && ( + + )} +
+ +
+ {withdrawn && ( +
+ The agent stopped waiting before you sent this, so it never got your text. Copy + it now if you want to keep it. +
+ )} + {draft.context && ( +
{draft.context}
+ )} +