Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas): type link notes only into an idle agent at an empty prompt (#1144) (#1229)
eneskircac3506997a3ca
diff --git a/CLAUDE.md b/CLAUDE.mdindex 77f39282f..54f2c66df 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5415,8 +5415,24 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilehost whose transcripts and tmux it reads, and SSH projects are a desktop-only concept. Discovery is the `get-linked-context` skill in each consentedcontext-link-capable agent's own skills dir (since #744; the old marker block`<!-- nodeterm:get-linked-context:start/end -->` in AGENTS.md / GEMINI.md is stripped — see- **Agent-integration consent**). On connect an idle-gated one-line note is injected into each endpoint- (claude → skill pointer; codex/gemini → inline CLI command via `contextLink.info()`).+ **Agent-integration consent**). On connect a one-line discovery note is typed into each endpoint+ (claude → skill pointer; codex/gemini → inline CLI command via `contextLink.info()`) — **only into+ an idle agent at an EMPTY prompt** (issue #1144: it used to be a bare `sendText` gated only on+ `state !== 'working'`, so it was pasted in front of the user's half-typed draft and the Enter+ submitted both as one prompt, and a `blocked`/`waiting` pane would have had its dialog ANSWERED).+ Two halves: the renderer's `linkNoteRefusal` (`renderer/lib/noteLink.ts` — the ⌘M composer's+ `chatSendRefusal`: never working / waiting / blocked / CLI gone) and core's+ `PtyManager.sendToEmptyPrompt` (`pty:send-to-empty-prompt`, both shells), which reads a STYLED+ capture with `readClaudeComposer` (`shared/agents/claude-screen.ts`) and writes only on `empty`,+ inside `serializePaneWrite`. MEASURED on Claude Code 2.1.301 (fixtures+ `__fixtures__/claude/composer-capture.json`): the empty composer's placeholder is SGR 2 (dim), a+ draft is not, shell mode (`!`) is a draft. Only dim text counts as placeholder, so a capture that+ lost its SGR reads `draft` — the safe direction. Emptiness is therefore provable only for an agent+ in `SCREEN_DIALOG_READABLE` (claude); **every other agent gets no note** (`unsupported`). A refused+ note is DROPPED, not queued — the link is the capability (pull-based), the note only advertises+ it, and a note arriving minutes later is the same unsolicited prompt at a moment nobody chose —+ and every skipped endpoint is named in ONE info strip (`linkNoteSkippedNotice`). Residual: a+ keystroke in the milliseconds between the capture and the write.(Replaced the earlier MCP-based bridge.)**One-way links (issue #852):** a context bridge may carry `reader` (`BridgeLink.reader`, the ONEendpoint allowed to read the other); absent = both read, which is every pre-#852 link, so old@@ -5443,9 +5459,9 @@ bridges enter live state only via `appendBridgeEdges`) and the serverwhich the peer then saved and published back. A malformed reader on the wire REFUSES the op(never dropped — dropping widens), and a rope never carries one.**Note links:** a sticky note can be connected to ANY terminal node (one-way, sticky →- terminal). On connect, agent sessions get a one-shot idle-gated push of the note text- (`buildNotePushMessage`, single-line, truncated at 2000 chars); plain terminals get no- push (sendText appends Enter — the text would execute). The note's live text also rides+ terminal). On connect, agent sessions get a one-shot push of the note text+ (`buildNotePushMessage`, single-line, truncated at 2000 chars) through the SAME empty-prompt gate+ as the context-link note above (#1144); plain terminals get no push (the text would execute). The note's live text also ridesthe link file (`ContextLinkInfo.note`), so Claude reads the current text via theget-linked-context CLI (`summary`/`transcript` print it; `list` marks `(note)`). Pureedge/push/map logic in `renderer/lib/noteLink.ts`.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a26a36a28..07786bd2b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -288,6 +288,13 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneinfluenced text: a process name is chosen by the process, so parse each owner group on its own andnever let a name reach a pid (see CLAUDE.md → Dev-server ports).+- **App-originated text goes only into an empty prompt.** A note nodeterm types into an agent on+ its own (the context-link discovery note, a sticky pushed over a note link) goes through+ `linkNoteRefusal` + `pty.sendToEmptyPrompt`, never a bare `pty.sendText`: `sendText` pastes and+ presses Enter, so it submits whatever the user had half-typed with it (#1144) and answers an open+ permission dialog. Emptiness is read off the screen (`readClaudeComposer`), so an agent without a+ measured composer reader gets no note — and a skipped note is named in a notice, never silent.+- **A GitHub issue reaches a pane only as a validated reference.** Issue titles and bodies arewritten by strangers on public repositories, and a launch line is typed into a shell. Anythingthat starts or instructs an agent about an issue goes through `@shared/github-issue-ref`:diff --git a/src/core/pty-manager.empty-prompt.test.ts b/src/core/pty-manager.empty-prompt.test.tsnew file mode 100644index 000000000..0e2e9c1ab--- /dev/null+++ b/src/core/pty-manager.empty-prompt.test.ts@@ -0,0 +1,101 @@+// `PtyManager.sendToEmptyPrompt` — the app's own link notes (issue #1144). A note may only be typed+// into an EMPTY composer: the reporter's draft was merged with the context-link note and the Enter+// submitted both. The composer reader is tested in shared/agents/claude-composer.test.ts; this file+// pins the dispatch: read first, write only on `empty`, and never for an agent we cannot read.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import capture from '../shared/agents/__fixtures__/claude/composer-capture.json'++vi.mock('node-pty', () => ({ spawn: () => ({}) }))++const NODE = 'node-1'+const S = capture.screens as Record<string, string>++type Internals = { sendTextNow: (k: string, t: string, o?: unknown) => Promise<unknown> }++async function manager(screen: string, delivered: boolean | 'pasted-not-submitted' = true) {+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager()+ const snapshot = vi.spyOn(mgr, 'captureSnapshot').mockResolvedValue(screen)+ const now = vi.spyOn(mgr as unknown as Internals, 'sendTextNow').mockResolvedValue(delivered)+ return { mgr, snapshot, now }+}++describe('PtyManager.sendToEmptyPrompt (#1144)', () => {+ beforeEach(() => {+ vi.resetModules()+ initPlatform(fakePlatform())+ })+ afterEach(() => {+ resetPlatformForTests()+ })++ it('types the note into an empty claude composer', async () => {+ const { mgr, now } = await manager(S.empty)+ expect(await mgr.sendToEmptyPrompt(NODE, 'note', 'claude')).toEqual({ sent: true })+ expect(now).toHaveBeenCalledWith(NODE, 'note', { typedFor: 'claude' })+ })++ it.each([+ ['draft', 'draft'],+ ['multiline', 'draft'],+ ['pasted', 'draft'],+ ['shellmode', 'draft']+ ])('writes nothing over a %s composer', async (name, reason) => {+ const { mgr, now } = await manager(S[name])+ expect(await mgr.sendToEmptyPrompt(NODE, 'note', 'claude')).toEqual({ sent: false, reason })+ expect(now).not.toHaveBeenCalled()+ })++ it('an unreadable screen is NOT evidence of emptiness (unlike the chat send)', async () => {+ const { mgr, now } = await manager('')+ expect(await mgr.sendToEmptyPrompt(NODE, 'note', 'claude')).toEqual({ sent: false, reason: 'unknown' })+ expect(now).not.toHaveBeenCalled()+ })++ it('a dialog owns the keyboard: nothing is written (its Enter would answer it)', async () => {+ const dialog = S.empty.replace(/\n[^\n]*manual mode on[^\n]*/, '\n Enter to confirm · Esc to cancel')+ const { mgr, now } = await manager(dialog)+ expect(await mgr.sendToEmptyPrompt(NODE, 'note', 'claude')).toEqual({ sent: false, reason: 'no-prompt' })+ expect(now).not.toHaveBeenCalled()+ })++ it('an agent without a measured composer reader is refused without a capture', async () => {+ const { mgr, snapshot, now } = await manager(S.empty)+ expect(await mgr.sendToEmptyPrompt(NODE, 'note', 'codex')).toEqual({ sent: false, reason: 'unsupported' })+ expect(snapshot).not.toHaveBeenCalled()+ expect(now).not.toHaveBeenCalled()+ })++ it('reports an Enter that was withheld, and a failed transport, as not sent', async () => {+ const a = await manager(S.empty, 'pasted-not-submitted')+ expect(await a.mgr.sendToEmptyPrompt(NODE, 'note', 'claude')).toEqual({ sent: false, reason: 'not-submitted' })+ const b = await manager(S.empty, false)+ expect(await b.mgr.sendToEmptyPrompt(NODE, 'note', 'claude')).toEqual({ sent: false, reason: 'failed' })+ })++ it('reads and writes inside the pane write chain: a write already in flight finishes first', async () => {+ const { mgr, snapshot } = await manager(S.empty)+ const order: string[] = []+ let release!: () => void+ const gate = new Promise<void>((r) => (release = r))+ ;(vi.mocked((mgr as unknown as Internals).sendTextNow)).mockImplementation(async (_k: string, t: string) => {+ order.push(`write ${t}`)+ if (t === 'slow') await gate+ return true+ })+ snapshot.mockImplementation(async () => {+ order.push('capture')+ return S.empty+ })+ const first = mgr.sendText(NODE, 'slow')+ const note = mgr.sendToEmptyPrompt(NODE, 'note', 'claude')+ await Promise.resolve()+ await new Promise((r) => setTimeout(r, 0))+ expect(order).toEqual(['write slow'])+ release()+ await Promise.all([first, note])+ expect(order).toEqual(['write slow', 'capture', 'write note'])+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex ead6d6d1b..c5f8d8d13 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1,5 +1,5 @@-import type { ChatPromptBlocked, ChatPromptResult, TextDeliveryResult } from '../shared/text-delivery'-import { claudeScreenBlocksInput, readClaudeScreen } from '../shared/agents/claude-screen'+import type { ChatPromptBlocked, ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from '../shared/text-delivery'+import { claudeScreenBlocksInput, readClaudeComposer, readClaudeScreen } from '../shared/agents/claude-screen'import os from 'os'import fs from 'fs'import path from 'path'@@ -2184,6 +2184,10 @@ export class PtyManager {// picks none (plain `sendText`), never a wrong one.this.sendChatPrompt(persistKey, text, typeof agentId === 'string' ? agentId : ''))+ platform().handle(IPC.ptySendToEmptyPrompt, (persistKey: string, text: string, agentId: unknown) =>+ // Like `agentId` above: it only picks the composer reader, and a non-string picks none.+ this.sendToEmptyPrompt(persistKey, text, typeof agentId === 'string' ? agentId : '')+ )platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))platform().handle(IPC.ptyPaneCwd, (persistKey: string) => this.paneCwd(persistKey))@@ -6495,6 +6499,44 @@ export class PtyManager {return typesChatInput(agentId) ? this.sendText(persistKey, text, { typedFor: agentId }) : this.sendText(persistKey, text)}+ /**+ * Write `text` + Enter into an agent's composer ONLY when that composer is empty — the app's own+ * unsolicited notes (the context-link discovery note, a sticky note pushed over a note link).+ * Issue #1144: those were `sendText` calls gated on nothing but `state !== 'working'`, so a note+ * landed in front of the user's half-typed draft and the Enter submitted both as one prompt (and a+ * `blocked`/`waiting` pane would have had its dialog ANSWERED by that Enter).+ *+ * Emptiness is read off a STYLED capture (`readClaudeComposer`: the placeholder is dim, a draft is+ * not), so only an agent with a measured composer reader may receive one (`readsScreenDialogs`);+ * every other agent answers `unsupported` and nothing is written. The read and the write run inside+ * `serializePaneWrite`, so no other app write lands between them. What no gate closes: a keystroke+ * the user makes in the milliseconds between the capture and the paste. A claude composer is TYPED+ * (`typesChatInput`) and re-checks for a dialog before its Enter, like a chat prompt.+ */+ async sendToEmptyPrompt(persistKey: string, text: string, agentId: string): Promise<EmptyPromptResult> {+ if (!readsScreenDialogs(agentId)) return { sent: false, reason: 'unsupported' }+ return this.serializePaneWrite(persistKey, async (): Promise<EmptyPromptResult> => {+ const composer = readClaudeComposer(await this.captureStyledScreen(persistKey))+ if (composer !== 'empty') return { sent: false, reason: composer }+ const delivered = await this.sendTextNow(+ persistKey,+ text,+ typesChatInput(agentId) ? { typedFor: agentId } : undefined+ )+ if (delivered === true) return { sent: true }+ return { sent: false, reason: delivered === 'pasted-not-submitted' ? 'not-submitted' : 'failed' }+ })+ }++ /** The visible screen WITH its SGR, for `readClaudeComposer`: an ssh-project node's capture already+ * carries `-e` (`remoteCapturePaneArgs`), everything else is `captureSnapshot`. '' on any failure. */+ private async captureStyledScreen(persistKey: string): Promise<string> {+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.sshRemote) return this.captureSession(persistKey)+ if (live?.nativeWindowsPane) return ''+ return this.captureSnapshot(persistKey)+ }+/*** The command currently in the foreground of a node's tmux pane (e.g. 'claude', 'zsh') — how* the in-place agent restart observes that the CLI has exited and a shell owns the pane again.diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex 652f63fa6..3a1c05635 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -293,6 +293,7 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([IPC.ptySessionAge,IPC.ptySendText,IPC.ptySendChatPrompt,+ IPC.ptySendToEmptyPrompt,IPC.ptyPaneOwner,// A host filesystem path, not a view of the terminal — a viewer's file links keep the node cwd.IPC.ptyPaneCwd,diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex ccb563bde..a4dcffabe 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -319,6 +319,7 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({[IPC.ptyReadScrollback]: nodeArg0,[IPC.ptySendText]: nodeArg0,[IPC.ptySendChatPrompt]: nodeArg0,+ [IPC.ptySendToEmptyPrompt]: nodeArg0,[IPC.ptyTmuxStatus]: pass,[IPC.ptyPaneCommand]: nodeArg0,[IPC.ptyPaneCwd]: nodeArg0,diff --git a/src/preload/index.ts b/src/preload/index.tsindex c9296b3cb..b69cacedd 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -113,6 +113,8 @@ const api: NodeTerminalApi = {ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),sendChatPrompt: (persistKey, text, agentId) =>ipcRenderer.invoke(IPC.ptySendChatPrompt, persistKey, text, agentId),+ sendToEmptyPrompt: (persistKey, text, agentId) =>+ ipcRenderer.invoke(IPC.ptySendToEmptyPrompt, persistKey, text, agentId),tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex b2108442a..c05a69aea 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -27,7 +27,7 @@ import {type RpcMessage} from '../../shared/rpc'import { IPC } from '../../shared/ipc'-import type { ChatPromptResult } from '../../shared/text-delivery'+import type { ChatPromptResult, EmptyPromptResult } from '../../shared/text-delivery'import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'import {UNKNOWN_CLAUDE_CLI_CAPS,@@ -294,6 +294,8 @@ export function buildRealApi(client.request(IPC.ptySendText, persistKey, text, opts?.enter) as Promise<boolean>,sendChatPrompt: (persistKey, text, agentId) =>client.request(IPC.ptySendChatPrompt, persistKey, text, agentId) as Promise<ChatPromptResult>,+ sendToEmptyPrompt: (persistKey, text, agentId) =>+ client.request(IPC.ptySendToEmptyPrompt, persistKey, text, agentId) as Promise<EmptyPromptResult>,// A failed read is unknown, never evidence that persistence is available.tmuxStatus: () =>clientdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex abf97490f..fd5b10410 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,6 +1,5 @@import { PrepareUpdateDialog } from '../components/PrepareUpdateDialog'import type { PrepNode } from '../lib/updatePrep'-import { reportTextDelivery } from '../lib/textDelivery'import { useDevPortScanner } from './useDevPortScanner'import { withCodexNoDaemon } from '@shared/agents/codex-daemon'import { codexApprovalCaps } from '../state/codexCli'@@ -657,7 +656,7 @@ import { answerHostedRequest, type HostedAnswer } from '../lib/hostedOwner'import { headRequest, type QueuedRequest } from '../lib/hostedPendingQueue'import { useHostedPending } from '../state/hostedPending'import { hostedInfoFor, isHostedReadOnly, useHostedTeams } from '../state/hostedTeams'-import { appendBridgeEdges, bridgeToEdge, buildContextLinkNote, contextLinkForEdge, buildNotePushMessage, classifyLink, edgeToBridge, gainedReaders, hiddenLinkIds, isCurrentLinkDirection, linkIdsCoveredByRopes, linkReadPairs, pairKey, planBridges, withLinkReader, type LinkEndpoint } from '../lib/noteLink'+import { appendBridgeEdges, bridgeToEdge, buildContextLinkNote, contextLinkForEdge, buildNotePushMessage, classifyLink, edgeToBridge, gainedReaders, hiddenLinkIds, isCurrentLinkDirection, linkIdsCoveredByRopes, linkNoteRefusal, linkNoteSkippedNotice, linkReadPairs, pairKey, planBridges, withLinkReader, type LinkEndpoint, type LinkNoteSkip } from '../lib/noteLink'import {deliveriesToRetire,launchesToFire,@@ -4834,22 +4833,57 @@ export function Canvas() {[agentIdOf])- // One-shot discovery note into an idle agent endpoint that can now read `otherId` (skip a node- // mid-turn so we don't interrupt it). Claude gets the skill pointer; codex/gemini the CLI inline.+ // Type one link note into an agent node — ONLY into an idle agent at an EMPTY prompt (issue+ // #1144: the note used to be pasted + Enter'd over the user's half-typed draft, and into a+ // blocked/waiting pane whose dialog the Enter would answer). The state gate is the renderer's+ // (`linkNoteRefusal`), the empty-composer proof is core's (`pty.sendToEmptyPrompt`). Answers why+ // it was skipped, or null when it was delivered; nothing is queued for later.+ const pushLinkNote = useCallback(+ async (targetId: string, text: string): Promise<LinkNoteSkip | null> => {+ const agentId = agentIdOf(targetId)+ if (!agentId) return 'unsupported'+ const refused = linkNoteRefusal(agentId, useAgentStatus.getState().byId[targetId] ?? {})+ if (refused) return refused+ try {+ const r = await api.pty.sendToEmptyPrompt(targetId, text, capabilityAgentId(agentId))+ return r.sent ? null : r.reason+ } catch {+ return 'failed'+ }+ },+ [agentIdOf]+ )++ // One-shot discovery note into an agent endpoint that can now read `otherId`. Claude gets the+ // skill pointer; codex/gemini the CLI inline. Answers the skip (with the node's title for the+ // notice), or null when delivered.const announceContextLink = useCallback(- async (selfId: string, otherId: string) => {- if (useAgentStatus.getState().byId[selfId]?.state === 'working') return- const title = (nodesRef.current.find((n) => n.id === otherId)?.data.title as string) || 'a linked node'- const { shimPath, platform: shimHost } = await window.nodeTerminal.contextLink.info()- // The shim named here is the LOCAL core's; an SSH node's agent runs on its host, whose skill- // is POSIX, so only a local node gets the host-platform wording (`.cmd` on Windows).+ async (selfId: string, otherId: string): Promise<{ title: string; reason: LinkNoteSkip } | null> => {const selfData = nodesRef.current.find((n) => n.id === selfId)?.data- void api.pty.sendText(- selfId,- buildContextLinkNote(agentIdOf(selfId), title, shimPath, isRemoteSessionNode(selfData) ? undefined : shimHost)- ).then(reportTextDelivery)+ const selfTitle = (selfData?.title as string) || selfId+ const title = (nodesRef.current.find((n) => n.id === otherId)?.data.title as string) || 'a linked node'+ let note: string+ try {+ const { shimPath, platform: shimHost } = await window.nodeTerminal.contextLink.info()+ // The shim named here is the LOCAL core's; an SSH node's agent runs on its host, whose skill+ // is POSIX, so only a local node gets the host-platform wording (`.cmd` on Windows).+ note = buildContextLinkNote(agentIdOf(selfId), title, shimPath, isRemoteSessionNode(selfData) ? undefined : shimHost)+ } catch {+ return { title: selfTitle, reason: 'failed' }+ }+ const reason = await pushLinkNote(selfId, note)+ return reason ? { title: selfTitle, reason } : null},- [agentIdOf]+ [agentIdOf, pushLinkNote]+ )+ // Every endpoint that was not told is named in ONE strip — a skipped note is never silent.+ const reportLinkNotes = useCallback(+ async (kind: 'context' | 'note', pending: Promise<{ title: string; reason: LinkNoteSkip } | null>[]) => {+ const skips = (await Promise.all(pending)).filter((s): s is { title: string; reason: LinkNoteSkip } => s !== null)+ const n = linkNoteSkippedNotice(kind, skips)+ if (n) setNotice(n)+ },+ [])// Draw a link: context (two agent nodes read each other) or note (sticky text becomes@@ -4877,28 +4911,29 @@ export function Canvas() {addEdge({ id: `bridge-${source}-${target}`, source, target }, es))markDirty()- const status = useAgentStatus.getState().byIdif (kind === 'context') {- // Discovery: tell each idle endpoint it is now linked (skip a node mid-turn so we- // don't interrupt it). Claude gets the skill pointer; codex/gemini get the CLI inline.- void announceContextLink(source, target)- void announceContextLink(target, source)+ // Discovery: tell each endpoint it is now linked — only where it is idle at an empty+ // prompt (pushLinkNote); every endpoint skipped is named in one notice.+ void reportLinkNotes('context', [announceContextLink(source, target), announceContextLink(target, source)])return}- // Note link: push the note text once into the terminal — agent sessions only.- // pty.sendText appends Enter, so pushing into a plain shell would EXECUTE the text- // as a command; plain terminals get the link file but no injection.+ // Note link: push the note text once into the terminal — agent sessions only. A plain+ // shell would EXECUTE the text as a command; plain terminals get the link file but no+ // injection, and say nothing (there is no agent there to tell).if (!agentIdOf(target)) return- if (status[target]?.state === 'working') returnconst sticky = nodes.find((n) => n.id === source)const msg = buildNotePushMessage((sticky?.data.title as string) || 'Note',(sticky?.data.text as string) ?? '',agentIdOf(target))- if (msg) void api.pty.sendText(target, msg).then(reportTextDelivery)+ if (!msg) return+ const targetTitle = (nodes.find((n) => n.id === target)?.data.title as string) || target+ void reportLinkNotes('note', [+ pushLinkNote(target, msg).then((reason) => (reason ? { title: targetTitle, reason } : null))+ ])},- [linkEndpointOf, agentIdOf, setLinkEdges, markDirty, nodes, announceContextLink]+ [linkEndpointOf, agentIdOf, setLinkEdges, markDirty, nodes, announceContextLink, pushLinkNote, reportLinkNotes])// Right-click a context link: pick its direction (issue #852) or remove it. Direction is a@@ -4926,9 +4961,10 @@ export function Canvas() {es.map((x) => (x.id === link.id ? { ...bridgeToEdge(next), selected: x.selected } : x)))markDirty()- for (const id of gainedReaders(current, next)) {- void announceContextLink(id, id === next.source ? next.target : next.source)- }+ void reportLinkNotes(+ 'context',+ gainedReaders(current, next).map((id) => announceContextLink(id, id === next.source ? next.target : next.source))+ )}const a = titleOf(link.source)const b = titleOf(link.target)@@ -4960,7 +4996,7 @@ export function Canvas() {]})},- [setLinkEdges, markDirty, announceContextLink]+ [setLinkEdges, markDirty, announceContextLink, reportLinkNotes])// Of these ropes, the ones that are NOT live waits. A waiting rope's removal means "stop waitingdiff --git a/src/renderer/lib/noteLink.linkNoteGate.test.ts b/src/renderer/lib/noteLink.linkNoteGate.test.tsnew file mode 100644index 000000000..69955c765--- /dev/null+++ b/src/renderer/lib/noteLink.linkNoteGate.test.ts@@ -0,0 +1,74 @@+// Issue #1144: the context-link discovery note (and a sticky pushed over a note link) is typed only+// into an idle agent at an EMPTY prompt. This file pins the renderer half of the gate and the strip+// that names every skipped endpoint; core's empty-composer proof is pty-manager.empty-prompt.test.ts.+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { linkNoteRefusal, linkNoteSkippedNotice } from './noteLink'++describe('linkNoteRefusal (#1144)', () => {+ it('lets an idle (done) or not-yet-reported claude through to the composer check', () => {+ expect(linkNoteRefusal('claude', { state: 'done' })).toBeNull()+ expect(linkNoteRefusal('claude', {})).toBeNull()+ })++ it('never into a busy agent', () => {+ expect(linkNoteRefusal('claude', { state: 'working' })).toBe('working')+ })++ it('never into blocked/waiting — the Enter would ANSWER the permission prompt or question', () => {+ expect(linkNoteRefusal('claude', { state: 'blocked' })).toBe('dialog')+ expect(linkNoteRefusal('claude', { state: 'waiting' })).toBe('dialog')+ })++ it('never into a pane the CLI has left — the note would run as a shell command', () => {+ expect(linkNoteRefusal('claude', { state: 'done', hibernated: true })).toBe('asleep')+ expect(linkNoteRefusal('claude', { state: 'done', paused: true })).toBe('paused')+ expect(linkNoteRefusal('claude', { state: 'done', dropped: true })).toBe('dropped')+ expect(linkNoteRefusal('claude', { sessionEnded: true })).toBe('exited')+ })++ it('an agent whose composer cannot be read is refused: emptiness cannot be proven', () => {+ for (const a of ['codex', 'gemini', 'opencode', 'grok']) expect(linkNoteRefusal(a, { state: 'done' })).toBe('unsupported')+ })+})++describe('linkNoteSkippedNotice (#1144)', () => {+ it('says nothing when every note was delivered', () => {+ expect(linkNoteSkippedNotice('context', [])).toBeNull()+ })++ it('names every skipped endpoint with its reason in one info strip', () => {+ const n = linkNoteSkippedNotice('context', [+ { title: 'Alpha', reason: 'draft' },+ { title: 'Beta', reason: 'dialog' }+ ])+ expect(n?.kind).toBe('info')+ expect(n?.text).toContain('"Alpha" (its input already has text in it)')+ expect(n?.text).toContain('"Beta" (it is waiting for your answer)')+ expect(n?.text).toContain('get-linked-context')+ })++ it('a note that may have been left unsubmitted in the input is an error', () => {+ expect(linkNoteSkippedNotice('note', [{ title: 'A', reason: 'not-submitted' }])?.kind).toBe('error')+ })++ it('a title cannot break the strip onto several lines', () => {+ expect(linkNoteSkippedNotice('note', [{ title: 'a\nb', reason: 'draft' }])?.text).not.toContain('\n')+ })+})++describe('Canvas link-note wiring (#1144)', () => {+ const src = readFileSync(join(__dirname, '../canvas/Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')++ it('link notes reach a pane only through the empty-prompt write, never a raw sendText', () => {+ const start = src.indexOf('const pushLinkNote = useCallback(')+ const end = src.indexOf(" // Right-click a context link: pick its direction")+ expect(start).toBeGreaterThan(-1)+ expect(end).toBeGreaterThan(start)+ const block = src.slice(start, end)+ expect(block).toContain('api.pty.sendToEmptyPrompt(')+ expect(block).toContain('linkNoteRefusal(')+ expect(block).not.toMatch(/pty\.sendText\(/)+ })+})diff --git a/src/renderer/lib/noteLink.ts b/src/renderer/lib/noteLink.tsindex 2fe06502c..29174cb17 100644--- a/src/renderer/lib/noteLink.ts+++ b/src/renderer/lib/noteLink.ts@@ -6,6 +6,9 @@ import type { Edge } from '@xyflow/react'import { oneLine } from '@shared/one-line'import type { BridgeLink } from '@shared/types'import { shimCommand, shimDialectFor } from '@shared/agents/shim-invocation'+import { capabilityAgentId, readsScreenDialogs } from '@shared/agents/config'+import type { EmptyPromptRefusal } from '@shared/text-delivery'+import { chatSendRefusal, type ChatGateStatus, type ChatSendRefusal } from './chatSendGate'import {classifyLink,planBridges,@@ -189,3 +192,67 @@ export {buildBackgroundLinkMaps,type LinkNodeInfo} from '@shared/context-link-map'++/**+ * Why a link note (the context-link discovery note, a sticky pushed over a note link) was NOT typed+ * into a node — issue #1144. Either the renderer's state gate refused (`ChatSendRefusal`: busy, a+ * permission/question dialog, no CLI in the pane) or core's composer gate did+ * (`EmptyPromptRefusal`: a draft in the input, no readable composer, …).+ */+export type LinkNoteSkip = Exclude<ChatSendRefusal, null> | EmptyPromptRefusal++/**+ * The renderer half of the link-note gate, decided before anything crosses to core. The note is+ * unsolicited text typed into someone's session, so it goes only where it cannot hurt:+ * - never into a `working` agent (it would land mid-turn), never into `waiting`/`blocked` (the+ * Enter would ANSWER the permission prompt or question), never into a pane the CLI has left (it+ * would run as a shell command) — the ⌘M composer's own gate, `chatSendRefusal`;+ * - only into an agent whose composer we can READ (`readsScreenDialogs`), because "the input is+ * empty" must be proven on screen, not assumed — the reporter's draft was sitting in an idle+ * agent's input. Core proves it (`pty.sendToEmptyPrompt`) and refuses otherwise.+ *+ * A refused note is DROPPED, not queued: the link itself is the capability (the linked agent reads+ * on demand with the get-linked-context skill), the note only advertises it, and a note delivered+ * minutes later would be the same unsolicited prompt arriving at a moment nobody chose. The caller+ * says what was skipped and why (`linkNoteSkippedNotice`).+ */+export function linkNoteRefusal(agentId: string, s: ChatGateStatus): LinkNoteSkip | null {+ const state = chatSendRefusal(agentId, s)+ if (state !== null) return state+ return readsScreenDialogs(capabilityAgentId(agentId)) ? null : 'unsupported'+}++const SKIP_REASON: Record<LinkNoteSkip, string> = {+ working: 'it is busy',+ dialog: 'it is waiting for your answer',+ 'no-prompt': 'its input box is not on screen',+ draft: 'its input already has text in it',+ asleep: 'its agent is not running',+ paused: 'its agent is not running',+ dropped: 'its agent is not running',+ exited: 'its agent is not running',+ unsupported: 'nodeterm cannot check that its input is empty',+ unknown: 'its screen could not be read',+ 'not-submitted': 'the note was typed but not submitted — check its input',+ failed: 'the write failed'+}++/** Did a skip possibly leave bytes in the pane, or fail outright? Those are errors, the rest info. */+const isErrorSkip = (r: LinkNoteSkip): boolean => r === 'not-submitted' || r === 'failed'++/**+ * One strip for every endpoint that was not told, so drawing a link never passes in silence and two+ * endpoints never race for the strip. `null` when every note was delivered.+ */+export function linkNoteSkippedNotice(+ kind: 'context' | 'note',+ skips: readonly { title: string; reason: LinkNoteSkip }[]+): { kind: 'info' | 'error'; text: string } | null {+ if (skips.length === 0) return null+ const who = skips.map((s) => `"${oneLine(s.title)}" (${SKIP_REASON[s.reason] ?? 'skipped'})`).join(', ')+ const text =+ kind === 'context'+ ? `Linked. Not announced to ${who}. The link works anyway: an agent can read it with the get-linked-context skill.`+ : `Note linked. Not sent to ${who}. The note is still readable through the link.`+ return { kind: skips.some((s) => isErrorSkip(s.reason)) ? 'error' : 'info', text }+}diff --git a/src/shared/agents/__fixtures__/claude/composer-capture.json b/src/shared/agents/__fixtures__/claude/composer-capture.jsonnew file mode 100644index 000000000..ee7ab8ce2--- /dev/null+++ b/src/shared/agents/__fixtures__/claude/composer-capture.json@@ -0,0 +1,11 @@+{+ "_note": "Captured 2026-10-16 from Claude Code 2.1.301 (fullscreen TUI) in a private tmux server, `tmux capture-pane -p -e` (visible screen, with SGR). Throwaway CLAUDE_CONFIG_DIR and a fake API key; the placeholder suggestion is drawn SGR 2 (dim), typed text is not. Issue #1144.",+ "claudeVersion": "2.1.301",+ "screens": {+ "empty": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.301\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mOpus 5.5 · API Usage Billing\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m~/work\u001b[39m\n\n\u001b[38;5;220m⚠\u001b[39m \u001b[38;5;220mRemote managed settings failed to load (authentication rejected (401)) · no remote policy applied\u001b[38;5;246m · /status for \u001b[39m\n \u001b[38;5;246mdetails\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ \u001b[2mTry \"fix typecheck errors\"\u001b[0m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m⏸ manual mode on · ? for shortcuts · ← for agents\u001b[39m\n",+ "draft": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.301\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mOpus 5.5 · API Usage Billing\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m~/work\u001b[39m\n\n\u001b[38;5;220m⚠\u001b[39m \u001b[38;5;220mRemote managed settings failed to load (authentication rejected (401)) · no remote policy applied\u001b[38;5;246m · /status for \u001b[39m\n \u001b[38;5;246mdetails\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ heb ik getest\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m⏸ manual mode on\u001b[39m\n",+ "multiline": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.301\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mOpus 5.5 · API Usage Billing\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m~/work\u001b[39m\n\n\u001b[38;5;220m⚠\u001b[39m \u001b[38;5;220mRemote managed settings failed to load (authentication rejected (401)) · no remote policy applied\u001b[38;5;246m · /status for \u001b[39m\n \u001b[38;5;246mdetails\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mctrl+g to edit in Vim\u001b[39m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ heb ik getest\n line two\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246m⏸ manual mode on\u001b[39m\n",+ "pasted": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.301\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mOpus 5.5 · API Usage Billing\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m~/work\u001b[39m\n\n\u001b[38;5;220m⚠\u001b[39m \u001b[38;5;220mRemote managed settings failed to load (authentication rejected (401)) · no remote policy applied\u001b[38;5;246m · /status for \u001b[39m\n \u001b[38;5;246mdetails\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mCtrl+Y to paste deleted text\u001b[39m\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m❯ [Pasted text #2 +6 lines]\n\u001b[38;5;244m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246mpaste again to expand\u001b[39m\n",+ "shellmode": "\n\u001b[38;5;174m ▐\u001b[48;5;16m▛███▛█\u001b[39m\u001b[49m \u001b[1mClaude Code\u001b[0m \u001b[38;5;246mv2.1.301\u001b[39m\n\u001b[38;5;174m▝▜\u001b[48;5;16m█████\u001b[49m█▀\u001b[39m \u001b[38;5;246mOpus 5.5 · API Usage Billing\u001b[39m\n\u001b[38;5;174m ▝▝ ▝▝ \u001b[39m \u001b[38;5;246m~/work\u001b[39m\n\n\u001b[38;5;220m⚠\u001b[39m \u001b[38;5;220mRemote managed settings failed to load (authentication rejected (401)) · no remote policy applied\u001b[38;5;246m · /status for \u001b[39m\n \u001b[38;5;246mdetails\u001b[39m\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \u001b[38;5;246mCtrl+Y to paste deleted text\u001b[39m\n\u001b[38;5;211m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n! \u001b[2m\u001b[39mTry \"fix typecheck errors\"\u001b[0m\n\u001b[38;5;211m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\u001b[39m \u001b[38;5;246mpaste again to expand\u001b[39m\n"+ }+}diff --git a/src/shared/agents/claude-composer.test.ts b/src/shared/agents/claude-composer.test.tsnew file mode 100644index 000000000..111c2cb2d--- /dev/null+++ b/src/shared/agents/claude-composer.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest'+import { readClaudeComposer } from './claude-screen'+import capture from './__fixtures__/claude/composer-capture.json'++// Real captures (Claude Code 2.1.301, `capture-pane -p -e`) — see the fixture's `_note`. Issue #1144.+const S = capture.screens as Record<string, string>++describe('readClaudeComposer (#1144)', () => {+ it('reads the dim placeholder as an EMPTY composer', () => {+ expect(readClaudeComposer(S.empty)).toBe('empty')+ })++ it('reads a typed draft as a draft — the reporter’s case', () => {+ expect(readClaudeComposer(S.draft)).toBe('draft')+ })++ it('reads a multi-line draft as a draft', () => {+ expect(readClaudeComposer(S.multiline)).toBe('draft')+ })++ it('reads a collapsed paste placeholder as a draft (it is the user’s pasted text)', () => {+ expect(readClaudeComposer(S.pasted)).toBe('draft')+ })++ it('reads shell mode as a draft even with a dim placeholder — text there runs as a command', () => {+ expect(readClaudeComposer(S.shellmode)).toBe('draft')+ })++ it('reads the placeholder words TYPED by the user (not dim) as a draft', () => {+ const typed = S.empty.replace('\x1b[2mTry "fix typecheck errors"\x1b[0m', 'Try "fix typecheck errors"')+ expect(typed).not.toBe(S.empty)+ expect(readClaudeComposer(typed)).toBe('draft')+ })++ it('a capture that lost its SGR fails closed (draft, never empty)', () => {+ // eslint-disable-next-line no-control-regex+ expect(readClaudeComposer(S.empty.replace(/\x1b\[[0-9;]*m/g, ''))).toBe('draft')+ })++ it('a bare prompt with nothing after it is empty', () => {+ const bare = S.empty.replace(' \x1b[2mTry "fix typecheck errors"\x1b[0m', ' ')+ expect(readClaudeComposer(bare)).toBe('empty')+ })++ it('does not read the 2 inside a 38;2;r;g;b colour as dim', () => {+ const coloured = S.empty.replace('\x1b[2mTry "fix typecheck errors"\x1b[0m', '\x1b[38;2;200;200;200mhello\x1b[0m')+ expect(readClaudeComposer(coloured)).toBe('draft')+ })++ it('a dialog or a missing input box is no-prompt; an empty capture is unknown', () => {+ const lines = S.empty.split('\n')+ const noBox = lines.filter((l) => !l.includes('─')).join('\n')+ expect(readClaudeComposer(noBox)).toBe('no-prompt')+ const dialog = S.empty.replace(/\n[^\n]*manual mode on[^\n]*/, '\n Enter to confirm · Esc to cancel')+ expect(readClaudeComposer(dialog)).toBe('no-prompt')+ expect(readClaudeComposer('')).toBe('unknown')+ expect(readClaudeComposer('\n\n')).toBe('unknown')+ })+})diff --git a/src/shared/agents/claude-screen.ts b/src/shared/agents/claude-screen.tsindex 7c3601860..8b37b998c 100644--- a/src/shared/agents/claude-screen.ts+++ b/src/shared/agents/claude-screen.ts@@ -107,3 +107,82 @@ export function readClaudeScreen(screen: string): ClaudeScreen {export function claudeScreenBlocksInput(s: ClaudeScreen): boolean {return s.kind === 'dialog' || s.kind === 'no-prompt'}++/**+ * Is Claude Code's composer EMPTY right now? Read from a STYLED capture (`capture-pane -e`): the one+ * fact the plain text cannot carry is the placeholder. MEASURED on Claude Code 2.1.301 (fullscreen+ * TUI, fixtures in `__fixtures__/claude/composer-capture.json`): an empty composer reads+ * `❯ Try "fix typecheck errors"` with the suggestion drawn SGR 2 (dim); a typed draft is the same+ * line in the default style. Shell mode (`!`) is a draft even with a dim placeholder after it — the+ * mode itself was typed, and text sent there runs as a shell command. A multi-line draft fills the+ * lines under the prompt line.+ *+ * Exists for issue #1144: the context-link discovery note was pasted + Enter'd into a composer that+ * already held the user's half-typed text, and both were submitted as one prompt.+ *+ * - `empty` — a live input box whose prompt line holds nothing but dim text (or nothing at all).+ * - `draft` — anything typed into it.+ * - `no-prompt` — a dialog owns the keyboard, or no input box is on screen (see `readClaudeScreen`).+ * - `unknown` — nothing readable (a failed or empty capture).+ *+ * The error is asymmetric on purpose: only dim text counts as placeholder, so a capture that lost+ * its SGR (or a CLI that styles the placeholder differently) reads `draft` and the caller does NOT+ * type — the safe direction.+ */+export type ClaudeComposer = 'empty' | 'draft' | 'no-prompt' | 'unknown'++/** Does any visible, non-blank character of this styled line (from `from`, a plain-text column)+ * sit outside SGR dim? Walks the SGR state; non-SGR escapes are skipped. */+function hasUndimmedText(styled: string, from: number): boolean {+ let dim = false+ let col = 0+ let i = 0+ while (i < styled.length) {+ if (styled[i] === '\x1b') {+ const csi = /^\x1b\[([0-?]*)([ -/]*)([@-~])/.exec(styled.slice(i))+ if (csi) {+ if (csi[3] === 'm') dim = applySgrDim(csi[1], dim)+ i += csi[0].length+ continue+ }+ // eslint-disable-next-line no-control-regex+ const osc = /^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(styled.slice(i))+ i += osc ? osc[0].length : 1+ continue+ }+ const ch = String.fromCodePoint(styled.codePointAt(i)!)+ if (col >= from && ch.trim() !== '' && !dim) return true+ col += ch.length+ i += ch.length+ }+ return false+}++/** The dim flag after one SGR sequence's parameters. Extended colours (`38;5;n`, `38;2;r;g;b`, and+ * the 48/58 forms) consume their arguments, so the `2` in `38;2;…` is never read as dim. */+function applySgrDim(params: string, dim: boolean): boolean {+ const ps = params === '' ? ['0'] : params.split(/[;:]/)+ for (let k = 0; k < ps.length; k++) {+ const p = ps[k] === '' ? 0 : Number(ps[k])+ if (p === 38 || p === 48 || p === 58) {+ const mode = Number(ps[k + 1])+ k += mode === 5 ? 2 : mode === 2 ? 4 : 1+ } else if (p === 0 || p === 22) dim = false+ else if (p === 2) dim = true+ }+ return dim+}++export function readClaudeComposer(styledScreen: string): ClaudeComposer {+ const styled = styledScreen.split(/\r?\n/)+ const lines = styled.map((l) => l.replace(ANSI, '').trimEnd())+ if (lines.every((l) => l === '')) return 'unknown'+ if (readClaudeScreen(styledScreen).kind !== 'prompt') return 'no-prompt'+ const box = inputBox(lines)+ if (!box) return 'no-prompt'+ const promptAt = box[0] + 1+ const prompt = lines[promptAt]+ if (!prompt.startsWith('❯')) return 'draft'+ for (let i = promptAt + 1; i < box[1]; i++) if (lines[i].trim() !== '') return 'draft'+ return hasUndimmedText(styled[promptAt], 1) ? 'draft' : 'empty'+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex ddac4b0ca..fa4980896 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -29,6 +29,7 @@ export const IPC = {ptyReadScrollback: 'pty:read-scrollback',ptySendText: 'pty:send-text',ptySendChatPrompt: 'pty:send-chat-prompt',+ ptySendToEmptyPrompt: 'pty:send-to-empty-prompt',ptyTmuxStatus: 'pty:tmux-status',/** The foreground command of a node's tmux pane (`#{pane_current_command}`) — how the in-place* agent restart sees that the CLI has exited and a shell owns the pane again. */diff --git a/src/shared/text-delivery.ts b/src/shared/text-delivery.tsindex 541fd6aa4..9504b689a 100644--- a/src/shared/text-delivery.ts+++ b/src/shared/text-delivery.ts@@ -15,3 +15,15 @@ export interface ChatPromptBlocked {export type ChatPromptResult = TextDeliveryResult | ChatPromptBlockedexport const isChatPromptBlocked = (r: ChatPromptResult): r is ChatPromptBlocked =>typeof r === 'object' && r !== null && r.blocked === 'screen'++/**+ * Why a write that must land only in an EMPTY composer (`pty.sendToEmptyPrompt` — the context-link+ * and note-link pushes, issue #1144) was not made. Every refusal is decided before a byte is written,+ * except `not-submitted` (typed, but the Enter was withheld) and `failed` (the transport refused).+ * - `unsupported` — no measured reader for this agent's composer, so emptiness cannot be proven.+ * - `draft` — the composer already holds the user's text.+ * - `no-prompt` — a dialog owns the keyboard, or no input box is on screen (a shell, a starting CLI).+ * - `unknown` — the screen could not be read.+ */+export type EmptyPromptRefusal = 'unsupported' | 'draft' | 'no-prompt' | 'unknown' | 'not-submitted' | 'failed'+export type EmptyPromptResult = { sent: true } | { sent: false; reason: EmptyPromptRefusal }diff --git a/src/shared/types.ts b/src/shared/types.tsindex c3b310be8..d578be792 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,4 +1,4 @@-import type { ChatPromptResult, TextDeliveryResult } from './text-delivery'+import type { ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'import type { IdentitySeedEntry } from './agent-identity-seed'import type { PrWaitHold } from './pr-wait'@@ -1354,6 +1354,10 @@ export interface PtyApi {* (`readsScreenDialogs`), refused BEFORE anything is written when the agent's own dialog owns the* keyboard (`ChatPromptBlocked`) — such dialogs fire no hook. Otherwise the `sendText` contract. */sendChatPrompt(persistKey: string, text: string, agentId: string): Promise<ChatPromptResult>+ /** Type `text` + Enter ONLY into an empty composer of an agent whose composer can be read+ * (issue #1144 — the app's own link notes). Refused, with the reason, before anything is written+ * when the composer holds a draft, a dialog owns the keyboard, or emptiness cannot be proven. */+ sendToEmptyPrompt(persistKey: string, text: string, agentId: string): Promise<EmptyPromptResult>/** Is tmux available on this host (else the silent plain-shell fallback), plus a suggested* install command for the "tmux not found" banner. */tmuxStatus(): Promise<TmuxStatus>