Skip to content

Commit 84a49b2

Browse files
authored
fix: restore subagent resume after restart and harden web open, telemetry, and journal paths (#296)
## Summary - What changed and why: four reconciliation fixes from the September reference pass, adapted to local architecture: 1. **Subagent resume after restart** — `Agent(resume=<id>)` now rebuilds a persisted subagent from session metadata when it is not live in the current process, instead of failing with "does not exist". The rebuilt subagent syncs to the caller's current permission mode (unless tower-pinned) and approval rules match its persisted profile label. 2. **Ambient telemetry model context** — the bound model alias is written into the ambient telemetry context (and restored after a cold resume), so `pfc_*` events carry `model` alongside `provider_type`/`protocol`. 3. **Gateway journal close** — the session event broadcaster drains in-flight state creations on close, skips global-state creation when closed, and the event journal ignores appends after close, so no journal writes land after server shutdown. 4. **Web auto-open on wildcard binds** — `--open` now rewrites a wildcard bind origin (`0.0.0.0` / `::`) to `localhost` for the browser, and the ready banner parses the port without `new URL` (which throws on `::`). - User-visible behavior: resuming a subagent by id works across process restarts; telemetry events gain the model field; no stray journal writes after gateway shutdown; browser opens a navigable localhost URL on wildcard binds. - Scope deliberately excluded: remaining September reference items (loop-machine batch, file history, staleGuard removal, survey, web reconstruction, docs restructure, flag graduation) — tracked separately. ## Risk - Risk level and affected boundaries: low. Engine subagent lifecycle (resume path only — spawn/fork untouched), telemetry context payload (additive field), gateway WS event journal (shutdown path), CLI web auto-open (open path only). - Failure, security, data, concurrency, dependency, and lifecycle considerations: resume validates ownership and subagent type before rebuild and keeps the running-state guard; journal close now awaits pending state creations (bounded by existing pending map); no new dependencies; lifecycle impact is the fix itself (post-close writes eliminated). - New dependency or telemetry approval, if applicable: none; telemetry change is additive to existing payloads and preserves the `pfc_` contract. ## Verification - Exact commands and outcomes: `pnpm run build` 0 · `pnpm run typecheck` 0 · `pnpm run lint` 0 errors (3271 pre-existing warnings) · `pnpm run sherif` 0 · `pnpm test` 21,381 passed, 8 load-flake failures each re-run green in isolation (5s timeouts, one ENOTEMPTY teardown, one 120s perf baseline) · `pnpm -C apps/vscode run typecheck` 0 · `pnpm -C apps/vscode test` 0 · `nix build .#pythinker-code` 0 · `node scripts/check-nix-workspace.mjs` 0 · targeted suites: agent-core-v2 lifecycle/tool 170, telemetry-affected 364, gateway broadcaster/journal 98, web CLI 68 — all green. - Tests added or updated: 6 subagent rebuild/sync tests, 2 lifecycle metadata tests, 3 ambient-model tests, 3 journal-close tests, 5 web-open tests; exact telemetry payload assertions updated for the new `model` field. - Checks not run, warnings, or limitations: lint warnings are the pre-existing baseline; mutation checks run on the three new guards (permission-mode sync, rebuild path, journal close guard) — each kills its test. ## Rollback and review - Rollback path: revert the four commits; no schema, wire, or config-format changes. - Residual risk: rebuilt subagents start from persisted metadata + wire replay, identical to fresh process startup; cold-resume telemetry restore covered by test. - Human review required: normal review; changesets included for the three user-perceivable changes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Subagents can be resumed after reopening a session or starting a new process, with labels, profiles, and permission settings restored. - The Web UI opens at `localhost` instead of a wildcard network address, with improved IPv6 URL handling. - Telemetry includes the selected model, including after session restoration. - Session event handling is more reliable during shutdown, preventing late events from recreating closed journals. - **Tests** - Added coverage for subagent recovery, model telemetry persistence, Web UI URLs, IPv6 handling, and session event shutdown behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 27daa89 commit 84a49b2

20 files changed

Lines changed: 589 additions & 40 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@pymodel/pythinker-code": patch
3+
---
4+
5+
Resuming a subagent by its agent id works again after the session is reopened in a new process.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@pymodel/pythinker-code": patch
3+
---
4+
5+
Include the bound model in telemetry event context.

‎.changeset/web-open-localhost.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@pymodel/pythinker-code": patch
3+
---
4+
5+
Open the browser on localhost instead of the wildcard bind address when auto-opening the web UI.

‎apps/pythinker-code/src/cli/sub/web/access-urls.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,19 @@ function isWildcard(host: string): boolean {
4141
return host === '' || host === '0.0.0.0' || host === '::';
4242
}
4343

44+
/**
45+
* Rewrite a bound origin for browser auto-open. A wildcard bind host
46+
* (`0.0.0.0` / `::` / empty, bracketed or bare) is not navigable, so open
47+
* localhost on the same port instead — the same address the ready banner's
48+
* `Local:` line shows.
49+
*/
50+
export function browserOpenOrigin(origin: string): string {
51+
const separator = origin.lastIndexOf(':');
52+
const host = origin.slice(origin.indexOf('://') + 3, separator);
53+
if (!isWildcard(host.replace(/^\[/, '').replace(/\]$/, ''))) return origin;
54+
return `http://localhost${origin.slice(separator)}`;
55+
}
56+
4457
/** True when `host` is a loopback address (this host only). */
4558
export function isLoopbackHost(host: string): boolean {
4659
return host === 'localhost' || host === '127.0.0.1' || host === '::1';

‎apps/pythinker-code/src/cli/sub/web/run.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,12 @@ import {
3535
} from '../../version';
3636
import {
3737
accessUrlLines,
38+
browserOpenOrigin,
3839
buildOpenableUrl,
3940
isLoopbackHost,
4041
splitTokenFragment,
4142
} from './access-urls';
42-
import { type NetworkAddress } from './networks';
43+
import { formatHostForUrl, type NetworkAddress } from './networks';
4344
import {
4445
formatRemoteControlOutput,
4546
formatRemoteControlStatus,
@@ -289,7 +290,8 @@ export async function handleWebCommand(
289290
: formatReadyLine(origin, token, parsed.dangerousBypassAuth),
290291
);
291292
if (opts.open === true) {
292-
deps.openUrl(token !== undefined ? buildWebUrl(origin, token) : origin);
293+
const openOrigin = browserOpenOrigin(origin);
294+
deps.openUrl(token !== undefined ? buildWebUrl(openOrigin, token) : openOrigin);
293295
}
294296
},
295297
onShutdown: async () => {
@@ -417,7 +419,7 @@ async function runServerInProcess(
417419
});
418420
logger.info('serving the REST/WS API and the bundled web UI');
419421
running = {
420-
address: `http://${v2.host}:${v2.port}`,
422+
address: `http://${formatHostForUrl(v2.host, v2.host.includes(':') ? 'IPv6' : 'IPv4')}:${v2.port}`,
421423
logger,
422424
close: () => v2.close(),
423425
};
@@ -517,7 +519,7 @@ export function formatReadyBanner(
517519
return frag === '' ? url(base) : url(base) + dim(frag);
518520
};
519521

520-
const port = Number(new URL(origin).port);
522+
const port = Number(origin.slice(origin.lastIndexOf(':') + 1));
521523
const lines: string[] =
522524
opts.useTuiLogo === true
523525
? [

‎apps/pythinker-code/test/cli/web/web.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,66 @@ describe('`pythinker web` opens the browser', () => {
381381
expect(openUrl).toHaveBeenCalledWith('http://127.0.0.1:58627');
382382
});
383383

384+
it('opens localhost rather than the wildcard bind address', async () => {
385+
const { handleWebCommand } = await import('#/cli/sub/web/run');
386+
const { runner } = makeRunner('http://0.0.0.0:58627');
387+
const { stdout, stderr } = makeIo();
388+
const openUrl = vi.fn();
389+
390+
await handleWebCommand(
391+
{ host: '0.0.0.0', open: true },
392+
{
393+
startServerForeground: runner,
394+
resolveToken: () => 'tok-xyz',
395+
openUrl,
396+
stdout,
397+
stderr,
398+
},
399+
);
400+
401+
expect(openUrl).toHaveBeenCalledWith('http://localhost:58627/#token=tok-xyz');
402+
});
403+
404+
it('opens localhost for a wildcard IPv6 bind', async () => {
405+
const { handleWebCommand } = await import('#/cli/sub/web/run');
406+
const { runner } = makeRunner('http://[::]:58627');
407+
const { stdout, stderr } = makeIo();
408+
const openUrl = vi.fn();
409+
410+
await handleWebCommand(
411+
{ host: '::', open: true },
412+
{
413+
startServerForeground: runner,
414+
resolveToken: () => undefined,
415+
openUrl,
416+
stdout,
417+
stderr,
418+
},
419+
);
420+
421+
expect(openUrl).toHaveBeenCalledWith('http://localhost:58627');
422+
});
423+
424+
it('opens the bracketed loopback origin for an IPv6 bind', async () => {
425+
const { handleWebCommand } = await import('#/cli/sub/web/run');
426+
const { runner } = makeRunner('http://[::1]:58627');
427+
const { stdout, stderr } = makeIo();
428+
const openUrl = vi.fn();
429+
430+
await handleWebCommand(
431+
{ host: '::1', open: true },
432+
{
433+
startServerForeground: runner,
434+
resolveToken: () => 'tok-xyz',
435+
openUrl,
436+
stdout,
437+
stderr,
438+
},
439+
);
440+
441+
expect(openUrl).toHaveBeenCalledWith('http://[::1]:58627/#token=tok-xyz');
442+
});
443+
384444
it('does not open the browser when open is false', async () => {
385445
const { handleWebCommand } = await import('#/cli/sub/web/run');
386446
const { runner } = makeRunner('http://127.0.0.1:9000');
@@ -1034,6 +1094,22 @@ describe('accessUrlLines', () => {
10341094
});
10351095
});
10361096

1097+
describe('browserOpenOrigin', () => {
1098+
it('rewrites wildcard bind hosts to localhost on the same port', async () => {
1099+
const { browserOpenOrigin } = await import('#/cli/sub/web/access-urls');
1100+
expect(browserOpenOrigin('http://0.0.0.0:58627')).toBe('http://localhost:58627');
1101+
expect(browserOpenOrigin('http://:::58627')).toBe('http://localhost:58627');
1102+
expect(browserOpenOrigin('http://[::]:58627')).toBe('http://localhost:58627');
1103+
});
1104+
1105+
it('keeps navigable origins unchanged', async () => {
1106+
const { browserOpenOrigin } = await import('#/cli/sub/web/access-urls');
1107+
expect(browserOpenOrigin('http://127.0.0.1:58627')).toBe('http://127.0.0.1:58627');
1108+
expect(browserOpenOrigin('http://192.168.1.5:58627')).toBe('http://192.168.1.5:58627');
1109+
expect(browserOpenOrigin('http://[::1]:58627')).toBe('http://[::1]:58627');
1110+
});
1111+
});
1112+
10371113
describe('`pythinker web rotate-token`', () => {
10381114
let dir: string;
10391115
let prevHome: string | undefined;

‎packages/agent-core-v2/src/agent/profile/profileService.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,12 @@ export class AgentProfileService extends Disposable implements IAgentProfileServ
174174
this.states.contributeState(profileEmittedToolPatternWarningsKey);
175175
this.states.contributeState(profileEmittedPluginBudgetWarningsKey);
176176
this.configure({});
177+
this._register(
178+
this.dispatcher.hooks.onDidRestore.register('profile', async (_ctx, next) => {
179+
this.syncTelemetryModelContext(this.modelAlias);
180+
await next();
181+
}),
182+
);
177183
this._register(
178184
this.config.onDidSectionChange(({ domain }) => {
179185
if (domain === TOOLS_SECTION) {
@@ -545,11 +551,7 @@ export class AgentProfileService extends Disposable implements IAgentProfileServ
545551

546552
private afterConfigDispatch(changed: Omit<ProfileUpdateData, 'activeToolNames'>): void {
547553
if (changed.modelAlias !== undefined) {
548-
const model = this.tryResolveRawModel();
549-
this.telemetryContext.set({
550-
provider_type: model?.providerType ?? model?.protocol,
551-
protocol: model?.protocol,
552-
});
554+
this.syncTelemetryModelContext(changed.modelAlias);
553555
}
554556
if (changed.modelAlias !== undefined || changed.thinkingLevel !== undefined) {
555557
this.warnAboutAnthropicThinkingEffort();
@@ -559,6 +561,18 @@ export class AgentProfileService extends Disposable implements IAgentProfileServ
559561
);
560562
}
561563

564+
private syncTelemetryModelContext(modelAlias: string | undefined): void {
565+
if (modelAlias === undefined) {
566+
return;
567+
}
568+
const model = this.tryResolveRawModel();
569+
this.telemetryContext.set({
570+
model: modelAlias,
571+
provider_type: model?.providerType ?? model?.protocol,
572+
protocol: model?.protocol,
573+
});
574+
}
575+
562576
private warnAboutAnthropicThinkingEffort(): void {
563577
try {
564578
const model = this.tryResolveRawModel();

‎packages/agent-core-v2/src/agent/tools/agent/agentTool.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
import { IAgentToolPolicyService } from '#/agent/toolPolicy/toolPolicy';
2323
import { IAgentScopeContext } from '#/agent/scopeContext/scopeContext';
2424
import { IAgentLoopService } from '#/agent/loop/loop';
25+
import { IAgentPermissionModeService } from '#/agent/permissionMode/permissionMode';
2526
import {
2627
ToolAccesses,
2728
type ExecutableToolContext,
@@ -44,8 +45,15 @@ import { ILogService } from '#/_base/log/log';
4445
import { IConfigService } from '#/app/config/config';
4546
import { IFlagService } from '#/app/flag/flag';
4647
import { IAgentLifecycleService } from '#/session/agentLifecycle/agentLifecycle';
47-
import { isSubagentMeta, subagentLabels, subagentParentAgentId } from '#/session/agentLifecycle/subagentMetadata';
48-
import { ISessionMetadata } from '#/session/sessionMetadata/sessionMetadata';
48+
import { hasPinnedPermissionMode } from '#/features/tower/tower';
49+
import {
50+
isSubagentMeta,
51+
labelsFromAgentMeta,
52+
subagentLabels,
53+
subagentParentAgentId,
54+
subagentProfileName,
55+
} from '#/session/agentLifecycle/subagentMetadata';
56+
import { type AgentMeta, ISessionMetadata } from '#/session/sessionMetadata/sessionMetadata';
4957

5058
import { emitAgentRunSpawned, mirrorAgentRun, SubagentStarted } from '#/session/subagent/mirrorAgentRun';
5159
import { IEventDispatcher } from '#/state/eventDispatcher';
@@ -108,6 +116,7 @@ export class SubagentTool implements ISubagentTool {
108116
@IAgentProfileService private readonly profile: IAgentProfileService,
109117
@IAgentToolPolicyService private readonly toolPolicy: IAgentToolPolicyService,
110118
@IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService,
119+
@IAgentPermissionModeService private readonly permissionMode: IAgentPermissionModeService,
111120
@ISessionMetadata private readonly sessionMetadata: ISessionMetadata,
112121
@ILogService private readonly log: ILogService,
113122
@IConfigService private readonly config: IConfigService,
@@ -232,7 +241,7 @@ export class SubagentTool implements ISubagentTool {
232241

233242
const profileNameForDisplay =
234243
resumeAgentId !== undefined && resumeAgentId.length > 0
235-
? this.resumeProfileName(resumeAgentId) ?? RESUMED_LABEL
244+
? (await this.resumeProfileName(resumeAgentId)) ?? RESUMED_LABEL
236245
: (requestedProfileName ??
237246
(args.fork === true
238247
? (this.profile.data().profileName ?? DEFAULT_PROFILE_NAME)
@@ -253,10 +262,10 @@ export class SubagentTool implements ISubagentTool {
253262
};
254263
}
255264

256-
private resumeProfileName(agentId: string): string | undefined {
265+
private async resumeProfileName(agentId: string): Promise<string | undefined> {
257266
const target = this.agentLifecycle.handleOf(agentId);
258-
if (target === undefined) return undefined;
259-
return target.accessor.get(IAgentProfileService).data().profileName;
267+
if (target !== undefined) return target.accessor.get(IAgentProfileService).data().profileName;
268+
return subagentProfileName((await this.sessionMetadata.read()).agents?.[agentId]);
260269
}
261270

262271
private async launch(
@@ -283,13 +292,7 @@ export class SubagentTool implements ISubagentTool {
283292
let currentRoutingEnvironmentRevision: string | undefined;
284293
let promptText = args.prompt;
285294
if (isResume) {
286-
const target = this.agentLifecycle.handleOf(resumeAgentId);
287-
if (target === undefined) {
288-
throw new Error2(ErrorCodes.AGENT_NOT_FOUND, `Agent instance "${resumeAgentId}" does not exist`, {
289-
details: { agentId: resumeAgentId },
290-
});
291-
}
292-
await this.ensureOwnedIdleSubagent(resumeAgentId, target);
295+
const target = await this.resolveResumeTarget(resumeAgentId);
293296
agentId = target.id;
294297
const resumed = target.accessor.get(IAgentProfileService).data();
295298
profileName = resumed.profileName ?? RESUMED_LABEL;
@@ -349,12 +352,15 @@ export class SubagentTool implements ISubagentTool {
349352
};
350353
}
351354

352-
private async ensureOwnedIdleSubagent(
353-
agentId: string,
354-
target: IAgentScopeHandle,
355-
): Promise<void> {
355+
private async resolveResumeTarget(agentId: string): Promise<IAgentScopeHandle> {
356+
const live = this.agentLifecycle.handleOf(agentId);
356357
const meta = (await this.sessionMetadata.read()).agents?.[agentId];
357-
if (!isSubagentMeta(meta)) {
358+
if (meta === undefined && live === undefined) {
359+
throw new Error2(ErrorCodes.AGENT_NOT_FOUND, `Agent instance "${agentId}" does not exist`, {
360+
details: { agentId },
361+
});
362+
}
363+
if (meta === undefined || !isSubagentMeta(meta)) {
358364
throw new Error2(ErrorCodes.AGENT_NOT_A_SUBAGENT, `Agent instance "${agentId}" is not a subagent`, {
359365
details: { agentId },
360366
});
@@ -366,13 +372,34 @@ export class SubagentTool implements ISubagentTool {
366372
{ details: { agentId, callerAgentId: this.callerAgentId } },
367373
);
368374
}
375+
const target = live ?? (await this.rebuildSubagent(agentId, meta));
369376
if (target.accessor.get(IAgentLoopService).status().state === 'running') {
370377
throw new Error2(
371378
ErrorCodes.AGENT_ALREADY_RUNNING,
372379
`Agent instance "${agentId}" is already running and cannot run concurrently`,
373380
{ details: { agentId } },
374381
);
375382
}
383+
return target;
384+
}
385+
386+
private async rebuildSubagent(agentId: string, meta: AgentMeta): Promise<IAgentScopeHandle> {
387+
await this.agentLifecycle.create({
388+
agentId,
389+
labels: labelsFromAgentMeta(meta),
390+
forkedFrom: meta.forkedFrom,
391+
});
392+
const rebuilt = this.agentLifecycle.handleOf(agentId);
393+
if (rebuilt === undefined) {
394+
throw new Error2(ErrorCodes.AGENT_NOT_FOUND, `Agent instance "${agentId}" does not exist`, {
395+
details: { agentId },
396+
});
397+
}
398+
if (!hasPinnedPermissionMode(rebuilt.accessor.get(IAgentProfileService).data().profileName)) {
399+
rebuilt.accessor.get(IAgentPermissionModeService).setMode(this.permissionMode.mode);
400+
}
401+
this.log.info('subagent rebuilt for resume', { agentId, callerAgentId: this.callerAgentId });
402+
return rebuilt;
376403
}
377404

378405
private async execution(

‎packages/agent-core-v2/src/app/telemetry/agentTelemetryContext.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { createDecorator } from '#/_base/di/instantiation';
22

33
export type AgentTelemetryContext = {
44
mode: 'agent' | 'plan';
5+
model?: string;
56
provider_type?: string;
67
protocol?: string;
78
turn_id?: number;

‎packages/agent-core-v2/src/features/tower/tower.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ export const TOWER_TOOL_NAMES = [
1515

1616
export const TOWER_WORKER_PROFILE = 'tower-worker';
1717

18+
export function hasPinnedPermissionMode(profileName: string | undefined): boolean {
19+
return profileName === TOWER_WORKER_PROFILE;
20+
}
21+
1822
export const TOWER_FLAG_ID = 'tower';
1923

2024
export interface IAgentTowerService {

0 commit comments

Comments
 (0)