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
30 changes: 30 additions & 0 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import {
acquireSleepInhibitor,
clearGoalTerminalObserver,
setGoalTerminalObserver,
sessionIdContext,
} from '@qwen-code/qwen-code-core';
import { NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE } from '@qwen-code/acp-bridge/bridgeErrors';
import { getCommandSubcommandNames } from '../../services/commandMetadata.js';
Expand Down Expand Up @@ -894,6 +895,19 @@ export class Session implements SessionContext {
async #executePrompt(
params: PromptRequest,
pendingSend: AbortController,
): Promise<PromptResponse> {
// Bind this turn to the session's ID via AsyncLocalStorage so shell
// subprocesses (and hooks) read the CURRENT session's ID instead of
// the process-global env slot, which in daemon mode only ever holds
// the first session created in this process.
return sessionIdContext.run(this.config.getSessionId(), () =>
this.#executePromptInner(params, pendingSend),
);
}

async #executePromptInner(
params: PromptRequest,
pendingSend: AbortController,
): Promise<PromptResponse> {
return Storage.runWithRuntimeBaseDir(
this.runtimeBaseDir,
Expand Down Expand Up @@ -1836,6 +1850,13 @@ export class Session implements SessionContext {
* `_meta.source='cron'`, streams the model response, and handles tool calls.
*/
async #executeCronPrompt(prompt: string): Promise<void> {
// Same session-ID binding rationale as #executePrompt.
return sessionIdContext.run(this.config.getSessionId(), () =>
this.#executeCronPromptInner(prompt),
);
}

async #executeCronPromptInner(prompt: string): Promise<void> {
return Storage.runWithRuntimeBaseDir(
this.runtimeBaseDir,
this.config.getWorkingDir(),
Expand Down Expand Up @@ -2096,6 +2117,15 @@ export class Session implements SessionContext {

async #executeBackgroundNotificationPrompt(
item: BackgroundNotificationQueueItem,
): Promise<void> {
// Same session-ID binding rationale as #executePrompt.
return sessionIdContext.run(this.config.getSessionId(), () =>
this.#executeBackgroundNotificationPromptInner(item),
);
}

async #executeBackgroundNotificationPromptInner(
item: BackgroundNotificationQueueItem,
): Promise<void> {
return Storage.runWithRuntimeBaseDir(
this.runtimeBaseDir,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ export {
} from './utils/runtimeFetchOptions.js';
export * from './utils/runtimeStatus.js';
export * from './utils/schemaValidator.js';
export * from './utils/sessionIdContext.js';
export * from './utils/shell-utils.js';
export * from './utils/subagentGenerator.js';
export * from './utils/symlink.js';
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/telemetry/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ vi.mock('./tracer.js', () => ({
import { LogToSpanProcessor } from './log-to-span-processor.js';
import { setSessionContext } from './session-context.js';
import { setShellTracePropagation } from './trace-context.js';
import { createSessionRootContext } from './tracer.js';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';

Expand Down
25 changes: 25 additions & 0 deletions packages/core/src/utils/sessionIdContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

import { AsyncLocalStorage } from 'node:async_hooks';

/**
* Per-async-context session ID, mirroring {@link promptIdContext}.
*
* `QWEN_CODE_SESSION_ID` historically lived only in `process.env`, which is
* a single process-global slot. That is fine for the interactive CLI (one
* session per process, switched via `Config.startNewSession()`), but breaks
* in daemon mode where one process hosts many concurrent sessions: only the
* first `Config` ever claims the env slot (see `sessionEnvClaimed` in
* config.ts), so shells spawned by every later session would read a stale
* session ID.
*
* Daemon-style hosts should wrap each session's execution entry points in
* `sessionIdContext.run(sessionId, ...)`. `getShellContextEnvVars()` prefers
* this context over `process.env`, falling back to the env var so the
* single-session CLI behavior is unchanged.
*/
export const sessionIdContext = new AsyncLocalStorage<string>();
42 changes: 42 additions & 0 deletions packages/core/src/utils/shellContextEnv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { getShellContextEnvVars } from './shellContextEnv.js';
import { runWithAgentContext } from '../agents/runtime/agent-context.js';
import { promptIdContext } from './promptIdContext.js';
import { sessionIdContext } from './sessionIdContext.js';
import {
isShellTracePropagationEnabled,
getTraceContext,
Expand Down Expand Up @@ -76,6 +77,47 @@ describe('getShellContextEnvVars', () => {
});
});

describe('session ID from AsyncLocalStorage (daemon multi-session)', () => {
it('prefers sessionIdContext over process.env', () => {
// Daemon mode: process.env holds the FIRST session's ID forever
// (constructor guard `sessionEnvClaimed` in config.ts), so a later
// session must win via its own async context.
process.env['QWEN_CODE_SESSION_ID'] = 'stale-first-session';
const env = sessionIdContext.run('current-session', () =>
getShellContextEnvVars(),
);
expect(env['QWEN_CODE_SESSION_ID']).toBe('current-session');
});

it('falls back to process.env outside any session context (single-session CLI)', () => {
process.env['QWEN_CODE_SESSION_ID'] = 'cli-session';
const env = getShellContextEnvVars();
expect(env['QWEN_CODE_SESSION_ID']).toBe('cli-session');
});

it('isolates concurrent sessions in the same process', async () => {
// Regression: two daemon sessions interleaving must each see their
// own ID at spawn time, even though process.env is a single slot.
process.env['QWEN_CODE_SESSION_ID'] = 'stale-first-session';
let envSeenByA: Record<string, string> = {};
let envSeenByB: Record<string, string> = {};

await Promise.all([
sessionIdContext.run('session-A', async () => {
await new Promise((resolve) => setTimeout(resolve, 5));
envSeenByA = getShellContextEnvVars();
}),
sessionIdContext.run('session-B', async () => {
await new Promise((resolve) => setTimeout(resolve, 5));
envSeenByB = getShellContextEnvVars();
}),
]);

expect(envSeenByA['QWEN_CODE_SESSION_ID']).toBe('session-A');
expect(envSeenByB['QWEN_CODE_SESSION_ID']).toBe('session-B');
});
});

it('sets empty string for agent/prompt to override inherited env', () => {
// Simulates a nested qwen-code process where parent injected these
const env = getShellContextEnvVars();
Expand Down
25 changes: 18 additions & 7 deletions packages/core/src/utils/shellContextEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,25 @@
/**
* Returns context environment variables to inject into shell subprocesses.
*
* Reads dynamic context (agent ID, prompt ID) from AsyncLocalStorage at
* call time, and session ID from process.env (set by Config at session
* start). This enables downstream scripts to identify which session,
* agent, and prompt triggered their execution — useful for tracing,
* audit logging, and business context correlation.
* Reads dynamic context (session ID, agent ID, prompt ID) from
* AsyncLocalStorage at call time, falling back to process.env for the
* session ID (set by Config at session start in the single-session CLI).
* This enables downstream scripts to identify which session, agent, and
* prompt triggered their execution — useful for tracing, audit logging,
* and business context correlation.
*
* The ALS-first lookup matters in daemon mode: one process hosts many
* sessions, but only the first Config ever claims the process-global
* env slot (`sessionEnvClaimed` in config.ts), so process.env alone
* would report a stale session ID for every later session.
*
* Must be called at spawn time within the executing async context to
* capture the correct agent/prompt frame.
* capture the correct session/agent/prompt frame.
*/

import { getCurrentAgentId } from '../agents/runtime/agent-context.js';
import { promptIdContext } from './promptIdContext.js';
import { sessionIdContext } from './sessionIdContext.js';
import {
isShellTracePropagationEnabled,
getTraceContext,
Expand All @@ -28,7 +35,11 @@ import {
export function getShellContextEnvVars(): Record<string, string> {
const env: Record<string, string> = {};

const sessionId = process.env['QWEN_CODE_SESSION_ID'];
// Prefer the per-async-context session ID (set by multi-session hosts
// like the daemon) over the process-global env slot, which only ever
// reflects the first session created in this process.
const sessionId =
sessionIdContext.getStore() ?? process.env['QWEN_CODE_SESSION_ID'];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] 当 sessionIdContext.getStore() 为 undefined 时,代码静默回退到 process.env — 零诊断输出。如果有任何未来代码路径遗漏了 ALS 包裹,错误 session ID 会毫无预警地传播,生产环境极难排查。建议在 daemon 模式下,ALS 为空时加一条 debug 级别日志。

— DeepSeek/deepseek-v4-pro via Qwen Code /review

if (sessionId) {
env['QWEN_CODE_SESSION_ID'] = sessionId;
}
Expand Down