Skip to content
Merged
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
48 changes: 48 additions & 0 deletions packages/agent/__tests__/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
type AssistantMessage,
type Context,
createAssistantMessageEventStream,
injectDeferralResults,
type Message,
type ModelDescriptor,
type ToolCallContent,
Expand Down Expand Up @@ -372,6 +373,53 @@ describe('@agentic-kit/agent — pausable tools', () => {
expect(execute).not.toHaveBeenCalled();
});

it('injectDeferralResults + prompt() places the synthetic toolResult adjacent to its assistant block', async () => {
const provider = createScriptedProvider({
responses: [pauseResponse(), finalResponse()],
});
const execute = jest.fn(async () => ({
content: [{ type: 'text' as const, text: 'should not run' }],
}));

const agent = new Agent({
initialState: { model: makeFakeModel() },
streamFn: provider.stream,
});
agent.setTools([makeApprovalTool(execute)]);

await agent.prompt('approve thing');

const withDeferrals = injectDeferralResults(agent.state.messages);
agent.replaceMessages(withDeferrals);

const typed: Message = {
role: 'user',
content: 'never mind',
timestamp: Date.now(),
};
await agent.prompt(typed);

const messages = agent.state.messages;
const assistantIdx = messages.findIndex(
(m) =>
m.role === 'assistant' &&
(m as AssistantMessage).content.some(
(b) => b.type === 'toolCall' && b.id === 'tool_1'
)
);
const toolResultIdx = messages.findIndex(
(m) => m.role === 'toolResult' && m.toolCallId === 'tool_1'
);
const typedIdx = messages.findIndex(
(m) => m.role === 'user' && m.content === 'never mind'
);

expect(assistantIdx).toBeGreaterThanOrEqual(0);
expect(toolResultIdx).toBe(assistantIdx + 1);
expect(typedIdx).toBe(toolResultIdx + 1);
expect(execute).not.toHaveBeenCalled();
});

it('abort() while paused stops further work without throwing', async () => {
const provider = createScriptedProvider({ responses: [pauseResponse()] });

Expand Down
73 changes: 73 additions & 0 deletions packages/react/__tests__/use-chat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,49 @@ describe('useChat', () => {
expect(result.current.executingToolCallIds.size).toBe(0);
});

it('hydrates pendingDecisions from initialMessages when a paused tool call is present', () => {
const initial: Message[] = [
makeUser('hi'),
makeAssistantWithToolCall('call_pending'),
];

const { result } = renderHook(() =>
useChat({ api: '/chat', initialMessages: initial })
);

expect(result.current.pendingDecisions.has('call_pending')).toBe(true);
expect(result.current.pendingDecisions.get('call_pending')).toMatchObject({
toolCallId: 'call_pending',
toolName: 'echo',
});
});

it('send(): two rapid synchronous sends both reach the outgoing request body', async () => {
const final = makeFinalAssistant('ok');
const fetchFn = jest.fn(
async (_url: RequestInfo | URL, _init?: RequestInit): Promise<Response> =>
streamFromEvents([
{ type: 'agent_start' },
{ type: 'agent_end', messages: [makeUser('first'), makeUser('second'), final] },
])
);

const { result } = renderHook(() => useChat({ api: '/chat', fetch: fetchFn }));

await act(async () => {
const p1 = result.current.send('first');
const p2 = result.current.send('second');
await Promise.allSettled([p1, p2]);
});

const lastInit = fetchFn.mock.calls.at(-1)![1] as RequestInit;
const sent = JSON.parse(lastInit.body as string);
const contents = sent.messages.map((m: Message) =>
typeof m.content === 'string' ? m.content : null
);
expect(contents).toEqual(['first', 'second']);
});

it('sends, streams, and folds messages into the log', async () => {
const final = makeFinalAssistant('world');
const userEcho = makeUser('hello');
Expand Down Expand Up @@ -656,6 +699,36 @@ describe('useChat', () => {
expect(result.current.isStreaming).toBe(false);
});

it('unmount aborts the in-flight fetch', async () => {
let capturedSignal: AbortSignal | undefined;
const fetchFn = jest.fn(
(_url: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
capturedSignal = init?.signal ?? undefined;
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
const err = new Error('aborted');
err.name = 'AbortError';
reject(err);
});
});
}
);

const { result, unmount } = renderHook(() =>
useChat({ api: '/chat', fetch: fetchFn })
);

act(() => {
void result.current.send('hi');
});
await waitFor(() => expect(fetchFn).toHaveBeenCalled());
expect(capturedSignal?.aborted).toBe(false);

unmount();

expect(capturedSignal?.aborted).toBe(true);
});

it('drops events that arrive after abort', async () => {
let pushFn!: (event: AgentEvent) => void;
let closeFn!: () => void;
Expand Down
10 changes: 9 additions & 1 deletion packages/react/src/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function useChat(options: UseChatOptions): UseChatResult {
const [isStreaming, setIsStreaming] = useState(false);
const [pendingDecisions, setPendingDecisions] = useState<
ReadonlyMap<string, ToolDecisionPendingEvent>
>(() => new Map());
>(() => rederivePendingDecisions(options.initialMessages ?? []));
const [executingToolCallIds, setExecutingToolCallIds] = useState<ReadonlySet<string>>(
() => new Set()
);
Expand Down Expand Up @@ -293,6 +293,7 @@ export function useChat(options: UseChatOptions): UseChatResult {
const userMessage: Message =
typeof input === 'string' ? createUserMessage(input) : input;
const requestMessages = [...messagesRef.current, userMessage];
messagesRef.current = requestMessages;
await runStream(requestMessages, userMessage);
},
[runStream]
Expand Down Expand Up @@ -358,6 +359,13 @@ export function useChat(options: UseChatOptions): UseChatResult {
[]
);

useEffect(() => {
return () => {
abortControllerRef.current?.abort();
abortControllerRef.current = null;
};
}, []);

const abort = useCallback(() => {
abortControllerRef.current?.abort();
abortControllerRef.current = null;
Expand Down
Loading