AI-native design editor. Open-source Figma alternative.
fix(ai): keep a Pi session when its reply is stopped (#1126)
Danila Poyarkov48464a9b8093
diff --git a/changes/1126/fixed.md b/changes/1126/fixed.mdnew file mode 100644index 000000000..640ac82a4--- /dev/null+++ b/changes/1126/fixed.md@@ -0,0 +1 @@+- Stopping a Pi reply in the desktop app cancels that turn and keeps the session. Pi remembers the conversation and its sandbox for your next message. Before, the stop raised an error, dropped the connection, and started a new Pi process, leaving the old one running.diff --git a/packages/harness/src/service.ts b/packages/harness/src/service.tsindex 036ca6ec4..2fc6663c0 100644--- a/packages/harness/src/service.ts+++ b/packages/harness/src/service.ts@@ -5,6 +5,8 @@ import type { ResumeStateStore } from './session-store'export class HarnessSessionService {private readonly sessions = new Map<string, BackendSession>()private readonly turns = new Map<string, AbortController>()+ /** Sessions whose last turn ended because it was cancelled. */+ private readonly cancelled = new Set<string>()constructor(private readonly backends: ReadonlyMap<string, HarnessBackend>,@@ -57,9 +59,16 @@ export class HarnessSessionService {} finally {signal?.removeEventListener('abort', abort)if (this.turns.get(sessionId) === controller) this.turns.delete(sessionId)+ if (controller.signal.aborted) this.cancelled.add(sessionId)+ else this.cancelled.delete(sessionId)}}+ /** Whether the session's last turn ended because it was cancelled, not because it finished. */+ lastTurnCancelled(sessionId: string): boolean {+ return this.cancelled.has(sessionId)+ }+cancelTurn(sessionId: string): void {this.requireSession(sessionId)this.turns.get(sessionId)?.abort()@@ -70,6 +79,7 @@ export class HarnessSessionService {const state = await session.stop()await this.store.save(sessionId, state)this.sessions.delete(sessionId)+ this.cancelled.delete(sessionId)}/**@@ -92,6 +102,7 @@ export class HarnessSessionService {await session.destroy()await this.store.remove(sessionId)this.sessions.delete(sessionId)+ this.cancelled.delete(sessionId)}async shutdown(): Promise<void> {diff --git a/packages/harness/src/stdio.ts b/packages/harness/src/stdio.tsindex f69d9dbce..8d9748dd6 100644--- a/packages/harness/src/stdio.ts+++ b/packages/harness/src/stdio.ts@@ -74,10 +74,17 @@ async function dispatch(line: string): Promise<boolean> {return true}if (request.method === 'session.turn') {- for await (const event of service.runTurn(request.params.sessionId, request.params.prompt)) {+ const { sessionId, prompt } = request.params+ for await (const event of service.runTurn(sessionId, prompt)) {await emit({ type: 'turn.event', id: request.id, event })}- await emit({ type: 'response', id: request.id, result: { completed: true } })+ // A cancelled turn ends its stream quietly; its answer says it was cancelled.+ const cancelled = service.lastTurnCancelled(sessionId)+ await emit({+ type: 'response',+ id: request.id,+ result: cancelled ? { cancelled: true } : { completed: true }+ })return true}if (request.method === 'session.cancel') {diff --git a/packages/harness/tests/service.test.ts b/packages/harness/tests/service.test.tsindex 158381026..7175bec2d 100644--- a/packages/harness/tests/service.test.ts+++ b/packages/harness/tests/service.test.ts@@ -121,6 +121,22 @@ describe('HarnessSessionService', () => {expect(await service.createSession('session-1', configuration)).toEqual({ isResume: true })})+ test('says whether a turn ended because it was cancelled', async () => {+ const backend = new FakeBackend()+ const service = new HarnessSessionService(new Map([[backend.id, backend]]), new MemoryStore())+ await service.createSession('session', configuration)++ for await (const event of service.runTurn('session', 'count')) {+ if (event.type === 'text-delta') service.cancelTurn('session')+ }+ expect(service.lastTurnCancelled('session')).toBeTrue()++ for await (const _event of service.runTurn('session', 'again')) {+ // A turn that runs to its end.+ }+ expect(service.lastTurnCancelled('session')).toBeFalse()+ })+test('destroys a session and removes resumability', async () => {const backend = new FakeBackend('persistent')const store = new MemoryStore()diff --git a/src/app/ai/harness/transport.ts b/src/app/ai/harness/transport.tsindex 2e9dc4241..af3e2078b 100644--- a/src/app/ai/harness/transport.ts+++ b/src/app/ai/harness/transport.ts@@ -25,6 +25,18 @@ function requestID(): string {return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('')}+/** Sends chunks to a reply still being read; once it finished or was cancelled, they are dropped. */+function emit(pending: PendingRequest, ...chunks: UIMessageChunk[]): void {+ for (const chunk of chunks) pending.controller?.enqueue(chunk)+}++/** Ends a reply's stream, once; later events for its turn go nowhere. */+function close(pending: PendingRequest): void {+ const { controller } = pending+ pending.controller = undefined+ controller?.close()+}+function mapEvent(event: HarnessTurnEvent, pending: PendingRequest): UIMessageChunk[] {const chunks: UIMessageChunk[] = []if (event.type === 'text-delta') {@@ -95,39 +107,51 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {.map((part) => part.text).join('\n') ?? ''const requestId = requestID()+ const pending = this.createPending(requestId)+ let cancelled = false+ // Stop cancels the turn, which keeps its session and sandbox. The turn's entry stays until+ // the companion answers it, so that answer and any late events are consumed, not misread.+ const cancel = () => {+ if (cancelled) return+ cancelled = true+ void process+ .send({ id: requestID(), method: 'session.cancel', params: { sessionId: this.sessionId } })+ .catch(this.fail)+ }return new ReadableStream<UIMessageChunk>({start: (controller) => {- const pending = this.createPending(requestId)pending.controller = controller- this.pending.set(requestId, pending)- controller.enqueue({ type: 'start' })- controller.enqueue({ type: 'start-step' })- const cancel = () => {- void process- .send({- id: requestID(),- method: 'session.cancel',- params: { sessionId: this.sessionId }- })- .catch((error) =>- this.failAll(error instanceof Error ? error : new Error(String(error)))- )- }+ emit(pending, { type: 'start' }, { type: 'start-step' })if (abortSignal?.aborted) {- cancel()- controller.enqueue({ type: 'finish-step' })- controller.enqueue({ type: 'finish', finishReason: 'stop' })- controller.close()- this.pending.delete(requestId)+ emit(pending, { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })+ close(pending)return}- abortSignal?.addEventListener('abort', cancel, { once: true })- void process.send({- id: requestId,- method: 'session.turn',- params: { sessionId: this.sessionId, prompt: text }- })+ this.pending.set(requestId, pending)+ abortSignal?.addEventListener(+ 'abort',+ () => {+ // A turn already answered has nothing to stop, and a cancel now would hit the next one.+ if (!this.pending.has(requestId)) return+ cancel()+ emit(pending, { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })+ close(pending)+ },+ { once: true }+ )+ void process+ .send({+ id: requestId,+ method: 'session.turn',+ params: { sessionId: this.sessionId, prompt: text }+ })+ .catch(this.fail)+ },+ // The reader went away, as Stop makes it: nothing more is read from this turn.+ cancel: () => {+ pending.controller = undefined+ cancel()}})}@@ -221,48 +245,46 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {const message = next.valueif (message.type === 'turn.event') {const pending = this.pending.get(message.id)- if (pending?.controller) {- for (const chunk of mapEvent(message.event, pending)) pending.controller.enqueue(chunk)- }+ if (pending) emit(pending, ...mapEvent(message.event, pending))} else {const pending = this.pending.get(message.id)if (pending) {this.pending.delete(message.id)if (message.error) {const error = new Error(message.error)- pending.controller?.enqueue({ type: 'error', errorText: error.message })+ emit(pending, { type: 'error', errorText: error.message })pending.reject(error)} else {if (pending.reasoningStarted) {- pending.controller?.enqueue({- type: 'reasoning-end',- id: `reasoning-${pending.textId}`- })- }- if (pending.textStarted) {- pending.controller?.enqueue({ type: 'text-end', id: pending.textId })+ emit(pending, { type: 'reasoning-end', id: `reasoning-${pending.textId}` })}- pending.controller?.enqueue({ type: 'finish-step' })- pending.controller?.enqueue({ type: 'finish', finishReason: 'stop' })+ if (pending.textStarted) emit(pending, { type: 'text-end', id: pending.textId })+ emit(pending, { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })pending.resolve(message)}- pending.controller?.close()+ close(pending)}}next = await reader.read()}} catch (error) {- this.failAll(error instanceof Error ? error : new Error(String(error)))+ // A process whose messages can no longer be read is given up on, so it must not outlive it.+ await process.child.kill().catch(() => undefined)+ this.fail(error)}}+ private readonly fail = (error: unknown): void => {+ this.failAll(error instanceof Error ? error : new Error(String(error)))+ }+private failAll(error: Error): void {if (this.destroyed) returnthis.process = nullthis.sessionCreated = falsefor (const pending of this.pending.values()) {- pending.controller?.enqueue({ type: 'error', errorText: error.message })- pending.controller?.close()+ emit(pending, { type: 'error', errorText: error.message })+ close(pending)pending.reject(error)}this.pending.clear()diff --git a/tests/app/ai/harness/transport.test.ts b/tests/app/ai/harness/transport.test.tsnew file mode 100644index 000000000..ed8a6f1aa--- /dev/null+++ b/tests/app/ai/harness/transport.test.ts@@ -0,0 +1,205 @@+import { expect, test } from 'bun:test'++import type { HarnessSidecarMessage } from '@open-pencil/harness'++import { HarnessChatTransport } from '@/app/ai/harness/transport'++test('failed session stop kills the process without deleting resume state', async () => {+ let output: ReadableStreamDefaultController<HarnessSidecarMessage> | undefined+ const methods: string[] = []+ let kills = 0+ const transport = new HarnessChatTransport(+ 'test-session',+ {+ adapter: 'pi',+ sandbox: 'just-bash',+ model: 'test',+ settings: {},+ instructions: '',+ mcpServers: {}+ },+ {},+ async () => ({+ child: {+ write: async () => undefined,+ kill: async () => {+ kills+++ output?.close()+ }+ },+ messages: new ReadableStream({+ start(controller) {+ output = controller+ }+ }),+ send: async (request) => {+ if (+ !('id' in request) ||+ !('method' in request) ||+ typeof request.id !== 'string' ||+ typeof request.method !== 'string'+ )+ throw new Error('Invalid request')+ methods.push(request.method)+ output?.enqueue({+ type: 'response',+ id: request.id,+ ...(request.method === 'session.stop'+ ? { error: 'Resume storage failed' }+ : { result: {} })+ })+ }+ })+ )+ const stream = await transport.sendMessages({+ chatId: 'test',+ trigger: 'submit-message',+ messageId: undefined,+ messages: [{ id: 'user', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }],+ abortSignal: undefined+ })+ const reader = stream.getReader()+ while (!(await reader.read()).done) {+ /* Drain the completed turn. */+ }+ await expect(transport.stop()).rejects.toThrow('Resume storage failed')+ expect(kills).toBe(1)+ expect(methods).toContain('session.stop')+ expect(methods).not.toContain('session.destroy')+ await transport.stop()+ expect(kills).toBe(1)+})++const configuration = {+ adapter: 'pi',+ sandbox: 'just-bash',+ model: 'test',+ settings: {},+ instructions: '',+ mcpServers: {}+} as const++/**+ * A companion that answers session requests at once and holds each turn open, so the test+ * decides when its events and its answer arrive, as Pi's do after a Stop.+ */+function fakeCompanion({ turnsFail = false } = {}) {+ let output: ReadableStreamDefaultController<HarnessSidecarMessage> | undefined+ const methods: string[] = []+ const turns: string[] = []+ let spawns = 0+ const spawn = async () => {+ spawns+++ return {+ child: { write: async () => undefined, kill: async () => output?.close() },+ messages: new ReadableStream<HarnessSidecarMessage>({+ start(controller) {+ output = controller+ }+ }),+ send: async (request: object) => {+ if (!('id' in request) || !('method' in request)) throw new Error('Invalid request')+ const { id, method } = request+ if (typeof id !== 'string' || typeof method !== 'string') throw new Error('Invalid request')+ methods.push(method)+ if (method === 'session.turn' && turnsFail) throw new Error('Pipe closed')+ if (method === 'session.turn') turns.push(id)+ else output?.enqueue({ type: 'response', id, result: {} })+ }+ }+ }+ return {+ spawn,+ methods,+ get spawns() {+ return spawns+ },+ /** The turn's next event or its final answer, as the companion would send it. */+ text: (turn: string, text: string) =>+ output?.enqueue({ type: 'turn.event', id: turn, event: { type: 'text-delta', text } }),+ complete: (turn: string) =>+ output?.enqueue({ type: 'response', id: turn, result: { completed: true } }),+ turns+ }+}++function send(transport: HarnessChatTransport, abortSignal?: AbortSignal) {+ return transport.sendMessages({+ chatId: 'test',+ trigger: 'submit-message',+ messageId: undefined,+ messages: [{ id: crypto.randomUUID(), role: 'user', parts: [{ type: 'text', text: 'Hi' }] }],+ abortSignal+ })+}++test('stopping a turn keeps the session, and its late events and answer are ignored', async () => {+ const companion = fakeCompanion()+ const transport = new HarnessChatTransport('stop-session', configuration, {}, companion.spawn)+ const stop = new AbortController()+ const reader = (await send(transport, stop.signal)).getReader()+ await Promise.resolve()+ const [first = ''] = companion.turns+ companion.text(first, 'one')++ // As the AI SDK's Chat.stop does: abort the request, then drop the reader.+ stop.abort()+ await reader.cancel()+ companion.text(first, 'two')+ companion.complete(first)+ await Promise.resolve()++ const next = (await send(transport)).getReader()+ await Promise.resolve()+ const second = companion.turns.at(1) ?? ''+ companion.text(second, 'pong')+ companion.complete(second)+ const chunks: string[] = []+ for (let read = await next.read(); !read.done; read = await next.read()) {+ if (read.value.type === 'text-delta') chunks.push(read.value.delta)+ }++ expect(chunks).toEqual(['pong'])+ expect(companion.spawns).toBe(1)+ expect(companion.methods.filter((method) => method === 'session.create')).toHaveLength(1)+ expect(companion.methods.filter((method) => method === 'session.cancel')).toHaveLength(1)+ await transport.destroy()+})++test('stopping a turn that already ended does not cancel the next one', async () => {+ const companion = fakeCompanion()+ const transport = new HarnessChatTransport('late-stop', configuration, {}, companion.spawn)+ const stop = new AbortController()+ const reader = (await send(transport, stop.signal)).getReader()+ await Promise.resolve()+ companion.complete(companion.turns[0] ?? '')+ while (!(await reader.read()).done);++ const next = (await send(transport)).getReader()+ await Promise.resolve()+ stop.abort()+ const second = companion.turns.at(1) ?? ''+ companion.text(second, 'pong')+ companion.complete(second)+ const chunks: string[] = []+ for (let read = await next.read(); !read.done; read = await next.read()) {+ if (read.value.type === 'text-delta') chunks.push(read.value.delta)+ }++ expect(chunks).toEqual(['pong'])+ expect(companion.methods).not.toContain('session.cancel')+ await transport.destroy()+})++test('a turn the companion could not be sent ends with an error', async () => {+ const companion = fakeCompanion({ turnsFail: true })+ const transport = new HarnessChatTransport('broken-pipe', configuration, {}, companion.spawn)+ const reader = (await send(transport)).getReader()+ const types: string[] = []+ for (let read = await reader.read(); !read.done; read = await reader.read()) {+ types.push(read.value.type)+ }++ expect(types.at(-1)).toBe('error')+ await transport.destroy()+})diff --git a/tests/engine/app/ai/harness/transport.test.ts b/tests/engine/app/ai/harness/transport.test.tsdeleted file mode 100644index fe72622cf..000000000--- a/tests/engine/app/ai/harness/transport.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { expect, test } from 'bun:test'--import type { HarnessSidecarMessage } from '@open-pencil/harness'--import { HarnessChatTransport } from '@/app/ai/harness/transport'--test('failed session stop kills the process without deleting resume state', async () => {- let output: ReadableStreamDefaultController<HarnessSidecarMessage> | undefined- const methods: string[] = []- let kills = 0- const transport = new HarnessChatTransport(- 'test-session',- {- adapter: 'pi',- sandbox: 'just-bash',- model: 'test',- settings: {},- instructions: '',- mcpServers: {}- },- {},- async () => ({- child: {- write: async () => undefined,- kill: async () => {- kills++- output?.close()- }- },- messages: new ReadableStream({- start(controller) {- output = controller- }- }),- send: async (request) => {- if (- !('id' in request) ||- !('method' in request) ||- typeof request.id !== 'string' ||- typeof request.method !== 'string'- )- throw new Error('Invalid request')- methods.push(request.method)- output?.enqueue({- type: 'response',- id: request.id,- ...(request.method === 'session.stop'- ? { error: 'Resume storage failed' }- : { result: {} })- })- }- })- )- const stream = await transport.sendMessages({- chatId: 'test',- trigger: 'submit-message',- messageId: undefined,- messages: [{ id: 'user', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }],- abortSignal: undefined- })- const reader = stream.getReader()- while (!(await reader.read()).done) {- /* Drain the completed turn. */- }- await expect(transport.stop()).rejects.toThrow('Resume storage failed')- expect(kills).toBe(1)- expect(methods).toContain('session.stop')- expect(methods).not.toContain('session.destroy')- await transport.stop()- expect(kills).toBe(1)-})diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txtindex 4283a8054..a998c3b4d 100644--- a/tools/checks/test-homes/engine-baseline.txt+++ b/tools/checks/test-homes/engine-baseline.txt@@ -8,7 +8,6 @@ tests/engine/app/ai/attachment/image.test.tstests/engine/app/ai/catalog.test.tstests/engine/app/ai/context.test.tstests/engine/app/ai/failure.test.ts-tests/engine/app/ai/harness/transport.test.tstests/engine/app/ai/markdown.test.tstests/engine/app/ai/model-roles.test.tstests/engine/app/ai/model-settings.test.ts