From 5ce30b20c941fb9e96272f1f12ca33cbb3d765f9 Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Sat, 7 Nov 2026 09:13:48 +0900 Subject: [PATCH] feat(cli): auto-steer ping-peer messages into active peer turns (#2298) * refactor(shared): describe steering support with a per-flavor capability table Replace the flavor comparison chains in isSteeringSupportedForFlavor and isSteeringSupportedForSession with a table keyed by flavor, so a protocol restriction such as legacy Cursor sessions sits next to the flavor it applies to. Results are unchanged for every flavor and Cursor session shape. * feat(cli): auto-steer ping-peer messages into active peer turns Peer messages in auto mode only steered Codex turns. Record each flavor's active-turn signal in the steering capability table, expose it as hasActiveSteeringTurn(), and use it in both the peer sender and the waiting queue's Steer gate, so remote Claude, Pi, OpenCode and Cursor ACP targets with an active, steerable turn also get the queued message steered into it. Auto still stores one ordinary queued message first and attempts the existing steer action at most once. A steer that the hub rejects or that stays unconfirmed keeps the accepted message without resending, and the receipt now says which of "not attempted", "rejected by hub" or "not confirmed" applied. Inactive targets, --wake, explicit steer and explicit queue are unchanged. * fix(cli): keep ping-peer steer notes accurate when delivery is unresolved Auto receipts reported every unsuccessful steer response as "rejected by hub" and promised the message stays queued. Only a refusal before any native steer is dispatched (an HTTP 4xx, or a Hub failure without a localId) is definitive. A failure that carries a localId, such as an RPC timeout or an OpenCode steer that is still being reconciled, now reads "steer not confirmed; delivery unresolved" without promising queued delivery. Auto notes for a skipped steer used the explicit-steer refusal text, so an accepted receipt could say "no message sent". They now use separate reasons (for example "target is idle"); explicit steer wording is unchanged. --- cli/README.md | 46 ++-- cli/src/claude/utils/startHappyServer.test.ts | 23 ++ cli/src/claude/utils/startHappyServer.ts | 2 +- cli/src/commands/pingPeer.test.ts | 30 ++ cli/src/commands/pingPeer.ts | 9 +- .../modules/pingPeer/pingPeer.auto.test.ts | 257 ++++++++++++++++++ cli/src/modules/pingPeer/pingPeer.test.ts | 31 ++- cli/src/modules/pingPeer/pingPeer.ts | 103 +++++-- shared/src/modes.test.ts | 77 ++++++ shared/src/modes.ts | 85 ++++-- shared/src/sessionCitation.test.ts | 5 +- shared/src/sessionCitation.ts | 7 +- web/src/components/SessionChat.tsx | 7 +- 13 files changed, 579 insertions(+), 103 deletions(-) create mode 100644 cli/src/modules/pingPeer/pingPeer.auto.test.ts diff --git a/cli/README.md b/cli/README.md index ad75ef9d..caf163e2 100644 --- a/cli/README.md +++ b/cli/README.md @@ -48,18 +48,22 @@ Choose a supported coding agent from your terminal and control its sessions remo - `hapi inspect-peer ` - Read-only peer metadata + recent message text (no resume). Prefer this or MCP `inspect_peer` when a user cites `[title](/sessions/)` or Copy-reference `See session "…" (/sessions/) for context`. `/sessions/` is a hub path, not a local file. Optional `--limit`. - `hapi set-mode ` - Change the permission mode of an existing session, like the web permission picker. Active sessions switch immediately; inactive ones use it on next resume. An invalid mode prints the modes allowed for that agent. -Peer messages default to `auto`: use the target's live state to steer an active -Codex turn when steering is available; otherwise queue. Auto currently queues -for all other agent flavors. Prefer -auto for routine collaboration when queueing is an acceptable fallback. +Peer messages default to `auto`: use the target's live capabilities and turn +state to steer an active, eligible turn; otherwise queue. Inactive peers require explicit `wake: true`; awakened peers enter the ordinary queue. This applies to every steering-supported +flavor: remote Claude, Pi, Codex, OpenCode, and Cursor ACP. Unsupported agents and +legacy Cursor sessions queue instead. Prefer auto for routine collaboration +when queueing is an acceptable fallback. + Use explicit `queue` for non-urgent updates that can wait. Use `steer` for important, time-sensitive findings the peer needs to know now, not after its current turn: a correction that invalidates its assumptions, a blocker, or a result that changes its next action. State why it matters now and what the peer -should adjust. Steer requires insertion into an active Claude (remote), Pi, Codex, or Cursor ACP -turn; it does not abort that turn or guarantee an immediate response. MCP `ping_peer` accepts -the same optional `deliveryMode: "auto" | "queue" | "steer"` field. Auto is -resolved by the peer sender; ordinary web/native chat delivery is unchanged. +should adjust. +Explicit steer rejects unsupported agents, idle targets, and inactive targets +before sending. It does not abort the current turn or guarantee an immediate +response. MCP `ping_peer` accepts the same optional +`deliveryMode: "auto" | "queue" | "steer"` field. Auto is a peer-sender policy; +ordinary web/native chat delivery is unchanged. Peer messages never wake an inactive session by default: `ping_peer` refuses with `inactive` and sends nothing. Pass MCP `wake: true` (CLI `--wake`) only @@ -75,20 +79,20 @@ hapi ping-peer 'Run the next check' --delivery-mode queue hapi ping-peer 'Use the corrected input path' --delivery-mode steer ``` -Queue success reports `accepted` with a `ping-peer-` localId, not confirmed -delivery. Delivery is shown in the recipient chat only after its runtime -acknowledges consumption. Steer messages retain the same peer identity prefix. +Every submission retains one `ping-peer-` localId. Auto first stores an ordinary +queued message, then tries the existing queued-message Steer action when the +live target is eligible. A steer rejection or unconfirmed steer response retains +that same accepted message without resending or retrying the action. The +receipt and progress output say whether steering was not attempted, rejected by +the Hub, or not confirmed with delivery unresolved. An +`accepted` receipt proves Hub acceptance, not whether the message remains queued +or has already been consumed. Actual runtime acknowledgements determine delivery. -Steer rejects unsupported agents, idle targets, and inactive targets before -sending. It reuses the queued-message Steer action: success reports `steered`, -or `invoked` if the target consumed the message before the action arrived. -Auto uses Codex's `steeringActive` state and control capabilities, not just -`active` or `thinking`. If the turn changes after selection, auto uses the same -safe error handling as explicit steer; it does not resend or silently retry. -If steering fails after the message was accepted, the error includes its -`localId`; it may still be queued or already consumed. Inspect the target -before retrying; do not automatically resend the prompt. Steering does not -abort the current turn. +Steer success reports `steered`, or `invoked` when consumption won the race. +Explicit steer still reports an error if steering cannot be confirmed after +acceptance, including the original localId. Initial send failures or ACK loss +are never converted into successful auto fallback. Inspect the target before +retrying an unconfirmed send; do not automatically resend the prompt. The picker lists agents alphabetically by command name. Use Up/Down and Enter to choose; Esc or Ctrl-C cancels. It appears on every bare invocation, even diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index c7e1843f..5c9002c1 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -248,6 +248,29 @@ describe('startHappyServer skill_lookup', () => { } }) + it.each([ + 'steer not attempted: target is idle', + 'steer rejected by hub: Session not found', + 'steer not confirmed; delivery unresolved: Steer outcome is being reconciled' + ])('appends the auto steer note to an accepted ping_peer receipt without claiming nothing was sent: %s', async (steerNote) => { + const ping = vi.spyOn(peerMessages, 'pingPeer').mockResolvedValue({ + sessionId: 'peer-id', name: 'Peer', resumed: false, + localId: 'ping-peer-test', delivery: 'accepted', steerNote + }) + try { + const mcp = await connect(false) + const result = await mcp.callTool({ + name: 'ping_peer', arguments: { sessionIdPrefix: 'peer-id', message: 'hello' } + }) as ToolResult + expect(result.isError).toBe(false) + expect(result.content?.[0]?.text).toBe( + `Accepted for peer-id (Peer) localId=ping-peer-test — delivery shows in the recipient chat when its runtime consumes it (${steerNote})`) + expect(result.content?.[0]?.text).not.toMatch(/no message sent/i) + } finally { + ping.mockRestore() + } + }) + it('forwards ping_peer wake only when explicitly requested', async () => { const ping = vi.spyOn(peerMessages, 'pingPeer').mockResolvedValue({ sessionId: 'peer-id', name: 'Peer', resumed: true, diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index b59ff669..afd22f35 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -413,7 +413,7 @@ function createHapiMcpServer( { type: 'text' as const, text: result.delivery === 'accepted' - ? `Accepted for ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId} — delivery shows in the recipient chat when its runtime consumes it` + ? `Accepted for ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId} — delivery shows in the recipient chat when its runtime consumes it${result.steerNote ? ` (${result.steerNote})` : ''}` : `${result.delivery} to ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId}`, }, ], diff --git a/cli/src/commands/pingPeer.test.ts b/cli/src/commands/pingPeer.test.ts index 18d4cb76..7fe855e7 100644 --- a/cli/src/commands/pingPeer.test.ts +++ b/cli/src/commands/pingPeer.test.ts @@ -94,4 +94,34 @@ describe('handlePingPeerCommand receipts', () => { ? 'OK - accepted for peer-id localId=ping-peer-test — delivery shows in the recipient chat when its runtime consumes it' : `OK - ${delivery} to peer-id localId=ping-peer-test`)) }) + + it.each([ + 'steer not attempted: target is idle', + 'steer rejected by hub: Session not found', + 'steer not confirmed; delivery unresolved: Steer outcome is being reconciled' + ])('appends the auto steer note to an accepted receipt: %s', async (steerNote) => { + vi.spyOn(tokenInit, 'initializeToken').mockResolvedValue(undefined) + vi.spyOn(peerMessages, 'pingPeer').mockResolvedValue({ + sessionId: 'peer-id', name: 'Peer', resumed: false, + localId: 'ping-peer-test', delivery: 'accepted', steerNote + }) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await handlePingPeerCommand(['peer-id', 'hello']) + + expect(log).toHaveBeenCalledWith(expect.stringContaining( + `consumes it (${steerNote})`)) + expect(log).not.toHaveBeenCalledWith(expect.stringMatching(/no message sent/i)) + }) +}) + +describe('ping-peer help', () => { + afterEach(() => vi.restoreAllMocks()) + + it('includes remote Claude and OpenCode in the explicit steer contract', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + await handlePingPeerCommand(['--help']) + expect(log).toHaveBeenCalledWith(expect.stringContaining('remote Claude, Pi, Codex')) + expect(log).toHaveBeenCalledWith(expect.stringContaining('Codex, OpenCode,')) + }) }) diff --git a/cli/src/commands/pingPeer.ts b/cli/src/commands/pingPeer.ts index 47b2e71d..c879a94a 100644 --- a/cli/src/commands/pingPeer.ts +++ b/cli/src/commands/pingPeer.ts @@ -43,13 +43,14 @@ ${chalk.bold('Notes:')} Message only peers tied to your task; never broadcast to the --list output. Inactive targets are refused (exit 5) unless --wake, which resumes them via POST /api/sessions/:id/resume first. Wake only when the peer must act, not for FYI. - Delivery defaults to auto: steer a steerable active Codex turn, otherwise queue. - Other agent flavors currently queue in auto mode. + Delivery defaults to auto: steer an active turn when its target supports steering + and is ready; otherwise queue. If steering cannot be confirmed after acceptance, + auto keeps the same accepted message without resending; acceptance is not consumption. Use auto for routine collaboration when queueing is an acceptable fallback. Use queue for non-urgent updates that can wait. Use steer for important findings the peer needs to know now to adjust its current work, not after its current turn. State why the finding matters now and what the peer should adjust. - Explicit steer requires an active turn in Pi, Codex, + Explicit steer requires an active turn in remote Claude, Pi, Codex, OpenCode, or Cursor ACP; it neither resumes inactive targets nor sends to idle targets. Steer uses the existing queued-message action. If it fails after send, inspect the target before retrying: the accepted message may still be queued or consumed. @@ -233,7 +234,7 @@ export async function handlePingPeerCommand(args: string[]): Promise { }) const receipt = result.delivery === 'accepted' - ? `accepted for ${result.sessionId} localId=${result.localId} — delivery shows in the recipient chat when its runtime consumes it` + ? `accepted for ${result.sessionId} localId=${result.localId} — delivery shows in the recipient chat when its runtime consumes it${result.steerNote ? ` (${result.steerNote})` : ''}` : `${result.delivery} to ${result.sessionId} localId=${result.localId}` console.log(chalk.green(`hapi ping-peer: OK - ${receipt}`)) } diff --git a/cli/src/modules/pingPeer/pingPeer.auto.test.ts b/cli/src/modules/pingPeer/pingPeer.auto.test.ts new file mode 100644 index 00000000..f40974b2 --- /dev/null +++ b/cli/src/modules/pingPeer/pingPeer.auto.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it, vi } from 'vitest' +import { pingPeer, exitCodeForPingPeerError, PingPeerError, type PingPeerSessionSummary } from './pingPeer' + +const sessionId = '99999999-1111-4111-8111-111111111111' +const flavors = ['claude', 'codex', 'opencode', 'pi', 'cursor'] as const +type Flavor = typeof flavors[number] +type Response = { status: number; data: unknown } +type Submission = { text: string; localId: string; deliveryMode?: string } + +function target(flavor: Flavor, active = true, steering = true): PingPeerSessionSummary { + return { + id: sessionId, active, thinking: steering, + metadata: { + flavor, + ...(flavor === 'pi' ? { piSessionId: 'synthetic-pi' } : {}), + ...(flavor === 'cursor' ? { cursorSessionProtocol: 'acp' as const } : {}) + }, + agentState: { steeringActive: steering } + } +} + +function transport(initial: PingPeerSessionSummary, options: { + steer?: Response | Error + send?: Response | Error + live?: PingPeerSessionSummary + afterResume?: PingPeerSessionSummary +} = {}) { + let current = options.live ?? initial + const rows: Submission[] = [] + const steers: string[] = [] + const http = { + get: vi.fn(async (url: string) => url.endsWith('/api/sessions') + ? { status: 200, data: { sessions: [initial] } } + : { status: 200, data: { session: current } }), + post: vi.fn(async (url: string, body?: unknown) => { + if (url.endsWith('/api/auth')) return { status: 200, data: { token: 'synthetic-jwt' } } + if (url.endsWith('/resume')) { + current = options.afterResume ?? { ...current, active: true } + return { status: 200, data: { type: 'success', sessionId } } + } + if (url.endsWith('/messages')) { + rows.push(body as Submission) + if (options.send instanceof Error) throw options.send + return options.send ?? { status: 200, data: { ok: true } } + } + if (url.endsWith('/steer')) { + steers.push(url) + if (options.steer instanceof Error) throw options.steer + return options.steer ?? { status: 200, data: { status: 'steered' } } + } + throw new Error(`Unexpected synthetic route ${url}`) + }) + } + return { + rows, steers, http, + input: { sessionIdPrefix: sessionId, message: 'Synthetic peer update', + apiUrl: 'http://hub.test', accessToken: 'synthetic-access', http: http as never } + } +} + +describe.each(flavors)('auto delivery to %s', (flavor) => { + it.each([undefined, 'auto'] as const)('steers an eligible active turn with mode %s using one ordinary queued row', async (deliveryMode) => { + const t = transport(target(flavor)) + const result = await pingPeer({ ...t.input, deliveryMode }) + expect(result.delivery).toBe('steered') + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([`http://hub.test/api/sessions/${sessionId}/messages/${result.localId}/steer`]) + }) + + it('queues an idle target without a steer request', async () => { + const t = transport(target(flavor, true, false)) + const result = await pingPeer({ ...t.input, deliveryMode: 'auto' }) + expect(result.delivery).toBe('accepted') + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([]) + }) + + it('queues when concurrent control is explicitly disabled for a local target', async () => { + const session = target(flavor) + session.agentState = { steeringActive: true, controlledByUser: true } + session.metadata = { ...session.metadata, capabilities: { concurrentClients: false } } + const t = transport(session) + expect((await pingPeer({ ...t.input, deliveryMode: 'auto' })).delivery).toBe('accepted') + expect(t.rows).toHaveLength(1) + expect(t.steers).toEqual([]) + }) + + it('resumes an inactive target and queues even if the resumed turn reports steering ready', async () => { + const t = transport(target(flavor, false), { afterResume: target(flavor) }) + const result = await pingPeer({ ...t.input, deliveryMode: 'auto', wake: true }) + expect(result.resumed).toBe(true) + expect(result.delivery).toBe('accepted') + expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(1) + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([]) + }) + + it.each(['auto', 'queue'] as const)('refuses an inactive target by default in %s mode without resume, row or RPC', async (deliveryMode) => { + const t = transport(target(flavor, false)) + const error = await pingPeer({ ...t.input, deliveryMode }).catch(error => error) + expect(error).toBeInstanceOf(PingPeerError) + expect(error.code).toBe('inactive') + expect(exitCodeForPingPeerError(error)).toBe(5) + expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(0) + expect(t.rows).toEqual([]) + expect(t.steers).toEqual([]) + }) + + it('rejects explicit steer to an inactive target even with wake enabled', async () => { + const t = transport(target(flavor, false)) + await expect(pingPeer({ ...t.input, deliveryMode: 'steer', wake: true })).rejects.toMatchObject({ code: 'bad_args' }) + expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(0) + expect(t.rows).toEqual([]) + expect(t.steers).toEqual([]) + }) + + it.each(['auto', 'queue'] as const)('preserves opt-in wake for an active-list/inactive-live race in %s mode', async (deliveryMode) => { + for (const wake of [false, true]) { + const t = transport(target(flavor), { live: target(flavor, false), afterResume: target(flavor) }) + if (wake) { + const result = await pingPeer({ ...t.input, deliveryMode, wake }) + expect(result.resumed).toBe(true) + expect(result.delivery).toBe('accepted') + expect(result.steerNote).toBe(deliveryMode === 'auto' ? 'steer not attempted: target was just resumed' : undefined) + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + } else { + await expect(pingPeer({ ...t.input, deliveryMode, wake })).rejects.toMatchObject({ code: 'inactive' }) + expect(t.rows).toEqual([]) + } + expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(wake ? 1 : 0) + expect(t.steers).toEqual([]) + } + }) + + it.each([ + [{ status: 200, data: { status: 'failed', error: 'Session not found', localId: null } }, 'steer rejected by hub: Session not found', 'stays queued'], + [{ status: 409, data: { error: 'Session became inactive' } }, 'steer rejected by hub: Session became inactive', 'stays queued'], + [{ status: 200, data: { status: 'failed', error: 'RPC timeout: steer-queued-message', localId: 'ping-peer-x' } }, + 'steer not confirmed; delivery unresolved: RPC timeout: steer-queued-message', 'delivery unresolved'], + [{ status: 200, data: { status: 'failed', error: 'Steer outcome is being reconciled', localId: 'ping-peer-x' } }, + 'steer not confirmed; delivery unresolved: Steer outcome is being reconciled', 'delivery unresolved'], + [{ status: 500, data: { error: 'Hub unavailable' } }, 'steer not confirmed; delivery unresolved: Hub unavailable', 'delivery unresolved'], + [new Error('Synthetic steer ACK lost'), 'steer not confirmed; delivery unresolved: Synthetic steer ACK lost', 'delivery unresolved'] + ] as const)('retains the one accepted row and words the steer outcome by its evidence: %j', async (steer, steerNote, progressTail) => { + const t = transport(target(flavor), { steer }) + const progress: string[] = [] + const result = await pingPeer({ ...t.input, deliveryMode: 'auto', onProgress: (m) => progress.push(m) }) + expect(result.delivery).toBe('accepted') + expect(result.steerNote).toBe(steerNote) + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([`http://hub.test/api/sessions/${sessionId}/messages/${result.localId}/steer`]) + expect(t.http.post.mock.calls).toHaveLength(3) + const line = progress.find((m) => m.startsWith(steerNote)) + expect(line).toBeDefined() + expect(line).toContain(progressTail) + if (progressTail === 'delivery unresolved') expect(line).not.toContain('stays queued') + }) + + it.each([ + { status: 500, data: { error: 'Synthetic hub failure' } }, + { status: 409, data: { error: 'Session is inactive' } } + ])('does not hide a non-2xx initial submission or attempt a steer: %j', async (send) => { + const t = transport(target(flavor), { send }) + await expect(pingPeer({ ...t.input, deliveryMode: 'auto' })).rejects.toMatchObject({ code: 'send_failed' }) + expect(t.rows).toHaveLength(1) + expect(t.steers).toEqual([]) + }) + + it('queues without a steer when the target only became active through waitForInitialActive', async () => { + const t = transport(target(flavor, false), { live: target(flavor, true) }) + const result = await pingPeer({ ...t.input, deliveryMode: 'auto', waitForInitialActive: true }) + expect(result.delivery).toBe('accepted') + expect(result.steerNote).toBe('steer not attempted: target was not active') + expect(result.resumed).toBe(false) + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([]) + expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(0) + }) + + it('keeps authoritative consumption instead of claiming a queue fallback', async () => { + const t = transport(target(flavor), { steer: { status: 200, data: { status: 'invoked' } } }) + const result = await pingPeer({ ...t.input, deliveryMode: 'auto' }) + expect(result.delivery).toBe('invoked') + expect(t.rows).toHaveLength(1) + expect(t.steers).toHaveLength(1) + }) + + it('does not hide an unconfirmed initial message submission or attempt a steer', async () => { + const t = transport(target(flavor), { send: new Error('Synthetic message ACK lost') }) + await expect(pingPeer({ ...t.input, deliveryMode: 'auto' })).rejects.toThrow(/Send not confirmed.*Do not resend automatically/) + expect(t.rows).toHaveLength(1) + expect(t.steers).toEqual([]) + }) + + it('preserves explicit steer rejection and its existing queued-row payload', async () => { + const t = transport(target(flavor), { steer: { status: 200, data: { status: 'failed', error: 'No active turn' } } }) + await expect(pingPeer({ ...t.input, deliveryMode: 'steer' })).rejects.toThrow(/Message accepted.*steer was not confirmed/) + expect(t.rows).toHaveLength(1) + expect(t.rows[0]).toEqual({ text: t.input.message, localId: t.rows[0]?.localId }) + expect(t.steers).toHaveLength(1) + }) + + it('preserves explicit queue without attempting a steer', async () => { + const t = transport(target(flavor)) + const result = await pingPeer({ ...t.input, deliveryMode: 'queue' }) + expect(result.delivery).toBe('accepted') + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([]) + }) +}) + +describe('auto delivery to a legacy Cursor stream-json session', () => { + it('queues without a steer request because the session cannot steer', async () => { + const legacy: PingPeerSessionSummary = { + id: sessionId, active: true, thinking: true, + metadata: { flavor: 'cursor', cursorSessionProtocol: 'stream-json' as never }, + agentState: { steeringActive: true } + } + const t = transport(legacy) + const result = await pingPeer({ ...t.input, deliveryMode: 'auto' }) + expect(result.delivery).toBe('accepted') + expect(result.steerNote).toMatch(/^steer not attempted: /) + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([]) + }) +}) + +describe.each([ + ['idle', { active: true, steering: false }, 'steer not attempted: target is idle'], + ['locally controlled', { active: true, steering: true, local: true }, 'steer not attempted: target is controlled locally'], +] as const)('auto delivery to a %s target', (_label, shape, note) => { + it('accepts the message and explains the skipped steer without claiming nothing was sent', async () => { + const base = target('claude', shape.active, shape.steering) + const peer: PingPeerSessionSummary = 'local' in shape + ? { ...base, agentState: { ...base.agentState, controlledByUser: true } } + : base + const t = transport(peer) + const progress: string[] = [] + const result = await pingPeer({ ...t.input, deliveryMode: 'auto', onProgress: (m) => progress.push(m) }) + expect(result.delivery).toBe('accepted') + expect(result.steerNote).toBe(note) + expect(result.steerNote).not.toMatch(/no message sent/i) + expect(progress.join('\n')).not.toMatch(/no message sent/i) + expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }]) + expect(t.steers).toEqual([]) + }) + + it('still refuses an explicit steer with the pre-send wording', async () => { + const base = target('claude', shape.active, shape.steering) + const peer: PingPeerSessionSummary = 'local' in shape + ? { ...base, agentState: { ...base.agentState, controlledByUser: true } } + : base + const t = transport(peer) + await expect(pingPeer({ ...t.input, deliveryMode: 'steer' })).rejects.toThrow(/no message sent/) + expect(t.rows).toEqual([]) + }) +}) diff --git a/cli/src/modules/pingPeer/pingPeer.test.ts b/cli/src/modules/pingPeer/pingPeer.test.ts index 271fcd89..6f425347 100644 --- a/cli/src/modules/pingPeer/pingPeer.test.ts +++ b/cli/src/modules/pingPeer/pingPeer.test.ts @@ -394,6 +394,7 @@ describe('pingPeer', () => { name: 'Spawned', resumed: false, delivery: 'accepted', + steerNote: expect.stringMatching(/^steer not attempted: /), localId: expect.stringMatching(/^ping-peer-/), }) }) @@ -619,10 +620,8 @@ describe('pingPeer delivery modes', () => { { name: 'Codex without steering state', session: { ...active, agentState: null } }, { name: 'local Codex without concurrent control', session: { ...active, agentState: { steeringActive: true, controlledByUser: true } } }, { name: 'unknown flavor', session: { ...active, metadata: null } }, - { name: 'Pi', session: { ...active, metadata: { flavor: 'pi', piSessionId: 'pi-thread' } } }, - { name: 'Cursor ACP', session: { ...active, metadata: { flavor: 'cursor', cursorSessionProtocol: 'acp' as const } } }, { name: 'legacy Cursor', session: { ...active, metadata: { flavor: 'cursor', cursorSessionProtocol: 'stream-json' as const } } }, - { name: 'Claude', session: { ...active, metadata: { flavor: 'claude' } } } + { name: 'idle Claude', session: { ...active, agentState: { steeringActive: false }, metadata: { flavor: 'claude' } } } ])('auto queues for $name', async ({ session }) => { const { http, options } = setup(session) expect((await pingPeer({ ...options, deliveryMode: 'auto' })).delivery).toBe('accepted') @@ -650,7 +649,7 @@ describe('pingPeer delivery modes', () => { expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(steeringActive ? 1 : 0) }) - it.each([true, false])('auto re-evaluates Codex steeringActive=%s after resume', async (steeringActive) => { + it.each([true, false])('auto queues after resume even with Codex steeringActive=%s', async (steeringActive) => { let resumed = false const http = createHttpMock({ get: (url) => url.endsWith('/api/sessions') @@ -672,16 +671,18 @@ describe('pingPeer delivery modes', () => { apiUrl: 'http://hub.test', accessToken: 'tok', http: http as never }) expect(result.resumed).toBe(true) - expect(result.delivery).toBe(steeringActive ? 'steered' : 'accepted') + expect(result.delivery).toBe('accepted') expect(http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(1) expect(http.post.mock.calls.filter(([url]) => url.endsWith('/messages'))).toHaveLength(1) - expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(steeringActive ? 1 : 0) + expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(0) }) it.each([ { flavor: 'codex' }, { flavor: 'pi', piSessionId: 'pi-thread' }, - { flavor: 'cursor', cursorSessionProtocol: 'acp' as const } + { flavor: 'cursor', cursorSessionProtocol: 'acp' as const }, + { flavor: 'claude' }, + { flavor: 'opencode' } ])('steers an ackable message in $flavor using its localId', async (metadata) => { const { http, options } = setup({ ...active, metadata }) const result = await pingPeer({ ...options, deliveryMode: 'steer' }) @@ -726,7 +727,9 @@ describe('pingPeer delivery modes', () => { { flavor: 'codex', steeringActive: false }, { flavor: 'codex', steeringActive: undefined }, { flavor: 'cursor', steeringActive: false }, - { flavor: 'cursor', steeringActive: undefined } + { flavor: 'cursor', steeringActive: undefined }, + { flavor: 'opencode', steeringActive: false }, + { flavor: 'opencode', steeringActive: undefined } ])('does not send to a thinking $flavor peer with steeringActive=$steeringActive', async ({ flavor, steeringActive }) => { const { http, options } = setup({ ...active, metadata: { flavor }, agentState: { steeringActive } @@ -766,11 +769,15 @@ describe('pingPeer delivery modes', () => { { status: 200, data: { status: 'failed', error: 'Message not in queue' } }, { status: 409, data: { error: 'Session inactive' } }, new Error('Request timed out') - ])('reports accepted but unconfirmed steer without fallback or resending: %j', async (failure) => { + ])('preserves the single submission when steer is unconfirmed: %j', async (failure) => { const { http, options } = setup(active, failure) - await expect(pingPeer({ ...options, deliveryMode })).rejects.toThrow( - /Message accepted \(localId=ping-peer-.+\), but steer was not confirmed: .*Do not resend automatically/ - ) + if (deliveryMode === 'steer') { + await expect(pingPeer({ ...options, deliveryMode })).rejects.toThrow( + /Message accepted \(localId=ping-peer-.+\), but steer was not confirmed: .*Do not resend automatically/ + ) + } else { + expect((await pingPeer({ ...options, deliveryMode })).delivery).toBe('accepted') + } expect(http.post.mock.calls.filter(([url]) => url.endsWith('/messages'))).toHaveLength(1) expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(1) }) diff --git a/cli/src/modules/pingPeer/pingPeer.ts b/cli/src/modules/pingPeer/pingPeer.ts index f2a33b51..fa52fa2f 100644 --- a/cli/src/modules/pingPeer/pingPeer.ts +++ b/cli/src/modules/pingPeer/pingPeer.ts @@ -16,6 +16,7 @@ import { getPermissionModesForFlavor, isObject, isSteeringSupportedForSession, + hasActiveSteeringTurn, type MessageDeliveryMode, } from '@hapi/protocol' import { normalizeSessionIdPrefix } from '@hapi/protocol/sessionCitation' @@ -113,6 +114,12 @@ export type PingPeerResult = { name: string resumed: boolean delivery: 'accepted' | 'steered' | 'invoked' + /** + * Auto only: why an `accepted` receipt did not steer. Distinguishes a steer + * that was never attempted from one the hub rejected or that stayed + * unconfirmed. The accepted message itself is never resent. + */ + steerNote?: string /** * Known client submit identity for the peer row (`ping-peer-` prefix). * The recipient runtime's consumption ACK is the only delivery proof; @@ -430,8 +437,10 @@ async function sendMessage( message: string, localId: string, http: AxiosInstance, - deliveryMode: MessageDeliveryMode -): Promise { + deliveryMode: MessageDeliveryMode, + autoSteerFallback = false, + onProgress?: (message: string) => void +): Promise<{ delivery: PingPeerResult['delivery']; steerNote?: string }> { // The existing queued-message steer action accepts localId as well as id. // Both modes retain the peer identity so only runtime ACKs prove delivery. const response = await http.post( @@ -450,7 +459,8 @@ async function sendMessage( if (response.status >= 200 && response.status < 300 && response.data?.ok === true) { // HTTP success means hub-accepted, not proof the row is still queued: // the recipient runtime's consumption ACK may race this response. - if (deliveryMode === 'queue') return 'accepted' + if (deliveryMode === 'queue') return { delivery: 'accepted' } + let hubRejection: string | null = null try { const steer = await http.post( `${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(localId)}/steer`, @@ -458,14 +468,34 @@ async function sendMessage( { headers: authHeaders(jwt), timeout: 30_000, validateStatus: () => true } ) if (steer.status >= 200 && steer.status < 300) { - if (steer.data?.status === 'steered') return 'steered' + if (steer.data?.status === 'steered') return { delivery: 'steered' } // The target consumed the message before the steer request. // Do not claim it was inserted into the active turn. - if (steer.data?.status === 'invoked') return 'invoked' + if (steer.data?.status === 'invoked') return { delivery: 'invoked' } } - throw new Error(typeof steer.data?.error === 'string' ? steer.data.error : `HTTP ${steer.status}`) + const rejection: string = typeof steer.data?.error === 'string' ? steer.data.error : `HTTP ${steer.status}` + // Only a refusal before any native request is dispatched is definitive: + // an HTTP 4xx, or a Hub 'failed' reply without a localId. A 'failed' reply + // that carries a localId means the native steer was requested, and its + // timeout or "being reconciled" outcome leaves delivery unresolved. + const refusedBeforeDispatch = (steer.status >= 400 && steer.status < 500) + || (steer.status >= 200 && steer.status < 300 + && steer.data?.status === 'failed' && steer.data?.localId == null) + if (refusedBeforeDispatch) hubRejection = rejection + throw new Error(rejection) } catch (error) { const detail = error instanceof Error ? error.message : String(error) + // POST acceptance already owns one row; never resend after a failed or uncertain steer. + // Auto keeps the queued receipt but reports why the steer did not happen. + if (autoSteerFallback) { + const steerNote = hubRejection !== null + ? `steer rejected by hub: ${detail}` + : `steer not confirmed; delivery unresolved: ${detail}` + onProgress?.(hubRejection !== null + ? `${steerNote}; message stays queued as ${localId}` + : `${steerNote}; message accepted as ${localId}`) + return { delivery: 'accepted', steerNote } + } throw new PingPeerError( 'send_failed', `Message accepted (localId=${localId}), but steer was not confirmed: ${detail}. ` + @@ -646,25 +676,37 @@ export function formatPeerSessionsList( return rows.join('\n') } -function getSteeringUnavailableReason(session: PingPeerSessionSummary): string | null { - if (!session.active) { - return 'Steering requires an active turn; target is inactive, no message sent. Use queue with wake to resume it' - } - if (!isSteeringSupportedForSession(session.metadata)) { - return 'Steering is only supported for Claude, Pi, Codex, and Cursor ACP sessions; no message sent' - } - if (session.agentState?.controlledByUser && !session.metadata?.capabilities?.concurrentClients) { - return 'Steering is only available for remote sessions; no message sent' - } - const steeringActive = session.metadata?.flavor === 'pi' - ? session.thinking - : session.agentState?.steeringActive === true - if (!steeringActive) { - return 'Steering requires an active turn; target is idle, no message sent. Use queue to start a turn' - } +type SteeringIneligibility = 'inactive' | 'unsupported' | 'local' | 'idle' + +function getSteeringIneligibility(session: PingPeerSessionSummary): SteeringIneligibility | null { + if (!session.active) return 'inactive' + if (!isSteeringSupportedForSession(session.metadata)) return 'unsupported' + if (session.agentState?.controlledByUser && !session.metadata?.capabilities?.concurrentClients) return 'local' + if (!hasActiveSteeringTurn(session)) return 'idle' return null } +// Explicit steer refuses before sending, so these texts say no message was sent. +const EXPLICIT_STEER_REFUSAL: Record = { + inactive: 'Steering requires an active turn; target is inactive, no message sent. Use queue with wake to resume it', + unsupported: 'Steering is only supported for Claude, Pi, Codex, OpenCode, and Cursor ACP sessions; no message sent', + local: 'Steering is only available for remote sessions; no message sent', + idle: 'Steering requires an active turn; target is idle, no message sent. Use queue to start a turn' +} + +// Auto has already accepted the message, so its notes must not claim otherwise. +const AUTO_NOT_ATTEMPTED: Record = { + inactive: 'target is inactive', + unsupported: 'target does not support steering', + local: 'target is controlled locally', + idle: 'target is idle' +} + +function getSteeringUnavailableReason(session: PingPeerSessionSummary): string | null { + const ineligibility = getSteeringIneligibility(session) + return ineligibility === null ? null : EXPLICIT_STEER_REFUSAL[ineligibility] +} + export async function pingPeer(options: PingPeerOptions): Promise { assertPeerToolsEnabled() const knownSessionId = (options.sessionId ?? '').trim() @@ -750,11 +792,12 @@ export async function pingPeer(options: PingPeerOptions): Promise { @@ -191,3 +193,78 @@ describe('isSteeringSupportedForSession', () => { expect(isSteeringSupportedForSession(null)).toBe(false) }) }) + +describe('hasActiveSteeringTurn', () => { + it.each(['claude', 'codex', 'cursor', 'opencode'])('uses steeringActive rather than thinking for %s', (flavor) => { + expect(hasActiveSteeringTurn({ metadata: { flavor }, thinking: false, + agentState: { steeringActive: true } })).toBe(true) + expect(hasActiveSteeringTurn({ metadata: { flavor }, thinking: true, + agentState: { steeringActive: false } })).toBe(false) + expect(hasActiveSteeringTurn({ metadata: { flavor }, thinking: true })).toBe(false) + }) + + it('uses the Pi runtime thinking signal', () => { + expect(hasActiveSteeringTurn({ metadata: { flavor: 'pi' }, thinking: true, + agentState: { steeringActive: false } })).toBe(true) + expect(hasActiveSteeringTurn({ metadata: { flavor: 'pi' }, thinking: false, + agentState: { steeringActive: true } })).toBe(false) + }) + + it.each([ + null, undefined, { flavor: 'gemini' }, { flavor: 'unknown' }, + { flavor: '__proto__' }, { flavor: 'constructor' }, + { flavor: 'cursor', cursorSessionProtocol: 'stream-json' as const }, + { flavor: 'cursor', cursorSessionId: 'legacy' }, + ])('rejects unsupported metadata even when every turn signal is true: %j', (metadata) => { + expect(hasActiveSteeringTurn({ metadata, thinking: true, + agentState: { steeringActive: true } })).toBe(false) + expect(isSteeringSupportedForSession(metadata)).toBe(false) + if (metadata?.flavor !== 'cursor') { + expect(isSteeringSupportedForFlavor(metadata?.flavor)).toBe(false) + } + }) +}) + +describe('steering support table', () => { + // The pre-table branching, kept as the reference the table must match. + type Metadata = { flavor?: string | null; cursorSessionId?: string | null; cursorSessionProtocol?: 'acp' | 'stream-json' | null } + function referenceSupportsSession(metadata?: Metadata | null): boolean { + if (metadata?.flavor === 'claude' || metadata?.flavor === 'codex' + || metadata?.flavor === 'opencode' || metadata?.flavor === 'pi') return true + if (metadata?.flavor !== 'cursor') return false + if (metadata.cursorSessionProtocol === 'stream-json') return false + if (!metadata.cursorSessionProtocol && metadata.cursorSessionId) return false + return true + } + + const flavors = [ + 'claude', 'codex', 'cursor', 'opencode', 'pi', 'gemini', 'agy', 'unknown', '', + '__proto__', 'constructor', 'toString', null, undefined, + ] + const cursorShapes: Array> = [ + {}, { cursorSessionId: 'id' }, { cursorSessionId: null }, { cursorSessionProtocol: 'acp' }, + { cursorSessionProtocol: 'stream-json' }, { cursorSessionProtocol: null }, + { cursorSessionId: 'id', cursorSessionProtocol: 'acp' }, + { cursorSessionId: 'id', cursorSessionProtocol: 'stream-json' }, + { cursorSessionId: 'id', cursorSessionProtocol: null }, + ] + + it('gives the same session answer as the previous branching for every flavor and Cursor shape', () => { + for (const flavor of flavors) { + for (const shape of cursorShapes) { + const metadata = { flavor, ...shape } + expect(isSteeringSupportedForSession(metadata), JSON.stringify(metadata)) + .toBe(referenceSupportsSession(metadata)) + } + } + expect(isSteeringSupportedForSession(null)).toBe(referenceSupportsSession(null)) + expect(isSteeringSupportedForSession(undefined)).toBe(referenceSupportsSession(undefined)) + }) + + it('answers the flavor-only gate from the same flavor list', () => { + for (const flavor of flavors) { + expect(isSteeringSupportedForFlavor(flavor), String(flavor)) + .toBe((STEERING_SUPPORTED_FLAVORS as readonly string[]).includes(flavor ?? '')) + } + }) +}) diff --git a/shared/src/modes.ts b/shared/src/modes.ts index 8c374f10..fccdf60f 100644 --- a/shared/src/modes.ts +++ b/shared/src/modes.ts @@ -184,6 +184,23 @@ export function getCodexCollaborationModeOptions(): CodexCollaborationModeOption })) } +type SteeringSessionMetadata = { + flavor?: string | null + cursorSessionId?: string | null + cursorSessionProtocol?: 'acp' | 'stream-json' | null +} + +type SteeringSessionState = { + metadata?: SteeringSessionMetadata | null + thinking?: boolean + agentState?: { steeringActive?: boolean | null } | null +} + +type SteeringCapability = { + activeTurnState: 'thinking' | 'steeringActive' + supportsSession?: (metadata: SteeringSessionMetadata) => boolean +} + /** * Flavors that can deliver a queued message into an active turn on demand * (per-message "Steer" from the waiting queue), without waiting for full-turn end. @@ -203,37 +220,49 @@ export function getCodexCollaborationModeOptions(): CodexCollaborationModeOption */ export const STEERING_SUPPORTED_FLAVORS = ['claude', 'codex', 'cursor', 'opencode', 'pi'] as const +type SteeringFlavor = typeof STEERING_SUPPORTED_FLAVORS[number] + +// Keep protocol restrictions and the runtime's active-turn signal together so +// peer senders and the waiting queue do not need their own flavor branches. +const STEERING_CAPABILITIES = { + claude: { activeTurnState: 'steeringActive' }, + codex: { activeTurnState: 'steeringActive' }, + cursor: { + activeTurnState: 'steeringActive', + supportsSession: (metadata: SteeringSessionMetadata) => + metadata.cursorSessionProtocol !== 'stream-json' + && (Boolean(metadata.cursorSessionProtocol) || !metadata.cursorSessionId) + }, + opencode: { activeTurnState: 'steeringActive' }, + pi: { activeTurnState: 'thinking' } +} satisfies Record + +function getSteeringCapability(flavor?: string | null): SteeringCapability | undefined { + if (!flavor || !Object.hasOwn(STEERING_CAPABILITIES, flavor)) return undefined + return STEERING_CAPABILITIES[flavor as SteeringFlavor] +} + export function isSteeringSupportedForFlavor(flavor?: string | null): boolean { - return (STEERING_SUPPORTED_FLAVORS as readonly string[]).includes(flavor ?? '') + return getSteeringCapability(flavor) !== undefined } /** - * Session-aware steer gate. Prefer this over {@link isSteeringSupportedForFlavor} - * when metadata is available: legacy Cursor stream-json sessions advertise - * flavor `cursor` but cannot steer. - * - * Matches CLI legacy detection: explicit `stream-json`, or a pre-ACP session - * that has `cursorSessionId` without `cursorSessionProtocol: 'acp'`. + * Session-aware steer gate. Legacy Cursor stream-json sessions advertise + * flavor `cursor` but cannot steer, including pre-ACP sessions with only an id. + * Native admission and remote-control checks remain the caller's responsibility. */ -export function isSteeringSupportedForSession(metadata?: { - flavor?: string | null - cursorSessionId?: string | null - cursorSessionProtocol?: 'acp' | 'stream-json' | null -} | null): boolean { - if (metadata?.flavor === 'claude' - || metadata?.flavor === 'codex' - || metadata?.flavor === 'opencode' - || metadata?.flavor === 'pi') { - return true - } - if (metadata?.flavor !== 'cursor') { - return false - } - if (metadata.cursorSessionProtocol === 'stream-json') { - return false - } - if (!metadata.cursorSessionProtocol && metadata.cursorSessionId) { - return false - } - return true +export function isSteeringSupportedForSession(metadata?: SteeringSessionMetadata | null): boolean { + const capability = getSteeringCapability(metadata?.flavor) + return capability !== undefined && (capability.supportsSession?.(metadata ?? {}) ?? true) +} + +/** + * Whether the provider reports an active steerable turn. This does not imply + * that the session is active, remotely controlled, or will accept a native steer. + */ +export function hasActiveSteeringTurn(session: SteeringSessionState): boolean { + if (!isSteeringSupportedForSession(session.metadata)) return false + return getSteeringCapability(session.metadata?.flavor)?.activeTurnState === 'thinking' + ? session.thinking === true + : session.agentState?.steeringActive === true } diff --git a/shared/src/sessionCitation.test.ts b/shared/src/sessionCitation.test.ts index 3ca62bac..03508910 100644 --- a/shared/src/sessionCitation.test.ts +++ b/shared/src/sessionCitation.test.ts @@ -106,8 +106,9 @@ describe('buildSessionCitationSteerInstruction', () => { expect(text).toContain(PEER_DELIVERY_MODE_DESCRIPTION) expect(PING_PEER_TOOL_DESCRIPTION).toContain(PEER_DELIVERY_MODE_DESCRIPTION) expect(text).toContain('auto (default)') - expect(text).toContain('active Codex turn') - expect(text).toContain('Auto currently queues for other agent flavors') + expect(text).toContain('active turn when the target supports steering and is ready') + expect(text).toContain('auto retains the same single accepted message without resending') + expect(text).not.toContain('Auto currently queues for other agent flavors') expect(text).toContain('Prefer auto for routine collaboration when queueing is an acceptable fallback') expect(text).toContain('queue: explicitly defer non-urgent updates') expect(text).toContain('steer: use for important, time-sensitive findings the peer needs to know now') diff --git a/shared/src/sessionCitation.ts b/shared/src/sessionCitation.ts index 57d0781e..ad4680b6 100644 --- a/shared/src/sessionCitation.ts +++ b/shared/src/sessionCitation.ts @@ -79,13 +79,14 @@ export const LIST_PEERS_TOOL_DESCRIPTION = /** Shared delivery guidance for the peer MCP schemas, descriptions, and prompts. */ export const PEER_DELIVERY_MODE_DESCRIPTION = - 'auto (default): steer an active Codex turn when steering is available; otherwise queue. ' + - 'Auto currently queues for other agent flavors. Prefer auto for routine collaboration when queueing is an acceptable fallback. ' + + 'auto (default): steer an active turn when the target supports steering and is ready; otherwise queue. Inactive peers require explicit wake=true and then receive a queued message. ' + + 'Prefer auto for routine collaboration when queueing is an acceptable fallback. ' + + 'If steering cannot be confirmed after acceptance, auto retains the same single accepted message without resending; accepted does not confirm consumption. ' + 'queue: explicitly defer non-urgent updates that can wait instead of steering. ' + 'steer: use for important, time-sensitive findings the peer needs to know now, not after finishing its current turn ' + '(e.g. a correction that invalidates its assumptions, a blocker, or a result that changes its next action). ' + 'State why the finding matters now and what the peer should adjust. ' + - 'Steer requires insertion into an active Claude, Pi, Codex, or Cursor ACP turn; unsupported, idle, or inactive targets are rejected before sending. ' + + 'Steer requires insertion into an active Claude, Pi, Codex, OpenCode, or Cursor ACP turn; unsupported, idle, or inactive targets are rejected before sending. ' + 'Steering does not abort the current turn or guarantee an immediate response. ' + 'If send or steer is unconfirmed after submission, inspect the target before retrying; do not resend automatically.' diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index 492a095a..572bd2a1 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -63,7 +63,7 @@ import { type ComposerSendIntent, } from '@/lib/messageDelivery' import type { MessageDeliveryMode } from '@hapi/protocol' -import { isSteeringSupportedForSession } from '@hapi/protocol' +import { hasActiveSteeringTurn } from '@hapi/protocol' import { AGY_MODEL_LABELS, AGY_MODEL_PRESETS, getAgyModelChoices, splitAgyModelSelection, getClaudeEffortLevelsForModel, resolveClaudeEffortForModel } from '@hapi/protocol' import { getClaudeCatalogOptions } from '@/components/AssistantChat/modelOptions' import { createAttachmentAdapter } from '@/lib/attachmentAdapter' @@ -2205,10 +2205,7 @@ function SessionChatInner(props: SessionChatProps) { }} deliveryActive={props.session.active && props.session.thinking} canSteer={props.session.active && props.session.thinking - && isSteeringSupportedForSession(props.session.metadata) - && (agentFlavor === 'pi' - ? props.session.thinking - : props.session.agentState?.steeringActive === true) + && hasActiveSteeringTurn(props.session) && !controlledByUser} />