Skip to content
Closed
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
b92fde1
feat(core): add a live-session registry and `qwen sessions ps`
qqqys Aug 8, 2026
88cb405
Merge branch 'main' into feat/session-registry
qqqys Aug 8, 2026
4a9e64c
feat(core): accept cross-session messages behind an inbound gate
qqqys Aug 8, 2026
a9e9cee
test(cli): restore gemini.test.tsx mocks for the session registry
qqqys Aug 8, 2026
63978ac
Merge branch 'feat/session-registry' into feat/cross-session-inbox
qqqys Aug 8, 2026
ed2fc2f
feat(core): address other sessions by name from send_message and list…
qqqys Aug 8, 2026
9d0b053
fix(i18n): translate the /peers command description
qqqys Aug 8, 2026
c9befd6
Merge remote-tracking branch 'upstream/main' into autofix/8733
qqqys Aug 8, 2026
ea222f2
Merge remote-tracking branch 'origin/feat/cross-session-inbox' into a…
qqqys Aug 8, 2026
34b5eec
fix(core): reconcile send_message contract changes with main
qqqys Aug 8, 2026
41bb857
fix(core): address the six Critical findings from review round 1
qqqys Aug 8, 2026
b201019
fix(core): verify provenance before adopting a session record as our own
qqqys Aug 8, 2026
e68c5c0
fix(core): drain live peer connections instead of dropping them on close
qqqys Aug 9, 2026
06ab9e2
fix(core): stop accepting before draining the peer inbox
qqqys Aug 9, 2026
452c448
fix(core): address round 5 review on peer addressing
qqqys Aug 9, 2026
1ae6576
fix(cli): keep delivered peer messages out of shell preprocessing
qqqys Aug 9, 2026
170a1b0
fix(core): wire SendMessageType.Peer into the top-level-interaction b…
qqqys Aug 10, 2026
45b9659
fix(core): wire SendMessageType.Peer into the last three top-level br…
qqqys Aug 10, 2026
a420dc7
Merge branch 'main' into feat/peer-addressing
qwen-code-dev-bot Aug 10, 2026
248165f
fix(core): close the outstanding Criticals on cross-session messaging
qqqys Aug 10, 2026
505a638
Merge branch 'main' into feat/peer-addressing
qwen-code-dev-bot Aug 10, 2026
8d97cf5
chore(cli): merge main into feat/peer-addressing
qwen-code-dev-bot Aug 11, 2026
16b1e61
fix(cli): address peer messaging review blockers
qqqys Aug 11, 2026
4a19a90
fix(peer): harden peer message boundaries
qqqys Aug 11, 2026
3e5a76d
fix(peer): harden inbox input boundaries
qqqys Aug 11, 2026
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
14 changes: 12 additions & 2 deletions packages/cli/src/commands/sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@

import { describe, it, expect, vi } from 'vitest';

// Subcommand modules are stubbed so this file tests wiring only — loading
// the real ones would pull the whole core barrel in behind them.
vi.mock('./sessions/list.js', () => ({
listCommand: {
command: 'list',
describe: 'List sessions',
},
}));

vi.mock('./sessions/ps.js', () => ({
psCommand: {
command: 'ps',
describe: 'List Qwen Code sessions running right now',
},
}));

import { sessionsCommand } from './sessions.js';
import { type Argv } from 'yargs';
import yargs from 'yargs';
Expand Down Expand Up @@ -42,7 +51,7 @@ describe('sessions command', () => {
expect(options.key).toHaveProperty('help');
});

