fix(web): bind prompts to plan selection

This commit is contained in:
fz
2026-07-24 16:33:53 +08:00
parent 14524880b6
commit 76450b0c55
14 changed files with 252 additions and 21 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ The layering/protocol decisions are recorded in the [GUI layering and RPC protoc
The mux stream projects the latest log-backed title as a validated `session/title` control frame after each attached-session subscription baseline and immediately after the corresponding live raw title event. This projection does not add titles to `session.list`; cold sessions remain metadata-only there until opening or resuming attaches their logs.
Plan mode uses two unary methods instead of deriving current state from a history page: `session.planMode` returns the committed state plus any boundary-pending selection, and `session.setPlanMode` records a selection and returns the same authoritative shape. A present `pending` target must differ from `active`; a net-zero service cleanup intent projects as `{ active }`, and the wire schema rejects equal values. Both methods return `null` when the optional host service is absent; `null` is capability absence, while `{ active: false }` is a supported inactive session. Committed changes still arrive through the raw logged `plan/mode` session event.
Plan mode uses two unary methods instead of deriving current state from a history page: `session.planMode` returns the committed state plus any boundary-pending selection, and `session.setPlanMode` records a selection and returns the same authoritative shape. A present `pending` target must differ from `active`; a net-zero service cleanup intent projects as `{ active }`, and the wire schema rejects equal values. Both methods return `null` when the optional host service is absent; `null` is capability absence, while `{ active: false }` is a supported inactive session. Committed changes still arrive through the raw logged `plan/mode` session event. `session.prompt` may carry a `planMode` target so the host records that selection immediately before accepting the prompt; it fails when the capability is absent and restores the prior target after a synchronous prompt rejection.
## Carrier layer (`/client` + root)
@@ -92,6 +92,7 @@ export const sessionPromptRequestSchema = z.object({
sessionId: sessionIdSchema,
mode: z.union([z.literal('queue'), z.literal('steer')]),
content: z.array(contentBlockSchema),
planMode: z.boolean().optional(),
}) as unknown as z.ZodType<RequestPayload<'session.prompt'>>
/** session.prompt response value. */
+11 -2
View File
@@ -74,8 +74,17 @@ export interface SessionsApi {
history(request: RpcRequest<{ sessionId: SessionId; beforeSeq?: number; maxMessages?: number }>):
Promise<RpcResponse<{ events: HistoryEntry[]; hasMore: boolean }>>
/** Sends a message. content is core's ContentBlock[] verbatim; mode maps 1:1 — queue→send, steer→steer. */
prompt(request: RpcRequest<{ sessionId: SessionId; mode: 'queue' | 'steer'; content: ContentBlock[] }>):
/**
* Sends a message. `content` is core's ContentBlock[] verbatim and `mode`
* maps 1:1 — queue→send, steer→steer. An optional `planMode` target is
* admitted atomically with the prompt.
*/
prompt(request: RpcRequest<{
sessionId: SessionId
mode: 'queue' | 'steer'
content: ContentBlock[]
planMode?: boolean
}>):
Promise<RpcResponse<{ accepted: true }>>
/** Stops: clears both FIFOs + aborts the current step (1:1 with agent.cancel). */
@@ -84,7 +84,12 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
it('covers create/prompt/cancel/plan/describe passthrough', async () => {
const c = client()
expect((await c.sessions.create({})).result.ok).toBe(true)
expect((await c.sessions.prompt({ sessionId: 's' as never, mode: 'queue', content: [{ type: 'text', text: 'x' }] })).result.ok).toBe(true)
expect((await c.sessions.prompt({
sessionId: 's' as never,
mode: 'queue',
content: [{ type: 'text', text: 'x' }],
planMode: true,
})).result.ok).toBe(true)
expect((await c.sessions.cancel({ sessionId: 's' as never })).result.ok).toBe(true)
expect((await c.sessions.planMode({ sessionId: 's' as never })).result).toEqual({ ok: true, value: null })
expect((await c.sessions.setPlanMode({ sessionId: 's' as never, active: true })).result).toEqual({ ok: true, value: null })
@@ -101,9 +101,14 @@ describe('sessions domain schemas', () => {
expect(sessionHistoryRequestSchema.parse({ sessionId: 's1', beforeSeq: 3, maxMessages: 5 }).beforeSeq).toBe(3)
expect(() => sessionHistoryRequestSchema.parse({ sessionId: 's1', maxMessages: 0 })).toThrow()
expect(sessionHistoryValueSchema.parse({ events: [], hasMore: false }).hasMore).toBe(false)
const prompt = sessionPromptRequestSchema.parse({ sessionId: 's1', mode: 'queue', content: [{ type: 'text', text: 'hi' }] })
expect(prompt.mode).toBe('queue')
const prompt = sessionPromptRequestSchema.parse({
sessionId: 's1', mode: 'queue', content: [{ type: 'text', text: 'hi' }], planMode: true,
})
expect(prompt).toMatchObject({ mode: 'queue', planMode: true })
expect(() => sessionPromptRequestSchema.parse({ sessionId: 's1', mode: 'inject', content: [] })).toThrow()
expect(() => sessionPromptRequestSchema.parse({
sessionId: 's1', mode: 'queue', content: [], planMode: 'plan',
})).toThrow()
expect(sessionPromptValueSchema.parse({ accepted: true }).accepted).toBe(true)
expect(sessionCancelRequestSchema.parse({ sessionId: 's1' }).sessionId).toBe('s1')
expect(sessionCancelValueSchema.parse({ accepted: true }).accepted).toBe(true)
+1 -1
View File
@@ -18,7 +18,7 @@ Which plugins mount and with what defaults is decided only here — shells must
## ApiProxy implementation notes
Unary methods take the narrow `RpcRequest<P>` and echo `request.rpcId`; a prompt's rpcId rides `MessageSource` into the `user/message` event so clients can promote optimistic echoes. `history`/`prompt` on a cold session implicitly resume it, deduplicating concurrent calls through an in-flight table; `history` paginates backwards on message boundaries (never mid-message). `planMode` and `setPlanMode` use the same resume path, project the optional `ctx.planMode` service, canonicalize a net-zero cleanup intent by omitting `pending`, and return `null` when the service is not mounted. The mux stream replays a `session/subscribed` baseline per attached session and every still-pending question with its original rpcId. Question responses, including blank per-item answers, are validated against the owning session and exact request before an atomic first-wins claim; answer, whole-request cancellation, owner abort, and provider disposal broadcast `question/resolved`. The host stream carries session lifecycle, running flips, and `agent/error` as the only outlet for live failures with no turn position.
Unary methods take the narrow `RpcRequest<P>` and echo `request.rpcId`; a prompt's rpcId rides `MessageSource` into the `user/message` event so clients can promote optimistic echoes. `history`/`prompt` on a cold session implicitly resume it, deduplicating concurrent calls through an in-flight table; `history` paginates backwards on message boundaries (never mid-message). `planMode` and `setPlanMode` use the same resume path, project the optional `ctx.planMode` service, canonicalize a net-zero cleanup intent by omitting `pending`, and return `null` when the service is not mounted. A prompt carrying `planMode` sets that target and admits the message without an intervening await; missing capability fails closed, while synchronous admission failure restores the preceding target. The mux stream replays a `session/subscribed` baseline per attached session and every still-pending question with its original rpcId. Question responses, including blank per-item answers, are validated against the owning session and exact request before an atomic first-wins claim; answer, whole-request cancellation, owner abort, and provider disposal broadcast `question/resolved`. The host stream carries session lifecycle, running flips, and `agent/error` as the only outlet for live failures with no turn position.
## Model Experience
+15 -1
View File
@@ -443,16 +443,30 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
},
async prompt(request) {
const { sessionId, mode, content } = request.payload
const { sessionId, mode, content, planMode: planTarget } = request.payload
const found = await agentFor(sessionId)
if ('error' in found) return err(request, found.error)
const agent = found.agent
const planMode = ctx.get('planMode')
if (planTarget !== undefined && planMode === undefined) {
return err(request, {
code: 'internal',
message: 'prompt requested plan mode, but this host does not provide it',
details: {},
})
}
// No await separates selection from admission: another unary request
// cannot interleave a different target between these two operations.
const priorPlanState = planTarget === undefined ? undefined : planMode?.get(agent)
const priorPlanTarget = priorPlanState?.pending ?? priorPlanState?.active
if (planTarget !== undefined) planMode?.set(agent, planTarget)
// The rpcId rides MessageSource into user/message (merge declaration in api/sessions.ts; provisional correlation).
const source: MessageSource = { kind: 'user', rpcId: request.rpcId }
try {
if (mode === 'steer') agent.steer(content, { source })
else agent.send(content, { source })
} catch (error: unknown) {
if (priorPlanTarget !== undefined) planMode?.set(agent, priorPlanTarget)
// A synchronous throw from send/steer means disposed or invalid input; surface as agent-busy with the reason attached.
return err(request, { code: 'agent-busy', message: 'prompt rejected', details: { reason: String(error) } })
}
@@ -273,6 +273,72 @@ describe('sessions.planMode / setPlanMode', () => {
})
describe('sessions.prompt / cancel', () => {
it('admits a prompt and its plan target through one host operation', async () => {
const running = await boot([textResponse('planned')])
await running.ctx.plugin(PlanModeService, { section: 'Plan before acting.' })
const { sessionId } = expectOk(await running.api.sessions.create(request({})))
const agent = running.ctx.agents.get(sessionId) as Agent
const idle = waitForIdle(running.ctx, agent)
expectOk(await running.api.sessions.prompt(request({
sessionId,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'plan this' }],
planMode: true,
})))
await idle
const planEvent = agent.session.events.find(event => event.type === 'plan/mode')
const userEvent = agent.session.events.find(event => event.type === 'user/message')
const header = agent.session.events.find(event => event.type === 'request/header')
expect(planEvent?.type === 'plan/mode' && planEvent.data.active).toBe(true)
expect(planEvent?.seq).toBeLessThan(userEvent?.seq ?? Number.POSITIVE_INFINITY)
expect(header?.type === 'request/header' && header.data.header.system).toContain('Plan before acting.')
})
it('rolls back the plan target when prompt admission is rejected', async () => {
const running = await boot()
await running.ctx.plugin(PlanModeService, { section: 'Plan before acting.' })
const { sessionId } = expectOk(await running.api.sessions.create(request({})))
const agent = running.ctx.agents.get(sessionId) as Agent
const send = vi.spyOn(agent, 'send').mockImplementation(() => {
throw new Error('closed for admission')
})
try {
const response = await running.api.sessions.prompt(request({
sessionId,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'plan this' }],
planMode: true,
}))
expect(response.result).toMatchObject({
ok: false,
error: { code: 'agent-busy', details: { reason: 'Error: closed for admission' } },
})
expect(expectOk(await running.api.sessions.planMode(request({ sessionId })))).toEqual({
active: false,
})
} finally {
send.mockRestore()
}
})
it('fails closed when a prompt targets unavailable plan mode', async () => {
const running = await boot()
const { sessionId } = expectOk(await running.api.sessions.create(request({})))
const response = await running.api.sessions.prompt(request({
sessionId,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'must not run ambiguously' }],
planMode: true,
}))
expect(response.result).toMatchObject({
ok: false,
error: { code: 'internal', message: 'prompt requested plan mode, but this host does not provide it' },
})
expect((running.ctx.agents.get(sessionId) as Agent).session.events).toEqual([])
})
it.each([
{ name: 'host default', config: true, target: '5 words', maxTokens: 64 },
{