Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions cockpit/chat/debug/react/src/application.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentSnapshot, Message } from '@threadplane/core';
import type { AgentInterrupt, AgentSnapshot, Message } from '@threadplane/core';
import {
createMessageContent,
type MessageRow,
Expand Down Expand Up @@ -140,7 +140,9 @@ function captureNative(
toolCalls: captureData(
ownField(raw, 'toolCalls')
) as AgentSnapshot['toolCalls'],
interrupts: captureData(ownField(raw, 'interrupts')) as readonly unknown[],
interrupts: captureData(
ownField(raw, 'interrupts')
) as unknown as readonly AgentInterrupt[],
subgraphs: captureData(ownField(raw, 'subgraphs')) as readonly unknown[],
state: values.kind === 'available' ? values.values : undefined,
history,
Expand Down
2 changes: 1 addition & 1 deletion cockpit/chat/interrupts/react/src/application.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ it.each(['confirm', 'cancel'] as const)(
await h.app.submit('Forbidden while paused');
expect(h.session.resume).toHaveBeenCalledTimes(1);
expect(h.session.resume).toHaveBeenCalledWith(
value,
[{ interruptId: 'approval', status: 'resolved', value }],
expect.objectContaining({ signal: expect.any(AbortSignal) })
);
h.result();
Expand Down
25 changes: 22 additions & 3 deletions cockpit/chat/interrupts/react/src/application.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
AgentInterruptResponse,
AgentSession,
CompleteOutcome,
Message,
Expand All @@ -18,11 +19,12 @@ import {
type PauseAuthority,
} from './authority';

export interface InterruptsSession extends Omit<AgentSession, 'getSnapshot'> {
export interface InterruptsSession
extends Omit<AgentSession, 'getSnapshot' | 'resume'> {
getSnapshot(): InterruptsState;
load(options?: { readonly signal?: AbortSignal }): Promise<void>;
resume(
value: 'confirm' | 'cancel',
responses: readonly AgentInterruptResponse[],
options?: { readonly signal?: AbortSignal }
): Promise<CompleteOutcome>;
}
Expand Down Expand Up @@ -387,9 +389,26 @@ export function createInterruptsApplication(options: {
blocked();
return;
}
// A decision answers the one interrupt its authority was captured from.
const interruptId =
'text' in input ? undefined : dispatch.interrupts[0]?.id;
if (!('text' in input) && typeof interruptId !== 'string') {
selected.unsafe = true;
blocked();
return;
}
const outcome = await ('text' in input
? selected.session.submit(input.text, { signal: admitted.signal })
: selected.session.resume(input.value, { signal: admitted.signal }));
: selected.session.resume(
[
{
interruptId: interruptId as string,
status: 'resolved',
value: input.value,
},
],
{ signal: admitted.signal }
));
if (!valid()) return;
const live = read(selected, valid),
turn = selected.turn;
Expand Down
9 changes: 7 additions & 2 deletions cockpit/chat/interrupts/react/src/authority.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { AgentSnapshot, Message, ToolCall } from '@threadplane/core';
import type {
AgentInterrupt,
AgentSnapshot,
Message,
ToolCall,
} from '@threadplane/core';

export interface InterruptsState extends AgentSnapshot {
readonly interrupts: readonly unknown[];
readonly interrupts: readonly AgentInterrupt[];
readonly subgraphs: readonly unknown[];
readonly history:
| readonly {
Expand Down
9 changes: 7 additions & 2 deletions cockpit/chat/subagents/react/src/authority.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { AgentSnapshot, Message, ToolCall } from '@threadplane/core';
import type {
AgentInterrupt,
AgentSnapshot,
Message,
ToolCall,
} from '@threadplane/core';

export interface SubagentsState extends AgentSnapshot {
readonly interrupts: readonly unknown[];
readonly interrupts: readonly AgentInterrupt[];
readonly subgraphs: readonly unknown[];
readonly history:
| readonly {
Expand Down
4 changes: 2 additions & 2 deletions cockpit/chat/threads/react/src/authority.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AgentSnapshot, Message } from '@threadplane/core';
import type { AgentInterrupt, AgentSnapshot, Message } from '@threadplane/core';
export interface ThreadsState extends AgentSnapshot {
readonly interrupts: readonly unknown[];
readonly interrupts: readonly AgentInterrupt[];
readonly subgraphs: readonly unknown[];
readonly history:
| readonly {
Expand Down
9 changes: 7 additions & 2 deletions cockpit/chat/tool-calls/react/src/authority.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { AgentSnapshot, Message, ToolCall } from '@threadplane/core';
import type {
AgentInterrupt,
AgentSnapshot,
Message,
ToolCall,
} from '@threadplane/core';

export interface ToolCallsState extends AgentSnapshot {
readonly interrupts: readonly unknown[];
readonly interrupts: readonly AgentInterrupt[];
readonly subgraphs: readonly unknown[];
readonly history:
| readonly {
Expand Down
17 changes: 12 additions & 5 deletions cockpit/deep-agents/filesystem/react/src/application.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
AgentInterruptResponse,
AgentSession,
AgentSnapshot,
CompleteOutcome,
Expand Down Expand Up @@ -37,11 +38,12 @@ import {
type FilesystemSnapshot,
type Turn,
} from './authority';
export interface FilesystemSession extends Omit<AgentSession, 'getSnapshot'> {
export interface FilesystemSession
extends Omit<AgentSession, 'getSnapshot' | 'resume'> {
getSnapshot(): AgentSnapshot & FilesystemSnapshot;
load(options?: { readonly signal?: AbortSignal }): Promise<void>;
resume(
value: PlainValue,
responses: readonly AgentInterruptResponse[],
options?: { readonly signal?: AbortSignal }
): Promise<CompleteOutcome>;
}
Expand Down Expand Up @@ -497,11 +499,16 @@ export function createFilesystemApplication(client: FilesystemClient) {
(snapshot as FilesystemApplicationSnapshot).phase !== 'confirming'
)
throw Error('Unavailable whole batch');
// The whole batch is one interrupt; its id names the response.
const interruptId = selected.session.getSnapshot().interrupts[0]?.id;
if (typeof interruptId !== 'string')
throw Error('Unavailable whole batch');
publish({ phase: 'working', approval: null, decisionToken: null });
if (!current(run)) return false;
outcome = await selected.session.resume(decision, {
signal: run.controller.signal,
});
outcome = await selected.session.resume(
[{ interruptId, status: 'resolved', value: decision }],
{ signal: run.controller.signal }
);
if (!current(run)) return false;
observe(run);
if (!current(run)) return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ for (const consumed of [false, true]) {
const unsubscribe = session.subscribe(() => publications.push(session.getSnapshot()));
let rejected = false;
try {
await session.resume({ approved: false });
await session.resume([{ interruptId: session.getSnapshot().interrupts[0]?.id ?? 'consumed', status: 'resolved', value: { approved: false } }]);
} catch {
rejected = true;
} finally {
Expand All @@ -159,7 +159,7 @@ for (const consumed of [false, true]) {
expect(position((await api.threads.getState(threadId)).checkpoint)).toEqual(position(approved.checkpoint));
const stillPaused = await api.threads.getState(threadId, pausedPosition);
expect(stillPaused.tasks).toEqual([expect.objectContaining({ id: task.id, result: null, interrupts: task.interrupts })]);
expect(await session.resume({ approved: false })).toBe('success');
expect(await session.resume([{ interruptId: session.getSnapshot().interrupts[0].id, status: 'resolved', value: { approved: false } }])).toBe('success');
expect(transport.creations).toBe(beforeCreations + 1);
const exact = transport.finalPosition();
const rejected = await api.threads.getState(threadId, exact);
Expand Down
12 changes: 9 additions & 3 deletions cockpit/langgraph/interrupts/react/src/app.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function setup(
finish = resolve;
});
const batch = Object.freeze([{ id: 'refund', value: payload }]);
let interrupts: readonly { value: unknown }[] = batch;
let interrupts: readonly { id: string; value: unknown }[] = batch;
const session: InterruptSession = {
getSnapshot: () => ({
status: 'idle',
Expand Down Expand Up @@ -121,7 +121,7 @@ describe('native React refund approval', () => {
await s.pause();
fireEvent.click(s.view.getByRole('button', { name: label }));
expect(s.session.resume).toHaveBeenCalledWith(
{ approved },
[{ interruptId: 'refund', status: 'resolved', value: { approved } }],
expect.any(Object)
);
expect(s.session.submit).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -185,7 +185,13 @@ describe('native React refund approval', () => {
s.view.getByRole('button', { name: 'Approve edited amount' })
);
expect(s.session.resume).toHaveBeenCalledWith(
{ approved: true, amount: 0 },
[
{
interruptId: 'refund',
status: 'resolved',
value: { approved: true, amount: 0 },
},
],
expect.any(Object)
);
});
Expand Down
30 changes: 19 additions & 11 deletions cockpit/langgraph/interrupts/react/src/application.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ function setup() {
const creation = deferred<string>();
const run = deferred<CompleteOutcome>();
const resumed = deferred<CompleteOutcome>();
let snapshot: AgentSnapshot & { interrupts: readonly { value?: unknown }[] } =
Object.freeze({
status: 'idle',
messages: [],
toolCalls: [],
interrupts: Object.freeze([]),
});
let snapshot: AgentSnapshot & {
interrupts: readonly { id: string; value?: unknown }[];
} = Object.freeze({
status: 'idle',
messages: [],
toolCalls: [],
interrupts: Object.freeze([]),
});
const observers = new Set<() => void>();
const release = vi.fn();
const session: InterruptSession = {
Expand Down Expand Up @@ -142,9 +143,10 @@ describe('public interrupts owner', () => {
await s.application.decide(required(decision), response);
await s.application.submit('Duplicate text');
expect(s.session.resume).toHaveBeenCalledTimes(1);
expect(s.session.resume).toHaveBeenCalledWith(response, {
signal: expect.any(AbortSignal),
});
expect(s.session.resume).toHaveBeenCalledWith(
[{ interruptId: 'reused-id', status: 'resolved', value: response }],
{ signal: expect.any(AbortSignal) }
);
expect(s.application.getSnapshot().busy).toBe(true);
expect(s.application.getSnapshot().decision).toBeNull();
expect(s.session.submit).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -244,7 +246,13 @@ describe('public interrupts owner', () => {
const pending = s.application.decide(required(decision), response);
response.amount = 100;
expect(s.session.resume).toHaveBeenCalledWith(
{ approved: true, amount: 25 },
[
{
interruptId: 'reused-id',
status: 'resolved',
value: { approved: true, amount: 25 },
},
],
expect.any(Object)
);
s.resumed.reject(new Error('PRIVATE credential'));
Expand Down
29 changes: 23 additions & 6 deletions cockpit/langgraph/interrupts/react/src/application.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
AgentInterruptResponse,
AgentSession,
AgentSnapshot,
CompleteOutcome,
Expand All @@ -8,12 +9,16 @@ import {
type MessageRow,
} from '@threadplane/content/messages';

export interface InterruptSession extends Omit<AgentSession, 'getSnapshot'> {
export interface InterruptSession
extends Omit<AgentSession, 'getSnapshot' | 'resume'> {
getSnapshot(): AgentSnapshot & {
readonly interrupts: readonly { readonly value?: unknown }[];
readonly interrupts: readonly {
readonly id: string;
readonly value?: unknown;
}[];
};
resume(
value: RefundResponse,
responses: readonly AgentInterruptResponse[],
options?: { readonly signal?: AbortSignal }
): Promise<CompleteOutcome>;
}
Expand Down Expand Up @@ -112,6 +117,8 @@ export function createInterruptsApplication(options: {
let capturedBatch:
| ReturnType<InterruptSession['getSnapshot']>['interrupts']
| undefined;
/** The id of the one interrupt behind the projected decision. */
let capturedId: string | undefined;
let operation: AbortController | undefined;
let disposed = false;
let disposal: Promise<void> | undefined;
Expand All @@ -126,8 +133,13 @@ export function createInterruptsApplication(options: {
if (interrupts === capturedBatch) return;
capturedBatch = interrupts;
const root =
interrupts.length === 1 ? ownData(interrupts[0], ['value']) : undefined;
const refund = root && refundPayload(root['value']);
interrupts.length === 1
? ownData(interrupts[0], ['id', 'value'])
: undefined;
const id = root?.['id'];
const refund =
root && typeof id === 'string' ? refundPayload(root['value']) : undefined;
capturedId = refund && typeof id === 'string' ? id : undefined;
publish({
decision: refund ? Object.freeze({ refund }) : null,
canSubmit: false,
Expand Down Expand Up @@ -234,12 +246,17 @@ export function createInterruptsApplication(options: {
)
return;
const admittedBatch = capturedBatch;
const interruptId = capturedId;
if (interruptId === undefined) return;
await perform('decision', (owned, signal) => {
// Publishing pending state can synchronously replace the observed batch.
// Reproject that pause without dispatching the superseded decision.
if (owned.getSnapshot().interrupts !== admittedBatch)
return Promise.resolve('paused');
return owned.resume(captured, { signal });
return owned.resume(
[{ interruptId, status: 'resolved', value: captured }],
{ signal }
);
});
}
async function stop() {
Expand Down
19 changes: 10 additions & 9 deletions examples/chat/native/shared/application-approval.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ const resume = (thread: string, answer = 'approved', extra = {}) => ({
payload: {
assistant_id: 'assistant',
input: null,
command: { resume: { [id]: answer } },
// One pending approval: the answer is the plain resume value.
command: { resume: answer },
stream_mode: ['values', 'messages-tuple', 'updates', 'custom', 'checkpoints'],
stream_subgraphs: true,
stream_resumable: true,
Expand Down Expand Up @@ -452,8 +453,8 @@ test('approval rejected completion suppresses a real replacement pause even when
const actual = o.sessionFactory!(thread);
return {
...actual,
async resume(value, options) {
assert.equal(await actual.resume(value, options), 'paused');
async resume(responses, options) {
assert.equal(await actual.resume(responses, options), 'paused');
throw new Error('completion delivery failed');
},
};
Expand Down Expand Up @@ -495,10 +496,10 @@ for (const action of ['stop', 'select', 'dispose'] as const) {
const actual = o.sessionFactory!(thread);
return {
...actual,
resume(value, options) {
resume(responses, options) {
invocations++;
aborted = options?.signal?.aborted ?? false;
return actual.resume(value, options);
return actual.resume(responses, options);
},
};
},
Expand Down Expand Up @@ -554,8 +555,8 @@ test('approval held resume Stop closes HTTP but cannot release the shared slot b
const actual = o.sessionFactory!(thread);
return {
...actual,
async resume(value, options) {
const result = await actual.resume(value, options);
async resume(responses, options) {
const result = await actual.resume(responses, options);
settled.release();
await gate.promise;
return result;
Expand Down Expand Up @@ -654,8 +655,8 @@ for (const rejection of [false, true]) {
first = false;
return {
...actual,
async resume(value, options) {
const result = await actual.resume(value, options);
async resume(responses, options) {
const result = await actual.resume(responses, options);
if (delay) {
settled.release();
await gate.promise;
Expand Down
Loading
Loading