Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
39 changes: 27 additions & 12 deletions src/utils/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ import * as realConfig from './config.js'
import * as realEnv from './env.js'
import * as realEnvUtils from './envUtils.js'

// Snapshot each real module surface into a plain object BEFORE any
// mock.module call. `import * as` gives a live namespace: mock.module
// repoints it, so restoring with the namespace itself re-installs the mock
// rather than the real module -- permanently, since mock.module lasts for the
// life of the process. That is how this suite's stderr-less `execa` stub used
// to escape into every later suite, where `result.stderr.trim()` then threw.
const realAuthSnapshot = { ...realAuth }
const realConfigSnapshot = { ...realConfig }
const realEnvSnapshot = { ...realEnv }
const realEnvUtilsSnapshot = { ...realEnvUtils }
const realExecaSnapshot = { ...realExeca }

const originalEnv = { ...process.env }
const originalMacro = (globalThis as Record<string, unknown>).MACRO

Expand All @@ -18,16 +30,18 @@ async function importFreshUserModule() {

async function importActualUserTestDeps() {
const nonce = `${Date.now()}-${Math.random()}`
const [authModule, configModule, execaModule] = await Promise.all([
const [authModule, configModule] = await Promise.all([
import(`./auth.js?ts=${nonce}`),
import(`./config.js?ts=${nonce}`),
import('execa'),
])

// execa comes from the pre-mock snapshot: a plain `import('execa')` here
// resolves to whatever mock is currently installed, so spreading it would
// build each new stub on top of the previous one.
return {
authModule,
configModule,
execaModule,
execaModule: realExecaSnapshot,
}
}

Expand Down Expand Up @@ -64,13 +78,13 @@ async function installCommonMocks(options?: {
}))

mock.module('./env.js', () => ({
...realEnv,
env: { platform: 'windows' },
getHostPlatformForAnalytics: () => 'windows',
...realEnvSnapshot,
env: { platform: 'win32' },
getHostPlatformForAnalytics: () => 'win32',
}))

mock.module('./envUtils.js', () => ({
...realEnvUtils,
...realEnvUtilsSnapshot,
isEnvTruthy: (value: string | undefined) =>
!!value && value !== '0' && value.toLowerCase() !== 'false',
}))
Expand All @@ -80,6 +94,7 @@ async function installCommonMocks(options?: {
execa: async () => ({
exitCode: options?.gitEmail ? 0 : 1,
stdout: options?.gitEmail ?? '',
stderr: '',
}),
execaSync: () => ({
exitCode: 1,
Expand All @@ -97,11 +112,11 @@ beforeEach(async () => {
afterEach(() => {
try {
mock.restore()
mock.module('./auth.js', () => realAuth)
mock.module('./config.js', () => realConfig)
mock.module('./env.js', () => realEnv)
mock.module('./envUtils.js', () => realEnvUtils)
mock.module('execa', () => realExeca)
mock.module('./auth.js', () => realAuthSnapshot)
mock.module('./config.js', () => realConfigSnapshot)
mock.module('./env.js', () => realEnvSnapshot)
mock.module('./envUtils.js', () => realEnvUtilsSnapshot)
mock.module('execa', () => realExecaSnapshot)
process.env = { ...originalEnv }
if (originalMacro === undefined) {
delete (globalThis as Record<string, unknown>).MACRO
Expand Down
124 changes: 108 additions & 16 deletions tests/sdk/query-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,31 +239,123 @@ describe('Query interrupt lifecycle', () => {
}, 10_000)

test('interrupt() with reason undefined yields synthetic user cancellation message', async () => {
const q = query({
prompt: 'test undefined reason',
options: { cwd: process.cwd() },
// Deterministic query-loop path (same shape as the Stop-hook regression
// tests below). The public SDK query() path races model/VCR startup against
// interrupt timing and was papered over by an empty fixtures/734ad7.json
// capture; assert the abort-reason contract here instead.
const { query: queryLoop } = await import('../../src/query.js')
const { getDefaultAppState } = await import('../../src/state/AppStateStore.js')
const { asSystemPrompt } = await import('../../src/utils/systemPromptType.js')

const abortController = new AbortController()
const appStateRef = {
current: {
...getDefaultAppState(),
},
}

const toolUseContext: any = {
options: {
commands: [],
debug: false,
mainLoopModel: 'sonnet',
tools: [],
verbose: false,
thinkingConfig: { type: 'disabled' },
mcpClients: [],
mcpResources: {},
isNonInteractiveSession: true,
agentDefinitions: { activeAgents: [], allAgents: [], allowedAgentTypes: [] },
},
abortController,
getAppState: () => appStateRef.current,
setAppState: (updater: any) => {
appStateRef.current = updater(appStateRef.current)
},
}

const mockExecuteStopHooks = async function* () {
yield {
message: {
type: 'progress' as const,
toolUseID: 'mock-tool-use-id',
data: {
command: 'mock-command',
promptText: 'mock-prompt',
},
},
}
// Default abort() has undefined reason → normalizeAbortReason maps
// AbortError to 'user-abort' → synthetic cancellation message is emitted.
abortController.abort()
yield {
message: {
type: 'progress' as const,
toolUseID: 'mock-tool-use-id-2',
data: {
command: 'mock-command-2',
promptText: 'mock-prompt-2',
},
},
}
}

const mockCallModel = async function* () {
yield {
type: 'assistant' as const,
uuid: 'assistant-1',
message: {
id: 'assistant-1',
type: 'message' as const,
role: 'assistant' as const,
model: 'test-model',
stop_reason: 'end_turn' as const,
usage: {
input_tokens: 1,
output_tokens: 1,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
},
content: [{ type: 'text' as const, text: 'Hello' }],
},
}
}

const q = queryLoop({
messages: [],
systemPrompt: asSystemPrompt([]),
userContext: {},
systemContext: {},
canUseTool: async () => ({ behavior: 'allow' }),
toolUseContext,
querySource: 'sdk',
deps: {
callModel: mockCallModel as any,
microcompact: async (messages) => ({ messages }),
autocompact: async () => ({ wasCompacted: false }),
uuid: () => 'uuid-1',
stopHookExecutionDeps: {
executeStopHooks: mockExecuteStopHooks as any,
isTeammate: () => false,
getStopHookMessage: () => 'stop hook blocked',
},
},
})
const iterator = q[Symbol.asyncIterator]()
const firstPromise = iterator.next()

// Interrupt during execution
q.interrupt()

const messages: any[] = []
try {
let result = await firstPromise
while (!result.done) {
messages.push(result.value)
result = await iterator.next()
for await (const msg of q) {
messages.push(msg)
}
} catch (err) {
if (!isExpectedDrainAbort(err)) throw err
}

const userCancelMsg = messages.find((m: any) =>
m.type === 'user' &&
Array.isArray(m.message?.content) &&
m.message.content[0]?.text === '[Request interrupted by user]'
const userCancelMsg = messages.find(
(m: any) =>
m.type === 'user' &&
Array.isArray(m.message?.content) &&
m.message.content[0]?.text === '[Request interrupted by user]',
)
expect(userCancelMsg).toBeDefined()
}, 10_000)
Expand Down