it('should register list subcommand', () => {
it('should register list and ps subcommands', () => {
const mockYargs = {
command: vi.fn().mockReturnThis(),
demandCommand: vi.fn().mockReturnThis(),
Expand All @@ -55,12 +64,13 @@ describe('sessions command', () => {
}
builder(mockYargs as unknown as Argv);

expect(mockYargs.command).toHaveBeenCalledTimes(1);
expect(mockYargs.command).toHaveBeenCalledTimes(2);

const commandCalls = mockYargs.command.mock.calls;
const commandNames = commandCalls.map((call) => call[0].command);

expect(commandNames).toContain('list');
expect(commandNames).toContain('ps');

expect(mockYargs.demandCommand).toHaveBeenCalledWith(
1,
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/commands/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@

import type { CommandModule, Argv } from 'yargs';
import { listCommand } from './sessions/list.js';
import { psCommand } from './sessions/ps.js';

export const sessionsCommand: CommandModule = {
command: 'sessions',
describe: 'Manage Qwen Code sessions',
builder: (yargs: Argv) =>
yargs
.command(listCommand)
.command(psCommand)
.demandCommand(1, 'You need at least one command before continuing.')
.version(false),
// demandCommand(1) ensures a subcommand is always required;
Expand Down
147 changes: 147 additions & 0 deletions packages/cli/src/commands/sessions/ps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* @license
* Copyright 2026 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type { SessionRegistryRecord } from '@qwen-code/qwen-code-core';

const listLiveSessions = vi.fn();

vi.mock('@qwen-code/qwen-code-core', () => ({
listLiveSessions: (...args: unknown[]) => listLiveSessions(...args),
}));

const stdout: string[] = [];
const stderr: string[] = [];

vi.mock('../../utils/stdioHelpers.js', () => ({
writeStdoutLine: (line: string) => stdout.push(line),
writeStderrLine: (line: string) => stderr.push(line),
}));

const { psCommand, formatAge } = await import('./ps.js');

function record(
over: Partial<SessionRegistryRecord> = {},
): SessionRegistryRecord {
return {
schemaVersion: 1,
pid: 4242,
procStart: '123',
sessionId: 'sess-1',
cwd: '/w/app',
name: 'app-ab',
kind: 'interactive',
startedAt: Date.now() - 90_000,
qwenVersion: '1.0.0',
peerProtocol: 1,
...over,
};
}

async function run(argv: Record<string, unknown>): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (psCommand.handler as any)(argv);
}

beforeEach(() => {
stdout.length = 0;
stderr.length = 0;
listLiveSessions.mockReset();
});

afterEach(() => {
vi.restoreAllMocks();
});

describe('formatAge', () => {
it('scales the unit with the magnitude', () => {
expect(formatAge(5_000)).toBe('5s');
expect(formatAge(90_000)).toBe('1m');
expect(formatAge(3 * 3600_000)).toBe('3h');
expect(formatAge(50 * 3600_000)).toBe('2d');
});

it('clamps a record from the future to zero rather than showing a negative age', () => {
expect(formatAge(-10_000)).toBe('0s');
});
});

describe('qwen sessions ps', () => {
it('prints a table of live sessions', async () => {
listLiveSessions.mockResolvedValue([record()]);
await run({ json: false, all: false });

expect(stdout[0]).toMatch(/^NAME\s+PID\s+AGE\s+DIRECTORY$/);
expect(stdout[1]).toContain('app-ab');
expect(stdout[1]).toContain('4242');
expect(stdout[1]).toContain('/w/app');
Comment on lines +78 to +80

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.

Deferred to a follow-up: test-hardening suggestion (mutation pin / efficacy probe). This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:测试加固建议(变异钉/测试效力探针)。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

});

it('says so plainly when nothing else is running', async () => {
listLiveSessions.mockResolvedValue([]);
await run({ json: false, all: false });
expect(stdout).toEqual(['No other Qwen Code sessions are running.']);
});

it('emits one JSON object per line with no header', async () => {
listLiveSessions.mockResolvedValue([record(), record({ pid: 7 })]);
await run({ json: true, all: false });

expect(stdout).toHaveLength(2);
expect(JSON.parse(stdout[0]).pid).toBe(4242);

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.

Deferred to a follow-up: test-hardening suggestion (mutation pin / efficacy probe). This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:测试加固建议(变异钉/测试效力探针)。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

expect(JSON.parse(stdout[1]).pid).toBe(7);
});

it('prints nothing on stdout for an empty JSON listing', async () => {
listLiveSessions.mockResolvedValue([]);
await run({ json: true, all: false });
expect(stdout).toEqual([]);
});

it('excludes this process unless --all is passed', async () => {
listLiveSessions.mockResolvedValue([]);

await run({ json: true, all: false });
expect(listLiveSessions).toHaveBeenLastCalledWith({ includeSelf: false });

await run({ json: true, all: true });
expect(listLiveSessions).toHaveBeenLastCalledWith({ includeSelf: true });
});

it('neutralizes control sequences coming from another process record', async () => {
listLiveSessions.mockResolvedValue([
record({ name: 'evil\r', cwd: '/w/a\nb' }),
]);
await run({ json: false, all: false });

const row = stdout[1];
expect(row).not.toContain('');

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.

Deferred to a follow-up: test-hardening suggestion (mutation pin / efficacy probe). This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:测试加固建议(变异钉/测试效力探针)。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

expect(row).not.toContain('\r');
expect(row).not.toContain('\n');
});

it('reports a registry read failure on stderr and exits 1', async () => {
const exit = vi
.spyOn(process, 'exit')
.mockImplementation((() => undefined) as never);
listLiveSessions.mockRejectedValue(new Error('EACCES'));

await run({ json: false, all: false });

expect(stderr.join('\n')).toContain(
'failed to read the session registry: EACCES',
);
expect(exit).toHaveBeenCalledWith(1);
expect(stdout).toEqual([]);
});

it('truncates an over-long name instead of breaking the columns', async () => {
listLiveSessions.mockResolvedValue([record({ name: 'x'.repeat(80) })]);
await run({ json: false, all: false });
expect(stdout[1]).toContain('...');
expect(stdout[1]).toContain('4242');
});
});
152 changes: 152 additions & 0 deletions packages/cli/src/commands/sessions/ps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* @license
* Copyright 2026 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

/**
* `qwen sessions ps` — list the Qwen Code sessions running right now.
*
* The sibling `qwen sessions list` walks saved transcripts; this walks the
* live-process registry, so the two answer different questions: "what have
* I worked on" versus "what is running on this machine at this moment".
*/

import type { CommandModule, Argv } from 'yargs';
import {
listLiveSessions,
type SessionRegistryRecord,
} from '@qwen-code/qwen-code-core';
import stringWidth from 'string-width';
import { escapeAnsiCtrlCodes } from '../../ui/utils/textUtils.js';
import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js';

/** Fixed column widths for the human-readable table (exported for tests). */
export const NAME_COL = 22;

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.

Deferred to a follow-up: dead-surface removal. This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:移除无用接口。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

export const PID_COL = 9;
export const AGE_COL = 10;

interface PsArgs {
json?: boolean;
all?: boolean;
}

/**
* Sanitize a value for terminal output.
*
* `cwd` and `name` originate from another process's on-disk record, so
* they are attacker-influenced in exactly the way a log line is: a record
* containing an ANSI sequence or a stray `\r` could otherwise repaint or
* misalign this table. Mirrors `sessions list`.
*/
function sanitize(value: string): string {
const stripped = value.replace(/[\r\n\t]/g, '');
const escaped = escapeAnsiCtrlCodes(stripped);
Comment on lines +42 to +44

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.

Deferred to a follow-up: shared-helper refactor across an existing sibling command. This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:跨既有兄弟命令的共享助手重构。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

// eslint-disable-next-line no-control-regex
return escaped.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
Comment on lines +44 to +46

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.

Deferred to a follow-up: small robustness improvement. This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:小的健壮性改进。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

}

function padDisplay(str: string, width: number): string {
const currentWidth = stringWidth(str);
if (currentWidth >= width) return str;
return str + ' '.repeat(width - currentWidth);
}

function truncate(str: string, maxLen: number): string {
if (stringWidth(str) <= maxLen) return str;
const suffix = maxLen > 3 ? '...' : '';
const target = maxLen - stringWidth(suffix);
let result = '';
let w = 0;
for (const char of str) {
const cw = stringWidth(char);
if (w + cw > target) break;
Comment on lines +62 to +63

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.

Deferred to a follow-up: test-hardening suggestion (mutation pin / efficacy probe). This PR is past five change-producing review rounds, so per the repo's review budget this round takes only the Critical fixes; this finding is recorded in the round summary so it is tracked, not silently dropped. The open thread keeps it visible for the follow-up.

中文说明

推迟到后续处理:测试加固建议(变异钉/测试效力探针)。本 PR 已超过五个产生变更的评审轮次,按仓库的评审轮次预算,本轮只接收 Critical 修复;该发现已记录在本轮总结中,会被跟踪而不会被静默丢弃。保持打开的线程让它在后续处理中仍然可见。

result += char;
w += cw;
}
return result + suffix;
}

/**
* Render an age as a short, human-scannable string.
*
* A negative delta means the record's clock ran ahead of ours (a paused
* VM, a corrected clock). Showing "-3m" reads as a bug, so clamp to 0.
*/
export function formatAge(ms: number): string {
const seconds = Math.max(0, Math.floor(ms / 1000));
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h`;
return `${Math.floor(hours / 24)}d`;
}

function outputHuman(records: SessionRegistryRecord[], now: number): void {
writeStdoutLine(
padDisplay('NAME', NAME_COL) +
padDisplay('PID', PID_COL) +
padDisplay('AGE', AGE_COL) +
'DIRECTORY',
);
for (const record of records) {
writeStdoutLine(
padDisplay(truncate(sanitize(record.name), NAME_COL - 2), NAME_COL) +
padDisplay(String(record.pid), PID_COL) +
padDisplay(formatAge(now - record.startedAt), AGE_COL) +
sanitize(record.cwd),
);
}
}

async function handlePs(argv: PsArgs): Promise<void> {
let records: SessionRegistryRecord[];
try {
records = await listLiveSessions({ includeSelf: argv.all ?? false });
} catch (err) {
writeStderrLine(

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.

[Critical] This error path is unreachable with the production listLiveSessions() implementation: that function catches every fs.readdir() failure and returns []. An unreadable or failing registry (EACCES, EIO, etc.) therefore makes qwen sessions ps print “No other Qwen Code sessions are running.” and exit successfully, turning an inability to inspect session state into a false authoritative answer. Please preserve non-ENOENT failures (or otherwise surface them distinctly) so this command can fail instead of reporting an empty registry.

中文说明

生产环境中的 listLiveSessions() 会捕获所有 fs.readdir() 错误并返回 [],因此这里的错误分支实际上不可达。当注册表因 EACCES、EIO 等原因无法读取时,qwen sessions ps 仍会输出“没有其他正在运行的 Qwen Code 会话”并以成功状态退出,把“无法检查”错误地报告成“确认为空”。请保留并向上传递非 ENOENT 错误,或用其他方式明确暴露读取失败。

— qwen3.8-max via Qwen Code /review (v0.21.8)

`Error: failed to read the session registry: ${
err instanceof Error ? err.message : String(err)
}`,
);
process.exit(1);
return;
}

const now = Date.now();

if (argv.json) {
for (const record of records) {
writeStdoutLine(JSON.stringify(record));
}
return;
}

if (records.length === 0) {
writeStdoutLine('No other Qwen Code sessions are running.');
return;
}

outputHuman(records, now);
}

export const psCommand: CommandModule<unknown, PsArgs> = {
command: 'ps',
describe: 'List Qwen Code sessions running right now',
builder: (yargs: Argv) =>
yargs
.option('json', {
type: 'boolean',
describe: 'Output as JSON Lines',
default: false,
})
.option('all', {
type: 'boolean',
describe: 'Include this process, if it is itself a registered session',
default: false,
}),
handler: async (argv) => {
await handlePs(argv);
},
};
25 changes: 25 additions & 0 deletions packages/cli/src/config/settingsSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3121,6 +3121,31 @@ const SETTINGS_SCHEMA = {
},
},
},
crossSessionMessaging: {
type: 'boolean',
label: 'Cross-Session Messaging',
category: 'Advanced',
requiresRestart: true,
default: false,
description:
'Experimental. Let Qwen Code sessions on this machine send each other messages over a per-session local socket. Off by default; turning it on both opens this session to peer messages and makes it discoverable to others.',
showInDialog: false,
},
crossSessionInbound: {
type: 'enum',
label: 'Inbound Cross-Session Messages',
category: 'Advanced',
requiresRestart: false,
default: undefined as string | undefined,
description:
'What happens to messages other sessions send this one. "accept" delivers them; "hold" parks them for your review without letting the model act; "refuse" opts this session out. Unset means approval-mode parity: a message auto-delivers unless this session bypasses permission prompts (YOLO) while the sender does not, or does not say — those are held for you to review.',
showInDialog: false,
options: [
{ value: 'accept', label: 'Accept' },
{ value: 'hold', label: 'Hold for review' },
{ value: 'refuse', label: 'Refuse' },
],
},
modelGrades: {
type: 'object',
label: 'Model Grades',
Expand Down
Loading
Loading