From b85c72f09f0f652e02deac73231c43c2a758614d Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Sun, 6 Sep 2026 15:19:32 +0900 Subject: [PATCH] fix(claude): accept first fork child prompt on SessionStart:fork hook (#1671) * test(claude): reproduce fork child deadlock when init never arrives * fix(claude): accept first fork child prompt on SessionStart:fork hook A forked child starts query() before any prompt exists, and the SDK emits 'init' only after the first prompt is sent. Waiting for init deadlocked fork children until forever. Materialization is already signaled by the SessionStart:fork hook, so accept the child prompt on that signal instead. * chore: restore bun.lock --- cli/src/claude/claudeRemote.forkInit.test.ts | 88 ++++++++++++++++++++ cli/src/claude/claudeRemote.ts | 19 +++++ 2 files changed, 107 insertions(+) create mode 100644 cli/src/claude/claudeRemote.forkInit.test.ts diff --git a/cli/src/claude/claudeRemote.forkInit.test.ts b/cli/src/claude/claudeRemote.forkInit.test.ts new file mode 100644 index 00000000..574339bc --- /dev/null +++ b/cli/src/claude/claudeRemote.forkInit.test.ts @@ -0,0 +1,88 @@ +import { describe, it, expect, vi } from 'vitest'; +import * as claudeSdk from '@/claude/sdk'; +import type { SDKMessage } from '@/claude/sdk/types'; + +vi.mock('@/claude/utils/claudeCheckSession', () => ({ + claudeCheckSession: () => true +})); + +vi.mock('@/modules/watcher/awaitFileExist', () => ({ + awaitFileExist: async () => true +})); + +vi.mock('@/claude/sdk/utils', () => ({ + getDefaultClaudeCodePath: () => '/usr/bin/claude' +})); + +const queryMock = vi.fn(); + +async function waitFor(condition: () => boolean, timeoutMs = 2000, intervalMs = 10): Promise { + const startedAt = Date.now(); + while (!condition()) { + if (Date.now() - startedAt > timeoutMs) { + throw new Error('Timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, intervalMs)); + } +} + +describe('claudeRemote fork bootstrap', () => { + // A forked child starts query() before any prompt exists. Real SDK runs emit + // SessionStart hooks but no `init` until the first prompt is sent, so the + // child prompt must be accepted on the fork hook signal alone. + it('pushes the first child prompt after SessionStart:fork even when init never arrives', { timeout: 15_000 }, async () => { + const querySpy = vi.spyOn(claudeSdk, 'query').mockImplementation(queryMock as typeof claudeSdk.query); + const { claudeRemote } = await import('./claudeRemote'); + + let receivedPrompt: unknown; + let promptClosed = false; + + queryMock.mockImplementationOnce(({ prompt }: { prompt: AsyncIterable }) => ({ + async *[Symbol.asyncIterator]() { + const promptIterator = prompt[Symbol.asyncIterator](); + + // Fork bootstrap: hooks arrive while no prompt has been pushed yet. + yield { type: 'system', subtype: 'hook_started' } as unknown as SDKMessage; + yield { + type: 'system', + subtype: 'hook_response', + hook_name: 'SessionStart:fork', + outcome: 'success' + } as unknown as SDKMessage; + + // The fix must push the first child prompt here. + const next = await promptIterator.next(); + receivedPrompt = next.value; + promptClosed = true; + } + })); + + try { + await claudeRemote({ + sessionId: null, + path: process.cwd(), + mcpServers: {}, + claudeEnvVars: {}, + claudeArgs: ['--resume', 'source-session-id', '--fork-session'], + allowedTools: [], + hookSettingsPath: '/tmp/hook.json', + canCallTool: async () => ({ behavior: 'allow', updatedInput: {} }), + nextMessage: async () => + { return { message: 'Reply with exactly: PONG2', mode: { permissionMode: 'bypassPermissions' } }; }, + onReady: () => {}, + isAborted: () => false, + onSessionFound: () => {}, + onMessage: () => {} + }); + + await waitFor(() => promptClosed); + expect(receivedPrompt).toMatchObject({ + type: 'user', + message: { role: 'user', content: 'Reply with exactly: PONG2' } + }); + } finally { + queryMock.mockReset(); + querySpy.mockRestore(); + } + }); +}); diff --git a/cli/src/claude/claudeRemote.ts b/cli/src/claude/claudeRemote.ts index 8ef9f03f..e2494ccc 100644 --- a/cli/src/claude/claudeRemote.ts +++ b/cli/src/claude/claudeRemote.ts @@ -293,6 +293,25 @@ export async function claudeRemote(opts: { opts.onMessage(message); // Handle special system messages + if ( + message.type === 'system' + && message.subtype === 'hook_response' + && (message as { hook_name?: string }).hook_name === 'SessionStart:fork' + && awaitingForkInit + ) { + // A forked child starts query() before any prompt exists, and the + // SDK only emits `init` after the first prompt is sent. The fork + // itself materializes on the SessionStart:fork hook, so accept the + // first child prompt from that signal instead of deadlocking on + // an `init` that will not arrive until the prompt below is sent. + awaitingForkInit = false; + const first = await applyInitialTurn(); + if (!first) { + return; + } + initial = first; + } + if (message.type === 'system' && message.subtype === 'init') { // Start thinking when session initializes updateThinking(true);