Repository navigation
feat(daemon): record & query sub-session parentSessionId; drop isolated scheduled-task mode - #6676
Conversation
…uled-task mode Two changes bundled from this session (recovered after an external merge-test harness force-reset the worktree): 1. Remove the scheduled-task "isolated" run mode and its precondition machinery. All tasks now run in their bound session (shared). The create_sub_session tool is retained so users can request isolation from a prompt. Drops runMode/condition/withheld across the persistence type, scheduler, Session dispatch, REST route, Web Shell UI, i18n, and the daemon/SDK contract, with tests updated. 2. Add an immutable parentSessionId to sub-sessions created via create_sub_session, wired end to end: BridgeSpawnRequest -> SessionEntry -> session summary, persisted into the child transcript (new parent_session record + qwen/control/session/parent ext-method) and rehydrated by listSessions on daemon restart, surfaced on BridgeSessionSummary / DaemonSessionSummary.
- chatRecordingService: recordParentSession writes a parent_session record - sessionService: listSessions reads parentSessionId back from the transcript, including the head-window fallback past the 64KB tail - bridge: spawnOrAttach threads parentSessionId to the session summary and dispatches the sessionParent ext-method (and not when there is no parent) - create-sub-session launcher: passes callerSessionId as parentSessionId
GET /workspace/:id/sessions accepts a `parentSessionId` query param that returns only the sessions spawned by that parent (via create_sub_session). The default path gathers the whole workspace (persisted + live) and filters before paginating, so a page is never short of matches; results are sorted newest-activity-first with an opaque activity cursor. Rejected (400) when combined with view=organized. Threaded through the SDK (DaemonSessionListPageOptions.parentSessionId / listWorkspaceSessions).
Response-builder cases: filters to a parent's children, empty when none, paginates the filtered set completely (no dupes/gaps). Route cases: the query param filters GET /workspace/:id/sessions, 400s with view=organized (invalid_parent_session_filter) and on an empty value (invalid_parent_session_id).
Code Coverage Summary
CLI Package - Full Text ReportCore Package - Full Text ReportFor detailed HTML reports, please see the 'coverage-reports-22.x-ubuntu-latest' artifact from the main CI run. |
ytahdn
left a comment
There was a problem hiding this comment.
Reviewed — no blockers. Suggestion-level recommendations are in the Suggestion summary comment below.
— qwen3.7-plus via Qwen Code /review
Suggestions — commit
|
| File | Issue | Suggested fix |
|---|---|---|
packages/core/src/services/cronScheduler.ts |
Existing on-disk tasks with runMode: 'isolated' silently change behavior (now run inline, unconditionally). No startup warning or one-time migration log. Users who relied on isolation may not notice their tasks now accumulate in the bound session. |
Add a one-time migration or startup warning: log when a loaded task has runMode: 'isolated' and strip the orphaned fields from disk. |
packages/cli/src/acp-integration/acpAgent.ts |
No test for the new sessionParent ext-method handler. Input validation (empty/non-string params), persisted: true success path, and persisted: false (no recording service) path are untested at this layer. |
Add tests covering: valid call → persisted: true, no recording service → persisted: false, invalid params → invalidParams error. |
packages/cli/src/serve/server/session-list.ts |
No test verifies parentSessionId is correctly merged from live sessions when a session exists both persisted and live. The existing.parentSessionId ?? live.parentSessionId merge logic is untested for the live-only case. |
Add a test that spawns a session via the bridge with a parentSessionId, then lists sessions and verifies the parent appears before any transcript is written. |
packages/cli/src/serve/server/session-list.ts |
The persisted+live merge logic is duplicated in 3 places (listOrganizedWorkspaceSessionsForResponse, listWorkspaceSessionsForResponse, listWorkspaceSessionsByParentForResponse). Future changes must be applied in 3 spots. |
Extract a shared mergePersistedAndLive() helper. Each caller applies its own filter/sort/paginate on top. |
packages/core/src/services/sessionService.ts |
readParentSessionIdFromFile is called unconditionally for every session during listing, even when the caller doesn't need parentSessionId. Adds per-file I/O to the common listing path. |
Lazily read parentSessionId only when the caller opts in (e.g., includeParentSessionId flag), or cache it alongside the title. |
— qwen3.7-plus via Qwen Code /review
ytahdn
left a comment
There was a problem hiding this comment.
LGTM ✅
— qwen3.7-plus via Qwen Code /review
…ields; scope & persist parentSessionId Review follow-ups on the isolated-removal + parentSessionId work: - scheduled-tasks REST: reject a POST/PATCH that still carries `runMode` or `condition` (400 unsupported_field) instead of silently ignoring them, so a stale SDK / cached Web Shell fails closed rather than getting a plain unconditional task in place of the guarded one it asked for. - cron scheduler: a legacy on-disk task that still carries a `condition` precondition is skipped (left on disk), not run inline unconditionally — a removed safety gate must not silently become "always run". One-time operator breadcrumb points at remediation. - bridge: await + verify the sessionParent persistence instead of fire-and-forget, so a dropped transcript write is surfaced loudly rather than silently degrading the parent link to live-only after a restart. The child is not rolled back on failure. - session list: the ?parentSessionId= page cursor now binds its parentSessionId + archiveState and rejects a cursor replayed against a different parent / archive scope, matching the organized cursor contract. Tests added for all four.
Resolved conflicts in acp-bridge (both sides added a BridgeSpawnRequest field — kept parentSessionId + main's approvalMode; main relocated the defaultEntry assignment to after init, kept my awaited parentSessionId persistence in its place). Build + affected suites green.
wenshao
left a comment
There was a problem hiding this comment.
No review findings. Downgraded from Approve to Comment: self-PR.
— qwen3.7-max via Qwen Code /review
wenshao
left a comment
There was a problem hiding this comment.
| const archiveState = options.archiveState ?? 'active'; | ||
| const sessionService = new SessionService(workspaceCwd); | ||
| const bySessionId = new Map<string, BridgeSessionSummary>(); | ||
| const persisted = await listAllPersistedSummaries( |
There was a problem hiding this comment.
[Suggestion] Every parent-filter cursor page rematerializes the entire persisted workspace (up to 50,000 sessions), performs the per-transcript metadata reads, then filters/sorts before returning at most one page. Requesting page two repeats the same full scan, making pagination roughly O(workspace sessions × pages) and potentially gigabytes of synchronous transcript-window I/O. Prefer a storage-level parent iterator/index or a cached lineage snapshot that can resume from the cursor.
— GPT-5 via Qwen Code /review
There was a problem hiding this comment.
Acknowledged — this is a conscious tradeoff, not an oversight. The gather-all-then-filter approach was chosen for correctness (a page is never silently short of matches, and pagination stays consistent under the opaque cursor). A storage-level parent index/iterator is the right long-term answer but is a larger, separate piece of work; a parent has a bounded, small number of children in practice, so the full-scan cost is acceptable for now. Leaving this open for a maintainer to weigh — happy to do the index as a follow-up if desired.
… paths; surface parentSessionId persistence outcome - cron: remove obsolete callback-level "guarded task" tests (headless + interactive) — the guard moved to the scheduler load (fail-closed), so those callbacks never receive a guarded job. Fixes the CI failures. - scheduled-tasks REST: a legacy on-disk task that still carries a `condition` is now failed closed on EVERY path, not just the scheduler tick — GET reports it `enabled:false` with no `nextRunAt`, and POST /run rejects it (409 task_legacy_unsupported). Shared `taskHasLegacyCondition` helper (exported from core) is the single source of truth. - bridge: the sub-session parent-lineage write is now timeout-bounded (withTimeout, like the other init round-trips) and retried, and its outcome is surfaced to the caller via BridgeSession.parentSessionPersisted (threaded through the launcher → ext-method → spawner → tool) instead of only stderr. create_sub_session warns the model when the link is live-only. Requires persisted===true for success. Tests added for all of the above.
Follow-up: toView reports a legacy `condition` task as disabled, so the
only PATCH the Web Shell sends for it is the Enable toggle. Accepting that
(200) then reading back disabled again is an Enable control that can never
succeed with no error. PATCH `{enabled:true}` on such a task now returns
409 task_legacy_unsupported with the recreate remediation. Test added.
PR #6676 Review SummaryPR: feat(daemon): record & query sub-session parentSessionId; drop isolated scheduled-task mode Overall this PR makes two clean, well-motivated changes. The Critical
Suggestions
|
|
[Critical — not in GitHub diff, flagged from local review] The loop job path (line 867) and interactive/inbound path (line 3846) both register When the bridge emits Suggested fix — mirror the loop job handler: const onResponseBoundary = (sid: string) => {
if (sid !== sessionId || promptState.cancelled || promptState.cancelPending) return;
heldChunks.length = 0;
this.onResponseBoundary(target.chatId, sessionId);
};
promptBridge.on('responseBoundary', onResponseBoundary);
// ... in finally:
promptBridge.off('responseBoundary', onResponseBoundary);(This file does not appear in the GitHub diff due to the merge commit with main — flagging here for visibility.) |
wenshao
left a comment
There was a problem hiding this comment.
…idempotent parent record; perf + dedup Addressing ytahdn's review: - cron: a bare `runMode: 'isolated'` task (no precondition) has no safety gate, so it still fires — but it now accumulates history in its bound session instead of a fresh per-run one. It runs, with a one-time operator warning (the condition subset still fails closed). New shared `taskHasLegacyRunMode` helper. - chatRecordingService: `recordParentSession` is now idempotent (skips a repeat append for the same immutable lineage) — matters because the bridge write is now retried. - sessionService: read `parentSessionId` from the records already loaded for the listing instead of a second per-file open (the record is written at creation, within the scan window) — removes the extra I/O on the hot listing path. - session-list: extract the persisted+live merge into one `mergeLiveSessionSummary` helper (was duplicated across the default, organized and by-parent paths). Tests: legacy-runMode fires+warns-once, recordParentSession idempotency, and the acpAgent sessionParent ext-method handler (valid / no-recording / invalid-params).
|
Thanks @ytahdn — addressed in Critical
Suggestions
Also added tests for the |
|
@qwen-code /triage |
…le parent write; legacy tasks fail closed everywhere GPT-5 review round + a two-pass reverse audit: - forkSession no longer copies the source's `parent_session` record, so a fork is a fresh top-level session, not a phantom child of the original. - restore/resume now re-seed the persisted `parentSessionId` on the live entry (both the REST handler and the ACP-HTTP transport — the audit caught the ACP path being missed), so a restored sub-session still reports its parent after a daemon restart. - SDK: the ACP route mapping + `session/list` dispatcher now forward, filter, and project `parentSessionId`; `WorkspaceDaemonClient` serializes it too — the filter works over every SDK transport, not just the root HTTP client. - recordParentSession is awaited via the strict append path, so `persisted: true` never claims a write that silently failed; it stays idempotent so a retry can't double-append. - bridge parent-write is raced against transport close and treats a timeout as terminal (not a retry that would overlap an in-flight request), under one deadline. - legacy guarded tasks (removed isolated mode + precondition) now fail closed on ALL consumers — cron_list reports them disabled, keepalive won't bind or keep their sessions resident — not just the scheduler tick. - a bare legacy `runMode: 'isolated'` task (no gate) still runs, with a one-time behavior-change warning. - restored `withheld` as a read-only compat field so pre-upgrade withheld run-history is marked "skipped", not shown as a successful run. Tests added/updated across all of the above.
wenshao
left a comment
There was a problem hiding this comment.
Reviewed — no blockers. Suggestions are inline.
| if (attempt === MAX_PARENT_PERSIST_ATTEMPTS) { | ||
| parentSessionPersisted = false; | ||
| writeStderrLine( | ||
| `qwen serve: failed to persist parentSessionId for ${entry.sessionId} ` + |
There was a problem hiding this comment.
[Suggestion] The retry loop for persisting parentSessionId retries immediately with no delay between attempts. On a flapping connection, three rapid-fire attempts are less likely to succeed than attempts spaced apart.
| `qwen serve: failed to persist parentSessionId for ${entry.sessionId} ` + | |
| parentSessionPersisted = false; | |
| writeStderrLine( | |
| `qwen serve: parentSessionId for ${entry.sessionId} was not persisted — ` | |
| ); | |
| } else { | |
| await new Promise((r) => setTimeout(r, 200)); | |
| } |
— qwen3.7-max via Qwen Code /review
| * imported type, so core stays a type-only dependency of the fire path. */ | ||
| interface CronFire { | ||
| id?: string; | ||
| prompt: string; |
There was a problem hiding this comment.
[Suggestion] CronFire retains id and lastFiredAt fields that are no longer read anywhere in Session.ts — the sole consumer was #markCronRunWithheld, which this PR removes. Consider removing these dead fields.
— qwen3.7-max via Qwen Code /review
| } | ||
| const session = this.sessionOrThrow(sessionId); | ||
| const recording = session.getConfig().getChatRecordingService(); | ||
| let ok = false; |
There was a problem hiding this comment.
[Suggestion] await recording.flush() runs unconditionally whenever recording exists, even after recordParentSession returns false (an I/O error where no record was appended). When the write failed there is nothing new to flush. Consider gating: if (ok) { await recording.flush(); }.
— qwen3.7-max via Qwen Code /review
|
@qwen-code /triage |
|
@qwen-code /resolve |
|
Qwen Code resolved the merge conflicts and pushed the branch update. Merge Conflict Resolution SummaryPR: #6676 — feat(daemon): record & query sub-session parentSessionId; drop isolated scheduled-task mode Conflicted file
|
ytahdn
left a comment
There was a problem hiding this comment.
增量 Review(6ed44ae1 → 01546e0)
增量变更质量很高,上次 review 的核心 Suggestion 已妥善解决:
✅ 已修复
- parentSessionId 持久化:从 fire-and-forget 改为有界重试(最多 3 次)+ 超时 + transport-close 检测,通过
parentSessionPersisted标志向调用方报告结果。注释详尽,边界条件处理正确。 defaultEntry延迟发布:移到所有初始化(model switch + approval mode)成功之后,防止并发 attach 到即将关闭的 session。
👍 亮点
rollbackAttachRegistration清理逻辑完善,正确处理spawnOwnerWantedKill- 重试策略设计合理:仅同步拒绝才重试,超时/transport-close 是终态
create_sub_session返回值正确透传parentSessionPersisted- 新增
sessionTranscriptext-method(分页读取 transcript)是独立功能,与 parentSessionId 主线解耦
无 Critical 或 Suggestion 级别问题。
— qwen3.7-plus via Qwen Code /review
Summary
Two related scheduled-task / sub-session changes:
1. Remove the scheduled-task isolated run mode
Scheduled tasks no longer have a
sharedvsisolatedtoggle — every task runs in its bound session (the formersharedmodel). Thecreate_sub_sessiontool is kept, so per-run isolation is still available by asking for it in the prompt. This dropsrunMode/condition(precondition) /withheldacross the persistence type, scheduler,Sessiondispatch (#dispatchIsolatedCronFireand the precondition machinery), REST route, Web Shell UI + i18n, and the daemon/SDK contract.2. Record & query sub-session
parentSessionIdA sub-session created via
create_sub_sessionnow records the spawning session as an immutableparentSessionId, wired end to end:BridgeSpawnRequest → SessionEntry → session summaryparent_sessionrecord +qwen/control/session/parentext-method) and rehydrated bylistSessionson daemon restartBridgeSessionSummary/DaemonSessionSummaryGET /workspace/:id/sessions?parentSessionId=<id>returns only that parent's children. The whole workspace (persisted + live) is gathered and filtered before pagination, so a page is never short of matches; sorted newest-activity-first with an opaque cursor. Threaded through the SDK (DaemonSessionListPageOptions.parentSessionId,listWorkspaceSessions). Rejected (400) withview=organized.Real runtime verification
These were captured against a live
qwen servedaemon (not mocks/tests).create_sub_sessionlive invocation →parentSessionIdrecordedRan a real session and had the model actually call
create_sub_session(approval modeyolo, so the tool's'ask'gate auto-approved unattended). It spawned a child sessiondee3d4cd…whoseparentSessionIdis the caller2245b3e7…:Daemon-side proof — the spawned child carries the caller as
parentSessionId, both via the query API and persisted in the child's transcript (theparent_sessionrecord written by theqwen/control/session/parentext-method):parentSessionId session-list API
Started a real daemon over 4 on-disk sessions (1 parent, 2
create_sub_sessionchildren, 1 unrelated) and hit the endpoint withcurl. The children'sparentSessionIdis read purely from the transcript — i.e. this also exercises the restart/rehydrate path.parentSessionId; parent/unrelated arenull?parentSessionId=<parent>→ exactly the 2 children,nextCursor=null&view=organized→400 invalid_parent_session_filter; empty value →400 invalid_parent_session_idWeb Shell — "New scheduled task" form (isolated selector removed)
Drove the actual Web Shell UI (Chrome) to open the create-task form. It now has only Name / Prompt / Frequency / Time — no run-mode radios, no precondition field. Programmatic asserts on the live DOM:
input[name="runMode"]count = 0, precondition textarea count = 0.Testing
npm run build(all workspaces) — greeneslint --max-warnings 0on all changed files — cleancronTasksFile,cronScheduler,chatRecordingService.parentSession,sessionService), acp-bridge (bridge), cli (Session,scheduled-tasksroutes,create-sub-session,server,multi-workspace-sessions), web-shell (ScheduledTasksDialog)sessionParentext-method dispatch, launcher wiring, and the?parentSessionId=filter incl. pagination + 400 cases)Backward compatibility
On-disk tasks that still carry
runMode: 'isolated'/conditionload fine (unknown fields are ignored by validation) and now run inline in their bound session, unconditionally — the intended behavior change. Sessions with noparent_sessionrecord simply reportparentSessionId: undefined.中文说明(点击展开)
概述
两项相关的定时任务 / 子会话改动:
1. 移除定时任务的 isolated(隔离) 运行模式
定时任务不再有
shared/isolated开关——每个任务都在其绑定会话内执行(即原先的shared模型)。保留create_sub_session工具,用户仍可在 prompt 里自行请求按次隔离。此改动删除了runMode/condition(前置条件)/withheld,涉及持久化类型、调度器、Session派发(#dispatchIsolatedCronFire及前置条件相关逻辑)、REST 路由、Web Shell UI + i18n,以及守护进程 / SDK 契约。2. 记录并可查询子会话的
parentSessionId通过
create_sub_session创建的子会话,现在会把发起它的会话记录为不可变的parentSessionId,并一路打通:BridgeSpawnRequest → SessionEntry → session summaryparent_session记录 +qwen/control/session/parentext-method),并在守护进程重启后由listSessions从 transcript 重建BridgeSessionSummary/DaemonSessionSummary上GET /workspace/:id/sessions?parentSessionId=<id>只返回该父会话的子会话。默认路径会先聚合整个 workspace(持久化 + live)再过滤分页,保证每页不会因过滤而缺项;按活动时间倒序、使用不透明游标。已透传到 SDK(DaemonSessionListPageOptions.parentSessionId、listWorkspaceSessions)。与view=organized同用时返回 400。真实运行验证
以下截图均针对真实运行的
qwen serve守护进程捕获(非 mock / 单测)。create_sub_session实跑调用 → 记录parentSessionId在真实会话里让模型真正调用了
create_sub_session(approval 模式为yolo,工具的'ask'门在无人值守下自动放行)。它 spawn 出子会话dee3d4cd…,其parentSessionId就是发起方2245b3e7…:守护进程侧证据——spawn 出的子会话携带发起方作为
parentSessionId,既能通过查询 API 拿到,也持久化在子会话的 transcript 里(由qwen/control/session/parentext-method 写入的parent_session记录):parentSessionId 列表 API
针对 4 个磁盘会话(1 个父、2 个
create_sub_session子、1 个无关)启动真实守护进程并用curl请求。子会话的parentSessionId完全从 transcript 读回——因此这同时验证了重启 / rehydrate 路径。parentSessionId;父会话 / 无关会话为null?parentSessionId=<parent>→ 恰好 2 个子会话,nextCursor=null&view=organized→400 invalid_parent_session_filter;空值 →400 invalid_parent_session_idWeb Shell —「New scheduled task」表单(隔离选择器已移除)
用 Playwright 驱动真实 Web Shell UI(Chrome)打开新建任务表单,现在只有 Name / Prompt / Frequency / Time,无运行模式单选、无前置条件输入框。对 live DOM 的程序化断言:
input[name="runMode"]数量 = 0,前置条件 textarea 数量 = 0。测试
npm run build(所有 workspace)—— 通过eslint --max-warnings 0—— 无告警sessionParentext-method 下发、launcher 接线,以及?parentSessionId=过滤含分页与 400 用例)向后兼容
磁盘上仍带
runMode: 'isolated'/condition的旧任务能正常读取(校验忽略未知字段),现在会在绑定会话内无条件内联执行——这是预期的行为变更。没有parent_session记录的会话,parentSessionId为undefined。