From 40eaa9297ab69c6983cfefa4c193c6b4fac5d963 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 29 Oct 2026 14:21:44 -0400 Subject: [PATCH 1/7] Let agents hand drafts of copy to the human to edit New ness-control MCP tool `edit_copy`: the agent sends a draft (plus an optional title and context), Ness docks an editor over the bottom of the calling tab, and the call blocks until the human submits or dismisses. The agent gets back the human's final text to use verbatim, or an error on dismissal, plus any note they added. - copyDrafts slice holds pending drafts so every client renders them - CopyDraftBroker parks the control server's HTTP response until answered; a dropped connection (bridge timeout, notifications/cancelled, process exit) withdraws the card - Works in Chat and Terminal tabs; both get a needs-approval dot - The permission bridge always allows edit_copy so Chat tabs don't prompt twice for the same decision Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 +- resources/mcp-bridge.js | 102 ++++++++++++-- resources/mcp-bridge.test.js | 90 ++++++++++++ src/main/approval-bridge-rules.test.ts | 15 ++ src/main/approval-bridge.ts | 6 + src/main/build-initial-state.ts | 2 + src/main/control-server.test.ts | 100 ++++++++++++++ src/main/control-server.ts | 46 +++++++ src/main/copy-draft-broker.test.ts | 54 ++++++++ src/main/copy-draft-broker.ts | 84 ++++++++++++ src/main/hooks.ts | 8 +- src/main/index.ts | 29 ++++ src/main/json-claude-status-deriver.test.ts | 21 +++ src/main/json-claude-status-deriver.ts | 19 +++ src/renderer/build-backend.ts | 4 + src/renderer/components/CopyDraftOverlay.tsx | 137 +++++++++++++++++++ src/renderer/components/MobileApp.tsx | 4 + src/renderer/components/WorkspaceView.tsx | 4 + src/renderer/pending-tool.ts | 4 + src/renderer/store.ts | 7 + src/renderer/types.ts | 9 ++ src/shared/state/copy-drafts.test.ts | 52 +++++++ src/shared/state/copy-drafts.ts | 67 +++++++++ src/shared/state/index.ts | 25 +++- src/shared/state/json-claude.ts | 5 + 25 files changed, 885 insertions(+), 12 deletions(-) create mode 100644 src/main/copy-draft-broker.test.ts create mode 100644 src/main/copy-draft-broker.ts create mode 100644 src/renderer/components/CopyDraftOverlay.tsx create mode 100644 src/shared/state/copy-drafts.test.ts create mode 100644 src/shared/state/copy-drafts.ts diff --git a/CLAUDE.md b/CLAUDE.md index a960532b8..6e9d86712 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ slice has: Current slices: `settings`, `prs`, `onboarding`, `hooks`, `worktrees`, `terminals` (which also owns `panes` and `lastActive`), `updater`, -`repoConfigs`, `permissions`. Adding a new piece of shared state means picking the +`repoConfigs`, `permissions`, `copyDrafts`. Adding a new piece of shared state means picking the right slice (or making a new one) and editing the reducer + event union. ### How a state mutation flows end-to-end @@ -99,6 +99,7 @@ src/ │ ├── updater.ts # status (checking/available/downloading/…) │ ├── repo-configs.ts # byRepo: per-repo .ness.json contents │ ├── permissions.ts # global "Always allow" tool grants +│ ├── copy-drafts.ts # pending `edit_copy` drafts awaiting a human edit │ └── *.test.ts # vitest reducer tests, one per slice │ ├── main/ diff --git a/resources/mcp-bridge.js b/resources/mcp-bridge.js index 089a92cd7..f8662e0c0 100644 --- a/resources/mcp-bridge.js +++ b/resources/mcp-bridge.js @@ -92,8 +92,11 @@ 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. Matches Claude's own MCP idle +// timeout so the bridge never gives up before the agent does. +const COPY_DRAFT_TIMEOUT_MS = 1_800_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 +111,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 = '' @@ -579,6 +583,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: @@ -741,7 +771,32 @@ 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 + ) +} + +async function handleToolCall(name, args, signal) { if (name === 'create_worktree') { const prNumber = args && args.prNumber if (!args || (!args.branchName && !prNumber)) { @@ -1044,6 +1099,19 @@ 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 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) + } if (name === 'list_shells') { const r = await callControl('GET', '/shells') return JSON.stringify((r && r.shells) || [], null, 2) @@ -1080,6 +1148,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 { @@ -1098,6 +1171,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() @@ -1108,10 +1186,18 @@ 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 + ) + } finally { + inflight.delete(id) + } const content = result && typeof result === 'object' && Array.isArray(result.content) ? result.content @@ -1119,7 +1205,7 @@ async function handle(msg) { return { jsonrpc: '2.0', id, - result: { content } + result: { content, ...(result && result.isError ? { isError: true } : {}) } } } return { diff --git a/resources/mcp-bridge.test.js b/resources/mcp-bridge.test.js index 44fdfe503..936f421f4 100644 --- a/resources/mcp-bridge.test.js +++ b/resources/mcp-bridge.test.js @@ -378,6 +378,96 @@ 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() + } + + 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('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 } + }) + await bridge.next() + expect(closed).toBe(true) + }) +}) + describe('mcp-bridge log-size cap on startup', () => { let tmpDir diff --git a/src/main/approval-bridge-rules.test.ts b/src/main/approval-bridge-rules.test.ts index efb8898b0..56a0f4e8b 100644 --- a/src/main/approval-bridge-rules.test.ts +++ b/src/main/approval-bridge-rules.test.ts @@ -188,6 +188,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/approval-bridge.ts b/src/main/approval-bridge.ts index 1b3ff8676..ba77b306c 100644 --- a/src/main/approval-bridge.ts +++ b/src/main/approval-bridge.ts @@ -22,6 +22,7 @@ import { join } from 'node:path' import { mkdtempSync, existsSync, unlinkSync } from 'node:fs' import type { Store } from './store' import { + EDIT_COPY_TOOL_NAME, QUESTION_TOOL_NAME, type JsonClaudePendingApproval } from '../shared/state/json-claude' @@ -350,6 +351,11 @@ export class ApprovalBridge { // QUESTION_TOOL_NAME. Bail out above both auto-resolve paths. const isQuestion = basePayload.toolName === QUESTION_TOOL_NAME + if (basePayload.toolName === EDIT_COPY_TOOL_NAME) { + this.writeResponse(socket, frame.id, { behavior: 'allow', updatedInput: basePayload.input }) + return + } + // Two explicit-user-grant paths, both checked before the LLM // auto-reviewer because a grant the user made by hand is cheaper and // more authoritative than a Haiku call: diff --git a/src/main/build-initial-state.ts b/src/main/build-initial-state.ts index 8782ff715..28e7ab749 100644 --- a/src/main/build-initial-state.ts +++ b/src/main/build-initial-state.ts @@ -23,6 +23,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 { ruleKey, type StoredPermissionRule } from '../shared/permission-match' import { initialSettings, @@ -135,6 +136,7 @@ export function buildInitialAppState( permissions: config.permissionRules ? { rules: sanitizePermissionRules(config.permissionRules) } : initialPermissions, + copyDrafts: initialCopyDrafts, settings: { ...initialSettings, themeMode: diff --git a/src/main/control-server.test.ts b/src/main/control-server.test.ts index e297cd327..e6f082cfb 100644 --- a/src/main/control-server.test.ts +++ b/src/main/control-server.test.ts @@ -7,6 +7,7 @@ import { } from './control-server' import type { ChatDeliveryResult } from './chat-delivery' import type { CaptureResult } from './browser-manager-types' +import type { CopyDraftInput, CopyDraftOutcome } from './copy-draft-broker' import { parseAutomatedMessage } from '../shared/state/json-claude' // Integration test for the local HTTP control server. Exercises the @@ -67,6 +68,15 @@ let captureResult: CaptureResult | null = null * evaluated (load failed, or the eval timed out). */ let domResult: () => Promise = 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 + const deps: ControlServerDeps = { getRepoRoots: () => ['/repo'], getWorktreeBase: () => 'remote', @@ -122,6 +132,20 @@ const deps: ControlServerDeps = { describe: (path) => (path === CALLER_WORKTREE ? 'Callers Tree' : 'Other Tree'), send: (path, message) => sendMessage(path, message) }, + copyDrafts: { + 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) } @@ -641,3 +665,79 @@ describe('control-server /browser/dom endpoint', () => { expect(r.json.error).toMatch(/tab has no document loaded/) }) }) + +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('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) + }) +}) diff --git a/src/main/control-server.ts b/src/main/control-server.ts index 6d6198dbd..83b098d5e 100644 --- a/src/main/control-server.ts +++ b/src/main/control-server.ts @@ -10,6 +10,7 @@ import { normalizeViewport, type BrowserViewport } from '../shared/browser-viewp import type { PRStatus } from '../shared/state/prs' import type { ChatDeliveryResult } from './chat-delivery' import type { CaptureResult } from './browser-manager-types' +import type { CopyDraftInput, CopyDraftOutcome } from './copy-draft-broker' import { wrapAutomatedMessage } from '../shared/state/json-claude' import { writeResultImage } from './json-claude-attachments' import { log } from './debug' @@ -120,6 +121,11 @@ export interface MessagingQueries { send: (worktreePath: string, message: string) => ChatDeliveryResult } +export interface CopyDraftQueries { + 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. */ @@ -180,6 +186,7 @@ export interface ControlServerDeps { browser: BrowserQueries shell: ShellQueries messaging: MessagingQueries + 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 @@ -882,6 +889,45 @@ 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') { + 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 diff --git a/src/main/copy-draft-broker.test.ts b/src/main/copy-draft-broker.test.ts new file mode 100644 index 000000000..5be504572 --- /dev/null +++ b/src/main/copy-draft-broker.test.ts @@ -0,0 +1,54 @@ +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 } { + const store = new Store(initialState) + const broker = new CopyDraftBroker(store, (id) => chatSessions.includes(id)) + return { store, broker } +} + +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('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 000000000..456179f72 --- /dev/null +++ b/src/main/copy-draft-broker.ts @@ -0,0 +1,84 @@ +// 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). + +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>() + + constructor( + private store: Store, + private isChatSession: (terminalId: string) => boolean + ) {} + + 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: 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) + this.store.dispatch({ + type: '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: 'processing', pendingTool: null } + }) + } + } + log('copy-drafts', `resolved id=${id} outcome=${outcome.kind}`) + waiter(outcome) + return true + } + + /** The agent stopped waiting (call timed out, turn interrupted, process + * exited). Drop the card so nobody edits into the void. */ + cancel(id: string): void { + this.resolve(id, { kind: 'cancelled' }) + } +} diff --git a/src/main/hooks.ts b/src/main/hooks.ts index 32f383e4f..10b01598d 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 355efdd5f..e33e18e7a 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -20,6 +20,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' @@ -424,6 +425,10 @@ const approvalBridge = new ApprovalBridge(store, { getAutoApproveSteerInstructions: () => store.getSnapshot().state.settings.autoApproveSteerInstructions || '' }) +const copyDraftBroker = new CopyDraftBroker( + store, + (terminalId) => terminalId in store.getSnapshot().state.jsonClaude.sessions +) const jsonClaudeManager = new JsonClaudeManager(store, { getClaudeCommand: () => store.getSnapshot().state.settings.claudeCommand || DEFAULT_CLAUDE_COMMAND, @@ -3776,6 +3781,26 @@ 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( 'jsonClaude:resolveApproval', ( @@ -5101,6 +5126,10 @@ async function runBoot(): Promise { if (result.ok && result.renamed) await worktreesFSM.refreshList() return result }, + copyDrafts: { + request: (input) => copyDraftBroker.request(input), + cancel: (id) => copyDraftBroker.cancel(id) + }, messaging: { isEnabled: () => config.worktreeMessagingEnabled === true, resolveTarget: (query) => diff --git a/src/main/json-claude-status-deriver.test.ts b/src/main/json-claude-status-deriver.test.ts index 049a0433a..b62aeda8a 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 b95f5952b..a82d7f8f9 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 } from '../shared/state/copy-drafts' import type { PtyStatus, PendingTool } from '../shared/state/terminals' import { log } from './debug' @@ -46,6 +48,13 @@ export class JsonClaudeStatusDeriver { } private onEvent(event: StateEvent): void { + if (event.type === 'copyDrafts/requested' || event.type === 'copyDrafts/resolved') { + const jc = this.store.getSnapshot().state.jsonClaude + if (event.payload.terminalId in jc.sessions) { + this.deriveSession(event.payload.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 +116,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/renderer/build-backend.ts b/src/renderer/build-backend.ts index bdd742af4..35a2b7e30 100644 --- a/src/renderer/build-backend.ts +++ b/src/renderer/build-backend.ts @@ -647,6 +647,10 @@ 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), 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 000000000..6b5401b07 --- /dev/null +++ b/src/renderer/components/CopyDraftOverlay.tsx @@ -0,0 +1,137 @@ +import { useState } from 'react' +import { ChevronDown, ChevronUp, PenLine } from 'lucide-react' +import type { CopyDraftRequest } from '../../shared/state/copy-drafts' +import { useCopyDraftForTerminal } from '../store' +import { useBackend } from '../backend' + +/** Docked editor for an agent's `edit_copy` call, rendered over the bottom of + * the tab that made it. The agent is blocked until this is answered, so it + * covers the composer/TUI rather than sitting in the transcript where it + * could scroll out of view. */ +export function CopyDraftOverlay({ terminalId }: { terminalId: string }): JSX.Element | null { + const draft = useCopyDraftForTerminal(terminalId) + if (!draft) return null + return +} + +function CopyDraftEditor({ draft }: { draft: CopyDraftRequest }): JSX.Element { + const backend = useBackend() + const [text, setText] = useState(draft.draft) + const [note, setNote] = useState('') + const [collapsed, setCollapsed] = useState(false) + const [sending, setSending] = useState(false) + const edited = text !== draft.draft + + async function answer( + outcome: + | { kind: 'submitted'; text: string; note?: string } + | { kind: 'dismissed'; note?: string } + ): Promise { + setSending(true) + try { + await backend.resolveCopyDraft(draft.id, outcome) + } finally { + setSending(false) + } + } + + const submit = (): Promise => answer({ kind: 'submitted', text, note }) + const dismiss = (): Promise => answer({ kind: 'dismissed', note }) + + const heading = ( + <> + + + Edit copy + + {draft.title && {draft.title}} + + ) + + if (collapsed) { + return ( +
+ +
+ ) + } + + return ( +
+
+ {heading} + +
+ +
+ {draft.context && ( +
{draft.context}
+ )} +