Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Preserve local conversation recovery, interrupted history and live display continuity

wytfe4beb3552c1
diff --git a/docs/test/conversations-regression.md b/docs/test/conversations-regression.md
index 9accf206..756e406c 100644
--- a/docs/test/conversations-regression.md
+++ b/docs/test/conversations-regression.md
@@ -353,6 +353,24 @@ Orkas 不在 Commander、内置 in-process Agent 或 CLI Agent 的 prompt 中追
3. 自动恢复验证成功后返回 `cascade_failed` 并清理内部快照;验证不完整时返回
`cascade_recovery_incomplete` 并保留快照供重试。
+### Local history cleanup, repair and restoration
+
+- Cleanup operates on the confirmed preview only. After a successful run, show
+ the refreshed remaining count and clear selection. Tasks added afterwards
+ require a new selection; changing the age filter does not install a retention policy.
+- A repair paused during discovery must not overwrite a subsequent delete,
+ pin, create or explicit restore, or remove the restored metadata.
+- An explicitly deleted task must remain hidden if its old payload reappears
+ with a newer modification time. Missing or unreadable transcripts alone must
+ not be treated as permission to delete a task.
+- Repeat local repair after restarting. Deleted metadata must not reappear;
+ an explicit recycle-bin restoration must remain visible, including a task
+ whose archive contains metadata and drafts without a transcript.
+
+Automated owners: `test/main/features/chats.test.ts`,
+`test/main/features/recycle_bin.test.ts`, `test/renderer/task-cleanup.test.ts`
+and `test/e2e/task_cleanup_e2e_history.spec.ts`.
+
## 任务失败只来自明确执行错误(2026-08-20)
1. 模型正文不再携带成功/失败结果标记,宿主不得从模型自述推导任务状态。
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index b3e6a938..106c832e 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -50,7 +50,7 @@ import {
import { evictSession, deleteSessionFileForUser } from '../model/core-agent/session-store';
import {
nowIso, genConversationId, genId12, safeId,
- readJson, writeJson, invalidateLineCount, readJsonl, readJsonlPage, readJsonlWindow, appendJsonlAtomic,
+ readJson, writeJson, invalidateLineCount, readJsonl, readJsonlPage, readJsonlPageWithOffsets, readJsonlWindow, appendJsonlAtomic,
} from '../storage';
import { removeCodingDirectory } from './local_agents/project-directory';
import { createLogger } from '../logger';
@@ -96,10 +96,11 @@ import {
readMembers,
readRunningConversationRegistry,
readState,
- setStatus,
+ parseInFlightTurns,
+ recoverOrphanRunningState,
untrackRunningConversation,
} from './group_chat/state';
-import type { ActorKind } from './group_chat/state';
+import type { ActorKind, StateFile } from './group_chat/state';
import type { GroupMessage } from './group_chat/visibility';
function conversationIndexName(): string {
@@ -190,6 +191,7 @@ export interface Conversation {
* long enough to propagate across offline devices; user-facing readers
* filter them out. */
deleted_at?: string;
+ restored_at?: string;
/** Record-level conflict clock for aggregate `_index.json` merges. */
_sync_rev?: number;
_sync_device_id?: string;
@@ -478,6 +480,7 @@ function _normaliseConversation(raw: any, fallbackCid = ''): Conversation | null
if (typeof raw.pinned_at === 'string' && raw.pinned_at) out.pinned_at = raw.pinned_at;
if (typeof raw.pin_state_updated_at === 'string' && raw.pin_state_updated_at) out.pin_state_updated_at = raw.pin_state_updated_at;
if (raw.title_manually_set === true) out.title_manually_set = true;
+ if (typeof raw.restored_at === 'string' && raw.restored_at) out.restored_at = raw.restored_at;
if (typeof raw.deleted_at === 'string' && raw.deleted_at) out.deleted_at = raw.deleted_at;
if (Array.isArray(raw.agent_ids)) out.agent_ids = _normaliseAgentIds(raw.agent_ids);
if (typeof raw.commander_in_chat === 'boolean') out.commander_in_chat = raw.commander_in_chat;
@@ -960,14 +963,6 @@ async function _removeConversationMeta(userId: string, cid: string): Promise<voi
}
}
-function _notifyChatIndexDirty(projectId?: string | null): void {
- try {
- // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
- const sync = null as { markDirty?: (domain: string, relPath: string) => void };
- sync?.markDirty?.('chats', `cloud/chats/${conversationIndexName()}`);
- } catch { /* features/sync stripped */ }
-}
-
function _messageText(raw: any): string {
if (!raw || typeof raw !== 'object') return '';
if (typeof raw.text === 'string') return raw.text;
@@ -1071,57 +1066,53 @@ async function _withConversationWrite<T>(userId: string, fn: () => Promise<T>):
async function _repairConversationIndexFromDiskUnlocked(
userId: string,
items: Conversation[],
- discoveredMetaRows = 0,
+ discoveredMetaRows: number,
+ generation: number,
signal?: AbortSignal,
): Promise<ConversationRepairRun> {
if (signal?.aborted) return { items, cancelled: true };
const existing = new Set(items.map((c) => c.conversation_id).filter(Boolean));
const recovered: Conversation[] = [];
- let resurrected = 0;
- for (let index = 0; index < items.length; index++) {
- if (index > 0 && index % 100 === 0) {
- await new Promise<void>((resolve) => setImmediate(resolve));
- }
- const c = items[index];
- if (!isDeletedConversation(c) || !safeId(c.conversation_id)) continue;
- const file = conversationMessageReadFile(userId, c.conversation_id, c.project_id ?? null);
- let st: fs.Stats | null = null;
- try { st = await fsp.stat(file); } catch {
- await _removeConversationMeta(userId, c.conversation_id);
- continue;
- }
- if (!st.isFile()) {
- await _removeConversationMeta(userId, c.conversation_id);
- continue;
- }
- // A sync download has a fresh filesystem mtime too. Only an explicit
- // restore/recreation may clear the record tombstone.
- await _removeConversationMeta(userId, c.conversation_id);
- if (isExpiredIsoTombstone(c.deleted_at)) {
- try { await fsp.unlink(file); } catch { /* ignore */ }
- invalidateLineCount(file);
- }
- }
+ const tombstones = items.filter(c => isDeletedConversation(c) && safeId(c.conversation_id));
const compacted = pruneExpiredDeletedRecords(items) as Conversation[];
const expiredTombstoneCount = items.length - compacted.length;
items = compacted;
const finish = async (cancelled: boolean, includeRecovered: boolean): Promise<ConversationRepairRun> => {
const acceptedRecovered = includeRecovered ? recovered : [];
- if (!acceptedRecovered.length && !resurrected && !expiredTombstoneCount && !discoveredMetaRows) {
- return { items, cancelled };
- }
- const repaired = [...items, ...acceptedRecovered];
- // Once a repair commit begins it runs to completion. Stopping between
- // physical root writes could leave project/global indexes inconsistent.
- await saveConversations(userId, repaired);
- _notifyChatIndexDirty();
- try {
- createLogger('chats').info(
- `repaired conversation index user=${userId} recovered=${acceptedRecovered.length} recovered_meta=${discoveredMetaRows} resurrected=${resurrected} pruned_tombstones=${expiredTombstoneCount} cancelled=${cancelled}`,
- );
- } catch { /* early circular init */ }
- return { items: repaired, cancelled };
+ const snapshot = [...items, ...acceptedRecovered];
+ // Do not hold the lifecycle lock during discovery. Validate the snapshot
+ // inside that lock before any index, metadata, or transcript mutation.
+ return _withConversationWrite(userId, async () => {
+ if ((_conversationListGeneration.get(userId) || 0) !== generation) {
+ _invalidateConversationIndexCache(userId);
+ return { items: await _readIndexConversations(userId), cancelled: true };
+ }
+ const repaired = snapshot;
+ const changed = acceptedRecovered.length || expiredTombstoneCount || discoveredMetaRows;
+ try {
+ // Persist deletion intent before removing any remaining metadata.
+ if (changed) await _saveConversationsUnlocked(userId, repaired);
+ for (const c of tombstones) {
+ await _removeConversationMeta(userId, c.conversation_id);
+ if (isExpiredIsoTombstone(c.deleted_at)) {
+ const file = conversationMessageReadFile(userId, c.conversation_id, c.project_id ?? null);
+ try { await fsp.unlink(file); } catch { /* missing is fine */ }
+ invalidateLineCount(file);
+ }
+ }
+ if (changed) {
+ try {
+ createLogger('chats').info(
+ `repaired conversation index recovered=${acceptedRecovered.length} recovered_meta=${discoveredMetaRows} pruned_tombstones=${expiredTombstoneCount} cancelled=${cancelled}`,
+ );
+ } catch { /* early circular init */ }
+ }
+ return { items: repaired, cancelled };
+ } finally {
+ if (changed || tombstones.length) _invalidateConversationListCache(userId);
+ }
+ });
};
if (signal?.aborted) return finish(true, false);
@@ -1175,6 +1166,7 @@ async function _repairConversationIndexFromDisk(
const tails = _repairIndexTails();
const prev = tails.get(userId) || Promise.resolve({ items: [], cancelled: false });
const next = prev.catch(() => ({ items: [], cancelled: false })).then(async () => {
+ const generation = _conversationListGeneration.get(userId) || 0;
const indexed = await _readIndexConversations(userId);
if (signal?.aborted) return { items: indexed, cancelled: true };
const indexedCids = new Set(indexed.map((row) => row.conversation_id));
@@ -1184,7 +1176,7 @@ async function _repairConversationIndexFromDisk(
(count, row) => count + (indexedCids.has(row.conversation_id) ? 0 : 1),
0,
);
- return _repairConversationIndexFromDiskUnlocked(userId, latest, discoveredMetaRows, signal);
+ return _repairConversationIndexFromDiskUnlocked(userId, latest, discoveredMetaRows, generation, signal);
});
tails.set(userId, next);
try {
@@ -1227,7 +1219,12 @@ function _invalidateConversationIndexCache(userId: string): void {
const CONVERSATION_LIST_CACHE_TTL_MS = 2_000;
const _conversationListCache = new Map<string, { expiresAt: number; items: Conversation[] }>();
const _conversationListInFlight = new Map<string, Promise<Conversation[]>>();
-const _conversationListGeneration = new Map<string, number>();
+// Match the shared write queue across CJS/ESM instances. A module-local
+// generation would miss lifecycle mutations made through the other loader.
+const _conversationGenerationRegistry = globalThis as typeof globalThis & {
+ __orkasConversationListGeneration?: Map<string, number>;
+};
+const _conversationListGeneration = _conversationGenerationRegistry.__orkasConversationListGeneration ||= new Map<string, number>();
function _cloneConversationList(items: Conversation[]): Conversation[] {
return items.map((c) => ({
@@ -1401,8 +1398,8 @@ async function _listConversationsUncached(
const deviceId = _recordDeviceId(userId);
for (const c of summariesToBackfill) bumpRecordSyncVersion(c, deviceId);
const cleaned = pruneExpiredDeletedRecords(items.map(_cleanConversation)) as Conversation[];
- const writtenRoots = await _writeConversationIndexes(userId, cleaned);
- for (const root of writtenRoots) _notifyChatIndexDirty(root || undefined);
+ await _writeConversationIndexes(userId, cleaned);
+
log.info(`backfilled participant summaries user=${userId} conversations=${summariesToBackfill.length}`);
});
}
@@ -1822,7 +1819,6 @@ class ConversationIndexStore {
const rows = await this.readRoot(rootKey);
const cleaned = pruneExpiredDeletedRecords(rows.map(_cleanConversation)) as Conversation[];
await writeJson(conversationIndexFile(this.userId, rootKey || null), cleaned);
- _notifyChatIndexDirty(rootKey || undefined);
}));
// A rejected sibling must not keep writing after rollback has begun.
const failed = results.find((result) => result.status === 'rejected');
@@ -1879,6 +1875,14 @@ async function _writeConversationIndexes(
return roots;
}
+async function _saveConversationsUnlocked(userId: string, items: Conversation[]): Promise<void> {
+ const rawCleaned = items.map(_cleanConversation);
+ const cleaned = pruneExpiredDeletedRecords(rawCleaned) as Conversation[];
+ await _writeConversationIndexes(userId, cleaned);
+ await _saveConversationMetas(userId, rawCleaned);
+
+}
+
async function _saveConversations(
userId: string,
items: Conversation[],
@@ -1886,11 +1890,7 @@ async function _saveConversations(
_invalidateConversationListCache(userId);
try {
await _withConversationWrite(userId, async () => {
- const rawCleaned = items.map(_cleanConversation);
- const cleaned = pruneExpiredDeletedRecords(rawCleaned) as Conversation[];
- const writtenRoots = await _writeConversationIndexes(userId, cleaned);
- await _saveConversationMetas(userId, rawCleaned);
- for (const root of writtenRoots) _notifyChatIndexDirty(root || undefined);
+ await _saveConversationsUnlocked(userId, items);
});
} finally {
// A list can start while the index/meta writes above are in flight. Bump
@@ -2759,6 +2759,21 @@ interface ConversationStateCandidate {
journalTracked?: boolean;
}
+// The active-user startup pass and deferred maintenance may overlap. Serialize
+// the same conversation's reconciliation, including partial-write recovery.
+type StaleRecovery = Promise<void> & { recovery: { pendingFor?: string } };
+const _staleRecoveryTails = new Map<string, StaleRecovery>();
+
+function staleRecoveryIdentity(state: Pick<StateFile, 'in_flight' | 'in_flight_turns'>): string {
+ return JSON.stringify([state.in_flight, state.in_flight_turns]);
+}
+
+/** Status polling must not discard a startup receipt whose write is pending
+ * or failed. A newer state generation no longer belongs to that recovery. */
+export function isInterruptionRecoveryPending(uid: string, cid: string, state: StateFile): boolean {
+ return _staleRecoveryTails.get(`${uid}:${cid}`)?.recovery.pendingFor === staleRecoveryIdentity(state);
+}
+
/** A conversation blocked by pending move recovery has no resolvable layout.
* Skip it so one blocked cid cannot abort the sweep for every other run. */
function _stateCandidateFile(uid: string, cid: string, projectId: string | null | undefined): string | null {
@@ -2799,6 +2814,18 @@ async function _indexedConversationStateCandidates(uid: string): Promise<Convers
return out;
}
+function _isStaleTurnTerminal(record: GroupMessage): boolean {
+ if (record.deleted_at || record.from === 'user' || record.dispatch || record.cli_question) return false;
+ if (record.system_kind === 'reply_interrupted') return true;
+ if (!record.source_message_id?.trim()) return false;
+ // Public native segments retain the source too, but only the terminal
+ // segment settles the execution. Never mistake a saved commentary segment
+ // for a completed actor merely because it carries its causal input.
+ const phases = (record.process || []).filter(item => item.event?.stream === 'runtime')
+ .map(item => (item.event?.data as { phase?: string })?.phase);
+ return !phases.includes('segment_end') || phases.includes('end');
+}
+
function _latestHistorySettlesStaleRun(records: GroupMessage[]): boolean {
let latest: GroupMessage | undefined;
for (let index = records.length - 1; index >= 0; index -= 1) {
@@ -2809,24 +2836,48 @@ function _latestHistorySettlesStaleRun(records: GroupMessage[]): boolean {
}
}
if (!latest) return false;
- // A prior recovery notice already settles this stale state. This keeps a
- // damaged/recreated journal from appending the same notice on every boot.
- if (latest.system_kind === 'reply_interrupted') return true;
- // `source_message_id` is persisted on the actor's official terminal reply.
- // If that reply is the canonical tail, no newer user/dispatch record
- // started more work, so a lagging `state.json: running` is completion
- // residue rather than proof that the app exited mid-reply.
- const hasTerminalSource = typeof latest.source_message_id === 'string'
- && latest.source_message_id.trim().length > 0;
- return hasTerminalSource
- && latest.dispatch !== true
- && latest.from !== 'user';
-}
-
-async function _historySettlesStaleRun(uid: string, cid: string): Promise<boolean> {
+ return _isStaleTurnTerminal(latest);
+}
+
+async function _unsettledStaleActors(uid: string, cid: string, state: StateFile): Promise<string[]> {
const file = conversationMessageReadFile(uid, cid);
- const tail = await readJsonl<GroupMessage>(file, 8);
- return _latestHistorySettlesStaleRun(tail);
+ const actors = [...new Set(state.in_flight.filter(actor => safeId(actor) && actor !== 'user'))];
+ const readPage = async (cursor: number | null) => {
+ try { return await readJsonlPageWithOffsets<GroupMessage>(file, 8, cursor, { strict: true }); }
+ catch (error) {
+ // A locally journaled run can outlive its missing canonical file. Its
+ // interruption notice recreates that file; other I/O failures retry.
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { entries: [], nextCursor: null };
+ throw error;
+ }
+ };
+ if (!actors.length) {
+ const tail = await readPage(null);
+ return _latestHistorySettlesStaleRun(tail.entries.map(entry => entry.record)) ? [] : ['commander'];
+ }
+ const searching = new Set(actors), settled = new Set<string>();
+ let cursor: number | null = null;
+ do {
+ const page = await readPage(cursor);
+ for (let index = page.entries.length - 1; index >= 0 && searching.size; index--) {
+ const record = page.entries[index].record;
+ if (record.deleted_at) continue;
+ for (const actor of searching) {
+ const identity = state.in_flight_turns?.[actor];
+ if (record.from === actor && (!identity || record.turn_id === identity.turn_id) && _isStaleTurnTerminal(record)) {
+ settled.add(actor); searching.delete(actor);
+ } else if (identity ? record.id === identity.source_message_id : record.from === 'user') {
+ // This execution's input is a hard lower boundary. Legacy rosters
+ // have only the latest user turn as evidence; older replies cannot
+ // certify completion of newer work.
+ searching.delete(actor);
+ }
+ }
+ }
+ if (page.nextCursor === cursor) break;
+ cursor = page.nextCursor;
+ } while (cursor !== null && searching.size);
+ return actors.filter(actor => !settled.has(actor));
}
/**
@@ -2834,7 +2885,7 @@ async function _historySettlesStaleRun(uid: string, cid: string): Promise<boolea
* durable terminal history tail proves the status write merely lagged and is
* cleared silently. Otherwise the app stopped mid-run: flip to `idle` (not
* aborted — abort is a deliberate user action) and persist one actor-owned
- * interruption bubble so a reload cannot silently erase the live assistant
+ * interruption bubble per unfinished actor so a reload cannot erase a live
* placeholder. The next user message starts a fresh worker from durable state.
*/
export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swept: number }> {
@@ -2892,12 +2943,28 @@ export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swe
await _runBounded(candidates, 32, async ({
uid, cid, file, journalTracked,
}) => {
+ const key = `${uid}:${cid}`;
+ const previous = _staleRecoveryTails.get(key);
+ let release!: () => void;
+ const pending = new Promise<void>(resolve => { release = resolve; });
+ // Queue replacement must retain an earlier pending or failed receipt while
+ // the next sweep waits or reloads state and UI status polling continues.
+ const tail: StaleRecovery = Object.assign((previous || Promise.resolve()).then(() => pending), {
+ recovery: previous?.recovery || {},
+ });
+ _staleRecoveryTails.set(key, tail);
+ await previous;
+ let stateLoaded = false;
+ let recoveryFailed = false;
try {
- const raw = JSON.parse(await fsp.readFile(file, 'utf8'));
+ const raw = JSON.parse(await fsp.readFile(file, 'utf8')) as StateFile;
+ stateLoaded = true;
if (raw?.status !== 'running') {
if (journalTracked) await untrackRunningConversation(uid, cid);
return;
}
+ raw.in_flight = Array.isArray(raw.in_flight) ? raw.in_flight.filter(actor => typeof actor === 'string') : [];
+ raw.in_flight_turns = parseInFlightTurns(raw.in_flight, raw.in_flight_turns);
const lastActiveMs = Date.parse(String(raw.last_active_at || ''));
if (Number.isFinite(lastActiveMs) && lastActiveMs >= PROCESS_BOOT_CUTOFF_MS) {
// This state was created or refreshed by the current process. It is
@@ -2910,53 +2977,68 @@ export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swe
// live in-memory work always wins over disk maintenance.
return;
}
- const alreadySettled = await _historySettlesStaleRun(uid, cid);
- if (!journalTracked && !alreadySettled) {
+ if (journalTracked) tail.recovery.pendingFor = staleRecoveryIdentity(raw);
+ const interruptedActors = await _unsettledStaleActors(uid, cid, raw);
+ if (!journalTracked && interruptedActors.length) {
// A missing/corrupt local journal provides no ownership proof. This
// may be a live run synced from another device, so the migration scan
// may reconcile a durable terminal tail but must never manufacture an
// interruption from `state.json: running` alone.
return;
}
- await setStatus(uid, cid, 'idle');
- if (alreadySettled) {
+ if (!interruptedActors.length) {
// The terminal reply (or a prior recovery notice) is already durable.
// Reconcile only the stale status/journal; adding an interruption row
// here would turn a successfully completed task into a false failure.
+ await recoverOrphanRunningState(uid, cid, () => bus.isQuiescent(uid, cid));
return;
}
- const interruptedActors = Array.isArray(raw.in_flight)
- ? raw.in_flight.filter((actorId: unknown): actorId is string => safeId(actorId))
- : [];
const members = await readMembers(uid, cid);
- const memberIds = members.actors.map((actor) => actor.id).filter(safeId);
- const senderId = interruptedActors.find((actorId) => memberIds.includes(actorId))
- || interruptedActors[0]
- || 'commander';
+ const publicActors = new Set(raw.in_flight.filter(actor => raw.in_flight_turns?.[actor]
+ || members.actors.some(member => member.id === actor && member.kind !== 'worker')));
+ // Anonymous helpers have no public roster/turn receipt. Legacy retries
+ // could leave their ids in the roster; retain their public owner instead.
+ // A wholly legacy/missing roster still keeps the original actor fallback.
+ const senders = publicActors.size ? interruptedActors.filter(actor => publicActors.has(actor)) : interruptedActors;
const ts = new Date().toISOString();
- const interruptedMessage: GroupMessage = {
- id: genId12(),
- ts,
- from: senderId,
- to: ['user'],
- system_kind: 'reply_interrupted',
- text: t('chat.reply_interrupted'),
- model_text: 'The previous assistant run was interrupted by an application exit or crash before it produced a complete reply. Do not assume the interrupted operation completed; recover durable state before continuing.',
- };
const layout = conversationLayout(uid, cid);
- const { msgIndex, source } = await appendJsonlAtomic<GroupMessage>(layout.messageFile, interruptedMessage, true);
- await search.indexChatMessage(uid, cid, msgIndex, source ?? interruptedMessage);
- const senderKind = members.actors.find((actor) => actor.id === senderId)?.kind
- || (senderId === 'commander' ? 'commander' : 'agent');
- await bumpConversationActivity(uid, cid, ts, {
- senderKind,
- senderId,
- ...(senderKind === 'agent' ? { agentIds: [senderId] } : {}),
- }, layout.projectId);
+ for (const senderId of senders) {
+ const interruptedMessage: GroupMessage = {
+ id: genId12(),
+ ts,
+ from: senderId,
+ to: ['user'],
+ system_kind: 'reply_interrupted',
+ text: t('chat.reply_interrupted'),
+ model_text: 'The previous assistant run was interrupted by an application exit or crash before it produced a complete reply. Do not assume the interrupted operation completed; recover durable state before continuing.',
+ ...raw.in_flight_turns?.[senderId],
+ };
+ const { msgIndex, source } = await appendJsonlAtomic<GroupMessage>(layout.messageFile, interruptedMessage, true);
+ await search.indexChatMessage(uid, cid, msgIndex, source ?? interruptedMessage);
+ const senderKind = members.actors.find((actor) => actor.id === senderId)?.kind
+ || (senderId === 'commander' ? 'commander' : 'agent');
+ await bumpConversationActivity(uid, cid, ts, {
+ senderKind,
+ senderId,
+ ...(senderKind === 'agent' ? { agentIds: [senderId] } : {}),
+ }, layout.projectId);
+ }
+ // Clear ownership only after every receipt is durable. A failed append
+ // keeps the journal retryable; already-written actor notices dedupe by
+ // their retained turn identity on the next sweep.
+ await recoverOrphanRunningState(uid, cid, () => bus.isQuiescent(uid, cid));
swept += 1;
- } catch {
- // Missing/malformed state is idle; prune any stale journal row.
- if (journalTracked) await untrackRunningConversation(uid, cid);
+ } catch (error) {
+ recoveryFailed = true;
+ if (!stateLoaded && ((error as NodeJS.ErrnoException).code === 'ENOENT' || error instanceof SyntaxError)) {
+ if (journalTracked) await untrackRunningConversation(uid, cid);
+ } else {
+ log.warn('stale sweep recovery remains pending', { user: maskId(uid), cid: maskId(cid), ...logErrorSummary(error) });
+ }
+ } finally {
+ if (!recoveryFailed) delete tail.recovery.pendingFor;
+ release();
+ if (_staleRecoveryTails.get(key) === tail && !tail.recovery.pendingFor) _staleRecoveryTails.delete(key);
}
});
if (swept) log.info(`cleared ${swept} stale running conversations`);
diff --git a/src/main/features/conversation_history_cache.ts b/src/main/features/conversation_history_cache.ts
index a4bf076e..5b3c367a 100644
--- a/src/main/features/conversation_history_cache.ts
+++ b/src/main/features/conversation_history_cache.ts
@@ -31,7 +31,7 @@ import { restoreInterruptedCliHistory } from './local_agents/interrupted-history
import { DEFER_PROCESS_ITEMS, PROCESS_PAGE_REBUILD, PROCESS_PAGE_BYTES, processTextChunks, storeProcessPages, processSummary, readProcessPage, processPageReference } from './conversation-process-cache';
const log = createLogger('conversation-history-cache');
-const CACHE_VERSION = 10;
+const CACHE_VERSION = 12;
const MAX_INLINE_PROCESS_OUTPUT_BYTES = 1024;
const MAX_FAILURE_OUTPUT_PREVIEW_CHARS = 600;
const SOURCE_TAIL_FINGERPRINT_BYTES = 4 * 1024;
@@ -634,6 +634,8 @@ async function buildLatestPage(
await fsp.rm(path.join(files.entryDir, 'latest-page-v7.json'), { force: true });
await fsp.rm(path.join(files.entryDir, 'latest-page-v8.json'), { force: true });
await fsp.rm(path.join(files.entryDir, 'latest-page-v9.json'), { force: true });
+ await fsp.rm(path.join(files.entryDir, 'latest-page-v10.json'), { force: true });
+ await fsp.rm(path.join(files.entryDir, 'latest-page-v11.json'), { force: true });
return next;
}
// A message landed while the page was being projected. Keep the valid
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 87c43f7f..5a0c2370 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -826,7 +826,7 @@ export type GroupEvent =
* end-of-turn message still carries `msg.artifacts` for persistence; this
* live event lets the renderer mount the iframe immediately instead of
* waiting for the whole actor turn to finish. */
- | { type: 'artifact_created'; cid: string; actor: string; turn_id?: string; artifact: { id: string; title: string; agent_id: string } }
+ | { type: 'artifact_created'; cid: string; actor: string; turn_id?: string; artifact: { id: string; title: string; agent_id: string; revision?: number } }
/** A visible dispatch started before Commander emitted any prose. The
* renderer removes and temporarily suppresses the turn's initial placeholder
* so the later synthesis opens below the dispatched agent replies. */
@@ -848,7 +848,12 @@ export type GroupEvent =
* Distinct from the privacy-safe `taskRun` terminal state above — these
* carry the task snapshot for the board UI. */
| { type: 'task_created'; cid: string; task: taskBoard.ConversationTask }
- | { type: 'task_state'; cid: string; task: taskBoard.ConversationTask };
+ | { type: 'task_state'; cid: string; task: taskBoard.ConversationTask }
+ /** D29 planning window of one user send, for the board only (never
+ * persisted): `active` before the planner runs, with a clipped `preview` of
+ * the message, then inactive once its rows exist or planning ended without
+ * any. */
+ | { type: 'dispatch_planning'; cid: string; message_id: string; active: boolean; preview?: string };
export type GroupListener = (ev: GroupEvent) => void;
@@ -869,6 +874,7 @@ export interface ActiveTurn {
// ── Per-cid state ────────────────────────────────────────────────────────
interface QueueItem {
+ /** Shared by this user message's actors and descendants; never persisted. */
/** Target actor of this turn — who runs it. G8d: top-level turns funnel
* through one per-conversation runtime (not a per-actor worker map), so the
* target rides on the item and the runtime sets its `actor` per turn before
@@ -1106,6 +1112,8 @@ interface CidState {
// Read the existing public process trail only when a view is rebuilt. These
// closures own no second event log and are released with their actor turn.
liveDisplays?: Map<string, () => GroupMessage[]>;
+ shuttingDown?: boolean;
+ shutdownArchives?: Map<string, Promise<GroupMessage | null>>;
displaySequence?: number;
/** Test-only phantom Agent executions counted against the session cap. */
reservedAgentSlotsForTest?: number;
@@ -1139,6 +1147,9 @@ interface CidState {
/** In-flight dispatch-planner calls (D29). A whole-conversation Stop
* aborts them so no task is created for a stopped send. */
planningControllers?: Set<AbortController>;
+ /** User sends the dispatch planner is still splitting (D29): message id →
+ * clipped text. The board shows them as being arranged meanwhile. */
+ planningMessages?: Map<string, string>;
/** Tail of the user-send order (D29). Each ordinary user send waits until
* the previous one has dispatched (routing, task rows, floor) — normally
* milliseconds, but a planned send holds it while the planner runs, so a
@@ -1237,6 +1248,7 @@ interface CidState {
taskRun?: {
runId: string;
startedAtMs: number;
+ notificationKind?: 'task' | 'automation';
status: TaskTerminalStatus | null;
failure?: TaskFailureDiagnostic;
/** True only after a non-failure actor `turn_end` message was durably
@@ -1288,6 +1300,7 @@ export interface TaskTerminalEvent {
run_id: string;
user_id: string;
conversation_id: string;
+ kind?: 'task' | 'automation';
status: TaskTerminalStatus;
started_at_ms: number;
finished_at_ms: number;
@@ -1295,9 +1308,6 @@ export interface TaskTerminalEvent {
retry_mode?: 'resume' | 'restart';
uncertain_operation_count?: number;
failure?: TaskFailureDiagnostic;
- /** Creation time of the conversation, read once when the run started. Only
- * analytics derives a bounded day bucket from it; it is not content. */
- conversation_created_at?: string;
}
@@ -1332,6 +1342,10 @@ const _TASK_TERMINAL_LISTENERS_KEY = Symbol.for('orkas.group_chat.bus.task_termi
const _taskTerminalListeners: Set<TaskTerminalListener> =
((globalThis as any)[_TASK_TERMINAL_LISTENERS_KEY] ??= new Set<TaskTerminalListener>());
+const _SHUTDOWN_KEY = Symbol.for('orkas.group_chat.bus.shutdown');
+const _shutdown: { started: boolean; pending?: Promise<void> } =
+ ((globalThis as any)[_SHUTDOWN_KEY] ??= { started: false });
+
function cidKey(uid: string, cid: string): string { return `${uid}:${cid}`; }
let _enqueueAdmissionGateForTest: (() => Promise<void>) | null = null;
@@ -1538,6 +1552,7 @@ function _emitTaskRunTerminal(state: CidState, status: TaskTerminalStatus): void
run_id: run.runId,
user_id: state.uid,
conversation_id: state.cid,
+ kind: run.notificationKind || 'task',
status,
started_at_ms: run.startedAtMs,
finished_at_ms: Date.now(),
@@ -2209,6 +2224,11 @@ export interface EnqueueParams {
cid: string;
fromActorId: string;
text: string;
+ /** Await host feature facts before publishing any recipient work. This
+ * does not own runtime admission, sessions, or model lifecycle events. */
+ beforeDispatch?: () => Promise<void>;
+ /** Native notification copy for the host-admitted run. */
+ notificationKind?: 'task' | 'automation';
commander_mention_display?: CommanderMentionDisplay;
/** Host-only active-turn delivery decision. This is intentionally separate
* from ordinary queued sends: ordinary sends queue by default, while
@@ -2221,6 +2241,7 @@ export interface EnqueueParams {
* taxonomy only; the rendered text still controls failure actions/UI. */
failure_kind?: GroupMessageFailureKind;
failure_code?: string;
+ system_kind?: GroupMessage['system_kind'];
model_text?: string;
/** Host-verified failed-turn continuation. Kept off the persisted message
* schema; it only controls how the recipient worker opens its session. */
@@ -2244,7 +2265,7 @@ export interface EnqueueParams {
/** Interactive web-app artifacts produced this turn (via `create_artifact`).
* `agent_id` is the producing actor — the renderer routes a user→artifact
* interaction result back to it. */
- artifacts?: Array<{ id: string; title: string; agent_id: string }>;
+ artifacts?: Array<{ id: string; title: string; agent_id: string; revision?: number }>;
marketplace_requests?: MarketplaceInstallRequest[];
app_nav_requests?: AppNavRequest[];
saved_tasks?: GroupMessage['saved_tasks'];
@@ -2327,13 +2348,18 @@ export interface EnqueueParams {
* - Writes to canonical `<cid>.jsonl`.
* - Emits `message` event to listeners.
* - Wakes recipient workers (lazy-creates them).
- * - If sender was an agent, also marks them as in_flight=false (their
- * turn just ended) — though that's also done by the worker loop.
+ * The execution owner clears in-flight state after terminal persistence;
+ * publishing a message alone does not end the sender's running turn.
*/
export async function enqueue(params: EnqueueParams): Promise<GroupMessage> {
- const { uid, cid, fromActorId, text } = params;
- // Reject before creating task runtime state or writing the old layout.
+ const { uid, cid, fromActorId } = params;
assertConversationRelocationReady(uid, cid);
+ const rejectDuringShutdown = () => {
+ if (_shutdown.started && !(fromActorId !== USER_ID && params.forceTo?.length === 1 && params.forceTo[0] === USER_ID)) {
+ throw Object.assign(new Error('application is shutting down'), { code: 'E_APP_SHUTTING_DOWN' });
+ }
+ };
+ rejectDuringShutdown();
const enqueueStartedAtMs = Date.now();
const state = getOrInitCid(uid, cid);
if (state.terminating) {
@@ -2363,6 +2389,7 @@ export async function enqueue(params: EnqueueParams): Promise<GroupMessage> {
if (reflectionWrites) await reflectionWrites;
if (_enqueueAdmissionGateForTest) await _enqueueAdmissionGateForTest();
if (previousUserSend) await previousUserSend;
+ rejectDuringShutdown();
return await _enqueueBody(params, state, releaseUserSend, enqueueStartedAtMs);
} finally {
releaseUserSend?.();
@@ -2538,6 +2565,7 @@ async function _enqueueBody(
if (!state.taskRun) {
state.taskRun = {
runId: genId12(), startedAtMs: enqueueStartedAtMs,
+ notificationKind: params.notificationKind,
status: null,
...(params.failedTurnRetryMode ? {
retryMode: params.failedTurnRetryMode,
@@ -2725,6 +2753,7 @@ async function _enqueueBody(
...(displayText !== undefined ? { display_text: displayText } : {}),
...(params.failure_kind ? { failure_kind: params.failure_kind } : {}),
...(params.failure_code ? { failure_code: params.failure_code } : {}),
+ ...(params.system_kind ? { system_kind: params.system_kind } : {}),
...(params.model_text && params.model_text.trim() ? { model_text: params.model_text } : {}),
...(params.attachments && params.attachments.length ? { attachments: params.attachments } : {}),
...(useSelections.length ? { use_selections: useSelections } : {}),
@@ -2824,6 +2853,7 @@ async function _enqueueBody(
// Dispatch to non-user recipients.
const refreshed = await readMembers(uid, cid);
if (bubbleClock) bubbleClock.members = Date.now();
+ if (params.beforeDispatch) await params.beforeDispatch();
// P3 true form resume: a user form submission targeted at an agent
// RE-ENTERS its form-parked task (same task_id back to running) instead of
// creating a new row. Decoded once; submissions are single-recipient.
@@ -2914,7 +2944,7 @@ async function _enqueueBody(
}
}
// Admission may have awaited persistence while Stop or deletion ran.
- if (state.terminating || params.dispatchSignal?.aborted
+ if (state.terminating || state.shuttingDown || params.dispatchSignal?.aborted
|| (params.dispatchEpoch !== undefined && params.dispatchEpoch !== state.abortEpoch)) {
if (boardTaskId) {
const cancelled = await taskBoard.finishTask(uid, cid, boardTaskId, 'cancelled');
@@ -3580,11 +3610,17 @@ function _holdsCommanderRoutedFloor(stateFile: StateFile, agentId: string): bool
/** Turn-time reminder for an Agent holding a Commander-routed floor. Shared by
* CLI and in-process Agents so both close the routed interaction the same way. */
-function _returnControlProtocol(): string {
+function _returnControlProtocol(stateFile: StateFile, agentId: string): string {
+ if (!_holdsCommanderRoutedFloor(stateFile, agentId)) return '';
+ const ledger = stateFile.orchestration_ledger;
+ const commanderWillResume = ledger && ledger.status !== 'interrupted' && ledger.owner_agent_id === agentId;
return [
'## Return control to commander',
'This conversation is currently routed to you and you hold the user-facing conversation floor.',
- 'When this routed interaction is complete, include the concrete final result and end with `<handback reason="completed_handoff" />` so control returns to the commander.',
+ commanderWillResume
+ ? 'Return the result to Commander, who will continue the remaining work.'
+ : 'Deliver the final result to the user; completion returns only the conversation floor to Commander.',
+ 'When this routed interaction is complete, include the concrete result and end with `<handback reason="completed_handoff" />` to return the conversation floor to Commander.',
'Use `<handback reason="completed_handoff" />` only to close this routed interaction. Do not use it as a capability-routing or error signal, and do not combine it with a question or input form.',
].join('\n');
}
@@ -3970,6 +4006,7 @@ export function _agentSlotsForTest(uid: string, cid: string): { inUse: number; c
/** Coalesced admission kick. Callers fire-and-forget; the loop serializes
* itself per conversation and re-runs when kicked mid-flight. */
function _scheduleAdmissions(state: CidState): void {
+ if (state.shuttingDown) return;
if (state.admitting) { state.admitRerun = true; return; }
void _admitLoop(state).catch((err) => {
log.error(`admission loop failed cid=${state.cid}: ${(err as Error).message}`);
@@ -3981,11 +4018,11 @@ async function _admitLoop(state: CidState): Promise<void> {
state.admitting = true;
try {
for (;;) {
- if (state.terminating) return;
+ if (state.terminating || state.shuttingDown) return;
if (state.queue.length === 0) return;
const reflectionWrites = yieldReflectionForTask(state.uid);
if (reflectionWrites) await reflectionWrites;
- if (state.terminating) return;
+ if (state.terminating || state.shuttingDown) return;
// Preserve FIFO while a queued message is owned by the composer.
if (state.queue.some((item) => item.composerEditing)) return;
// Runaway/cost backstops (conversation level, same thresholds as the
@@ -4152,7 +4189,7 @@ async function _admitLoop(state: CidState): Promise<void> {
// on a conversation whose status is already sticky 'aborted'
// (2026-08-28 review A-1). The bubble, if any, is already in
// history — the turn is cancelled exactly like a running one.
- if (state.terminating || state.abortEpoch !== admissionEpoch) {
+ if (state.terminating || state.shuttingDown || state.abortEpoch !== admissionEpoch) {
log.info('dropping admitted turn after abort/teardown', {
cid: maskId(state.cid),
actor_id: maskId(item.actor.id),
@@ -4252,7 +4289,34 @@ async function _waitingReplyTask(
return waiting && !state.queue.some((queued) => queued.taskId === waiting.task_id) ? waiting : undefined;
}
-async function _dispatchPlannedUserSend(state: CidState, input: {
+const PLANNING_PREVIEW_CHARS = 200;
+
+function _beginDispatchPlanning(state: CidState, msgId: string, text: string): void {
+ const preview = String(text || '').slice(0, PLANNING_PREVIEW_CHARS);
+ (state.planningMessages ??= new Map()).set(msgId, preview);
+ emit(state, { type: 'dispatch_planning', cid: state.cid, message_id: msgId, active: true, preview });
+}
+
+function _endDispatchPlanning(state: CidState, msgId: string): void {
+ if (!state.planningMessages?.delete(msgId)) return;
+ emit(state, { type: 'dispatch_planning', cid: state.cid, message_id: msgId, active: false });
+}
+
+/** Planning takes seconds before any row exists, so the board shows the send
+ * as being arranged for that whole window, however planning ends. */
+async function _dispatchPlannedUserSend(
+ state: CidState,
+ input: Parameters<typeof _planAndQueueUserSend>[1],
+): Promise<string[]> {
+ _beginDispatchPlanning(state, input.msgId, input.msg.text);
+ try {
+ return await _planAndQueueUserSend(state, input);
+ } finally {
+ _endDispatchPlanning(state, input.msgId);
+ }
+}
+
+async function _planAndQueueUserSend(state: CidState, input: {
uid: string;
cid: string;
msg: GroupMessage;
@@ -4638,6 +4702,24 @@ function _startExecution(
releaseRuntimeContentTurn = await runtimeContentPublish.enterRuntimeContentTurn(w.uid);
await runTurn(state, w, item);
} catch (err) {
+ // Account teardown closes enqueue admission before an aborted actor can
+ // persist its terminal reply. That owned cancellation is not a runtime
+ // failure; settle its board rows consistently with the cancelled run.
+ if (state.terminating && w.stopRequested
+ && (err as { code?: string } | null)?.code === 'E_CONVERSATION_TERMINATING') {
+ const taskIds = new Set([item.taskId, ...w.absorbedTaskIds]);
+ for (const taskId of taskIds) {
+ if (!taskId) continue;
+ trackBackgroundWrite(
+ state,
+ taskBoard.finishTask(w.uid, w.cid, taskId, 'cancelled').then((changed) => {
+ if (changed) emit(state, { type: 'task_state', cid: w.cid, task: changed });
+ }),
+ 'task-board cancel-during-teardown',
+ );
+ }
+ return;
+ }
const failure = _taskFailureDiagnostic('runtime', 'worker_turn_exception');
_recordTaskRunOutcome(
state,
@@ -4670,22 +4752,7 @@ function _startExecution(
actor_id: maskId(w.actor.id),
error: logErrorSummary(err),
});
- // Restore the durable actor state as well as the in-memory execution
- // state. `runTurn` marks the actor in-flight before entering the reusable
- // turn body; an exception outside that body's settlement path otherwise
- // leaves the roster claiming the actor is still running after the
- // scheduler has gone idle.
- try {
- w.abortController = null;
- await markInFlight(w.uid, w.cid, w.actor.id, false);
- await emitStateChanged(state);
- } catch (settleErr) {
- log.warn('worker-turn failure state settlement failed', {
- cid: maskId(w.cid),
- actor_id: maskId(w.actor.id),
- error: logErrorSummary(settleErr),
- });
- }
+ w.abortController = null;
// A host exception used to end only with `turn_silent`: the spinner
// disappeared, but the transcript contained no explanation and no
@@ -4772,6 +4839,10 @@ function _startExecution(
}
}
} finally {
+ // Inference can finish long before files and the terminal reply are
+ // durable. Keep the actor's crash-recovery identity through that work,
+ // including the visible failure receipt in the catch path above.
+ await settleTurnInFlight(state, w);
// Deregister BEFORE the status sync so the reconciliation sees the
// real post-execution state; the follow-up enqueues this turn fired
// are already committed (runTurn returned fully), so quiescence
@@ -4803,6 +4874,20 @@ function _startExecution(
})();
}
+async function settleTurnInFlight(state: CidState, w: WorkerState): Promise<void> {
+ w.abortController = null;
+ try {
+ await markInFlight(w.uid, w.cid, w.actor.id, false);
+ await emitStateChanged(state);
+ } catch (err) {
+ // A failed state write must not prevent runtime deregistration or free
+ // slot admission. The existing status reconciliation still runs next.
+ log.warn('worker-turn state settlement failed', {
+ cid: maskId(w.cid), actor_id: maskId(w.actor.id), error: logErrorSummary(err),
+ });
+ }
+}
+
type RichSteerDrainOptions = {
/** Same mutable array held by this run's read tools and local write guards. */
runtimeReadOnlyRoots?: string[];
@@ -5179,7 +5264,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
w.running = true;
w.abortController = new AbortController();
await _syncStateStatus(state, /*forceRunning*/ true);
- await markInFlight(uid, cid, actor.id, true);
+ await markInFlight(uid, cid, actor.id, true, { turn_id: item.turnId, source_message_id: item.msgId });
await emitStateChanged(state);
log.info(`turn-start user=${uid} cid=${cid} actor=${actor.id} kind=${actor.kind} turn=${item.turnId} fromMsg=${item.msgId} from=${item.fromActorId}`);
@@ -5584,9 +5669,21 @@ async function runActorTurn(
turnStartedAt: number,
): Promise<ActorTurnResult> {
w.pendingSavedTasks = undefined;
+ if (item.actor.kind !== 'worker') {
+ state.liveDisplays ||= new Map();
+ state.liveDisplays.set(item.turnId, () => [{
+ id: '', from: item.actor.id, to: [USER_ID], ts: localIsoAt(turnStartedAt), text: '',
+ turn_id: item.turnId, source_message_id: item.msgId,
+ ...(item.taskId ? { task_id: item.taskId } : {}),
+ }]);
+ }
try {
- return await runActorTurnWithDisplay(state, w, item, turnStartedAt);
+ return await (() => runActorTurnWithDisplay(state, w, item, turnStartedAt))();
} finally {
+ // Retain the closure after an I/O failure so a subsequent quit can retry.
+ if (state.shuttingDown && state.liveDisplays?.has(item.turnId)) {
+ await archiveInterruptedTurn(state, item.turnId);
+ }
state.liveDisplays?.delete(item.turnId);
}
}
@@ -5650,19 +5747,17 @@ async function runActorTurnWithDisplay(
// enable-filter sites; do not add a 5th.
let turnProjectScope: import('../projects').ProjectBindings | null = null;
if (turnProjectId) {
- try {
- const projectsFeat = await import('../projects');
- turnProjectScope = await projectsFeat.resolveProjectScope(uid, turnProjectId);
- } catch (err) {
- log.warn(`resolve project scope cid=${cid} pid=${turnProjectId}: ${(err as Error).message}`);
- }
+ // An unreadable binding source is not an orphan conversation. Let the
+ // existing failed-turn path preserve a retry target before any inference.
+ const projectsFeat = await import('../projects');
+ turnProjectScope = await projectsFeat.resolveProjectScope(uid, turnProjectId);
}
let turnToolExtraRoots: string[] = [];
let turnSyncConflictResolution: NonNullable<StateFile['sync_conflict_resolution']>['conflicts'] = [];
- let turnHoldsRoutedFloor = false;
+ let turnReturnControlProtocol = '';
try {
const stateFile = await readState(uid, cid);
- turnHoldsRoutedFloor = actor.kind === 'agent' && _holdsCommanderRoutedFloor(stateFile, actor.id);
+ if (actor.kind === 'agent') turnReturnControlProtocol = _returnControlProtocol(stateFile, actor.id);
turnToolExtraRoots = Array.isArray(stateFile.tool_extra_roots)
? stateFile.tool_extra_roots.filter((r) => typeof r === 'string' && path.isAbsolute(r))
: [];
@@ -5690,8 +5785,8 @@ async function runActorTurnWithDisplay(
if (actor.kind === 'agent') {
preloadedNamedAgent = await agentsFeat.getAgent(actor.id);
}
- if (turnHoldsRoutedFloor && preloadedNamedAgent && !agentsFeat.isCliAgent(preloadedNamedAgent)) {
- messageText = `${_returnControlProtocol()}\n${messageText}`;
+ if (turnReturnControlProtocol && preloadedNamedAgent && !agentsFeat.isCliAgent(preloadedNamedAgent)) {
+ messageText = `${turnReturnControlProtocol}\n${messageText}`;
}
if (
isCommander
@@ -5949,19 +6044,14 @@ async function runActorTurnWithDisplay(
// bounded trusted surface; package/global Skills stay search-only.
// Skills are not project-scoped this round; see CLAUDE.md §6.
} else if (actor.kind === 'worker') {
- // G8b ephemeral worker — no agent.json. Synthesize a minimal worker config
- // and reuse the agent-in-group prompt (duck-typed). The fixed generic tool
- // profile (workspace / web / Library) comes from the runner. The shared
- // task browser is the one Web extra because it is conversation-scoped and
- // visible to the user; workers still get no Skill search, inputs, or forms
- // (headless — see WORKER_WORKFLOW).
- systemPrompt = await buildAgentInGroupSystemPrompt(uid, {
- agent_id: actor.id,
- name: actor.name || 'Worker',
- description: 'Ephemeral sub-task worker spun up by the commander.',
- workflow: WORKER_WORKFLOW,
- interactive: false,
- }, workingDir, turnLanguage);
+ // Anonymous helpers return privately to Commander. Their role does not
+ // inherit the named Agent's user-facing interaction protocols.
+ const { prompts } = await import('../../prompts/loader');
+ systemPrompt = composeChatPrompt({
+ main: prompts.load('chat_worker', { working_dir: workingDir }),
+ languageDirective: buildLanguageDirective(turnLanguage),
+ runtimeDatetimeBlock: buildRuntimeDatetimeBlock(),
+ });
skillList = [];
extraTools = [buildConversationBrowserTool(uid, cid)];
} else {
@@ -5990,7 +6080,6 @@ async function runActorTurnWithDisplay(
turn_id: item.turnId,
source_message_id: item.msgId,
});
- await markInFlight(uid, cid, actor.id, false);
await emitStateChanged(state);
// Note: runWorkerLoop owns w.running — its finally clears the flag
// when this returns. We DON'T touch it here.
@@ -6010,10 +6099,9 @@ async function runActorTurnWithDisplay(
// a synthetic queue and intentionally expose no user steer callback.
// Scheduled Commander children share this same live-input boundary;
// their original dispatch/result ownership stays with the scheduler.
- // Terminal hand-offs likewise preserve the admitted task boundary: new
- // user input stays in the ordinary FIFO instead of mutating this run.
- w.currentTurnSteerable = !item.nested
- && !item.terminalHandoff;
+ // Hand-offs use the same ingress without changing their task/floor
+ // ownership; only explicitly promoted user messages enter this run.
+ w.currentTurnSteerable = !item.nested;
if (!item.nested) await emitStateChanged(state);
systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir, turnLanguage);
// skill_list supplies default shared dependencies; owned private Skills
@@ -6093,6 +6181,10 @@ async function runActorTurnWithDisplay(
}
turnProduced.add(normalized);
state.producedPaths.add(normalized);
+ if (!preExistingPaths.has(normalized)) {
+ const { recordGeneratedAttachment } = await import('../chat_attachments');
+ recordGeneratedAttachment(uid, cid, normalized);
+ }
if (isPathInVersionControlledTree(normalized)) sourceTreePaths.add(normalized);
if (isPathAllowed(normalized, managedRoots) && !sourceTreePaths.has(normalized)) {
await recordProducedFile(normalized, { userId: uid, cid, source: 'group_chat.file_written' }, info);
@@ -6162,15 +6254,18 @@ async function runActorTurnWithDisplay(
// Attached to the actor's end-of-turn message so the renderer embeds each
// one as a sandboxed `<iframe>` (`chat-app://`); `agent_id` = this actor,
// the routing target for a user→artifact interaction result.
- const turnArtifacts: Array<{ id: string; title: string }> = [];
- const onArtifactCreated = (a: { id: string; title: string }) => {
- turnArtifacts.push(a);
+ const turnArtifacts: Array<{ id: string; title: string; revision?: number }> = [];
+ const onArtifactCreated = (a: { id: string; title: string; revision?: number }) => {
+ const index = turnArtifacts.findIndex(existing => existing.id === a.id);
+ if (index >= 0 && (turnArtifacts[index].revision ?? 0) >= (a.revision ?? 0)) return;
+ if (index >= 0) turnArtifacts[index] = a;
+ else turnArtifacts.push(a);
emit(state, {
type: 'artifact_created',
cid,
actor: actor.id,
turn_id: item.turnId,
- artifact: { id: a.id, title: a.title, agent_id: actor.id },
+ artifact: { ...a, agent_id: actor.id },
});
};
let finalText = '';
@@ -6193,6 +6288,8 @@ async function runActorTurnWithDisplay(
...(cliAgent?.runtime?.kind === 'cli' && cliAgent.runtime.cli === 'claude'
? { display_phase: 'pending' as const } : {}),
process: processItems.slice(segState.processStart),
+ ...(turnArtifacts.length ? { artifacts: turnArtifacts.map(a => ({ ...a, agent_id: actor.id })) } : {}),
+ ...(item.taskId ? { task_id: item.taskId } : {}),
},
]);
}
@@ -6372,7 +6469,9 @@ async function runActorTurnWithDisplay(
if (initialSelectionBlocks.length) {
messageText = `${initialSelectionBlocks.join('\n')}\n${messageText}`;
}
- if (cliAgent) {
+ if (state.shuttingDown) {
+ aborted = true;
+ } else if (cliAgent) {
// CLI-backed agent path: spawn the local CLI in the user's workspace
// and forward its events as `process` events so the same UI rail
// renders. The output text becomes finalText; failures populate
@@ -6444,6 +6543,7 @@ async function runActorTurnWithDisplay(
}
let persistedLiveCommentary = false;
let cliMessageWrites = Promise.resolve();
+ if (state.shuttingDown) throw Object.assign(new Error('aborted'), { name: 'AbortError' });
const cliOut = await _runCliAgentTurn({
uid, cid, actor, agent: cliAgent,
item, canonicalRows, workingDir: cliWorkingDir, projectDirectoryIssue,
@@ -6460,7 +6560,7 @@ async function runActorTurnWithDisplay(
}),
onAutoTaskDeleted: (taskId) => unstageSavedTask(w, item.turnId, 'automation', taskId),
onTodoTaskDeleted: (taskId, projectId) => unstageSavedTask(w, item.turnId, 'todo', taskId, projectId),
- ...(!item.nested && !item.terminalHandoff ? {
+ ...(!item.nested ? {
onActiveRunIngress: (ingress: LocalActiveRunIngress | null) => {
// Ignore a late callback from a run that has already lost this
// worker turn. The scheduler may reuse the same WorkerState for
@@ -6599,7 +6699,6 @@ async function runActorTurnWithDisplay(
});
} finally {
w.abortController = null;
- await markInFlight(uid, cid, actor.id, false);
await emitStateChanged(state);
}
} else {
@@ -6629,6 +6728,7 @@ async function runActorTurnWithDisplay(
...(turnConversationTitleUpdatedAt ? { conversationTitleUpdatedAt: turnConversationTitleUpdatedAt } : {}),
turnId: item.turnId,
historyBoundaryMessageId: item.msgId,
+ outputDelivery: item.outputDelivery || 'final',
// A channel retry continues the SAME persisted turn: without resume
// the second runner run would double-commit the turn's user message.
...(item.resumeActiveTurn || channelAttempt > 0 ? { resumeActiveTurn: true } : {}),
@@ -6682,8 +6782,8 @@ async function runActorTurnWithDisplay(
// workers) get no steer — the user can't address a worker, and their
// synthetic queue is empty anyway. Scheduled Commander children use
// the shared user queue while retaining their dispatch result waiter.
- // Terminal hand-offs also keep their admitted contract immutable.
- ...(item.nested || item.terminalHandoff ? {} : {
+ // Hand-offs retain their floor and terminal delivery ownership too.
+ ...(item.nested ? {} : {
richSteerEnabled: true,
runtimeReadOnlyRoots,
drainSteer: () => drainSteerInto(w, actor, {
@@ -6839,16 +6939,16 @@ async function runActorTurnWithDisplay(
// through the post-turn enqueue below so `isQuiescent` doesn't
// briefly report quiescent in the sync window between this finally
// and the `await enqueue(...)` that fires the next message.
- await markInFlight(uid, cid, actor.id, false);
- // Emit a state_changed so UI roster updates immediately, but don't
- // touch status (status is owned by _syncStateStatus, which runs after
- // the post-turn enqueue below — until then we're still 'running' from
- // the worker's perspective).
+ // Publish the closed ingress while retaining in-flight ownership until
+ // the execution owner has finished terminal persistence and settlement.
await emitStateChanged(state);
}
};
- w.stopRequested = false;
- await runModelAttempt(0);
+ if (state.shuttingDown || state.terminating || w.stopRequested || w.abortController?.signal.aborted) {
+ aborted = true;
+ } else {
+ await runModelAttempt(0);
+ }
// A tool/tool-input idle timeout is not a channel failure. The incomplete
// current JSON cannot execute, but an earlier tool in the same turn may
// already have produced a side effect; a silent full-turn replay could
@@ -6902,6 +7002,14 @@ async function runActorTurnWithDisplay(
}
} // end LLM branch (paired with `if (cliAgent) { ... } else {` above)
+ // Exit never parses partial prose into new side effects or starts another
+ // turn. Preserve the same public trail the user could inspect while live.
+ if (state.shuttingDown && actor.kind !== 'worker') {
+ const persistedMsg = await archiveInterruptedTurn(state, item.turnId);
+ return { kind: 'completed', text: persistedMsg?.text || '', produced: [],
+ outcome: { kind: 'silent' }, persistedMsg, aborted: true, terminalStatus: 'cancelled' };
+ }
+
let workingText = finalText || '';
if (turnSyncConflictResolution.length && workingText && !errText && !aborted) {
const results = extractSyncConflictResults(workingText);
@@ -7434,7 +7542,6 @@ async function runActorTurnWithDisplay(
detachAbort();
w.abortController = null;
aborted ||= w.stopRequested;
- await markInFlight(uid, cid, actor.id, false);
await emitStateChanged(state);
}
}
@@ -7663,6 +7770,7 @@ async function runActorTurnWithDisplay(
// so no empty commander bubble is persisted.
if (segState.flushedAny && outcome.kind === 'persist') {
const tail = streamingText.slice(segState.segStart);
+ const tailProcessItems = processItems.slice(segState.processStart);
const hasSide = !!(
outcome.form
|| (outcome.produced && outcome.produced.length)
@@ -7671,7 +7779,11 @@ async function runActorTurnWithDisplay(
|| turnArtifacts.length
|| turnMarketplaceRequests.length
);
- outcome = (!tail.trim() && !hasSide) ? { kind: 'silent' } : { ...outcome, text: tail };
+ // A tool-only tail can contain completed external writes. Its receipts
+ // have not been saved with an earlier segment and must survive even when
+ // no final prose follows. Keep the existing routing-only suppression.
+ const hasUnsavedWork = tailProcessItems.length > 0 && !processItemsAreRoutingOnly(tailProcessItems);
+ outcome = (!tail.trim() && !hasSide && !hasUnsavedWork) ? { kind: 'silent' } : { ...outcome, text: tail };
}
if (aborted) {
@@ -7790,7 +7902,7 @@ async function runActorTurnWithDisplay(
? { created_skills: outcome.createdSkills.map((s) => ({ skill_id: s.skill_id, name: s.name })) }
: {}),
...(turnArtifacts.length
- ? { artifacts: turnArtifacts.map((a) => ({ id: a.id, title: a.title, agent_id: actor.id })) }
+ ? { artifacts: turnArtifacts.map((a) => ({ ...a, agent_id: actor.id })) }
: {}),
...(turnMarketplaceRequests.length ? { marketplace_requests: turnMarketplaceRequests } : {}),
...(turnAppNavRequests.length ? { app_nav_requests: turnAppNavRequests } : {}),
@@ -7816,8 +7928,10 @@ async function runActorTurnWithDisplay(
...(reviewGateOpen ? { waitingForInput: true } : {}),
...(item.taskId ? { task_id: item.taskId } : {}),
});
+ state.liveDisplays?.delete(item.turnId);
await registerFinalOutputResources(outcome.produced || []);
} else if (outcome.kind === 'silent' && actor.kind !== 'worker') {
+ state.liveDisplays?.delete(item.turnId);
// outcome=silent → bus is NOT going to enqueue a message for this turn.
// Any placeholder the renderer parked for this actor (e.g. a fresh one
// created by post-tool process events after the original was consumed
@@ -8097,6 +8211,7 @@ async function buildCommanderSystemPrompt(
prompts.load('chat_user_intent_rules', {}),
prompts.load('chat_input_interaction_rules', {}),
prompts.load('chat_shared_rules', { working_dir: workingDir }),
+ prompts.load('chat_rich_output_rules', {}),
],
languageDirective: buildLanguageDirective(language),
runtimeDatetimeBlock: buildRuntimeDatetimeBlock(),
@@ -8186,7 +8301,7 @@ async function buildAgentsIndexBlock(
return markers.length ? `${head}\n ${markers.join('\n ')}` : head;
}).join('\n');
return `${header}${entries}`;
- } catch { return `${header}(no agents)`; }
+ } catch { throw new Error('Agent catalog unavailable'); }
}
async function buildAgentInGroupSystemPrompt(
@@ -8231,13 +8346,16 @@ async function buildAgentInGroupSystemPrompt(
prompts.load('chat_user_intent_rules', {}),
prompts.load('chat_input_interaction_rules', {}),
prompts.load('chat_shared_rules', { working_dir: workingDir }),
+ agent.output_format === 'text' || agent.output_format === 'markdown_only'
+ ? ''
+ : prompts.load('chat_rich_output_rules', {}),
],
languageDirective: buildLanguageDirective(language),
runtimeDatetimeBlock: buildRuntimeDatetimeBlock(),
});
}
-// Test-only export: assembles the real in-process worker prompt without
+// Test-only export: assembles the real named-Agent prompt without
// enqueuing or dispatching a group-chat turn.
export async function _buildAgentInGroupSystemPromptForTest(
agent: Parameters<typeof buildAgentInGroupSystemPrompt>[1],
@@ -8612,6 +8730,7 @@ async function runNestedDispatch(
// re-entrant and cannot deadlock.
let releaseDispatch: Releaser | undefined;
let surfaced = false;
+ let started = false;
try {
if (parentSignal?.aborted) onParentAbort();
else parentSignal?.addEventListener('abort', onParentAbort, { once: true });
@@ -8629,6 +8748,7 @@ async function runNestedDispatch(
// which is exactly why no start-of-turn state_changed listed this actor before.
surfaced = actor.kind === 'agent';
if (surfaced) {
+ await markInFlight(state.uid, state.cid, actor.id, true, { turn_id: item.turnId, source_message_id: item.msgId });
state.nestedTurns.set(item.turnId, {
actor: actor.id,
turn_id: item.turnId,
@@ -8642,6 +8762,7 @@ async function runNestedDispatch(
ac.signal.throwIfAborted();
let r: ActorTurnResult;
try {
+ started = true;
r = await runActorTurn(state, w, item, nestedTurnStartedAtMs);
_recordTaskRunOutcome(state, r.terminalStatus, r.failure);
} catch (err) {
@@ -8704,6 +8825,7 @@ async function runNestedDispatch(
} finally {
parentSignal?.removeEventListener('abort', onParentAbort);
try {
+ if (started || surfaced) await settleTurnInFlight(state, w);
if (surfaced) {
// Drop the active-turn mirror even when setup or inference failed.
state.nestedTurns.delete(item.turnId);
@@ -8908,19 +9030,6 @@ async function runScheduledDispatch(
};
}
-/** Generic role guidance for an ephemeral anonymous worker — fed as the
- * `workflow` field of a synthesized agent config (same template var the
- * agent-in-group prompt reads), so no new prompt file is needed. Headless: the
- * worker has no user to ask and its reply goes back to the commander, not the
- * chat. */
-const WORKER_WORKFLOW = [
- 'You are an ephemeral worker spun up by the commander to complete ONE isolated auxiliary sub-task. You are a separate helper, not the commander itself.',
- 'Complete only the boundary stated in the incoming message using your available tools (files, shell, web, library, etc.); do not infer or continue the surrounding user goal or later milestones.',
- 'If the message assigns a coupled milestone chain or work that needs the commander\'s ongoing shared context, stop without changing files and return a concise scope-mismatch result so the commander can retain ownership.',
- 'There is no user in this turn: never ask a question, request input, or emit a form — if something is ambiguous, make the most reasonable assumption and state it in your result.',
- 'Your reply is handed back to the commander verbatim (not shown to anyone else), so return the complete result for this delegated sub-task. Put large artifacts in files and reference their paths; keep the reply itself focused on the result and any pointers.',
-].join(' ');
-
function _toolError(error: string): { content: string; isError: true } {
return { content: JSON.stringify({ ok: false, error }), isError: true };
}
@@ -10050,9 +10159,66 @@ async function buildCommanderExtraTools(
return tools;
}
+/** Persist only the unsaved public tail; completed native segments already
+ * have canonical ids. A late provider settlement reuses this exact receipt. */
+async function archiveInterruptedTurn(state: CidState, turnId: string): Promise<GroupMessage | null> {
+ state.shutdownArchives ||= new Map();
+ const previous = state.shutdownArchives.get(turnId);
+ if (previous) return previous;
+ const tail = state.liveDisplays?.get(turnId)?.().find(row => !row.id);
+ if (!tail) return null;
+ const snapshot = structuredClone(tail);
+ const process = snapshot.process || [];
+ if (snapshot.text?.trim()) process.push({ type: 'progress', text: snapshot.text });
+ const startedAt = Date.parse(snapshot.ts);
+ const stoppedAt = Date.now();
+ const hasClock = process.some(item => item.event?.stream === 'runtime'
+ && ['end', 'interrupted'].includes(String((item.event.data as { phase?: string })?.phase)));
+ if (!hasClock && Number.isFinite(startedAt) && startedAt <= stoppedAt) {
+ process.push({ type: 'event', event: { stream: 'runtime', data: {
+ phase: 'interrupted', duration_ms: stoppedAt - startedAt,
+ } } });
+ }
+ const pending = enqueue({
+ uid: state.uid, cid: state.cid, fromActorId: snapshot.from,
+ forceTo: [USER_ID], text: t('chat.reply_interrupted', undefined, resolveLanguageForUser(state.uid)),
+ system_kind: 'reply_interrupted', turn_id: turnId, seg: snapshot.seg,
+ source_message_id: snapshot.source_message_id, task_id: snapshot.task_id,
+ turn_end: true, process, artifacts: snapshot.artifacts,
+ references: snapshot.references,
+ }).catch(error => { state.shutdownArchives?.delete(turnId); throw error; });
+ state.shutdownArchives.set(turnId, pending);
+ return pending;
+}
+
+/** Graceful exit only: stop admission, abort active work and allow a short
+ * settlement window before checkpointing unresponsive public displays. */
+export function prepareForShutdown(): Promise<void> {
+ if (_shutdown.pending) return _shutdown.pending;
+ _shutdown.started = true;
+ const states = [..._cids.values()];
+ for (const state of states) state.shuttingDown = true;
+ _shutdown.pending = Promise.resolve().then(async () => {
+ const active = states.filter(state => !isQuiescent(state.uid, state.cid));
+ await Promise.all(active.map(state => abort(state.uid, state.cid, { waitForSettlement: false })));
+ const deadline = Date.now() + 5_000;
+ while (active.some(state => !isQuiescent(state.uid, state.cid)) && Date.now() < deadline) {
+ await new Promise<void>(resolve => setTimeout(resolve, 25));
+ }
+ await Promise.all(states.flatMap(state => [...(state.liveDisplays?.keys() || [])]
+ .map(turnId => archiveInterruptedTurn(state, turnId))));
+ // Include archival still unwinding in a worker's finally, and existing
+ // background persistence, before search/database handles are closed.
+ await Promise.all(states.flatMap(state => [
+ ...(state.shutdownArchives?.values() || []), ...state.backgroundWrites,
+ ]));
+ }).catch(error => { _shutdown.pending = undefined; throw error; });
+ return _shutdown.pending;
+}
+
// ── Abort ────────────────────────────────────────────────────────────────
-export async function abort(uid: string, cid: string): Promise<void> {
+export async function abort(uid: string, cid: string, options?: { waitForSettlement?: boolean }): Promise<void> {
const state = _cids.get(cidKey(uid, cid));
let cleared = 0;
let aborted = 0;
@@ -10060,6 +10226,9 @@ export async function abort(uid: string, cid: string): Promise<void> {
if (state) {
state.abortEpoch += 1;
for (const controller of state.planningControllers || []) controller.abort();
+ // Stop tears the renderer's streams down first, and its board re-reads
+ // right away: settle the arranging state now, not when planning unwinds.
+ for (const msgId of [...(state.planningMessages?.keys() || [])]) _endDispatchPlanning(state, msgId);
_recordTaskRunOutcome(state, 'cancelled');
// Queued board rows will never run — cancel them now. Each RUNNING
// task's terminal comes from its own turn observing the abort
@@ -10116,7 +10285,7 @@ export async function abort(uid: string, cid: string): Promise<void> {
const bashPermissions = await import('../../model/core-agent/bash-permissions');
bashPermissions.cancelForCid(cid);
} catch { /* not loaded */ }
- await setStatus(uid, cid, 'aborted');
+ await setStatus(uid, cid, state?.shuttingDown ? 'idle' : 'aborted');
try {
await clearOrchestrationForCancellation(uid, cid);
} catch (err) {
@@ -10141,7 +10310,7 @@ export async function abort(uid: string, cid: string): Promise<void> {
// settles; the timeout is a safety net only — under healthy conditions
// the loop exits in well under a second.
const deadline = Date.now() + 10000;
- while (!isQuiescent(uid, cid) && Date.now() < deadline) {
+ while (options?.waitForSettlement !== false && !isQuiescent(uid, cid) && Date.now() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 25));
}
await _syncStateStatus(state).catch((err) => {
@@ -10240,7 +10409,7 @@ export async function sendConversationTaskNow(
uid: string,
cid: string,
taskId: string,
-): Promise<{ ok: boolean; error?: string; turn_id?: string }> {
+): Promise<{ ok: boolean; error?: string; turn_id?: string; message?: GroupMessage; task?: taskBoard.ConversationTask }> {
const state = _cids.get(cidKey(uid, cid));
if (!state || state.terminating) return { ok: false, error: 'runtime_unavailable' };
const item = state.queue.find((candidate) => candidate.taskId === taskId);
@@ -10253,12 +10422,14 @@ export async function sendConversationTaskNow(
if (!live || !live.running || !live.currentTurnId || live.currentTurnSteerable !== true) {
return { ok: false, error: 'turn_not_steerable' };
}
- if (item.steerActiveTurn) return { ok: true, turn_id: live.currentTurnId };
+ if (item.steerActiveTurn) return {
+ ok: true, turn_id: live.currentTurnId, message: item.sourceMessage,
+ task: (await taskBoard.listTasks(uid, cid)).find((row) => row.task_id === taskId),
+ };
if (item.sendNowPending) return { ok: false, error: 'send_in_progress' };
- // D21 queued-until-execution: folding into the live turn IS the moment the
- // message's work starts — persist the deferred bubble before delivery so
- // the transcript carries the message the runtime is about to consume. An
+ // D21: explicit Send now publishes the deferred bubble immediately. Model
+ // consumption still waits for the runtime's existing steer boundary. An
// unfolded leftover later claimed as its own turn is already persisted.
if (item.deferredBubble) {
item.sendNowPending = true;
@@ -10277,6 +10448,10 @@ export async function sendConversationTaskNow(
}
item.steerActiveTurn = true;
+ // Sending ends when the user bubble is persisted, not when the model next
+ // drains its inbox. Keep execution/absorption owned by the existing ACK.
+ const sentTask = await taskBoard.markMessageSent(uid, cid, taskId, item.sourceMessage?.ts || nowIso());
+ if (sentTask) emit(state, { type: 'task_state', cid, task: sentTask });
const hadAfter = Boolean(item.afterTaskIds?.length);
delete item.afterTaskIds;
delete item.skippedAfterTaskIds;
@@ -10292,7 +10467,7 @@ export async function sendConversationTaskNow(
}
if (live.currentTurnIngress) _scheduleCliSteerDrain(state, live);
log.info(`task send-now user=${uid} cid=${cid} task=${maskId(taskId)} actor=${maskId(item.actor.id)} turn=${maskId(live.currentTurnId)}`);
- return { ok: true, turn_id: live.currentTurnId };
+ return { ok: true, turn_id: live.currentTurnId, message: item.sourceMessage, ...(sentTask ? { task: sentTask } : {}) };
}
async function _releaseCancelledTaskFloor(
@@ -10527,6 +10702,12 @@ export async function reassignConversationTask(
return { ok: true };
}
+/** Sends still being arranged, for a board that (re)reads its rows. */
+export function listPlanningDispatches(uid: string, cid: string): Array<{ message_id: string; preview: string }> {
+ const planning = _cids.get(cidKey(uid, cid))?.planningMessages;
+ return [...(planning || [])].map(([message_id, preview]) => ({ message_id, preview }));
+}
+
/** Read-only board listing for the renderer task panel. */
export function listConversationTasks(
uid: string,
@@ -11520,6 +11701,13 @@ async function _buildCliContextPlan(
let projectContext = '';
const memoryFeat = await import('../memory');
const turnContext: string[] = [];
+ if (!passthrough) {
+ const { resolveConversationAssistanceForTurn } = await import('../conversation_assistance_context');
+ const assistance = await resolveConversationAssistanceForTurn(uid, cid, {
+ agentId: agent.agent_id, outputDelivery: item.outputDelivery,
+ });
+ if (assistance.guidance) turnContext.push(assistance.guidance);
+ }
let agentMemoryHash: string | undefined;
let agentMemoryEntryHashes: string[] | undefined;
if (localCliSupportsAgentMemory(cli)) {
@@ -11554,9 +11742,13 @@ async function _buildCliContextPlan(
let runtimeProtocol = '';
try {
const stateFile = await readState(uid, cid);
- if (_holdsCommanderRoutedFloor(stateFile, agent.agent_id)) runtimeProtocol = _returnControlProtocol();
+ runtimeProtocol = _returnControlProtocol(stateFile, agent.agent_id);
} catch (err) {
- log.warn(`cli handback state unavailable cid=${cid} agent=${agent.agent_id}: ${(err as Error).message}`);
+ const { message_hash, message_chars } = logErrorSummary(err);
+ log.warn('cli handback state unavailable', {
+ cid: maskId(cid), agent_id: maskId(agent.agent_id),
+ error: { message_hash, message_chars },
+ });
}
const runtimeGuidance = buildAgentRuntimeGuidance(agent.profile);
@@ -11606,6 +11798,7 @@ async function _buildCliContextPlan(
? taskBody
: buildCliTurnPrompt({
task: taskBody,
+ taskSource: item.fromActorId === USER_ID ? 'user' : 'agent',
projectContext: turnContext.filter((block) => block && block.trim()).join('\n\n'),
attachmentPaths: turnAttachments,
runtimeProtocol,
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 88878ad6..5b4109b2 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -41,6 +41,7 @@ import {
beginConversationTaskEdit as busBeginConversationTaskEdit,
cancelConversationTaskEdit as busCancelConversationTaskEdit,
listConversationTasks as busListConversationTasks,
+ listPlanningDispatches as busListPlanningDispatches,
setConversationTaskAfter as busSetConversationTaskAfter,
resumeBlockedTask as busResumeBlockedTask,
reorderConversationTask as busReorderConversationTask,
@@ -54,8 +55,7 @@ import {
export const busIsQuiescent = isQuiescent;
/** Reuse history's lazy tool-output projection for an active public turn. */
-export async function displaySnapshot(userId: string, cid: string, projectIdHint?: string | null) {
- const snapshot = liveDisplaySnapshot(userId, cid);
+async function buildDisplaySnapshot(userId: string, cid: string, snapshot: ReturnType<typeof liveDisplaySnapshot>, projectIdHint?: string | null) {
const source = conversationMessageReadFile(userId, cid, projectIdHint);
return {
...snapshot,
@@ -66,6 +66,25 @@ export async function displaySnapshot(userId: string, cid: string, projectIdHint
};
}
+const pendingDisplaySnapshots = new Map<string, { signature: unknown; pending: ReturnType<typeof buildDisplaySnapshot> }>();
+/** A process watermark covers the public event trail; compare all remaining
+ * display data too so changed prose or turn membership never reuses old work. */
+export function displaySnapshot(userId: string, cid: string, projectIdHint?: string | null) {
+ const snapshot = liveDisplaySnapshot(userId, cid);
+ const signature = { ...snapshot, turns: snapshot.turns.map(turn => ({ ...turn,
+ records: turn.records.map(({ process, ...record }) => ({ ...record, processCount: process?.length })),
+ })) };
+ const key = JSON.stringify([userId, cid, projectIdHint]);
+ const existing = pendingDisplaySnapshots.get(key);
+ if (existing && isDeepStrictEqual(existing.signature, signature)) return existing.pending;
+ const pending = buildDisplaySnapshot(userId, cid, snapshot, projectIdHint);
+ const entry = { signature, pending };
+ pendingDisplaySnapshots.set(key, entry);
+ const cleanup = () => { if (pendingDisplaySnapshots.get(key) === entry) pendingDisplaySnapshots.delete(key); };
+ void pending.then(cleanup, cleanup);
+ return pending;
+}
+
export async function runtimeStatus(
userId: string,
cid: string,
@@ -75,7 +94,11 @@ export async function runtimeStatus(
try {
let state = await readState(userId, cid, projectIdHint);
let runtime = runtimeSnapshot(userId, cid);
- if ((state.status === 'running' || state.in_flight.some(Boolean)) && !runtime.processing) {
+ const orphan = (state.status === 'running' || state.in_flight.some(Boolean)) && !runtime.processing;
+ const recoveryPending = orphan && (await import('../chats'))
+ .isInterruptionRecoveryPending(userId, cid, state);
+ if (orphan) runtime = runtimeSnapshot(userId, cid);
+ if (orphan && !recoveryPending) {
const result = await recoverOrphanRunningState(userId, cid, () => !runtimeSnapshot(userId, cid).processing);
state = result.state;
// Admission can also start during the asynchronous recovery write.
@@ -84,7 +107,7 @@ export async function runtimeStatus(
log.warn('healed orphan running state', { user_id: maskId(userId), cid: maskId(cid) });
}
}
- const diskInFlight = state.in_flight.filter(Boolean);
+ const diskInFlight = recoveryPending ? [] : state.in_flight.filter(Boolean);
// The conversation floor — included so a renderer reload / recovery poll
// restores the composer target (the agent the commander handed off to)
// instead of dropping back to the commander until the next state_changed.
@@ -94,7 +117,7 @@ export async function runtimeStatus(
...diskInFlight,
...runtime.inFlight,
].filter(Boolean)));
- const processing = state.status === 'running' || inFlight.length > 0 || runtime.processing;
+ const processing = (!recoveryPending && state.status === 'running') || inFlight.length > 0 || runtime.processing;
return {
processing,
processing_since: processing ? (state.last_active_at || null) : null,
@@ -112,7 +135,8 @@ export async function runtimeStatus(
* starts emitting events on the same microtask cycle as send's return —
* if subscribe runs after send, those first events are lost. */
export const subscribeBus = subscribe;
-export { submitCliAsyncInput } from './bus';
+export { submitCliAsyncInput, subscribeTaskTerminals } from './bus';
+export type { TaskTerminalEvent, TaskTerminalStatus } from './bus';
import type { ChatUseSelection, ChatMessageReference, GroupMessage } from './visibility';
import {
@@ -133,6 +157,10 @@ export interface SendInput {
userId: string;
cid: string;
text: string;
+ /** Host feature bookkeeping after routing accepts the message and before
+ * recipient work becomes runnable. Never part of the persisted message. */
+ beforeDispatch?: () => Promise<void>;
+ notificationKind?: 'task' | 'automation';
commander_mention_display?: CommanderMentionDisplay;
/** Host-owned delivery decision for the explicit queue "Send now" action.
* Analytics attribution must never imply this execution control. */
@@ -294,6 +322,8 @@ export async function send(
uid: userId, cid,
fromActorId: USER_ID,
text,
+ ...(input.beforeDispatch ? { beforeDispatch: input.beforeDispatch } : {}),
+ ...(input.notificationKind ? { notificationKind: input.notificationKind } : {}),
...(commander_mention_display === 'preserve' || commander_mention_display === 'hide_generated_prefix'
? { commander_mention_display } : {}),
...(steerActiveTurn === true ? { steerActiveTurn: true } : {}),
@@ -792,9 +822,9 @@ export async function dropConv(userId: string, cid: string): Promise<void> {
// ── Conversation task board (list + queued/running cancel) ───────────────
export async function listTasks(userId: string, cid: string) {
- if (!safeId(cid)) return { ok: false as const, error: 'invalid cid', tasks: [] };
+ if (!safeId(cid)) return { ok: false as const, error: 'invalid cid', tasks: [], planning: [] };
const tasks = await busListConversationTasks(userId, cid);
- return { ok: true as const, tasks };
+ return { ok: true as const, tasks, planning: busListPlanningDispatches(userId, cid) };
}
export async function cancelTask(userId: string, cid: string, taskId: string) {
@@ -1488,10 +1518,19 @@ export async function resolveMarketplaceInstallRequest(
// ── Read messages (UI initial load) ──────────────────────────────────────
-export async function readMessages(userId: string, cid: string, limit = 500): Promise<GroupMessage[]> {
+export async function readMessages(userId: string, cid: string, limit = 500, opts?: { strict?: boolean }): Promise<GroupMessage[]> {
if (!safeId(cid)) return [];
- return (await readJsonl<GroupMessage>(conversationMessageReadFile(userId, cid), limit))
- .filter((msg) => !msg.deleted_at);
+ let messages: GroupMessage[];
+ try {
+ messages = await readJsonl<GroupMessage>(conversationMessageReadFile(userId, cid), limit, opts);
+ } catch (error) {
+ if (opts?.strict && (error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ if (opts?.strict && messages.some(msg => !msg || typeof msg !== 'object' || Array.isArray(msg))) {
+ throw new Error('Conversation message is invalid');
+ }
+ return messages.filter((msg) => !msg.deleted_at);
}
function _deletedMessageRevision(message: GroupMessage, deletedAt: string): GroupMessage {
diff --git a/src/main/features/group_chat/message-display.ts b/src/main/features/group_chat/message-display.ts
index cefca893..b3383504 100644
--- a/src/main/features/group_chat/message-display.ts
+++ b/src/main/features/group_chat/message-display.ts
@@ -18,6 +18,9 @@ export function classifyNativeCommentary(record: GroupMessage): GroupMessage {
* public messages. Unknown shapes and active snapshots remain untouched.
* Runs in the history projection owner and is retained in its disk cache. */
export function normalizeNativeMessageDisplay(record: GroupMessage): GroupMessage {
+ // A host interruption receipt is already public reply content, not an
+ // unfinished native segment. Its clock may be absent or recovered later.
+ if (record.system_kind === 'reply_interrupted') return record;
if (record.display_phase || !record.id || !record.source_message_id || !record.turn_id
|| typeof record.text !== 'string'
|| !record.from || record.from === 'user' || record.from === 'commander'
diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.ts
index f3889602..d249e195 100644
--- a/src/main/features/group_chat/state.ts
+++ b/src/main/features/group_chat/state.ts
@@ -106,6 +106,9 @@ export interface StateFile {
last_active_at: string;
/** Actor ids currently running their worker loop. */
in_flight: string[];
+ /** Optional causal identity for startup recovery. Legacy actor-only rosters
+ * remain readable; settlement removes the corresponding entry atomically. */
+ in_flight_turns?: Record<string, { turn_id: string; source_message_id: string }>;
/** Per-conversation workspace subdirectory basename (relative to the
* user's root workspace). Lazily filled by `conv_workspace.ts` on the
* first write_file in this conversation; **empty / missing → legacy
@@ -434,6 +437,22 @@ export async function renameAgentInMembers(
// ── State IO ─────────────────────────────────────────────────────────────
+/** Shared decoding for the normal state reader and raw startup snapshots. */
+export function parseInFlightTurns(inFlight: unknown, value: unknown): StateFile['in_flight_turns'] {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const roster = new Set(Array.isArray(inFlight) ? inFlight : []);
+ const entries = Object.entries(value).filter(([actor, row]) => {
+ const turn = row as Record<string, unknown> | null;
+ return safeId(actor) && actor !== USER_ID && roster.has(actor)
+ && turn && typeof turn.turn_id === 'string' && safeId(turn.turn_id)
+ && typeof turn.source_message_id === 'string' && safeId(turn.source_message_id);
+ }).map(([actor, row]) => {
+ const turn = row as NonNullable<StateFile['in_flight_turns']>[string];
+ return [actor, { turn_id: turn.turn_id, source_message_id: turn.source_message_id }];
+ });
+ return entries.length ? Object.fromEntries(entries) : undefined;
+}
+
export async function readState(uid: string, cid: string, projectIdHint?: string | null, opts?: { strict?: boolean }): Promise<StateFile> {
const cloud = await readCloudState(uid, cid, projectIdHint, opts);
return { ...cloudConversationState(cloud),
@@ -458,6 +477,7 @@ async function readCloudState(
}
if (data && typeof data === 'object') {
const orchestrationLedger = _sanitizeOrchestrationLedger(data.orchestration_ledger);
+ const inFlightTurns = parseInFlightTurns(data.in_flight, data.in_flight_turns);
const recipients = Array.isArray(data.active_recipients)
? [...new Set<string>(data.active_recipients.filter((id: unknown) => (
typeof id === 'string' && safeId(id) && id !== USER_ID
@@ -473,6 +493,7 @@ async function readCloudState(
status: (data.status as GroupStatus) || 'idle',
last_active_at: typeof data.last_active_at === 'string' ? data.last_active_at : nowIso(),
in_flight: Array.isArray(data.in_flight) ? data.in_flight.filter((s: unknown) => typeof s === 'string') : [],
+ ...(inFlightTurns ? { in_flight_turns: inFlightTurns } : {}),
...(typeof data.workspace_dir === 'string' && data.workspace_dir
? { workspace_dir: data.workspace_dir }
: {}),
@@ -659,7 +680,7 @@ export async function setStatus(uid: string, cid: string, status: GroupStatus):
const current = s.status;
s.status = status;
s.last_active_at = nowIso();
- if (status !== 'running') s.in_flight = [];
+ if (status !== 'running') { s.in_flight = []; delete s.in_flight_turns; }
await _writeStatusTransition(uid, cid, current, status, s);
return s;
});
@@ -680,6 +701,7 @@ export async function recoverOrphanRunningState(
// Cancellation is sticky even if an orphan roster also needs clearing.
s.status = current === 'aborted' ? 'aborted' : 'idle';
s.in_flight = [];
+ delete s.in_flight_turns;
s.last_active_at = nowIso();
await _writeStatusTransition(uid, cid, current, s.status, s);
return { recovered: true, state: s };
@@ -703,7 +725,7 @@ export async function transitionStatus(
if (next === null || next === cur) return { changed: false, state: s };
s.status = next;
s.last_active_at = nowIso();
- if (next !== 'running') s.in_flight = [];
+ if (next !== 'running') { s.in_flight = []; delete s.in_flight_turns; }
await _writeStatusTransition(uid, cid, cur, next, s);
return { changed: true, state: s };
});
@@ -1132,12 +1154,22 @@ export async function takeOrchestrationLedgerForForm(
* Mutex-guarded against concurrent `setStatus` so the "read s, mutate
* in_flight, write s" cycle doesn't lose status changes that landed
* while we held a stale `s` snapshot. */
-export async function markInFlight(uid: string, cid: string, actorId: string, running: boolean): Promise<StateFile> {
+export async function markInFlight(
+ uid: string, cid: string, actorId: string, running: boolean,
+ turn?: NonNullable<StateFile['in_flight_turns']>[string],
+): Promise<StateFile> {
return _stateLock(uid, cid).runExclusive(async () => {
const s = await readState(uid, cid);
const have = s.in_flight.includes(actorId);
if (running && !have) s.in_flight.push(actorId);
if (!running && have) s.in_flight = s.in_flight.filter((id) => id !== actorId);
+ if (running && turn) s.in_flight_turns = { ...s.in_flight_turns, [actorId]: {
+ turn_id: turn.turn_id, source_message_id: turn.source_message_id,
+ } };
+ if (!running && s.in_flight_turns) {
+ delete s.in_flight_turns[actorId];
+ if (!Object.keys(s.in_flight_turns).length) delete s.in_flight_turns;
+ }
s.last_active_at = nowIso();
await writeStateRaw(uid, cid, s);
return s;
diff --git a/src/main/features/local_agents/interrupted-history.ts b/src/main/features/local_agents/interrupted-history.ts
index cfa35f86..7171c7ca 100644
--- a/src/main/features/local_agents/interrupted-history.ts
+++ b/src/main/features/local_agents/interrupted-history.ts
@@ -86,6 +86,17 @@ async function archiveRuns(userId: string, cid: string, actors: Set<string>): Pr
function collectTrigger(record: GroupMessage, candidate: Candidate): void {
if (candidate.settled) return;
+ if (candidate.record.source_message_id) {
+ // New receipts retain the exact causal input, including an Agent dispatch.
+ // Other user messages and older replies cannot substitute for that input.
+ if (record.id === candidate.record.source_message_id) {
+ const ts = Date.parse(record.ts);
+ if (Number.isFinite(ts)) candidate.users.set(record.id, ts);
+ else candidate.invalid = true;
+ candidate.settled = true;
+ }
+ return;
+ }
if (!candidate.actorResolved) {
// Startup falls back to Commander when the running roster was lost. The
// nearest structured question or single user destination can identify the
@@ -111,7 +122,7 @@ function collectTrigger(record: GroupMessage, candidate: Candidate): void {
}
}
-async function recoverRun(run: Run, store: (items: Item[]) => HistoryProcessPart | undefined): Promise<{
+async function recoverRun(run: Run, store: (items: Item[]) => HistoryProcessPart | undefined, includeProcess = true): Promise<{
parts: HistoryProcessPart[]; durationMs?: number; lastWrittenAt?: number;
}> {
const parts: HistoryProcessPart[] = [];
@@ -146,6 +157,7 @@ async function recoverRun(run: Run, store: (items: Item[]) => HistoryProcessPart
// A terminal from an earlier attempt cannot time work appended after it.
durationMs = event.type === 'done' && typeof event.durationMs === 'number'
&& Number.isFinite(event.durationMs) && event.durationMs >= 0 ? event.durationMs : undefined;
+ if (!includeProcess) continue;
if (event.type === 'text-delta') {
if (event.phase === 'commentary' && typeof event.text === 'string') {
commentary += filter ? filter.push(event.text) : event.text;
@@ -173,6 +185,42 @@ async function recoverRun(run: Run, store: (items: Item[]) => HistoryProcessPart
return { parts, durationMs, ...(hasEvents ? { lastWrittenAt } : {}) };
}
+function runTiming(run: Run, noticeEnd: number, recovered?: Awaited<ReturnType<typeof recoverRun>>): {
+ duration: number; estimated: boolean;
+} | undefined {
+ const start = Date.parse(run.startedAt);
+ const span = Date.parse(run.endedAt || '') - start;
+ let duration = typeof run.durationMs === 'number' && Number.isFinite(run.durationMs) && run.durationMs >= 0
+ ? run.durationMs : span;
+ let estimated = false;
+ if (!Number.isFinite(duration) && !run.endedAt) {
+ if (recovered?.durationMs != null) duration = recovered.durationMs;
+ else if (recovered?.lastWrittenAt != null) {
+ duration = recovered.lastWrittenAt - start;
+ estimated = true;
+ }
+ }
+ return Number.isFinite(duration) && duration >= 0 && start + duration <= noticeEnd
+ ? { duration, estimated } : undefined;
+}
+
+function hasInterruptionClock(record: GroupMessage): boolean {
+ return !!record.process?.some(item => {
+ const event = item.event;
+ const data = event?.data as Record<string, unknown> | undefined;
+ return event?.stream === 'runtime' && data?.phase !== 'segment_end' && data?.phase !== 'retrying'
+ && typeof data?.duration_ms === 'number' && Number.isFinite(data.duration_ms) && data.duration_ms >= 0;
+ });
+}
+
+function noticeEndUpperBound(ts: string): number {
+ // nowIso/localIsoAt persist whole seconds, whereas CLI archives retain
+ // milliseconds. A receipt at :24 can follow a run ending at :24.602.
+ // Only widen that explicit timestamp shape; precise receipts stay precise.
+ const secondPrecision = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})?$/.test(ts);
+ return Date.parse(ts) + (secondPrecision ? 999 : 0);
+}
+
/** `before` names the byte start of this selected page, so a notice whose
* trigger is on the previous page does not require a whole-chat scan. */
export async function restoreInterruptedCliHistory(
@@ -182,13 +230,13 @@ export async function restoreInterruptedCliHistory(
const candidates: Candidate[] = [];
for (let index = 0; index < records.length; index++) {
const record = records[index];
- if (record.system_kind !== 'reply_interrupted' || record.deleted_at
- || record.process?.length || record.process_parts?.length) continue;
+ if (record.system_kind !== 'reply_interrupted' || record.deleted_at || hasInterruptionClock(record)) continue;
const attempts: Candidate[] = [{ record, actorId: record.from, actorResolved: true,
users: new Map(), settled: false, invalid: false }];
// Keep the original sender's recovery first. A delegated question must
// not replace that actor's own archive when both runs are evidenced.
- if (record.from === 'commander' && !record.turn_id && !record.source_message_id) {
+ if (record.from === 'commander' && !record.turn_id && !record.source_message_id
+ && !record.process?.length && !record.process_parts?.length) {
attempts.push({ record, actorId: record.from, actorResolved: false,
users: new Map(), settled: false, invalid: false });
}
@@ -214,15 +262,16 @@ export async function restoreInterruptedCliHistory(
const recovered = new Map<string, GroupMessage>();
for (const { record, actorId, users, invalid } of candidates) {
if (invalid || !users.size || recovered.has(record.id)) continue;
- const end = Date.parse(record.ts);
+ const end = noticeEndUpperBound(record.ts);
const earliestUser = Math.min(...users.values());
const latestUser = Math.max(...users.values());
const matches = runs.filter(run => run.agentId === actorId
+ && (!record.source_message_id || run.currentMessageId === record.source_message_id)
// Cross-actor fallback requires the exact original trigger. Legacy time
// windows alone cannot prove which actor owned a generic startup notice.
&& (actorId === record.from || !!run.currentMessageId)
&& Date.parse(run.startedAt) >= (run.currentMessageId ? users.get(run.currentMessageId) ?? Infinity : earliestUser)
- && Date.parse(run.startedAt) < end
+ && Date.parse(run.startedAt) <= end
&& (!run.endedAt || (Date.parse(run.endedAt) >= latestUser && Date.parse(run.endedAt) <= end)));
// A legacy archive has no trigger identity. Ambiguity must not show work
// from another run as if it belonged to this interrupted reply.
@@ -230,34 +279,33 @@ export async function restoreInterruptedCliHistory(
&& (matches.some(run => !run.currentMessageId) || new Set(matches.map(run => run.currentMessageId)).size !== 1))) continue;
try {
const parts: HistoryProcessPart[] = [];
- let timing: Awaited<ReturnType<typeof recoverRun>> | undefined;
+ const savedProcess = !!(record.process?.length || record.process_parts?.length);
+ const intervals: { start: number; end: number }[] = [];
+ let estimated = false, allTimed = true;
for (const run of matches.sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt))) {
- const recovered = await recoverRun(run, store);
- parts.push(...recovered.parts);
- timing = recovered;
- }
- // A single archived attempt has a defined elapsed time. Prefer its
- // measured duration; use retained endpoints when both are known. Never
- // count app downtime up to the later startup notice or invent a terminal
- // success receipt merely to display the clock.
- const run = matches.length === 1 ? matches[0] : undefined;
- const span = run ? Date.parse(run.endedAt || '') - Date.parse(run.startedAt) : NaN;
- let duration = typeof run?.durationMs === 'number' && Number.isFinite(run.durationMs) && run.durationMs >= 0
- ? run.durationMs : span;
- let estimated = false;
- if (run && !Number.isFinite(duration)) {
- const startedAt = Date.parse(run.startedAt);
- // A crash may leave the terminal event durable before meta.json is
- // finalized. Otherwise the last archive write is an approximate stop
- // boundary, never the later startup notice (which includes downtime).
- if (timing?.durationMs != null && timing.durationMs <= end - startedAt) duration = timing.durationMs;
- else if (!run.endedAt && timing?.lastWrittenAt != null
- && timing.lastWrittenAt >= startedAt && timing.lastWrittenAt <= end) {
- duration = timing.lastWrittenAt - startedAt;
- estimated = true;
+ let timing = runTiming(run, end);
+ // A saved trail needs only its missing clock. Finalized metadata avoids
+ // rereading a potentially large archive or appending duplicate process.
+ if (!savedProcess || !timing) {
+ try {
+ const recoveredRun = await recoverRun(run, store, !savedProcess);
+ parts.push(...recoveredRun.parts);
+ timing = runTiming(run, end, recoveredRun);
+ } catch (error) { if (!timing) throw error; }
}
+ if (!timing) { allTimed = false; continue; }
+ estimated ||= timing.estimated;
+ const start = Date.parse(run.startedAt);
+ intervals.push({ start, end: start + timing.duration });
+ }
+ // Add evidenced execution intervals, excluding gaps between attempts and
+ // downtime before startup. Overlapping archives must not double the clock.
+ let duration = 0, coveredEnd = -Infinity;
+ for (const interval of intervals) {
+ duration += Math.max(0, interval.end - Math.max(interval.start, coveredEnd));
+ coveredEnd = Math.max(coveredEnd, interval.end);
}
- const runtime: Item[] = Number.isFinite(duration) && duration >= 0
+ const runtime: Item[] = allTimed && intervals.length
? [{ type: 'event', event: { stream: 'runtime', data: {
phase: 'interrupted', duration_ms: Math.round(duration), ...(estimated ? { duration_estimated: true } : {}),
} } }]
diff --git a/src/main/features/recycle_bin.ts b/src/main/features/recycle_bin.ts
index 65625a1c..9c058d34 100644
--- a/src/main/features/recycle_bin.ts
+++ b/src/main/features/recycle_bin.ts
@@ -1558,6 +1558,7 @@ async function reactivateChatIndexRows(
if (!bucket.changed) continue;
for (const row of bucket.rows) {
if (!row.deleted_at && cidToRelPath.has(row.conversation_id)) {
+ row.restored_at = restoredIso;
bumpRecordSyncVersion(row, row._sync_device_id || '');
}
}
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 8770e647..079f165f 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -1966,7 +1966,6 @@ function _transferNewChatRecipientTo(cid) {
}
}
-
// Quoted-line and code spans (start/end offsets) in composer text. `@` tokens
// inside them are context the user pulled in with quote-reply, not dispatch —
// the bus router strips those lines before parsing mentions, so every composer
@@ -2883,6 +2882,10 @@ function onEnterConversationView() {
// don't accumulate dead entries in localStorage forever.
function _forgetCidRecipient(cid) {
if (!cid) return;
+ _forgetConversationRuntime(cid);
+ const taskSurfaceOwner = _taskSurfaceAbortRefreshOwners.get(cid);
+ if (taskSurfaceOwner && taskSurfaceOwner.timer != null) clearTimeout(taskSurfaceOwner.timer);
+ _taskSurfaceAbortRefreshOwners.delete(cid);
if (_recipientByCid[cid]) {
delete _recipientByCid[cid];
_saveRecipientMap();
@@ -3132,9 +3135,11 @@ function _isPrimaryOwnedLiveEvent(evData) {
// task board is the whole set: its rows live in a cid-keyed Map that only
// repaints for the visible cid, and its states are absorbing — a terminal
// missed while the user is elsewhere is not re-read until the next stream
-// (re)connect, so the row stays painted "running" indefinitely.
+// (re)connect, so the row stays painted "running" indefinitely. A planned
+// send's arranging window (`dispatch_planning`) is board state of the same kind.
function _taskBoardEventBypassesViewGuard(evData) {
- return !!evData && (evData.type === 'task_created' || evData.type === 'task_state');
+ return !!evData && (evData.type === 'task_created' || evData.type === 'task_state'
+ || evData.type === 'dispatch_planning');
}
function _stopRuntimeActorRecovery(cid) {
@@ -3159,7 +3164,11 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {
// source; letting this path finish it can manufacture empty loading bubbles
// or clear pending in the middle of a plan handoff.
const allowController = !!opts.allowController;
- const hasLiveController = !!state.controller && _convChatCtrls.has(cid);
+ // A standalone recovery observer also occupies the controller map. It is
+ // not a primary send stream that can deliver replies after we cancel it.
+ const activeController = _convChatCtrls.get(cid);
+ const hasLiveController = !!state.controller && !!activeController
+ && activeController !== _groupObserverReservations.get(cid);
if (hasLiveController && !allowController) return false;
const loadingEl = state.loadingEl;
let data = null;
@@ -3170,7 +3179,7 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {
return false;
}
if (!data || data.ok === false) return false;
- if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) return false;
+ if (!isConvPending(cid) || pendingConvs.get(cid) !== state || state.aborted) return false;
const inFlight = Array.isArray(data.in_flight)
? data.in_flight.filter(Boolean).map(String)
: [];
@@ -3181,6 +3190,13 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {
try { window.ConversationInfo.refreshFiles(cid, { silent: true }); } catch (_) {}
}
if (!processing) {
+ // Runtime can be idle while a recovery stream still buffers the terminal
+ // reply. Read canonical history before cancelling that stream; otherwise
+ // an empty placeholder makes cleanup discard the only delivery path.
+ if (!hasLiveController && cid === currentCid) {
+ await _recoverObservedConversationHistory(cid);
+ if (pendingConvs.get(cid) !== state || state.aborted) return false;
+ }
_stopGroupEventObserver(cid);
if (hasLiveController) {
_latestInFlight.set(cid, []);
@@ -3241,7 +3257,7 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {
// Names/avatars are local data; warm members before revealing so the
// placeholder does not flash as an unknown agent.
try { await _refreshGroupMembers(cid); } catch (_) { /* best effort */ }
- if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) return false;
+ if (!isConvPending(cid) || pendingConvs.get(cid) !== state || state.aborted) return false;
if (cid !== currentCid) return true;
if (hasActiveTurnsField) {
const activeCommander = activeTurns.some((t) => t.actor === 'commander');
@@ -4068,6 +4084,7 @@ function _findRenderedGroupMessage(container, message, exclude = null) {
// real attachment-pool filename; `displayName` is the stable composer label.
const _chatAttachments = new Map(); // cid → Array<{name, displayName?, kind, bytes, dataUrl?, sha256?, reused?}>
+let _chatAttachmentSelectionSequence = 0;
// Attachment bytes live in the main process while composer chips live in this
// renderer. Track mutations from their earliest async boundary so Send cannot
// snapshot an empty chip list while file hashing, native picking, importing, or
@@ -4130,31 +4147,6 @@ function _chatAttachTargetOf(cid) {
return 'conversation';
}
-function _chatAttachPayload(cid, files, source) {
- const list = Array.from(files || []);
- const kinds = {};
- let totalBytes = 0;
- for (const file of list) {
- const name = file && (file.name || file.path || '');
- const kind = _chatAttachKindFromExt(_chatAttachExtOf(name));
- kinds[kind] = (kinds[kind] || 0) + 1;
- totalBytes += Number((file && (file.size || file.bytes)) || 0);
- }
- return {
- source,
- target: _chatAttachTargetOf(cid),
- file_count: list.length,
- total_bytes: totalBytes,
- image_count: kinds.image || 0,
- video_count: kinds.video || 0,
- audio_count: kinds.audio || 0,
- document_count:
- (kinds.pdf || 0) + (kinds.docx || 0) + (kinds.spreadsheet || 0)
- + (kinds.presentation || 0),
- text_count: kinds.text || 0,
- };
-}
-
function _chatAttachBaseName(p) {
const parts = String(p || '').split(/[\\/]/).filter(Boolean);
return parts.length ? parts[parts.length - 1] : String(p || '');
@@ -4173,6 +4165,9 @@ async function _chatAttachSha256(buf) {
return _chatAttachHex(digest);
}
+// Only closed, content-free diagnostics enter the aggregate terminal. Never
+// derive codes from translated errors, filenames, paths or exception messages.
+
async function _chatAttachPrepareUploadFiles(cid, fileList) {
const files = Array.from(fileList || []);
const rejected = [];
@@ -4187,6 +4182,7 @@ async function _chatAttachPrepareUploadFiles(cid, fileList) {
const ext = _chatAttachExtOf(file.name);
if (!CHAT_ATTACH_ACCEPT.includes(ext)) {
rejected.push(t('chat.attach_unsupported', { name: file.name }));
+
continue;
}
@@ -4196,6 +4192,7 @@ async function _chatAttachPrepareUploadFiles(cid, fileList) {
buf = await file.arrayBuffer();
} catch (err) {
rejected.push(t('chat.attach_upload_fail', { name: file.name, reason: err.message || t('chat.attach_upload_generic_fail') }));
+
continue;
}
try { sha256 = await _chatAttachSha256(buf); }
@@ -4252,6 +4249,10 @@ function _chatAttachHasPendingWork(cid) {
));
}
+function _chatAttachIsSending(cid) {
+ return _chatAttachmentSendLocks.has(cid);
+}
+
function _chatAttachTryBeginSend(cid) {
if (!cid || _chatAttachmentSendLocks.has(cid) || _chatAttachHasPendingWork(cid)) return null;
_chatAttachmentSendLocks.add(cid);
@@ -4272,7 +4273,7 @@ function _chatAttachItemsFromServer(cid, infos) {
.filter((item) => item && item.name)
.map((item) => [String(item.name), item]),
);
- return (Array.isArray(infos) ? infos : [])
+ return _chatAttachOrderItems(Array.isArray(infos) ? infos : [], _chatAttachPreferredNames(cid))
.filter((info) => info && info.name)
.map((info) => {
const previous = existing.get(String(info.name)) || {};
@@ -4293,6 +4294,34 @@ function _chatAttachItemsFromServer(cid, infos) {
});
}
+// Membership comes from storage; relative order belongs to the user's selection.
+// Unknown recovered files follow known chips without displacing their ordinals.
+function _chatAttachOrderItems(items, names, key = 'name') {
+ const remaining = new Map(items.filter((item) => item && item[key]).map((item) => [String(item[key]), item]));
+ const ordered = [];
+ for (const name of names) {
+ if (!remaining.has(String(name))) continue;
+ ordered.push(remaining.get(String(name)));
+ remaining.delete(String(name));
+ }
+ return ordered.concat(Array.from(remaining.values()));
+}
+
+function _chatAttachOrderKey(cid) {
+ const uid = typeof currentUserId === 'string' ? currentUserId : '';
+ return uid && cid ? `attachment_order:${JSON.stringify([uid, cid])}` : '';
+}
+
+function _chatAttachPreferredNames(cid) {
+ const local = _chatAttachList(cid);
+ if (local.length) return local.map((item) => item.name);
+ try {
+ const key = _chatAttachOrderKey(cid);
+ const saved = key ? JSON.parse(localStorage.getItem(key) || '[]') : [];
+ return Array.isArray(saved) ? saved.filter((name) => typeof name === 'string').slice(0, 20) : [];
+ } catch (_) { return []; }
+}
+
async function _chatAttachSnapshotForSend(cid, opts = {}) {
if (!cid || _chatAttachHasPendingWork(cid)) return { ok: false, reason: 'busy' };
const revision = _chatAttachRevision(cid);
@@ -4331,7 +4360,7 @@ async function _chatAttachSnapshotForSend(cid, opts = {}) {
const reusable = opts.requireServerMatch
? []
: localReady.filter((item) => item.reused && !serverNames.has(String(item.name)));
- const items = serverItems.concat(reusable);
+ const items = _chatAttachOrderItems(serverItems.concat(reusable), _chatAttachPreferredNames(cid));
const localNames = new Set(_chatAttachList(cid).filter((item) => item && item.name).map((item) => String(item.name)));
_convLog.info('attachment send snapshot ready', {
local_count: localNames.size,
@@ -4350,7 +4379,19 @@ async function _chatAttachSnapshotForSend(cid, opts = {}) {
}
function _chatAttachSet(cid, items) {
+ // Reserve a batch before any file reads/picker/import await; completion time
+ // must never determine where its chips appear relative to later additions.
+ items = items.map((item) => Number.isFinite(item.selectionBatch) ? item : {
+ ...item, selectionBatch: ++_chatAttachmentSelectionSequence, selectionIndex: 0,
+ }).sort((a, b) => a.selectionBatch - b.selectionBatch || (a.selectionIndex || 0) - (b.selectionIndex || 0));
_chatAttachments.set(cid, items);
+ try {
+ const key = _chatAttachOrderKey(cid);
+ if (key) {
+ if (items.length) localStorage.setItem(key, JSON.stringify(items.map((item) => item.name).slice(0, 20)));
+ else localStorage.removeItem(key);
+ }
+ } catch (_) { /* Storage may be unavailable; in-memory order still applies. */ }
if (typeof _persistQueueComposerEditState === 'function') _persistQueueComposerEditState(cid);
_chatAttachMarkMutation(cid);
_chatAttachRenderChips(cid);
@@ -4395,6 +4436,10 @@ async function _chatAttachClear(cid, opts = {}) {
if (deleteFiles) await _chatAttachDeleteItemFile(cid, item);
}
_chatAttachments.delete(cid);
+ try {
+ const key = _chatAttachOrderKey(cid);
+ if (key) localStorage.removeItem(key);
+ } catch (_) {}
_chatAttachMarkMutation(cid);
_chatAttachRenderChips(cid);
if (cid && cid === currentCid && window.ConversationInfo) {
@@ -4546,10 +4591,12 @@ function _chatAttachReplaceByTempId(cid, tempId, patch) {
? items.findIndex((it, i) => i !== idx && it.name === next.name && it.status !== 'uploading')
: -1;
if (dupIdx >= 0) {
- if (items[idx].dataUrl && items[idx].dataUrl.startsWith('blob:')) {
- try { URL.revokeObjectURL(items[idx].dataUrl); } catch (_) { /* ignore */ }
+ const removeIdx = Math.max(idx, dupIdx);
+ if (items[removeIdx].dataUrl && items[removeIdx].dataUrl.startsWith('blob:')) {
+ try { URL.revokeObjectURL(items[removeIdx].dataUrl); } catch (_) { /* ignore */ }
}
- items.splice(idx, 1);
+ if (idx < dupIdx) items[idx] = next;
+ items.splice(removeIdx, 1);
} else {
items[idx] = next;
}
@@ -4577,28 +4624,30 @@ async function _chatAttachUpload(cid, fileList, source = 'drop') {
// byte upload. Both routes paint the same placeholder chip, are bounded by the
// same main-side per-kind caps and hash dedupe.
async function _chatAttachUploadCore(cid, fileList, source) {
- const clickPayload = _chatAttachPayload(cid, fileList, source);
+ const selectionBatch = ++_chatAttachmentSelectionSequence;
+
const rejected = [];
+
const accepted = [];
for (const file of Array.from(fileList || [])) {
if (!CHAT_ATTACH_ACCEPT.includes(_chatAttachExtOf(file.name))) {
rejected.push(t('chat.attach_unsupported', { name: file.name }));
+
continue;
}
accepted.push(file);
}
- const local = _chatAttachStartLocalImport(cid, accepted);
+ const selection = new Map(accepted.map((file, selectionIndex) => [file, { selectionBatch, selectionIndex }]));
+ const local = _chatAttachStartLocalImport(cid, accepted, selection);
const byteFiles = accepted.filter((_file, index) => !local.resolved.has(index));
const [localOutcome, byteOutcome] = await Promise.all([
_chatAttachSettleLocalImport(cid, local, rejected),
- _chatAttachUploadBytes(cid, byteFiles, rejected),
+ _chatAttachUploadBytes(cid, byteFiles, rejected, selection),
]);
if (!localOutcome.attempted && !byteOutcome.attempted) {
if (rejected.length) uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));
return;
}
- const uploadedCount = localOutcome.uploaded + byteOutcome.uploaded;
- const failedCount = rejected.length;
if (rejected.length) {
uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));
@@ -4612,7 +4661,7 @@ function _chatAttachNewTempId() {
// Path route. Preload reports which Files resolved to a path synchronously
// (before main copies anything) so their chips appear at once; main returns
// one result per resolved index. `resolved` maps index → placeholder.
-function _chatAttachStartLocalImport(cid, files) {
+function _chatAttachStartLocalImport(cid, files, selection) {
const resolved = new Map();
if (!files.length || !window.orkas || typeof window.orkas.importLocalFiles !== 'function') {
return { resolved, promise: null };
@@ -4633,6 +4682,7 @@ function _chatAttachStartLocalImport(cid, files) {
try { localPreview = URL.createObjectURL(file); } catch (_) { /* ignore */ }
}
current.push({
+ ...selection.get(file),
tempId, name: file.name, displayName: file.name, kind, bytes: file.size || 0,
dataUrl: localPreview, sha256: '', status: 'uploading',
});
@@ -4659,6 +4709,7 @@ async function _chatAttachSettleLocalImport(cid, local, rejected) {
name: ph.file.name,
reason: reason || t('chat.attach_upload_generic_fail'),
}));
+
};
let data;
try {
@@ -4700,7 +4751,7 @@ async function _chatAttachSettleLocalImport(cid, local, rejected) {
// Byte route (path-less Files only). Unchanged contract: hash before painting
// so one paste of several identical blobs never flashes duplicate chips, then
// upload every placeholder in parallel.
-async function _chatAttachUploadBytes(cid, files, rejected) {
+async function _chatAttachUploadBytes(cid, files, rejected, selection) {
const outcome = { attempted: 0, uploaded: 0 };
if (!files.length) return outcome;
const prepared = await _chatAttachPrepareUploadFiles(cid, files);
@@ -4721,6 +4772,7 @@ async function _chatAttachUploadBytes(cid, files, rejected) {
try { localPreview = URL.createObjectURL(file); } catch (_) { /* ignore */ }
}
const entry = {
+ ...selection.get(file),
tempId, name: file.name, displayName: file.name, kind, bytes: file.size || 0,
dataUrl: localPreview, sha256, status: 'uploading',
};
@@ -4747,6 +4799,7 @@ async function _chatAttachUploadBytes(cid, files, rejected) {
_chatAttachReplaceByTempId(cid, ph.tempId, null);
uploadFailed += 1;
rejected.push(t('chat.attach_upload_fail', { name: ph.file.name, reason: data.error || t('chat.attach_upload_generic_fail') }));
+
return;
}
const info = data.info;
@@ -4768,6 +4821,7 @@ async function _chatAttachUploadBytes(cid, files, rejected) {
_chatAttachReplaceByTempId(cid, ph.tempId, { status: 'error' });
uploadFailed += 1;
rejected.push(t('chat.attach_upload_fail', { name: ph.file.name, reason: err.message || t('chat.attach_upload_generic_fail') }));
+
}
}));
outcome.uploaded = Math.max(0, placeholders.length - uploadFailed);
@@ -4789,7 +4843,7 @@ async function _chatAttachPickAndUpload(cid, source = 'picker') {
}
async function _chatAttachPickAndUploadCore(cid, source) {
- const basePayload = { source, target: _chatAttachTargetOf(cid) };
+ const selectionBatch = ++_chatAttachmentSelectionSequence;
let data;
try {
data = await window.orkas.invoke('conversations.attachments.pickAndUpload', { cid });
@@ -4797,7 +4851,11 @@ async function _chatAttachPickAndUploadCore(cid, source) {
_convLog.warn('native attachment picker failed', {
error_type: err && typeof err === 'object' ? 'Error' : typeof err,
});
- await uiAlert(t('chat.attach_upload_fail', { name: '', reason: err.message || t('chat.attach_upload_generic_fail') }));
+ data = { ok: false, code: err && err.code };
+ }
+ if (!data || data.ok === false) {
+
+ await uiAlert(t('chat.attach_upload_generic_fail'));
return;
}
if (data && data.cancelled) {
@@ -4810,8 +4868,16 @@ async function _chatAttachPickAndUploadCore(cid, source) {
for (const item of picked) {
const info = item && item.info;
if (!info || !info.name) continue;
- if (current.some((it) => it.name === info.name && it.status !== 'uploading')) continue;
+ const existing = current.find((it) => it.name === info.name && it.status !== 'uploading');
+ if (existing) {
+ if (selectionBatch < existing.selectionBatch) {
+ existing.selectionBatch = selectionBatch;
+ existing.selectionIndex = picked.indexOf(item);
+ }
+ continue;
+ }
current.push({
+ selectionBatch, selectionIndex: picked.indexOf(item),
tempId: `att-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
name: info.name,
displayName: item.displayName || info.name,
@@ -4877,7 +4943,7 @@ async function _chatAttachImportPaths(cid, entries, source = 'internal_drop') {
}
async function _chatAttachImportPathsCore(cid, files, source) {
- const clickPayload = _chatAttachPayload(cid, files, source);
+ const selectionBatch = ++_chatAttachmentSelectionSequence;
const placeholders = [];
const current = _chatAttachList(cid).slice();
@@ -4887,6 +4953,7 @@ async function _chatAttachImportPathsCore(cid, files, source) {
const kind = _chatAttachKindFromExt(ext);
const tempId = `att-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
current.push({
+ selectionBatch, selectionIndex: placeholders.length,
tempId,
name: displayName,
displayName,
@@ -4900,6 +4967,7 @@ async function _chatAttachImportPathsCore(cid, files, source) {
_chatAttachSet(cid, current);
const rejected = [];
+
let uploadFailed = 0;
await Promise.all(placeholders.map(async (ph) => {
try {
@@ -4913,6 +4981,7 @@ async function _chatAttachImportPathsCore(cid, files, source) {
_chatAttachReplaceByTempId(cid, ph.tempId, null);
uploadFailed += 1;
rejected.push(t('chat.attach_upload_fail', { name: ph.name, reason: data.error || t('chat.attach_upload_generic_fail') }));
+
return;
}
const info = data.info;
@@ -4929,9 +4998,9 @@ async function _chatAttachImportPathsCore(cid, files, source) {
_chatAttachReplaceByTempId(cid, ph.tempId, null);
uploadFailed += 1;
rejected.push(t('chat.attach_upload_fail', { name: ph.name, reason: err.message || t('chat.attach_upload_generic_fail') }));
+
}
}));
- const uploadedCount = Math.max(0, placeholders.length - uploadFailed);
if (rejected.length) {
uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));
@@ -4945,13 +5014,22 @@ window.addChatAttachmentsFromPaths = async function addChatAttachmentsFromPaths(
// Add an already-imported attachment (from a KB "ask the commander about this
// file" action) to a draft pool's chips. The file is imported server-side into
// the draft cid's pool; here we just surface it as a ready chip.
-function _addReadyDraftAttachment(cid, info) {
+function _addReadyDraftAttachment(cid, info, selectionBatch) {
if (!info || !info.name) return;
const items = _chatAttachList(cid).slice();
// The storage owner can reuse the same pending file across Library imports.
// Match upload completion: one stored attachment owns one removable chip.
- if (items.some((item) => item.name === info.name && item.status !== 'uploading')) return;
+ const existing = items.find((item) => item.name === info.name && item.status !== 'uploading');
+ if (existing) {
+ if (selectionBatch < existing.selectionBatch) {
+ existing.selectionBatch = selectionBatch;
+ existing.selectionIndex = 0;
+ _chatAttachSet(cid, items);
+ }
+ return;
+ }
items.push({
+ selectionBatch, selectionIndex: 0,
name: info.name,
displayName: info.displayName || info.name,
kind: info.kind,
@@ -4970,6 +5048,39 @@ function _addReadyDraftAttachment(cid, info) {
// draft chip. No conversation is created — the user's first message creates it
// and adopts the draft attachments.
window.COMMANDER_DRAFT_CID = DRAFT_CID;
+window.attachKbFileToDraft = async function attachKbFileToDraft(channel, payload, draftCid, afterNavigate) {
+ const selectionBatch = ++_chatAttachmentSelectionSequence;
+ const finishOperation = _chatAttachBeginOperation(draftCid);
+ let stage = 'draft_lock';
+ try {
+ if (!finishOperation) throw new Error(t('chat.attach_send_in_progress'));
+ stage = 'ipc_request';
+ const data = await window.orkas.invoke(channel, { ...(payload || {}), cid: draftCid });
+ if (!data || !data.ok) {
+ const error = new Error((data && data.error) || 'failed');
+ error.failure_stage = data && data.failure_stage;
+ error.failure_kind = data && data.failure_kind;
+ throw error;
+ }
+ stage = 'navigation';
+ if (typeof afterNavigate === 'function') afterNavigate();
+ stage = 'draft_render';
+ _addReadyDraftAttachment(draftCid, data.info, selectionBatch);
+ } catch (error) {
+ const safeStage = error && error.failure_stage;
+ const safeKind = error && error.failure_kind;
+ const failure_stage = ['input_validation', 'source_resolve', 'attachment_import'].includes(safeStage) ? safeStage : stage;
+ const failure_kind = ['not_found', 'permission_denied', 'disk_full'].includes(safeKind) ? safeKind : 'operation_failed';
+ // Keep the UI's original message; diagnostics receive only the enums.
+ const wrapped = new Error((error && error.message) || String(error));
+ wrapped.failure_stage = failure_stage;
+ wrapped.failure_kind = failure_kind;
+ _convLog.warn('library attachment failed', { failure_stage, failure_kind });
+ throw wrapped;
+ } finally {
+ if (finishOperation) finishOperation();
+ }
+};
async function _chatAttachRefreshFromServer(cid) {
// Navigation restores this selection from the edit marker. Pending files
@@ -5164,8 +5275,6 @@ function _mountMessageRunFactsFooter(msgDiv, facts) {
if (factsNode) bubble.appendChild(factsNode);
}
-
-
// Resolve only attachment references that could overlap a produced file. The
// basename filter avoids unrelated IPC; only the resolved full path establishes
// identity. Never infer attachment storage layout in the renderer.
@@ -7609,6 +7718,16 @@ async function loadConversationHistory(cid, opts = {}) {
} else if (!history.length) {
container.innerHTML = `<div class="empty">${escapeHtml(t('chat.empty'))}</div>`;
} else {
+ // A background rebuild must keep the action node that owns an in-flight
+ // updater and its result. Scope reuse to the exact message and actor;
+ // leaving this transcript still discards these transient controls.
+ const cliUpgradeControls = new Map();
+ for (const row of container.querySelectorAll('.chat-message[data-msg-id]')) {
+ const control = row.querySelector('.local-cli-upgrade-control');
+ if (control?.dataset.state) {
+ cliUpgradeControls.set(JSON.stringify([row.dataset.msgId, row.dataset.fromActor]), control);
+ }
+ }
container.innerHTML = '';
// The history array is already time-sorted above. Stage it off-DOM and
// bypass the live-event dedupe/sorted-insertion work: doing either for
@@ -7625,6 +7744,7 @@ async function loadConversationHistory(cid, opts = {}) {
msgIndex: Number.isSafeInteger(msg?._history_index) ? msg._history_index : undefined,
container: historyFragment,
historyHydration: true,
+ cliUpgradeControl: cliUpgradeControls.get(JSON.stringify([msg._msg_id, msg._from])),
});
// Retain terminal identity across the DOM rebuild so a stale live
// display snapshot or deferred process event cannot reopen this turn.
@@ -7781,7 +7901,6 @@ async function loadConversationHistory(cid, opts = {}) {
_replayOffViewGroupProcessEvents(cid, activePendingState.loadingEl, { archive: true });
}
-
// Re-add the inline "create agent" entry BEFORE scrolling so it's part of
// scrollHeight when we jump to the bottom — otherwise the MutationObserver
// adds it post-scroll and it ends up below the visible area.
@@ -7820,7 +7939,11 @@ function _messageRecordHasMountedSidecars(gm, el, opts = {}) {
if (Array.isArray(gm.saved_tasks) && gm.saved_tasks.some((task) => !el.querySelector(
`[data-saved-task-key="${CSS.escape(JSON.stringify([task.kind, task.project_id || '', task.task_id]))}"]`,
))) return false;
- if (Array.isArray(gm.artifacts) && gm.artifacts.length && !el.querySelector('.chat-artifact-host')) return false;
+ if (Array.isArray(gm.artifacts) && gm.artifacts.length && !el.querySelector('.chat-artifact-host')) {
+ const frames = Array.from(document.querySelectorAll('iframe.chat-artifact-frame'));
+ if (gm.artifacts.some(app => !frames.some(frame => frame.dataset.artifactCid === opts.cid
+ && frame.dataset.artifactId === String(app.id)))) return false;
+ }
if (Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length && !el.querySelector('.chat-marketplace-request')) return false;
if (_processItemsHaveRenderableLine(gm.process) && !el.querySelector('.stream-process')) return false;
if (_isInterruptedAssistantMessage(gm) && !el.querySelector('.bubble-retry-btn')) return false;
@@ -7881,7 +8004,7 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
}
}
_syncRenderedGroupMessageIdentity(existing, gm);
- if (!_messageRecordHasMountedSidecars(gm, existing, { checkMutableState: false })) {
+ if (!_messageRecordHasMountedSidecars(gm, existing, { cid, checkMutableState: false })) {
loadConversationHistory(cid, { preserveScroll: true });
return true;
}
@@ -8988,6 +9111,9 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// raw-markdown replies; sanitized HTML status stubs are not archivable.
if (role === 'assistant' && failedAssistant) {
_mountEmptyResponseNotice(msgDiv, message);
+ if (message.failure_code === 'version_too_old' && opts.cliUpgradeControl) {
+ msgDiv.querySelector('.chat-bubble')?.appendChild(opts.cliUpgradeControl);
+ }
_attachFailedAssistantActions(msgDiv, () => _messageTextForActions(msgDiv, rawContent));
// Live group-bus messages can arrive without a matching streaming
// placeholder (fast preflight failures and reconnect races). History
@@ -10536,7 +10662,10 @@ async function _openReferenceTargetPicker(payloads) {
if (target) _stageReferencesForNewTask(payloads, target.dataset.createProjectId);
});
overlay.querySelector('.chat-reference-target-close')?.addEventListener('click', _closeReferenceTargetPicker);
- overlay.addEventListener('keydown', (event) => { if (event.key === 'Escape') _closeReferenceTargetPicker(); });
+ overlay.addEventListener('keydown', (event) => {
+ if (event.isComposing || event.keyCode === 229) return;
+ if (event.key === 'Escape') _closeReferenceTargetPicker();
+ });
search.addEventListener('input', () => {
picker.limit = _REFERENCE_TARGET_PAGE_SIZE;
render();
@@ -10972,12 +11101,12 @@ async function _retryFailedAssistantMessage(msgDiv) {
// succeeds (so a failure keeps the user's text for retry). Without this flag, a
// held Enter (key auto-repeat) or a fast double-press during the create round
// trip re-runs the whole submit with the same text: two conversations, two paid
-// model runs. Existing conversations use the per-cid attachment send lock to
-// guard asynchronous preparation and acceptance of the submitted draft.
+// model runs. The attachment send lock also covers the earlier asynchronous
+// snapshot, while this flag preserves the conversation-create gate.
let _newChatSubmitting = false;
async function handleNewChatSubmit() {
- if (_newChatSubmitting) return;
+ if (_newChatSubmitting || _chatAttachIsSending(DRAFT_CID)) return;
const input = document.getElementById('new-chat-input');
const submittedDraft = composerSnapshot(input);
const navigationEpoch = _composerNavigationEpoch;
@@ -11006,183 +11135,196 @@ async function handleNewChatSubmit() {
await uiAlert(t('chat.attach_still_uploading'));
return;
}
- const attachmentSnapshot = await _chatAttachSnapshotForSend(DRAFT_CID, { requireServerMatch: true });
- if (!attachmentSnapshot.ok) {
- releaseAttachmentSend();
- await uiAlert(t('chat.attach_sync_failed'));
- return;
- }
- draftItems = attachmentSnapshot.items;
- const references = _referenceSnapshotsForQuotes(quotes);
- // Keep resource selections in the composer until attachment adoption has
- // completed. A failed preflight must leave the whole request retryable.
- const useSelections = pendingUseSelections;
- // Snapshot the new-chat recipient *now* so a stray view-change between
- // here and conv-create doesn't reset it before we can transfer.
- _pendingNewChatRecipient = _normaliseRecipientSnapshot(recipientSnapshot) || { ..._COMMANDER };
- // Keep the title seed separate from transport content. The body carries
- // routing mentions (panel-inserted or typed) and `content` may gain an
- // injected leading `@Agent`, while task titles describe only the user's
- // request.
- const titleSeed = _titleSeedWithoutRoutingMentions(raw, 'new-chat');
- const titleText = (typeof transformChatUseTokens === 'function')
- ? transformChatUseTokens(titleSeed)
- : titleSeed;
- const content = applyRecipientPrefix(transformWithChatUse(requestText), 'new-chat', {
- recipientSnapshot,
- });
- const commanderDisplay = _commanderMentionDisplayForSend(transformWithChatUse(requestText), recipientSnapshot, 'new-chat');
- const draftNames = draftItems.filter((a) => a.status !== 'error').map((a) => a.name);
- _convLog.info('new chat submit', {
- content_length: content.length,
- use: useSelections.map((sel) => sel.kind),
- attachments: draftNames.length,
-
- });
- const newBtn = document.getElementById('new-chat-send-btn');
- if (newBtn) newBtn.disabled = true;
- // Hold the re-entrancy gate while conversation creation is in flight. The
- // input is intentionally preserved until creation succeeds, so button state
- // alone does not protect Enter-key auto-repeat.
- _newChatSubmitting = true;
- let convId;
- let createdConversation = null;
try {
- const res = await apiFetch('/api/conversations/create', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ kind: 'normal' }),
- });
- const data = await res.json();
- if (!data.ok) throw new Error(data.error || t('chat.create_conv_failed'));
- const conv = data.conversation;
- convId = conv.conversation_id;
- // Optimistic title from the user-visible text (without recipient routing).
- // Use the shared `_autoTitle` so this matches backend `autoTitle` —
- // otherwise the optimistic + backend-refreshed titles disagree and
- // the sidebar entry flips on the next loadConversations.
- if (titleText) conv.title = _autoTitle(titleText);
- // Backend `createConversation` returns `created_at`/`updated_at` but
- // NOT the derived `last_active_at` (that lives only in `listConversations`'
- // output). Set it explicitly so `timeBucket` puts the brand-new row in
- // the 'today' bucket instead of falling through to 'older'.
- conv.last_active_at = new Date().toISOString();
- createdConversation = conv;
- } catch (e) {
- _convLog.warn('new chat conversation creation failed', {
+ const attachmentSnapshot = await _chatAttachSnapshotForSend(DRAFT_CID, { requireServerMatch: true });
+ if (!attachmentSnapshot.ok) {
+ releaseAttachmentSend();
- error: e && e.message ? e.message : String(e || ''),
+ await uiAlert(t('chat.attach_sync_failed'));
+ return;
+ }
+ draftItems = attachmentSnapshot.items;
+
+ const references = _referenceSnapshotsForQuotes(quotes);
+ // Keep resource selections in the composer until attachment adoption has
+ // completed. A failed preflight must leave the whole request retryable.
+ const useSelections = pendingUseSelections;
+ // Snapshot the new-chat recipient *now* so a stray view-change between
+ // here and conv-create doesn't reset it before we can transfer.
+ _pendingNewChatRecipient = _normaliseRecipientSnapshot(recipientSnapshot) || { ..._COMMANDER };
+ // Keep the title seed separate from transport content. The body carries
+ // routing mentions (panel-inserted or typed) and `content` may gain an
+ // injected leading `@Agent`, while task titles describe only the user's
+ // request.
+ const titleSeed = _titleSeedWithoutRoutingMentions(raw, 'new-chat');
+ const titleText = (typeof transformChatUseTokens === 'function')
+ ? transformChatUseTokens(titleSeed)
+ : titleSeed;
+ const content = applyRecipientPrefix(transformWithChatUse(requestText), 'new-chat', {
+ recipientSnapshot,
});
- await uiAlert(t('chat.create_conv_failed_with_reason', { reason: e.message || e }));
- if (newBtn) newBtn.disabled = false;
- _newChatSubmitting = false; // text kept in the input — allow a retry submit
- releaseAttachmentSend();
- return;
- }
-
- // Adopt local `main_chat/` draft files into `<convId>/` on disk.
- // Preprocessing caches (`.<name>.extracted.NNN.md`) move with their source
- // when present — nothing to re-run.
- let attachments = [];
- let adoptionError = '';
- try {
- // Always adopt. An empty renderer snapshot must not skip files that were
- // committed by the main process but lost from the renderer state.
- const res = await apiFetch('/api/conversations/attachments/adopt', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ from_cid: DRAFT_CID, to_cid: convId }),
+ const commanderDisplay = _commanderMentionDisplayForSend(transformWithChatUse(requestText), recipientSnapshot, 'new-chat');
+ const draftNames = draftItems.filter((a) => a.status !== 'error').map((a) => a.name);
+ _convLog.info('new chat submit', {
+ content_length: content.length,
+ use: useSelections.map((sel) => sel.kind),
+ attachments: draftNames.length,
});
- const data = await res.json();
- if (!data.ok) {
- adoptionError = String(data.error || 'attachment_adopt_failed');
- } else {
- const adoptedItems = (Array.isArray(data.items) ? data.items : [])
- .filter((item) => item && item.sourceName && item.targetName);
- const adoptedSources = new Set(adoptedItems.map((item) => String(item.sourceName)));
- if (draftNames.some((name) => !adoptedSources.has(String(name)))) {
- adoptionError = 'attachment_adopt_incomplete';
+ const newBtn = document.getElementById('new-chat-send-btn');
+ if (newBtn) newBtn.disabled = true;
+ // Hold the re-entrancy gate while conversation creation is in flight. The
+ // input is intentionally preserved until creation succeeds, so button state
+ // alone does not protect Enter-key auto-repeat.
+ _newChatSubmitting = true;
+ let convId;
+ let createdConversation = null;
+ try {
+ const res = await apiFetch('/api/conversations/create', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ kind: 'normal' }),
+ });
+ const data = await res.json();
+ if (!data.ok) throw new Error(data.error || t('chat.create_conv_failed'));
+ const conv = data.conversation;
+ convId = conv.conversation_id;
+ // Optimistic title from the user-visible text (without recipient routing).
+ // Use the shared `_autoTitle` so this matches backend `autoTitle` —
+ // otherwise the optimistic + backend-refreshed titles disagree and
+ // the sidebar entry flips on the next loadConversations.
+ if (titleText) conv.title = _autoTitle(titleText);
+ // Backend `createConversation` returns `created_at`/`updated_at` but
+ // NOT the derived `last_active_at` (that lives only in `listConversations`'
+ // output). Set it explicitly so `timeBucket` puts the brand-new row in
+ // the 'today' bucket instead of falling through to 'older'.
+ conv.last_active_at = new Date().toISOString();
+ createdConversation = conv;
+ } catch (e) {
+ _convLog.warn('new chat conversation creation failed', {
+ error: e && e.message ? e.message : String(e || ''),
+ });
+
+ await uiAlert(t('chat.create_conv_failed_with_reason', { reason: e.message || e }));
+ if (newBtn) newBtn.disabled = false;
+ _newChatSubmitting = false; // text kept in the input — allow a retry submit
+ releaseAttachmentSend();
+ return;
+ }
+
+ // Adopt local `main_chat/` draft files into `<convId>/` on disk.
+ // Preprocessing caches (`.<name>.extracted.NNN.md`) move with their source
+ // when present — nothing to re-run.
+ let attachments = [];
+ let adoptionError = '';
+ try {
+ // Always adopt. An empty renderer snapshot must not skip files that were
+ // committed by the main process but lost from the renderer state.
+ const res = await apiFetch('/api/conversations/attachments/adopt', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ from_cid: DRAFT_CID, to_cid: convId }),
+ });
+ const data = await res.json();
+ if (!data.ok) {
+ adoptionError = String(data.error || 'attachment_adopt_failed');
} else {
- // The adoption result is authoritative. Include any file that appeared
- // between the preflight list and the atomic directory move as well.
- attachments = adoptedItems.map((item) => String(item.targetName));
+ const adoptedItems = (Array.isArray(data.items) ? data.items : [])
+ .filter((item) => item && item.sourceName && item.targetName);
+ const adoptedSources = new Set(adoptedItems.map((item) => String(item.sourceName)));
+ if (draftNames.some((name) => !adoptedSources.has(String(name)))) {
+ adoptionError = 'attachment_adopt_incomplete';
+ } else {
+ // The adoption result is authoritative. Include any file that appeared
+ // between the preflight list and the atomic directory move as well.
+ attachments = _chatAttachOrderItems(adoptedItems, draftNames, 'sourceName')
+ .map((item) => String(item.targetName));
+ }
}
+ } catch (err) {
+ adoptionError = String(err && err.message ? err.message : err || 'attachment_adopt_failed');
}
- } catch (err) {
- adoptionError = String(err && err.message ? err.message : err || 'attachment_adopt_failed');
- }
- if (adoptionError) {
- try {
- const cleanup = await window.orkas.invoke('conversations.discardEmpty', { cid: convId });
- if (!cleanup || !cleanup.discarded) {
- _convLog.warn('discard empty conversation rejected', {
- error_code: 'discard_empty_rejected',
+ if (adoptionError) {
+ try {
+ const cleanup = await window.orkas.invoke('conversations.discardEmpty', { cid: convId });
+ if (!cleanup || !cleanup.discarded) {
+ _convLog.warn('discard empty conversation rejected', {
+ error_code: 'discard_empty_rejected',
+ });
+ }
+ } catch (_) {
+ _convLog.warn('discard empty conversation failed', {
+ error_code: 'discard_empty_failed',
});
}
- } catch (_) {
- _convLog.warn('discard empty conversation failed', {
- error_code: 'discard_empty_failed',
- });
+
+ await uiAlert(t('chat.attach_sync_failed'));
+ if (newBtn) newBtn.disabled = false;
+ _newChatSubmitting = false;
+ releaseAttachmentSend();
+ return;
}
- await uiAlert(t('chat.attach_sync_failed'));
- if (newBtn) newBtn.disabled = false;
- _newChatSubmitting = false;
+ if (createdConversation) {
+ _cacheCreatedConversation(createdConversation, createdConversation.title);
+ renderConversationList();
+ }
+ if (typeof consumeChatUseSelections === 'function') consumeChatUseSelections('new-chat');
+ // Adoption succeeded, so the draft chip pool can now be consumed.
+ _chatAttachClear(DRAFT_CID);
+ _chatAttachClear(convId);
releaseAttachmentSend();
- return;
- }
- if (createdConversation) {
- _cacheCreatedConversation(createdConversation, createdConversation.title);
- renderConversationList();
- }
- if (typeof consumeChatUseSelections === 'function') consumeChatUseSelections('new-chat');
- // Adoption succeeded, so the draft chip pool can now be consumed.
- _chatAttachClear(DRAFT_CID);
- _chatAttachClear(convId);
- releaseAttachmentSend();
- _consumeSubmittedQuotes(DRAFT_CID, quotes);
-
- const ownsDraft = submittedDraft.matches();
- const openCreated = ownsDraft && navigationEpoch === _composerNavigationEpoch;
- if (ownsDraft) {
- _clearQuickStartDraft(input);
- composerSetText(input, '');
- _draftHadRecipient.delete('new-chat');
- }
- _newChatSubmitting = false;
- _transferNewChatRecipientTo(convId);
- if (openCreated) {
- // Save the previous task before reusing its visible editor.
- if (currentCid) _flushDraftSave(currentCid);
- composerBindOwner('chat-input', convId);
- composerSetText('chat-input', '');
- setView('conversation', convId, { skipLoad: true });
- _renderRecipientChip('conversation');
- }
- if (newBtn) newBtn.disabled = false;
- const extra = {
- title_text: titleText,
- ...commanderDisplay,
- ...(attachments.length ? { attachments } : {}),
- ...(useSelections.length ? { use_selections: useSelections } : {}),
- ...(references.length ? { references } : {}),
- };
- // The initial turn uses the same abort-recovery contract as a follow-up:
- // stopping must restore the user's authored text and adopted attachments.
- if (typeof _rememberSentComposerSnapshot === 'function') {
- _rememberSentComposerSnapshot(convId, {
- text: requestText,
- recipient: recipientSnapshot,
- references: quotes,
- attachments: attachments.map((name) => ({ name })),
+ _consumeSubmittedQuotes(DRAFT_CID, quotes);
+
+ const ownsDraft = submittedDraft.matches();
+ const openCreated = ownsDraft && navigationEpoch === _composerNavigationEpoch;
+ if (ownsDraft) {
+ composerSetText(input, '');
+ _draftHadRecipient.delete('new-chat');
+ }
+ _newChatSubmitting = false;
+ _transferNewChatRecipientTo(convId);
+ if (openCreated) {
+ // Save the previous task before reusing its visible editor.
+ if (currentCid) _flushDraftSave(currentCid);
+ composerBindOwner('chat-input', convId);
+ composerSetText('chat-input', '');
+ setView('conversation', convId, { skipLoad: true });
+ _renderRecipientChip('conversation');
+ }
+ if (newBtn) newBtn.disabled = false;
+ const extra = {
+ title_text: titleText,
+ ...commanderDisplay,
+ ...(attachments.length ? { attachments } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ ...(references.length ? { references } : {}),
+ };
+ // Attachments were adopted into the new conversation, so the snapshot carries
+ // the adopted names — the draft-cid originals no longer exist.
+ if (typeof _rememberSentComposerSnapshot === 'function') {
+ _rememberSentComposerSnapshot(convId, {
+ text: requestText,
+ recipient: recipientSnapshot,
+ references: quotes,
+ attachments: attachments.map((name) => ({ name })),
+ });
+ }
+ // Finish composer preparation in finally before waiting for the model reply.
+ return sendInConversation(convId, content, Object.keys(extra).length ? extra : undefined, {
+ restoreComposerOnFailure: true,
+ source_view: 'new_chat',
+ content_length: requestText.length,
});
+ } finally {
+ releaseAttachmentSend();
+ _newChatSubmitting = false;
+ const btn = document.getElementById('new-chat-send-btn');
+ if (btn) btn.disabled = false;
}
- await sendInConversation(convId, content, Object.keys(extra).length ? extra : undefined, {
- restoreComposerOnFailure: true,
-
- });
}
async function handleChatSubmit() {
+ // A repeated submit shares the in-flight send, not an attachment upload.
+ if (_chatAttachIsSending(currentCid)) return;
if (typeof _isQueueItemEditing === 'function' && _isQueueItemEditing(currentCid)) {
await _finishQueueItemEdit(currentCid);
return;
@@ -11216,144 +11358,147 @@ async function handleChatSubmit() {
await uiAlert(t('chat.attach_still_uploading'));
return;
}
- // Freeze all composer-owned dispatch inputs before the first async boundary.
- const recipientSnapshot = _recipientSnapshotForSend('conversation');
- const commanderDisplay = _commanderMentionDisplayForSend(requestText, recipientSnapshot);
- const content = transformWithChatUse(_applyRecipientPrefixWithSnapshot(requestText, recipientSnapshot));
- const pendingFloorSync = _floorSyncByCid.get(cid);
- const clearSubmittedComposer = () => {
- const ownsVisibleDraft = currentCid === cid && submittedDraft.matches();
- if (ownsVisibleDraft) {
- _clearQuickStartDraft(input);
- composerSetText(input, '');
- _draftHadRecipient.delete('conversation');
- autoGrow(input, 200);
- }
- // Navigation saves the old draft under cid; never clear a newer draft
- // authored in this same composer while the send was waiting.
- if (ownsVisibleDraft) _clearDraft(cid);
- else if (typeof _discardSubmittedDraft === 'function') _discardSubmittedDraft(cid, submittedDraft);
- };
- const attachmentSnapshot = await _chatAttachSnapshotForSend(cid);
- if (!attachmentSnapshot.ok) {
- releaseAttachmentSend();
- await uiAlert(t('chat.attach_sync_failed'));
- return;
- }
- attachList = attachmentSnapshot.items;
- attachments = attachmentSnapshot.names;
- if (recipientSnapshot.resetFloor) _pendingFloorResetByCid.delete(cid);
- const references = _referenceSnapshotsForQuotes(quotes);
- _convLog.info('chat submit', { cid, length: raw.length, use: useSelections.map((sel) => sel.kind), attachments: attachments.length });
-
- // Queue absorption (task-board plan P2 UI half): a busy conversation no
- // longer parks new messages in the renderer-local queue — they go straight
- // to the backend, where the scheduler queues them as visible, cancellable
- // board tasks. The LOCAL queue survives only to drain legacy rows already
- // stored (order preserved: while any remain, new sends line up behind
- // them). A newly queued task can still be folded into the active turn with
- // its task-board row's explicit "Send now" action.
- if (pendingFloorSync) {
- await Promise.race([pendingFloorSync, new Promise((r) => setTimeout(r, 1500))]);
- }
- if (isConvPending(cid)) {
- // Lightweight direct send while busy (same transport the queue rows'
- // "Send now" used): plain /send, no local controller — the already-open
- // event stream renders the bubble and the board row. Composer sends
- // always queue; only an existing task-board row offers "Send now".
- try {
- const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/send`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- content,
- ...commanderDisplay,
- ...(attachments.length ? { attachments } : {}),
- ...(useSelections.length ? { use_selections: useSelections } : {}),
- ...(references.length ? { references } : {}),
- }),
- });
- const data = await res.json();
- if (!data || data.ok === false) {
- _convLog.warn('busy direct send failed', { failure_stage: 'response' });
- await uiAlert(t('chat.send_failed', { msg: String((data && data.error) || 'unknown') }));
- releaseAttachmentSend();
- return; // keep the composer content for retry
+ try {
+ // The shared composer can change tasks during either preflight await.
+ // Resolve its routing context while it still belongs to this submission.
+ const recipientSnapshot = _recipientSnapshotForSend('conversation');
+ const commanderDisplay = _commanderMentionDisplayForSend(requestText, recipientSnapshot);
+ const content = transformWithChatUse(_applyRecipientPrefixWithSnapshot(requestText, recipientSnapshot));
+
+ const clearSubmittedComposer = () => {
+ const ownsVisibleDraft = currentCid === cid && submittedDraft.matches();
+ if (ownsVisibleDraft) {
+ composerSetText(input, '');
+ _draftHadRecipient.delete('conversation');
+ autoGrow(input, 200);
}
- // A busy-path send can race the previous turn's settlement: the backend
- // may have gone idle and closed the event streams a beat before the
- // POST landed, leaving this send's events (bubble, board row, reply)
- // with no subscriber — nothing visible happens and the user resends
- // (on-device 2026-08-27). Repair at the boundary: paint the user
- // message from the response when it already entered history (admitted
- // immediately), re-arm the observer for a live turn, refresh the board
- // rows from disk, and let recovery+polling reconcile a stale busy
- // flag. Best-effort — a repair failure must never fail the accepted
- // send itself.
+ // Navigation saves the old draft under cid; never clear a newer draft
+ // authored in this same composer while the send was waiting.
+ if (ownsVisibleDraft) _clearDraft(cid);
+ else if (typeof _discardSubmittedDraft === 'function') _discardSubmittedDraft(cid, submittedDraft);
+ };
+ const attachmentSnapshot = await _chatAttachSnapshotForSend(cid);
+ if (!attachmentSnapshot.ok) {
+ releaseAttachmentSend();
+
+ await uiAlert(t('chat.attach_sync_failed'));
+ return;
+ }
+ attachList = attachmentSnapshot.items;
+ attachments = attachmentSnapshot.names;
+
+ const references = _referenceSnapshotsForQuotes(quotes);
+ _convLog.info('chat submit', { cid, length: raw.length, use: useSelections.map((sel) => sel.kind), attachments: attachments.length });
+
+ // Queue absorption (task-board plan P2 UI half): a busy conversation no
+ // longer parks new messages in the renderer-local queue — they go straight
+ // to the backend, where the scheduler queues them as visible, cancellable
+ // board tasks. The LOCAL queue survives only to drain legacy rows already
+ // stored (order preserved: while any remain, new sends line up behind
+ // them). A newly queued task can still be folded into the active turn with
+ // its task-board row's explicit "Send now" action.
+ _takeRecipientSnapshotForSend('conversation', recipientSnapshot, cid);
+ const pendingFloorSync = _floorSyncByCid.get(cid);
+ if (pendingFloorSync) {
+ await Promise.race([pendingFloorSync, new Promise((r) => setTimeout(r, 1500))]);
+ }
+ if (isConvPending(cid)) {
+ // Lightweight direct send while busy (same transport the queue rows'
+ // "Send now" used): plain /send, no local controller — the already-open
+ // event stream renders the bubble and the board row. Composer sends
+ // always queue; only an existing task-board row offers "Send now".
try {
- if (data.msg && data.msg.persisted !== false
- && cid === currentCid
- && typeof _renderOrClaimPersistedUserMessage === 'function') {
- _renderOrClaimPersistedUserMessage(cid, data.msg);
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/send`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ content,
+ ...commanderDisplay,
+ ...(attachments.length ? { attachments } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ ...(references.length ? { references } : {}),
+ }),
+ });
+ const data = await res.json();
+ if (!data || data.ok === false) {
+ _convLog.warn('busy direct send failed', { failure_stage: 'response' });
+ await uiAlert(t('chat.send_failed', { msg: String((data && data.error) || 'unknown') }));
+ releaseAttachmentSend();
+ return; // keep the composer content for retry
}
- if (typeof _observeConversationRunFromPlanAction === 'function') {
- _observeConversationRunFromPlanAction(cid, { attachExisting: true, allowWithController: true });
+ // A busy-path send can race the previous turn's settlement: the backend
+ // may have gone idle and closed the event streams a beat before the
+ // POST landed, leaving this send's events (bubble, board row, reply)
+ // with no subscriber — nothing visible happens and the user resends
+ // (on-device 2026-08-27). Repair at the boundary: paint the user
+ // message from the response when it already entered history (admitted
+ // immediately), re-arm the observer for a live turn, refresh the board
+ // rows from disk, and let recovery+polling reconcile a stale busy
+ // flag. Best-effort — a repair failure must never fail the accepted
+ // send itself.
+ try {
+ if (data.msg && data.msg.persisted !== false
+ && cid === currentCid
+ && typeof _renderOrClaimPersistedUserMessage === 'function') {
+ _renderOrClaimPersistedUserMessage(cid, data.msg);
+ }
+ if (typeof _observeConversationRunFromPlanAction === 'function') {
+ _observeConversationRunFromPlanAction(cid, { attachExisting: true, allowWithController: true });
+ }
+ if (window.TaskBoard && typeof window.TaskBoard.resync === 'function') window.TaskBoard.resync(cid);
+ if (typeof _startRuntimeActorRecovery === 'function') _startRuntimeActorRecovery(cid);
+ if (typeof startPolling === 'function') startPolling(cid);
+ } catch (_) {
+ _convLog.warn('post-send visibility repair failed', { failure_stage: 'visibility_repair' });
}
- if (window.TaskBoard && typeof window.TaskBoard.resync === 'function') window.TaskBoard.resync(cid);
- if (typeof _startRuntimeActorRecovery === 'function') _startRuntimeActorRecovery(cid);
- if (typeof startPolling === 'function') startPolling(cid);
- } catch (_) {
- _convLog.warn('post-send visibility repair failed', { failure_stage: 'visibility_repair' });
+ } catch (err) {
+ _convLog.warn('busy direct send failed', { failure_stage: 'request' });
+ await uiAlert(t('chat.send_failed', { msg: String((err && err.message) || err) }));
+ releaseAttachmentSend();
+ return;
}
- } catch (err) {
- _convLog.warn('busy direct send failed', { failure_stage: 'request' });
- await uiAlert(t('chat.send_failed', { msg: String((err && err.message) || err) }));
+ clearSubmittedComposer();
+ _consumeSubmittedQuotes(cid, quotes);
+ if (attachments.length) _chatAttachClear(cid);
releaseAttachmentSend();
return;
}
+
+ // Keep the authored composer state (raw text with inline use tokens, chips)
+ // so stopping this turn can hand the message back for a quick edit.
+ if (typeof _rememberSentComposerSnapshot === 'function') {
+ _rememberSentComposerSnapshot(cid, {
+ text: requestText,
+ recipient: recipientSnapshot,
+ references: quotes,
+ attachments: attachList.filter((attachment) => attachment.status !== 'error'),
+ });
+ }
clearSubmittedComposer();
+ // Persist remaining references after clearing the accepted text, so a quote
+ // added during preflight also survives reload.
_consumeSubmittedQuotes(cid, quotes);
+ // Clear chip area immediately — the server will return with the final
+ // attachment state tied to the user message record. If the send fails or
+ // is aborted, the files remain on disk but the user can re-attach via the
+ // "+" button (listAttachments shows what's still there).
if (attachments.length) _chatAttachClear(cid);
releaseAttachmentSend();
- return;
- }
-
- // D9 UI half: no hidden recipient-prefix synthesis on the direct send —
- // inline mentions the user typed ARE the dispatch; a mention-less message
- // routes by the floor the chip already set via IPC. Await any in-flight
- // chip floor write (bounded) so a click-then-send burst cannot race it.
- // Keep the authored composer state (raw text with inline use tokens, chips)
- // so stopping this turn can hand the message back for a quick edit.
- if (typeof _rememberSentComposerSnapshot === 'function') {
- _rememberSentComposerSnapshot(cid, {
- text: requestText,
- recipient: recipientSnapshot,
- references: quotes,
- attachments: attachList.filter((attachment) => attachment.status !== 'error'),
+ const extra = {
+ ...(attachments.length ? { attachments } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ ...(references.length ? { references } : {}),
+ ...commanderDisplay,
+ };
+ return sendInConversation(cid, content, Object.keys(extra).length ? extra : undefined, {
+ restoreComposerOnFailure: true,
+ source_view: 'conversation',
+ background: cid !== currentCid,
+ content_length: requestText.length,
});
+ } finally {
+ releaseAttachmentSend();
}
- clearSubmittedComposer();
- // Persist remaining references after clearing the accepted text, so a quote
- // added during preflight also survives reload.
- _consumeSubmittedQuotes(cid, quotes);
- // Clear chip area immediately — the server will return with the final
- // attachment state tied to the user message record. If the send fails or
- // is aborted, the files remain on disk but the user can re-attach via the
- // "+" button (listAttachments shows what's still there).
- if (attachments.length) _chatAttachClear(cid);
- releaseAttachmentSend();
- const extra = {
- ...(attachments.length ? { attachments } : {}),
- ...(useSelections.length ? { use_selections: useSelections } : {}),
- ...(references.length ? { references } : {}),
- ...commanderDisplay,
- };
- await sendInConversation(cid, content, Object.keys(extra).length ? extra : undefined, {
- restoreComposerOnFailure: true,
- ...(recipientSnapshot && recipientSnapshot.kind === 'agent' && recipientSnapshot.id
- ? { agent_id: recipientSnapshot.id }
- : {}),
- });
}
// One transient controller per conversation send. Multi-cid support comes
@@ -11970,6 +12115,7 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {
} finally {
settled = true;
clearTimeout(noActivityTimer);
+ if (_forgottenTaskSurfaceObservers.has(ctrl)) return;
// Whether this observer is still the conversation's current one. A newer
// send registers its own observer, and once that happens every global
// teardown below belongs to that newer run, not to this finishing one.
@@ -12564,7 +12710,7 @@ function _refreshProcessCompactGroup(group) {
const groupBody = _processCompactGroupBody(group);
const summary = _processCompactGroupSummary(group);
if (!key || !groupBody || !summary) return;
- const count = Array.from(groupBody.children || []).filter((node) => (
+ const count = group._processOperationCount ?? Array.from(groupBody.children || []).filter((node) => (
node?.dataset?.processOperation === '1'
)).length;
summary.innerHTML = `
@@ -12584,6 +12730,7 @@ function _createProcessCompactGroup(key) {
groupBody.className = 'stream-process-compact-body';
group._processCompactSummary = summary;
group._processCompactBody = groupBody;
+ group._processOperationCount = 0;
group.appendChild(summary);
group.appendChild(groupBody);
_refreshProcessCompactGroup(group);
@@ -12593,10 +12740,28 @@ function _createProcessCompactGroup(key) {
// Collapse maximal adjacent operation runs. Creating a fresh wrapper preserves
// exact child order when a live row joins an existing group. An open group stays
// open as more items arrive; otherwise every group starts closed.
-function _compactAdjacentProcessRows(body) {
+function _compactAdjacentProcessRows(body, appended = null) {
if (!body
|| typeof body.insertBefore !== 'function'
|| _hasProcessClass(body, 'stream-process-compact-body')) return;
+ // An append cannot change earlier adjacency. Narration-heavy turns must
+ // not rescan their whole rail each time another isolated operation lands.
+ if (appended && _processCompactNodeKey(appended)) {
+ const previous = appended.previousElementSibling || body.children?.[body.children.length - 2];
+ if (_hasProcessClass(previous, 'stream-process-compact-group')
+ && _processCompactNodeKey(previous) === _processCompactNodeKey(appended)) {
+ _processCompactGroupBody(previous).appendChild(appended);
+ previous._processOperationCount += appended.dataset?.processOperation === '1' ? 1 : 0;
+ _refreshProcessCompactGroup(previous);
+ } else {
+ const group = _createProcessCompactGroup(_processCompactNodeKey(appended));
+ body.insertBefore(group, appended);
+ _processCompactGroupBody(group).appendChild(appended);
+ group._processOperationCount = appended.dataset?.processOperation === '1' ? 1 : 0;
+ _refreshProcessCompactGroup(group);
+ }
+ return;
+ }
// Live-append fast path: the newest row continues the trailing group, so
// move just that row. The general rebuild below re-created the group and
// reparented every earlier row on each appended operation — O(rows²) DOM
@@ -12612,6 +12777,7 @@ function _compactAdjacentProcessRows(body) {
const groupBody = _processCompactGroupBody(trailingGroup);
if (groupBody && typeof groupBody.appendChild === 'function') {
groupBody.appendChild(newest);
+ trailingGroup._processOperationCount += newest.dataset?.processOperation === '1' ? 1 : 0;
_refreshProcessCompactGroup(trailingGroup);
return;
}
@@ -12646,10 +12812,14 @@ function _compactAdjacentProcessRows(body) {
for (const node of run) {
if (_hasProcessClass(node, 'stream-process-compact-group')) {
const nestedBody = _processCompactGroupBody(node);
- for (const child of Array.from(nestedBody?.children || [])) groupBody.appendChild(child);
+ for (const child of Array.from(nestedBody?.children || [])) {
+ groupBody.appendChild(child);
+ group._processOperationCount += child.dataset?.processOperation === '1' ? 1 : 0;
+ }
node.remove?.();
} else {
groupBody.appendChild(node);
+ group._processOperationCount += node.dataset?.processOperation === '1' ? 1 : 0;
}
}
group.open = keepOpen;
@@ -12661,13 +12831,22 @@ function _compactAdjacentProcessRows(body) {
function _processLifecycleRow(body, lifecycleKey) {
if (!body || !lifecycleKey) return null;
- for (const line of Array.from(body.children || [])) {
- if (line?.dataset?.processCallId === lifecycleKey) return line;
- if (!_hasProcessClass(line, 'stream-process-compact-group')) continue;
- const nested = _processLifecycleRow(_processCompactGroupBody(line), lifecycleKey);
- if (nested) return nested;
+ if (!body._processLifecycleRows || body.children?.length === 0) {
+ body._processLifecycleRows = new Map();
+ const visit = (container) => {
+ for (const line of Array.from(container?.children || [])) {
+ if (line?.dataset?.processCallId) body._processLifecycleRows.set(line.dataset.processCallId, line);
+ if (_hasProcessClass(line, 'stream-process-compact-group')) visit(_processCompactGroupBody(line));
+ }
+ };
+ visit(body);
}
- return null;
+ const line = body._processLifecycleRows.get(lifecycleKey);
+ if (line && body.contains?.(line) === false) {
+ body._processLifecycleRows.delete(lifecycleKey);
+ return null;
+ }
+ return line || null;
}
function _setProcessRowPresentation(
@@ -12762,7 +12941,6 @@ function _appendProcessTextLines(
false,
lifecycleTerminal,
);
- _compactAdjacentProcessRows(body);
return 1;
}
}
@@ -12785,8 +12963,12 @@ function _appendProcessTextLines(
const compactGroup = _processCompactGroupKey();
if (compactGroup) line.dataset.processCompactGroup = compactGroup;
body.appendChild(line);
+ if (lifecycleKey && index === 0) {
+ if (!body._processLifecycleRows) body._processLifecycleRows = new Map();
+ body._processLifecycleRows.set(lifecycleKey, line);
+ }
+ _compactAdjacentProcessRows(body, line);
}
- _compactAdjacentProcessRows(body);
return lines.length;
}
@@ -12816,7 +12998,7 @@ function _runtimeDurationMsFromEvent(evt) {
function _runtimeDurationFromEvent(evt) {
const durationMs = _runtimeDurationMsFromEvent(evt);
- return durationMs == null ? '' : _formatProcessDuration(durationMs);
+ return durationMs == null ? '' : (evt.data?.duration_estimated === true ? '≈ ' : '') + _formatProcessDuration(durationMs);
}
function _runtimeDurationFromProcessItem(item) {
@@ -12942,7 +13124,7 @@ function _updateStreamingRuntimeSummary(msg, evt, elapsedMs) {
} else {
delete container.dataset.runtimeTerminal;
}
- _setProcessSummaryRuntime(msg, _formatProcessDuration(durationMs));
+ _setProcessSummaryRuntime(msg, hasRuntimeEvent ? _runtimeDurationFromEvent(evt) : _formatProcessDuration(durationMs));
return container;
}
@@ -14922,6 +15104,10 @@ function _anchorPlaceholderToTurnStart(ph, startedAtMs) {
startMs,
Number.isFinite(activitySortAfter) ? activitySortAfter : 0,
));
+ // Recovery creates the DOM now, but this header describes the running turn,
+ // not when the user reopened the page. Keep it aligned with the row anchor.
+ const timeEl = ph.querySelector?.('.chat-msg-time');
+ if (timeEl) timeEl.textContent = formatTime(new Date(Number(ph.dataset.ts)).toISOString());
const container = ph.parentElement;
if (!container) return;
if (!_isTimestampPositionCorrect(container, ph)) _insertByTimestamp(container, ph);
@@ -16302,7 +16488,7 @@ function _formatEventLine(evt, displayContext) {
// Keep the process summary compact: expose only total wall time. Provider,
// aggregate tool, compaction, and retry breakdowns remain internal
// diagnostics; individual completed tool rows show their persisted E2E time.
- return t('chat.stream.runtime_total', { duration: _formatProcessDuration(runtimeDurationMs) });
+ return t('chat.stream.runtime_total', { duration: _runtimeDurationFromEvent(evt) });
}
if (stream === 'tool') {
@@ -16661,8 +16847,11 @@ function _appendProjectedProcessRowToBody(body, projection) {
else if (line.dataset) delete line.dataset.toolResultRef;
line._fullOutput = projection.fullOutput || '';
line.title = t('chat.tool_result_expand_hint');
- if (!existing) body.appendChild(line);
- _compactAdjacentProcessRows(body);
+ if (!existing) {
+ body.appendChild(line);
+ if (projection.lifecycleKey) body._processLifecycleRows.set(projection.lifecycleKey, line);
+ _compactAdjacentProcessRows(body, line);
+ }
// One delegated handler per process body. Persisted messages use the same
// handler as the live bubble once the outer process disclosure is opened.
@@ -16742,7 +16931,7 @@ function _materializeReasoningSummary(msg, evt) {
// text deltas update the single "live" line; everything else becomes a new
// process-pane line (via _formatEventLine).
function _renderAgentEvent(msg, evt) {
- window.OrkasCommercialEntry?.observeToolResult(msg, evt);
+
if (!evt || typeof evt !== 'object') return;
evt = _materializeReasoningSummary(msg, evt);
const { stream, data } = evt;
@@ -17034,22 +17223,70 @@ function _renderConvDisabledBanner(cid) {
if (cid === currentCid) _updateConvSendUI(cid);
}
-function _refreshTaskSurfacesAfterAbort(cid) {
- if (!cid) return;
+const _taskSurfaceAbortRefreshOwners = new Map();
+const _forgottenTaskSurfaceObservers = new WeakSet();
+
+function _forgetConversationRuntime(cid) {
+ const state = pendingConvs.get(cid);
+ if (state) state.aborted = true;
+ const sources = new Set([
+ _convChatCtrls.get(cid), _groupObserverReservations.get(cid),
+ _groupObserverCtrls.get(cid), state?.controller,
+ ].filter(Boolean));
+ // Remove the cached identities before abort callbacks can settle. Restoring
+ // this cid must create fresh controllers through the normal entry points.
+ _convChatCtrls.delete(cid);
+ _groupObserverReservations.delete(cid);
+ _groupObserverCtrls.delete(cid);
+ pendingConvs.delete(cid);
+ _stopRuntimeActorRecovery(cid);
+ stopPolling(cid);
+ for (const source of sources) {
+ if (typeof source === 'object' || typeof source === 'function') _forgottenTaskSurfaceObservers.add(source);
+ try { source.abort?.(); } catch (_) {}
+ }
+}
+
+function _beginTaskSurfaceAbortRefresh(cid) {
+ const previous = _taskSurfaceAbortRefreshOwners.get(cid);
+ if (previous && previous.timer != null) clearTimeout(previous.timer);
+ const owner = { timer: null, settled: false };
+ _taskSurfaceAbortRefreshOwners.set(cid, owner);
+ return owner;
+}
+
+function _refreshTaskSurfacesAfterAbort(cid, owner) {
+ if (!owner) {
+ // This entry is the bus-owned abort, independent of a local Stop request.
+ // Its active transport was already checked by the original reader loop.
+ // Confirmed forget removes and aborts all three cid source identities.
+ if (!cid || !(_convChatCtrls.has(cid) || _groupObserverReservations.has(cid) || _groupObserverCtrls.has(cid))) return;
+ owner = _taskSurfaceAbortRefreshOwners.get(cid);
+ if (!owner) {
+ owner = _beginTaskSurfaceAbortRefresh(cid);
+ owner.settled = true;
+ }
+ }
+ // A confirmed forget invalidates both queued timers and abort responses that
+ // are still in flight. A restored conversation gets a fresh owner identity.
+ if (!cid || _taskSurfaceAbortRefreshOwners.get(cid) !== owner) return;
try {
if (window.ConversationInfo) window.ConversationInfo.refreshFiles(cid, { silent: true });
} catch (_) {}
- // The Stop click tears the event streams down BEFORE the bus settles the
- // aborted turn's task, so the terminal `task_state` has no subscriber —
- // re-seed the board once now and once after the settlement window. Without
- // this the cancelled task stayed painted "running" until the next send
- // reopened a stream (observed on-device 2026-08-23).
+ // Stop detaches streams before task settlement. Keep the immediate refresh
+ // and one refresh after the latest settlement window, owned by this abort.
try {
if (window.TaskBoard && typeof window.TaskBoard.resync === 'function') {
window.TaskBoard.resync(cid);
- setTimeout(() => { try { window.TaskBoard.resync(cid); } catch (_) {} }, 1500);
}
} catch (_) {}
+ if (owner.timer != null) clearTimeout(owner.timer);
+ owner.timer = setTimeout(() => {
+ owner.timer = null;
+ if (_taskSurfaceAbortRefreshOwners.get(cid) !== owner) return;
+ try { window.TaskBoard?.resync?.(cid); } catch (_) {}
+ if (owner.settled) _taskSurfaceAbortRefreshOwners.delete(cid);
+ }, 1500);
}
// A restored/reconnected run is owned by the group-events observer rather than
@@ -17072,6 +17309,7 @@ function _settleConversationPlaceholdersOnAbort(cid, state) {
}
function abortConvStream(cid, options = {}) {
+ const taskSurfaceOwner = _beginTaskSurfaceAbortRefresh(cid);
const state = pendingConvs.get(cid);
if (options && options.userInitiated) {
// A user stop is normally followed by an edit and resend. Restore the
@@ -17081,6 +17319,11 @@ function abortConvStream(cid, options = {}) {
_stopRuntimeActorRecovery(cid);
_stopGroupEventObserver(cid);
setGroupConversationBusy(cid, false);
+ // The detached streams cannot deliver the cancelled turns' final state.
+ // Expire their question cards locally without answering or forgetting drafts;
+ // a later authoritative update can still describe a replacement turn.
+ _latestActiveTurns.set(cid, []);
+ window.CliAsyncInput?.setActiveTurns(cid, []);
// Group chat: also tell the bus to abort all in-flight worker turns + clear
// queues. Cancelling just the IPC stream would leave agents running in the
// background. Fire-and-forget — no need to block the UI on the response.
@@ -17088,12 +17331,16 @@ function abortConvStream(cid, options = {}) {
apiFetch(`/api/conversations/${cid}/abort`, { method: 'POST' })
.catch(() => {})
.finally(() => {
- _refreshTaskSurfacesAfterAbort(cid);
- });
- } catch (_) {}
+ taskSurfaceOwner.settled = true;
+ _refreshTaskSurfacesAfterAbort(cid, taskSurfaceOwner);
+ });
+ } catch (_) {
+ taskSurfaceOwner.settled = true;
+ _refreshTaskSurfacesAfterAbort(cid, taskSurfaceOwner);
+ }
if (!state) {
_updateConvSidebarBadge(cid, false);
- _refreshTaskSurfacesAfterAbort(cid);
+ _refreshTaskSurfacesAfterAbort(cid, taskSurfaceOwner);
if (cid === currentCid) _updateConvSendUI(cid);
return;
}
@@ -17112,7 +17359,7 @@ function abortConvStream(cid, options = {}) {
stopPolling(cid);
if (state.loadingEl && state.loadingEl.isConnected) state.loadingEl.remove();
_updateConvSidebarBadge(cid, false);
- _refreshTaskSurfacesAfterAbort(cid);
+ _refreshTaskSurfacesAfterAbort(cid, taskSurfaceOwner);
if (cid === currentCid) _updateConvSendUI(cid);
return;
}
@@ -18032,42 +18279,6 @@ function _selectedMessageElements() {
.filter((msg) => _messageSelectionState.selected.has(msg.dataset.msgId || ''));
}
-
-window.attachKbFileToDraft = async function attachKbFileToDraft(channel, payload, draftCid, afterNavigate) {
- const finishOperation = _chatAttachBeginOperation(draftCid);
- let stage = 'draft_lock';
- try {
- if (!finishOperation) throw new Error(t('chat.attach_send_in_progress'));
- stage = 'ipc_request';
- const data = await window.orkas.invoke(channel, { ...(payload || {}), cid: draftCid });
- if (!data || !data.ok) {
- const error = new Error((data && data.error) || 'failed');
- error.failure_stage = data && data.failure_stage;
- error.failure_kind = data && data.failure_kind;
- throw error;
- }
- stage = 'navigation';
- if (typeof afterNavigate === 'function') afterNavigate();
- stage = 'draft_render';
- _addReadyDraftAttachment(draftCid, data.info);
- } catch (error) {
- const safeStage = error && error.failure_stage;
- const safeKind = error && error.failure_kind;
- const failure_stage = ['input_validation', 'source_resolve', 'attachment_import'].includes(safeStage) ? safeStage : stage;
- const failure_kind = ['not_found', 'permission_denied', 'disk_full'].includes(safeKind) ? safeKind : 'operation_failed';
- // Keep the UI's original message; diagnostics receive only the enums.
- const wrapped = new Error((error && error.message) || String(error));
- wrapped.failure_stage = failure_stage;
- wrapped.failure_kind = failure_kind;
- _convLog.warn('library attachment failed', { failure_stage, failure_kind });
- throw wrapped;
- } finally {
- if (finishOperation) finishOperation();
- }
-};
-
-
-
try {
if (window.orkas && typeof window.orkas.onPushEvent === 'function') {
window.orkas.onPushEvent('conversation:media_materialized', _conversationMediaHandleMaterialized);
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 27bf4bda..46172b6b 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -152,6 +152,7 @@ function startPolling(cid) {
// polling request that an earlier tick already started; the cid may also
// be stopped and re-started while that request is in flight.
if (pollTimers.get(cid) !== timer || pollInFlight.has(cid)) return;
+ const pendingOwner = pendingConvs.get(cid);
const requestToken = {};
pollInFlight.set(cid, requestToken);
try {
@@ -164,7 +165,7 @@ function startPolling(cid) {
// flight. Never let that stale poll fall through to _onPolledResponse:
// it would reload the whole transcript after the final bubble was
// already painted, causing a visible "Loading…" flash on every reply.
- if (pollTimers.get(cid) !== timer) return;
+ if (pollTimers.get(cid) !== timer || pendingConvs.get(cid) !== pendingOwner) return;
if (!runtimeRes.ok || !runtimeData || runtimeData.ok === false) return;
const hasServerRuntime = Object.prototype.hasOwnProperty.call(runtimeData, 'processing');
const runtimeBusy = hasServerRuntime
@@ -182,7 +183,7 @@ function startPolling(cid) {
: `/api/conversations/${encodeURIComponent(cid)}/history?limit=10`;
const historyRes = await apiFetch(historyUrl);
const data = await historyRes.json();
- if (pollTimers.get(cid) !== timer) return;
+ if (pollTimers.get(cid) !== timer || pendingConvs.get(cid) !== pendingOwner) return;
if (!historyRes.ok || !data || data.ok === false || !data.history) return;
// Same visibility filter as loadConversationHistory (drops `dispatch`
// records AND redundant routing-only commander tails) so the polled
@@ -220,8 +221,12 @@ function startPolling(cid) {
return;
}
- // If server is no longer processing but last message is still user → request was lost
+ // A send can be admitted after the runtime read but before this history
+ // read. Its primary stream still owns the reply; an idle snapshot must
+ // not replace that live bubble with an interruption notice. Reconnected
+ // observers have no isBusy method and still use the lost-stream fallback.
if (_isPolledUserMsg(last) && !runtimeBusy) {
+ if (pendingOwner?.controller?.isBusy?.()) return;
stopPolling(cid);
await _onPolledResponse(cid, t('chat.reply_interrupted'), true);
return;
@@ -299,8 +304,8 @@ async function _onPolledResponse(cid, contentOrMessage, isError = false) {
// Polling can finish after the user has already started reading
// upward. Reconcile the richer persisted message without treating
// this background refresh like a fresh conversation entry. Await
- // the rebuild so the next queued turn cannot race its DOM reset.
- await loadConversationHistory(cid, { preserveScroll: true });
+ // reconciliation so loaded pages remain available to the reader.
+ await loadConversationHistory(cid, { preserveScroll: true, refreshDisplay: true });
_updateConvSendUI(cid);
}
return;
@@ -326,7 +331,7 @@ async function _onPolledResponse(cid, contentOrMessage, isError = false) {
// Preserve the user's reading position across the terminal polling
// reconcile. Users who stayed near the bottom still follow the final
// message; users who scrolled up are no longer pulled back down.
- await loadConversationHistory(cid, { preserveScroll: true });
+ await loadConversationHistory(cid, { preserveScroll: true, refreshDisplay: true });
_updateConvSendUI(cid);
}
}
diff --git a/test/e2e/chat_e2e_interrupted_process.spec.ts b/test/e2e/chat_e2e_interrupted_process.spec.ts
index 8309c45e..39cb59f1 100644
--- a/test/e2e/chat_e2e_interrupted_process.spec.ts
+++ b/test/e2e/chat_e2e_interrupted_process.spec.ts
@@ -3,8 +3,51 @@ import path from 'node:path';
import { expect, test } from './fixtures/orkas';
+for (const [language, width] of [['en', 1280], ['zh', 760]] as const) {
+ test(`shows a cancelled CLI notice and same-second elapsed time after reopening (${language})`, async ({ orkas }, testInfo) => {
+ test.setTimeout(120_000);
+ await orkas.invoke('config.setLanguage', { language });
+ const { conversation } = await orkas.invoke<{ conversation: { conversation_id: string } }>(
+ 'conversations.create', { title: 'Cancelled CLI reply' });
+ const cid = conversation.conversation_id;
+ const file = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`);
+ const notice = language === 'zh' ? '上一次回复被中断,请发送消息继续。'
+ : 'The previous reply was interrupted. Send a message to continue.';
+ writeFileSync(file, [
+ { id: 'source', from: 'user', to: ['codex-agent'], ts: '2026-10-26T06:31:11Z', text: 'Update the pricing.' },
+ { id: 'interrupted', from: 'codex-agent', to: ['user'], ts: '2026-10-26T06:31:24Z', text: notice,
+ system_kind: 'reply_interrupted', turn_id: 'cancelled-turn', source_message_id: 'source', seg: 0,
+ process: [{ type: 'event', event: { stream: 'cli', data: { type: 'status', status: 'running' } } }] },
+ ].map(row => JSON.stringify(row)).join('\n') + '\n');
+ const archive = path.join(orkas.workspaceRoot, 'account-e2e', 'local', 'file_cache', 'local-agent-runs', '123456abcdef');
+ mkdirSync(archive, { recursive: true });
+ writeFileSync(path.join(archive, 'meta.json'), JSON.stringify({ cid, agentId: 'codex-agent', cli: 'codex',
+ currentMessageId: 'source', startedAt: '2026-10-26T06:31:11.226Z', endedAt: '2026-10-26T06:31:24.602Z',
+ durationMs: 13374, status: 'cancelled' }));
+ writeFileSync(path.join(archive, 'events.jsonl'), JSON.stringify({ type: 'done', status: 'cancelled', durationMs: 13311 }) + '\n');
+ const original = readFileSync(file, 'utf8');
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const page = await orkas.relaunch();
+ await page.setViewportSize({ width, height: 800 });
+ await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ const reply = page.locator('#chat-history .chat-message.assistant[data-system-kind="reply_interrupted"]');
+ await expect(reply).toHaveCount(1);
+ // The notice must be visible outside the collapsed process disclosure.
+ await expect(reply.locator('.chat-bubble > .markdown-body')).toBeVisible();
+ await expect(reply.locator('.chat-bubble > .markdown-body')).toHaveText(notice);
+ await expect(reply.locator('.stream-process-runtime')).toBeVisible();
+ await expect(reply.locator('.stream-process-runtime')).toHaveText(language === 'zh' ? '13秒' : '13s');
+ await expect(reply.locator('.stream-process')).not.toHaveAttribute('open');
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ if (!attempt) await page.screenshot({ path: testInfo.outputPath(`cancelled-reply-${language}.png`) });
+ }
+ expect(readFileSync(file, 'utf8')).toBe(original);
+ });
+}
+
for (const [language, width, timing] of [['en', 1280, 'timestamps'], ['zh', 760, 'last-write'],
- ['en', 1280, 'done'], ['zh', 760, 'fallback-actor']] as const) {
+ ['en', 1280, 'done'], ['zh', 760, 'fallback-actor'], ['en', 1280, 'partial-process'],
+ ['en', 1280, 'multiple-attempts']] as const) {
test(`opens archived process details after an application interruption (${language}, ${timing})`, async ({ orkas }, testInfo) => {
test.setTimeout(120_000);
await orkas.invoke('config.setLanguage', { language });
@@ -24,14 +67,23 @@ for (const [language, width, timing] of [['en', 1280, 'timestamps'], ['zh', 760,
...(timing === 'fallback-actor' ? [{ id: 'second-question', from: actorId, to: ['user'],
ts: '2026-10-17T03:00:00Z', turn_id: 'active-turn', cli_question: { questions: [] }, text: 'Continue reviewing?' }] : []),
{ id: 'interruption-1', from: 'commander', to: ['user'], ts: '2026-10-17T12:14:00Z', text: notice,
- system_kind: 'reply_interrupted' },
+ system_kind: 'reply_interrupted', ...(timing === 'partial-process' ? {
+ source_message_id: 'user-1', process: [
+ { type: 'progress', text: 'Checking the saved submission records.' },
+ ...[
+ { type: 'tool-event', phase: 'use', tool: 'bash', callId: 'saved-check', input: { command: 'python submission_queue.py report' } },
+ { type: 'tool-event', phase: 'result', tool: 'bash', callId: 'saved-check', output: 'Confirmed 15 of 50 submissions.' },
+ ].map(data => ({ type: 'event', event: { stream: 'cli', data } })),
+ ],
+ } : {}) },
].map(row => JSON.stringify(row)).join('\n') + '\n');
const archive = path.join(orkas.workspaceRoot, 'account-e2e', 'local', 'file_cache', 'local-agent-runs', '123456abcdef');
mkdirSync(archive, { recursive: true });
writeFileSync(path.join(archive, 'meta.json'), JSON.stringify({ runId: '123456abcdef', cid,
agentId: actorId, cli: 'codex', currentMessageId: 'user-1',
startedAt: '2026-10-17T01:00:03.973Z',
- ...(timing === 'timestamps' || timing === 'fallback-actor' ? { endedAt: '2026-10-17T12:13:55.849Z' } : {}) }));
+ ...(['timestamps', 'fallback-actor', 'partial-process', 'multiple-attempts'].includes(timing)
+ ? { endedAt: '2026-10-17T12:13:55.849Z' } : {}) }));
writeFileSync(path.join(archive, 'events.jsonl'), [
{ type: 'text-delta', phase: 'commentary', text: 'Checking the saved submission records.' },
{ type: 'tool-event', phase: 'use', tool: 'bash', callId: 'saved-check', input: { command: 'python submission_queue.py report' } },
@@ -43,6 +95,13 @@ for (const [language, width, timing] of [['en', 1280, 'timestamps'], ['zh', 760,
// reopening must never count that downtime as execution.
const lastWrite = new Date('2026-10-17T11:13:55.849Z');
utimesSync(path.join(archive, 'events.jsonl'), lastWrite, lastWrite);
+ if (timing === 'multiple-attempts') {
+ const second = path.join(path.dirname(archive), 'abcdef123456');
+ mkdirSync(second, { recursive: true });
+ writeFileSync(path.join(second, 'meta.json'), JSON.stringify({ cid, agentId: actorId, cli: 'codex',
+ currentMessageId: 'user-1', startedAt: '2026-10-17T12:13:56Z', endedAt: '2026-10-17T12:13:59Z', durationMs: 3000 }));
+ writeFileSync(path.join(second, 'events.jsonl'), JSON.stringify({ type: 'text-delta', phase: 'commentary', text: 'Verifying the final saved status.' }) + '\n');
+ }
const original = readFileSync(file, 'utf8');
// Relaunch uses the real history worker, IPC and renderer with an old
@@ -58,14 +117,19 @@ for (const [language, width, timing] of [['en', 1280, 'timestamps'], ['zh', 760,
await expect(rail).toBeVisible();
await expect(rail.locator('.stream-process-runtime')).toHaveText(timing === 'last-write'
? '≈ 10小时13分52秒' : timing === 'fallback-actor' ? '11小时13分52秒'
- : timing === 'done' ? '11h 13m 50s' : '11h 13m 52s');
+ : timing === 'done' ? '11h 13m 50s' : timing === 'multiple-attempts' ? '11h 13m 55s' : '11h 13m 52s');
await rail.locator('.stream-process-summary').focus();
await page.keyboard.press('Enter');
await expect(rail).toHaveAttribute('open', '');
await expect(rail).toContainText('Checking the saved submission records.');
+ if (timing === 'multiple-attempts') {
+ await rail.locator('.chat-process-load-more').click();
+ await expect(rail).toContainText('Verifying the final saved status.');
+ }
// Tool operations use the shipped nested disclosure inside the rail.
await rail.locator('.stream-process-compact-summary').click();
const tool = rail.locator('[data-process-call-id="cli:saved-check"]');
+ await expect(tool).toHaveCount(1);
await expect(tool).toBeVisible();
await expect(tool).toContainText('submission_queue.py report');
await tool.press('Enter');
diff --git a/test/e2e/chat_e2e_model_stream.spec.ts b/test/e2e/chat_e2e_model_stream.spec.ts
index a408335d..02c3c542 100644
--- a/test/e2e/chat_e2e_model_stream.spec.ts
+++ b/test/e2e/chat_e2e_model_stream.spec.ts
@@ -88,7 +88,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(page.locator('#chat-history .chat-message.user')).toContainText(
'Reply through the isolated E2E model.',
);
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toContainText(
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
'Hello from the local E2E model.',
{ timeout: 20_000 },
);
@@ -297,7 +297,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(lifecycleRow).toHaveText('Preparing: Edit file', { timeout: 20_000 });
expect(existsSync(outputPath)).toBe(false);
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toContainText(
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
'E2E delayed tool lifecycle completed.',
{ timeout: 20_000 },
);
@@ -355,25 +355,25 @@ test.describe('real chat pipeline with a local model', () => {
]);
await sendNewChat(modelOrkas, 'E2E_AGENT_CANONICAL_PRIOR_USER_FACT=amber-orbit');
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
hasText: 'E2E_AGENT_COMMANDER_PRIOR_REPLY',
})).toBeVisible({ timeout: 20_000 });
await page.locator('#chat-input').fill(`@${agentName} E2E_AGENT_FIRST_TASK`);
await page.locator('#chat-input').press('Enter');
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
hasText: 'E2E_AGENT_FIRST_REPLY',
})).toBeVisible({ timeout: 20_000 });
await page.locator('#chat-input').fill('@commander E2E_AGENT_INTERPOSED_USER_FACT=birch-field');
await page.locator('#chat-input').press('Enter');
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
hasText: 'E2E_AGENT_COMMANDER_INTERPOSED_REPLY',
})).toBeVisible({ timeout: 20_000 });
await page.locator('#chat-input').fill(`@${agentName} E2E_AGENT_SECOND_TASK`);
await page.locator('#chat-input').press('Enter');
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {
hasText: 'E2E_AGENT_SECOND_REPLY',
})).toBeVisible({ timeout: 20_000 });
@@ -396,7 +396,7 @@ test.describe('real chat pipeline with a local model', () => {
const refusal =
'I cannot help with that request because it conflicts with the provider safety policy.';
- const final = page.locator('#chat-history .chat-message.assistant [data-role="final"]');
+ const final = page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])');
await expect(final).toHaveText(refusal, { timeout: 20_000 });
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
expect(modelOrkas.modelRequests).toHaveLength(1);
@@ -467,7 +467,7 @@ test.describe('real chat pipeline with a local model', () => {
// Enter that real pointer journey before clicking the action itself.
await interrupted.hover();
await persistedRetry.click();
- await expect(relaunchedPage.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(relaunchedPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'Hello from the local E2E model.',
})).toBeVisible({ timeout: 20_000 });
expect(modelOrkas.modelRequests).toHaveLength(2);
@@ -506,7 +506,7 @@ test.describe('real chat pipeline with a local model', () => {
modelOrkas.clearModelToolScenario();
await restored.locator('.bubble-retry-btn').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'Hello from the local E2E model.',
})).toBeVisible({ timeout: 20_000 });
await expect(conversation.locator('.conv-item-status-label.is-failed')).toHaveCount(0);
@@ -531,7 +531,7 @@ test.describe('real chat pipeline with a local model', () => {
modelOrkas.setModelMode('success');
await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
await retry.click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'Hello from the local E2E model.',
})).toBeVisible({ timeout: 20_000 });
expect(modelOrkas.modelRequests).toHaveLength(requestsBeforeUserRetry + 1);
@@ -584,7 +584,7 @@ test.describe('real chat pipeline with a local model', () => {
await failedProcess.locator('.stream-process-summary').click();
}
await expect(failedProcess).toContainText('Hello from');
- await expect(failedBubble.locator('[data-role="final"]')).not.toContainText('Hello from');
+ await expect(failedBubble.locator('[data-role="final"]').filter({ hasText: 'Hello from' })).toHaveCount(0);
await expect(failedBubble).not.toContainText('Hello from the local E2E model.');
const requestsAfterFailure = modelOrkas.modelRequests.length;
expect(requestsAfterFailure).toBeGreaterThan(0);
@@ -605,7 +605,7 @@ test.describe('real chat pipeline with a local model', () => {
modelOrkas.setModelMode('success');
await persistedRetry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
await persistedRetry.click();
- await expect(relaunchedPage.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(relaunchedPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'Hello from the local E2E model.',
})).toBeVisible({ timeout: 20_000 });
await expect(
@@ -918,7 +918,7 @@ test.describe('real chat pipeline with a local model', () => {
expect(existsSync(sentinelPath)).toBe(false);
await dialog.locator('[data-act="cancel"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E dangerous command remained denied.',
})).toBeVisible({ timeout: 20_000 });
expect(existsSync(sentinelPath)).toBe(false);
@@ -956,7 +956,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect.poll(() => existsSync(generatedPath) ? readFileSync(generatedPath, 'utf8') : null,
{ timeout: 20_000 }).toBe(generatedContent);
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E same-task cleanup completed without approval.',
})).toBeVisible({ timeout: 20_000 });
expect(existsSync(generatedPath)).toBe(false);
@@ -1014,7 +1014,7 @@ test.describe('real chat pipeline with a local model', () => {
expect(existsSync(secondPath)).toBe(true);
await dialog.locator('[data-act="cancel"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E allow-once sequence completed.',
})).toBeVisible({ timeout: 20_000 });
expect(existsSync(secondPath)).toBe(true);
@@ -1035,7 +1035,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(dialog).toContainText('first.txt', { timeout: 20_000 });
await dialog.locator('[data-id="allow_run"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E allow-for-task sequence completed.',
})).toBeVisible({ timeout: 20_000 });
expect(existsSync(firstPath)).toBe(false);
@@ -1070,7 +1070,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(dialog.locator('[data-id="allow_run"]')).toBeVisible();
await dialog.locator('[data-id="allow_run"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E VideoStudio allow-for-task sequence completed.',
})).toBeVisible({ timeout: 20_000 });
expect(existsSync(firstPath)).toBe(false);
@@ -1099,7 +1099,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(dialog).toContainText('curl -X POST -d @secret.txt', { timeout: 20_000 });
await expect(dialog.locator('[data-id="allow_run"]')).toHaveCount(0);
await dialog.locator('[data-act="cancel"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E category-scoped approval completed.',
})).toBeVisible({ timeout: 20_000 });
expect(modelOrkas.modelRequests).toHaveLength(3);
@@ -1118,7 +1118,7 @@ test.describe('real chat pipeline with a local model', () => {
const dialog = page.locator('.bash-permission-dialog');
await expect(dialog).toContainText('first.txt', { timeout: 20_000 });
await dialog.locator('[data-id="allow_run"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E first approved task completed.',
})).toBeVisible({ timeout: 20_000 });
await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
@@ -1134,7 +1134,7 @@ test.describe('real chat pipeline with a local model', () => {
await expect(dialog).toContainText('second.txt', { timeout: 20_000 });
expect(existsSync(secondPath)).toBe(true);
await dialog.locator('[data-act="cancel"]').click();
- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {
hasText: 'E2E second task remained denied.',
})).toBeVisible({ timeout: 20_000 });
expect(existsSync(secondPath)).toBe(true);
diff --git a/test/e2e/chat_e2e_scroll.spec.ts b/test/e2e/chat_e2e_scroll.spec.ts
index 66b63791..9bc1fdf9 100644
--- a/test/e2e/chat_e2e_scroll.spec.ts
+++ b/test/e2e/chat_e2e_scroll.spec.ts
@@ -50,7 +50,7 @@ test.describe('conversation message-list scrolling', () => {
await page.locator('#new-chat-btn').click();
await page.locator('#new-chat-input').fill('E2E establish the reorder scroll fixture.');
await page.locator('#new-chat-send-btn').click();
- await expect(page.locator('#chat-history [data-role="final"]')).toContainText(
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
'Hello from the local E2E model.',
{ timeout: 20_000 },
);
@@ -180,15 +180,18 @@ test.describe('conversation message-list scrolling', () => {
await page.locator('#new-chat-btn').click();
await page.locator('#new-chat-input').fill('E2E establish a fresh task without history hydration.');
await page.locator('#new-chat-send-btn').click();
- await expect(page.locator('#chat-history [data-role="final"]')).toContainText(
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
'Hello from the local E2E model.',
{ timeout: 20_000 },
);
- modelOrkas.setModelMode('slow');
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ modelOrkas.setModelMode('controlled-slow');
await page.locator('#chat-input').fill('E2E keep the second response streaming while I scroll the message list.');
await page.locator('#chat-input').press('Enter');
await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ await expect.poll(() => modelOrkas.modelRequests.length).toBe(2);
+ modelOrkas.releaseControlledModelChunk();
await expect.poll(async () => historyScrollState(page)).toMatchObject({
pinActive: true,
spacerCount: 1,
@@ -198,15 +201,16 @@ test.describe('conversation message-list scrolling', () => {
await history.hover({ position: { x: 40, y: 80 } });
await page.mouse.wheel(0, 420);
- // Check before the deterministic slow stream reaches its 2.4s terminal
- // marker; terminal cleanup also removes the spacer and would mask a wheel
- // gesture that the message list never handled.
- await page.waitForTimeout(150);
- expect(await historyScrollState(page)).toEqual({
+ // Keep the terminal marker withheld so completion cannot remove the
+ // spacer and masquerade as a successful user-scroll release.
+ await expect.poll(() => historyScrollState(page)).toEqual({
pinActive: false,
stickyBound: true,
spacerCount: 0,
});
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ modelOrkas.finishControlledModelStream();
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
});
test('keeps a project-created task message list scrollable during streaming', async ({ modelOrkas }) => {
@@ -217,15 +221,18 @@ test.describe('conversation message-list scrolling', () => {
await page.locator('#project-chat-input').fill('E2E establish the project-created task.');
await page.locator('#project-chat-send-btn').click();
await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
- await expect(page.locator('#chat-history [data-role="final"]')).toContainText(
+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(
'Hello from the local E2E model.',
{ timeout: 20_000 },
);
- modelOrkas.setModelMode('slow');
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ modelOrkas.setModelMode('controlled-slow');
await page.locator('#chat-input').fill('E2E stream the project follow-up while I scroll downward.');
await page.locator('#chat-input').press('Enter');
await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ await expect.poll(() => modelOrkas.modelRequests.length).toBe(2);
+ modelOrkas.releaseControlledModelChunk();
await expect.poll(async () => historyScrollState(page)).toMatchObject({
pinActive: true,
stickyBound: true,
@@ -235,12 +242,13 @@ test.describe('conversation message-list scrolling', () => {
const history = page.locator('#chat-history');
await history.hover({ position: { x: 40, y: 80 } });
await page.mouse.wheel(0, 420);
- await page.waitForTimeout(150);
-
- expect(await historyScrollState(page)).toEqual({
+ await expect.poll(() => historyScrollState(page)).toEqual({
pinActive: false,
stickyBound: true,
spacerCount: 0,
});
+ await expect(page.locator('#chat-send-btn')).toHaveClass(/\bstreaming\b/);
+ modelOrkas.finishControlledModelStream();
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
});
});
diff --git a/test/e2e/history_e2e_loading.spec.ts b/test/e2e/history_e2e_loading.spec.ts
index 1c2ca25b..69025a02 100644
--- a/test/e2e/history_e2e_loading.spec.ts
+++ b/test/e2e/history_e2e_loading.spec.ts
@@ -1,3 +1,4 @@
+import { finished } from 'node:stream/promises';
import { expectComposerText } from './fixtures/composer';
import path from 'node:path';
import { cpSync, mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
@@ -730,7 +731,7 @@ test('loads and projects history from ASAR with the shipped dependency layout',
cpSync(path.join(pcRoot, 'node_modules', name), path.join(source, 'node_modules', name), { recursive: true, dereference: true });
}
const unpack = pkg.build.asarUnpack.map((p: string) => path.join(source, p).replaceAll('\\', '/'));
- await createPackageWithOptions(source, archive, { unpack: `{${unpack.join(',')}}` });
+ await finished(await createPackageWithOptions(source, archive, { unpack: `{${unpack.join(',')}}` }));
const esbuild = path.join(`${archive}.unpacked`, 'node_modules', '@esbuild', `${process.platform}-${process.arch}`,
...(process.platform === 'win32' ? ['esbuild.exe'] : ['bin', 'esbuild']));
await app.launch();
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index 5f12509f..e94e5c99 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
import * as os from 'node:os';
import * as path from 'node:path';
import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';
@@ -1556,6 +1557,55 @@ describe('chats › index repair', () => {
});
describe('chats › deleteConversation', () => {
+ it.each(['delete', 'edit', 'create', 'restore', 'module-delete'] as const)('does not publish an old repair snapshot across a concurrent %s', async action => {
+ const chats = await loadChats();
+ const task = await chats.createConversation(TEST_UID, { title: 'Before repair' });
+ const dir = path.join(tmpDir, TEST_UID, 'cloud', 'chats');
+ fs.mkdirSync(path.join(dir, 'unindexed'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'unindexed', 'meta.json'), JSON.stringify({
+ ...task, conversation_id: 'unindexed', title: 'Recovered metadata', _sync_rev: undefined,
+ }));
+ if (action === 'restore') await chats.deleteConversation(TEST_UID, task.conversation_id);
+ let release!: () => void;
+ let entered!: () => void;
+ const waiting = new Promise<void>(resolve => { entered = resolve; });
+ const original = fs.promises.readdir;
+ let held = false;
+ const spy = vi.spyOn(fs.promises, 'readdir').mockImplementation(async (...args: any[]) => {
+ if (!held && String(args[0]) === dir) {
+ held = true; entered();
+ await new Promise<void>(resolve => { release = resolve; });
+ }
+ return (original as any)(...args);
+ });
+ syncBuiltinESMExports();
+ const repair = chats.repairConversationIndex(TEST_UID);
+ await waiting;
+ let created: any;
+ if (action === 'module-delete') {
+ vi.resetModules();
+ await (await loadChats()).deleteConversation(TEST_UID, task.conversation_id);
+ }
+ if (action === 'delete') await chats.deleteConversation(TEST_UID, task.conversation_id);
+ if (action === 'edit') await chats.setConversationPinned(TEST_UID, task.conversation_id, true);
+ if (action === 'restore') await chats.createConversation(TEST_UID, { conversationId: task.conversation_id, title: 'Restored task' });
+ if (action === 'create') created = await chats.createConversation(TEST_UID, { title: 'New task' });
+ release(); await repair; spy.mockRestore(); syncBuiltinESMExports();
+ const rows = JSON.parse(fs.readFileSync(path.join(dir, '_index.json'), 'utf8'));
+ const current = rows.find((r: any) => r.conversation_id === task.conversation_id);
+ if (action === 'delete' || action === 'module-delete') {
+ expect(current.deleted_at).toBeTruthy();
+ expect(fs.existsSync(path.join(dir, task.conversation_id, 'meta.json'))).toBe(false);
+ }
+ if (action === 'restore') {
+ expect(current.deleted_at).toBeUndefined();
+ expect(current.title).toBe('Restored task');
+ expect(fs.existsSync(path.join(dir, task.conversation_id, 'meta.json'))).toBe(true);
+ }
+ if (action === 'edit') expect(current.pinned_at).toBeTruthy();
+ if (action === 'create') expect(rows.some((r: any) => r.conversation_id === created.conversation_id)).toBe(true);
+ });
+
it('keeps history and the live index when the maintenance guard rejects current metadata', async () => {
const chats = await loadChats();
const conv = await chats.createConversation(TEST_UID, { title: 'Protected during preview' });
@@ -1885,6 +1935,238 @@ describe('chats › autoTitle on first send', () => {
describe('chats › sweepStaleProcessing', () => {
const staleActiveAt = () => new Date(Date.now() - 60_000).toISOString();
+ it.each(['both', 'one-finished', 'prior-notice', 'old-turn', 'segment', 'paged', 'write-failure', 'concurrent-sweeps', 'missing-timestamp'])(
+ 'recovers each unfinished parallel actor independently and idempotently: %s', async scenario => {
+ const chats = await loadChats();
+ const paths = await import('../../../src/main/paths');
+ const storage = await import('../../../src/main/storage');
+ const conversation = await chats.createConversation(TEST_UID);
+ const cid = conversation.conversation_id;
+ const actors = ['agent-a', 'agent-b'];
+ const file = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ const stateFile = paths.groupChatStateFile(TEST_UID, cid);
+ const snapshot = { version: 1, status: 'running', ...(scenario === 'missing-timestamp' ? {} : { last_active_at: staleActiveAt() }), in_flight: actors,
+ in_flight_turns: Object.fromEntries(actors.map(id => [id, { turn_id: `turn-${id}`, source_message_id: 'user-1' }])) };
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify(snapshot));
+ fs.writeFileSync(paths.groupChatMembersFile(TEST_UID, cid), JSON.stringify({ version: 1,
+ actors: actors.map(id => ({ id, kind: 'agent', joined_at: staleActiveAt() })) }));
+ const user = { id: 'user-1', from: 'user', to: actors, ts: staleActiveAt(), text: 'Review in parallel.' };
+ const terminal = { id: 'terminal-a', from: 'agent-a', to: ['user'], ts: staleActiveAt(), text: 'Finished',
+ source_message_id: 'user-1', turn_id: scenario === 'old-turn' ? 'older-turn' : 'turn-agent-a',
+ ...(scenario === 'prior-notice' ? { system_kind: 'reply_interrupted' } : {}),
+ process: [{ type: 'event', event: { stream: 'runtime', data: {
+ phase: scenario === 'segment' ? 'segment_end' : 'end', duration_ms: 1000,
+ } } }] };
+ const rows = [user, ...(['both', 'write-failure', 'concurrent-sweeps', 'missing-timestamp'].includes(scenario) ? [] : [terminal]),
+ ...(scenario === 'paged' ? Array.from({ length: 24 }, (_, i) => ({ id: `side-${i}`, from: 'commander', to: ['user'],
+ ts: staleActiveAt(), text: 'Public progress', turn_id: 'other-turn' })) : [])];
+ fs.writeFileSync(file, rows.map(row => JSON.stringify(row)).join('\n') + '\n');
+ const journal = paths.userRunningConversationsFile(TEST_UID);
+ fs.mkdirSync(path.dirname(journal), { recursive: true });
+ fs.writeFileSync(journal, JSON.stringify({ version: 1, items: [{ conversation_id: cid }] }));
+ const readRows = () => fs.readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ if (scenario === 'write-failure') {
+ const original = storage.appendJsonlAtomic;
+ const append = vi.spyOn(storage, 'appendJsonlAtomic').mockImplementation(async (...args) => {
+ if (args[0] === file && (args[1] as any).from === 'agent-b') throw Object.assign(new Error('Injected archive failure'), { code: 'EIO' });
+ return original(...args);
+ });
+ try {
+ await chats.sweepStaleProcessing(TEST_UID);
+ const facade = await import('../../../src/main/features/group_chat');
+ expect((await facade.runtimeStatus(TEST_UID, cid)).processing, 'a recovery write failure is not a live model run').toBe(false);
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf8')).status).toBe('running');
+ expect(JSON.parse(fs.readFileSync(journal, 'utf8')).items).toHaveLength(1);
+ expect(readRows().filter(row => row.system_kind === 'reply_interrupted').map(row => row.from)).toEqual(['agent-a']);
+ expect(loggerMocks.warn).toHaveBeenCalledWith('stale sweep recovery remains pending', expect.any(Object));
+ } finally { append.mockRestore(); }
+ }
+ if (scenario === 'missing-timestamp') {
+ const later = Date.now() + 5000;
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(later);
+ try { await chats.sweepStaleProcessing(TEST_UID); }
+ finally { vi.useRealTimers(); }
+ } else if (scenario === 'concurrent-sweeps') await Promise.all([chats.sweepStaleProcessing(TEST_UID), chats.sweepStaleProcessing()]);
+ else await chats.sweepStaleProcessing(TEST_UID);
+ const recovered = readRows();
+ const expected = ['one-finished', 'paged'].includes(scenario) ? ['agent-b'] : ['agent-a', 'agent-b'];
+ expect(recovered.filter(row => row.system_kind === 'reply_interrupted').map(row => row.from)).toEqual(expected);
+ expect(recovered.slice(0, rows.length)).toEqual(rows);
+ expect(recovered.filter(row => row.system_kind === 'reply_interrupted' && row.id !== terminal.id))
+ .toEqual(expect.arrayContaining(expected.filter(id => scenario !== 'prior-notice' || id !== 'agent-a').map(id =>
+ expect.objectContaining({ from: id, turn_id: `turn-${id}`, source_message_id: 'user-1' }))));
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf8')).status).toBe('idle');
+ // Recreated stale journal/state simulates a second crash or sync replay
+ // after notices became durable, before state cleanup reached disk.
+ fs.writeFileSync(stateFile, JSON.stringify(snapshot));
+ fs.writeFileSync(journal, JSON.stringify({ version: 1, items: [{ conversation_id: cid }] }));
+ await chats.sweepStaleProcessing(TEST_UID);
+ expect(readRows()).toEqual(recovered);
+ });
+
+ it.each(['in-flight', 'failed'])('keeps %s startup receipts protected when another sweep queues before status polling', async firstState => {
+ const chats = await loadChats();
+ const paths = await import('../../../src/main/paths');
+ const storage = await import('../../../src/main/storage');
+ const state = await import('../../../src/main/features/group_chat/state');
+ const facade = await import('../../../src/main/features/group_chat');
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID);
+ const stateFile = paths.groupChatStateFile(TEST_UID, cid);
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 1, status: 'running', last_active_at: staleActiveAt(),
+ in_flight: ['agent-a'], in_flight_turns: { 'agent-a': { turn_id: 'old-turn', source_message_id: 'old-source' } } }));
+ const file = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ fs.writeFileSync(file, JSON.stringify({ id: 'old-source', from: 'user', to: ['agent-a'],
+ ts: staleActiveAt(), text: 'Recover this turn' }) + '\n');
+ const journal = paths.userRunningConversationsFile(TEST_UID);
+ fs.mkdirSync(path.dirname(journal), { recursive: true });
+ fs.writeFileSync(journal, JSON.stringify({ version: 1, items: [{ conversation_id: cid }] }));
+ let release!: () => void, entered!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const ready = new Promise<void>(resolve => { entered = resolve; });
+ const original = storage.appendJsonlAtomic;
+ const append = vi.spyOn(storage, 'appendJsonlAtomic').mockImplementation(async (...args) => {
+ if (args[0] === file) {
+ if (firstState === 'in-flight') { entered(); await gate; }
+ throw Object.assign(new Error('Injected archive failure'), { code: 'EIO' });
+ }
+ return original(...args);
+ });
+ const recoveries = [chats.sweepStaleProcessing(TEST_UID)];
+ let registry: ReturnType<typeof vi.spyOn> | undefined;
+ let readSpy: ReturnType<typeof vi.spyOn> | undefined;
+ try {
+ if (firstState === 'in-flight') await ready;
+ else {
+ // The active-user pre-window sweep failed. The deferred maintenance
+ // retry must retain its protection while reloading the same state.
+ await recoveries[0];
+ const read = fs.promises.readFile;
+ let blocked = false;
+ readSpy = vi.spyOn(fs.promises, 'readFile').mockImplementation(async (...args: any[]) => {
+ if (String(args[0]) === stateFile && !blocked) { blocked = true; entered(); await gate; }
+ return (read as any)(...args);
+ });
+ syncBuiltinESMExports();
+ }
+ // A resolved registry read makes the second sweep enqueue on the next
+ // microtask. The event-loop barrier drains that continuation while the
+ // first sweep remains blocked on the explicit append gate.
+ const tracked = await state.readRunningConversationRegistry(TEST_UID);
+ registry = vi.spyOn(state, 'readRunningConversationRegistry').mockResolvedValue(tracked);
+ recoveries.push(chats.sweepStaleProcessing(TEST_UID));
+ if (firstState === 'failed') await ready;
+ else await new Promise<void>(resolve => setImmediate(resolve));
+ expect(registry).toHaveBeenCalledOnce();
+ expect((await facade.runtimeStatus(TEST_UID, cid)).processing).toBe(false);
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf8')).status).toBe('running');
+ expect(JSON.parse(fs.readFileSync(journal, 'utf8')).items).toHaveLength(1);
+ } finally {
+ release(); await Promise.all(recoveries); append.mockRestore(); registry?.mockRestore();
+ readSpy?.mockRestore(); syncBuiltinESMExports();
+ }
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf8')).status).toBe('running');
+ await chats.sweepStaleProcessing(TEST_UID);
+ const readRows = () => fs.readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(readRows().filter(row => row.system_kind === 'reply_interrupted'))
+ .toEqual([expect.objectContaining({ from: 'agent-a', turn_id: 'old-turn', source_message_id: 'old-source' })]);
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf8')).status).toBe('idle');
+ expect(JSON.parse(fs.readFileSync(journal, 'utf8')).items).toHaveLength(0);
+ await chats.sweepStaleProcessing(TEST_UID);
+ expect(readRows().filter(row => row.system_kind === 'reply_interrupted')).toHaveLength(1);
+ });
+
+ it('recovers all legacy in-flight actors when only one has a durable terminal reply', async () => {
+ const chats = await loadChats();
+ const paths = await import('../../../src/main/paths');
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID);
+ const stateFile = paths.groupChatStateFile(TEST_UID, cid);
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 1, status: 'running', last_active_at: staleActiveAt(), in_flight: ['agent-a', 'agent-b'] }));
+ const file = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ fs.writeFileSync(file, [
+ { id: 'user-1', from: 'user', to: ['agent-a', 'agent-b'], ts: staleActiveAt(), text: 'Review' },
+ { id: 'reply-a', from: 'agent-a', to: ['user'], ts: staleActiveAt(), text: 'Done', source_message_id: 'user-1' },
+ ].map(row => JSON.stringify(row)).join('\n') + '\n');
+ const journal = paths.userRunningConversationsFile(TEST_UID);
+ fs.mkdirSync(path.dirname(journal), { recursive: true });
+ fs.writeFileSync(journal, JSON.stringify({ version: 1, items: [{ conversation_id: cid }] }));
+ await chats.sweepStaleProcessing(TEST_UID);
+ const rows = fs.readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(rows.filter(row => row.system_kind === 'reply_interrupted').map(row => row.from)).toEqual(['agent-b']);
+ });
+
+ it('keeps a legacy private worker out of user-visible interruption notices', async () => {
+ const chats = await loadChats();
+ const paths = await import('../../../src/main/paths');
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID);
+ const stateFile = paths.groupChatStateFile(TEST_UID, cid);
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 1, status: 'running', last_active_at: staleActiveAt(),
+ in_flight: ['commander', 'private-worker'] }));
+ fs.writeFileSync(paths.groupChatMembersFile(TEST_UID, cid), JSON.stringify({ version: 1,
+ actors: [{ id: 'commander', kind: 'commander', joined_at: staleActiveAt() }] }));
+ const file = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ fs.writeFileSync(file, JSON.stringify({ id: 'user-1', from: 'user', to: ['commander'], ts: staleActiveAt(), text: 'Review' }) + '\n');
+ const journal = paths.userRunningConversationsFile(TEST_UID);
+ fs.mkdirSync(path.dirname(journal), { recursive: true });
+ fs.writeFileSync(journal, JSON.stringify({ version: 1, items: [{ conversation_id: cid }] }));
+ await chats.sweepStaleProcessing(TEST_UID);
+ const rows = fs.readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(rows.filter(row => row.system_kind === 'reply_interrupted').map(row => row.from)).toEqual(['commander']);
+ });
+
+ it.each([false, true])('keeps newly admitted execution state when startup history inspection is delayed (old turn settled: %s)', async settled => {
+ const chats = await loadChats();
+ const paths = await import('../../../src/main/paths');
+ const storage = await import('../../../src/main/storage');
+ const state = await import('../../../src/main/features/group_chat/state');
+ const bus = require('../../../src/main/features/group_chat/bus') as typeof import('../../../src/main/features/group_chat/bus');
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID);
+ const stateFile = paths.groupChatStateFile(TEST_UID, cid);
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify({ version: 1, status: 'running', last_active_at: staleActiveAt(), in_flight: ['agent-a'],
+ in_flight_turns: { 'agent-a': { turn_id: 'old-turn', source_message_id: 'old-source' } } }));
+ const file = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ fs.writeFileSync(file, [
+ { id: 'old-source', from: 'user', to: ['agent-a'], ts: staleActiveAt(), text: 'Old task' },
+ ...(settled ? [{ id: 'old-reply', from: 'agent-a', to: ['user'], ts: staleActiveAt(), text: 'Finished',
+ turn_id: 'old-turn', source_message_id: 'old-source' }] : []),
+ ].map(row => JSON.stringify(row)).join('\n') + '\n');
+ const journal = paths.userRunningConversationsFile(TEST_UID);
+ fs.mkdirSync(path.dirname(journal), { recursive: true });
+ fs.writeFileSync(journal, JSON.stringify({ version: 1, items: [{ conversation_id: cid }] }));
+ const original = storage.readJsonlPageWithOffsets;
+ let release!: () => void, entered!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const ready = new Promise<void>(resolve => { entered = resolve; });
+ const page = vi.spyOn(storage, 'readJsonlPageWithOffsets').mockImplementation(async (...args) => {
+ const result = await original(...args);
+ if (args[0] === file) { entered(); await gate; }
+ return result;
+ });
+ const unsubscribe = bus.subscribe(TEST_UID, cid, () => {});
+ const live = bus._cidStateForTest(TEST_UID, cid)!;
+ const recovery = chats.sweepStaleProcessing(TEST_UID);
+ try {
+ await ready;
+ // Hold the scheduler's actual admission latch while disk inspection is
+ // delayed. No model request is needed to establish admitted work.
+ live.admittedInFlight += 1;
+ await state.setStatus(TEST_UID, cid, 'running');
+ await state.markInFlight(TEST_UID, cid, 'commander', true, { turn_id: 'new-turn', source_message_id: 'new-source' });
+ const current = fs.readFileSync(stateFile, 'utf8');
+ release(); await recovery;
+ expect(fs.readFileSync(stateFile, 'utf8')).toBe(current);
+ expect(JSON.parse(fs.readFileSync(journal, 'utf8')).items).toHaveLength(1);
+ } finally {
+ release(); await recovery; page.mockRestore();
+ live.admittedInFlight = 0; unsubscribe(); await bus.dropConv(TEST_UID, cid);
+ }
+ });
+
it('does not load the Group Chat runtime when the compact journal is empty', async () => {
const paths = await import('../../../src/main/paths');
const journal = paths.userRunningConversationsFile(TEST_UID);
diff --git a/test/main/features/conversation-history-cache.test.ts b/test/main/features/conversation-history-cache.test.ts
index b4b76683..152a4928 100644
--- a/test/main/features/conversation-history-cache.test.ts
+++ b/test/main/features/conversation-history-cache.test.ts
@@ -75,6 +75,113 @@ afterEach(async () => {
});
describe('conversation history projection cache', () => {
+ it.each([
+ ['local seconds', '2026-10-26T14:31:24', '2026-10-26T14:31:11.226', '2026-10-26T14:31:24.602', 13374, true],
+ ['UTC seconds', '2026-10-26T06:31:24Z', '2026-10-26T06:31:11.226Z', '2026-10-26T06:31:24.602Z', 13374, true],
+ ['offset seconds', '2026-10-26T14:31:24+08:00', '2026-10-26T06:31:11.226Z', '2026-10-26T06:31:24.602Z', 13374, true],
+ ['last millisecond', '2026-10-26T06:31:24Z', '2026-10-26T06:31:11.226Z', '2026-10-26T06:31:24.999Z', 13773, true],
+ ['next second', '2026-10-26T06:31:24Z', '2026-10-26T06:31:11.226Z', '2026-10-26T06:31:25.000Z', 13774, false],
+ ['explicit milliseconds', '2026-10-26T06:31:24.000Z', '2026-10-26T06:31:11.226Z', '2026-10-26T06:31:24.602Z', 13374, false],
+ ['subsecond run', '2026-10-26T06:31:24Z', '2026-10-26T06:31:24.226Z', '2026-10-26T06:31:24.602Z', 374, true],
+ ['duration exceeds notice precision', '2026-10-26T06:31:24Z', '2026-10-26T06:31:11.226Z', '2026-10-26T06:31:24.602Z', 14000, false],
+ ] as const)('preserves an interrupted reply and its evidenced clock at timestamp precision boundaries: %s',
+ async (_shape, ts, startedAt, endedAt, durationMs, expectedClock) => {
+ const notice = { ...message('interrupted'), from: 'codex-agent', ts, text: 'The previous reply was interrupted.',
+ system_kind: 'reply_interrupted', turn_id: 'turn-cancelled', source_message_id: 'source', seg: 0,
+ process: [{ type: 'event', event: { stream: 'cli', data: { type: 'status', status: 'running' } } }] };
+ writeRows([{ ...message('source'), from: 'user', ts: startedAt }, notice]);
+ const original = fs.readFileSync(sourceFile, 'utf8');
+ const paths = await import('../../../src/main/paths');
+ const run = paths.localAgentRunDir(TEST_UID, '123456abcdef');
+ fs.mkdirSync(run, { recursive: true });
+ fs.writeFileSync(path.join(run, 'meta.json'), JSON.stringify({ cid: 'canonical', agentId: 'codex-agent', cli: 'codex',
+ currentMessageId: 'source', startedAt, endedAt, durationMs, status: 'cancelled' }));
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const { records: [record] } = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1);
+ const clocks = record.process?.filter(item => item.event?.stream === 'runtime') || [];
+ expect(clocks).toEqual(expectedClock ? [{ type: 'event', event: { stream: 'runtime', data: {
+ phase: 'interrupted', duration_ms: durationMs,
+ } } }] : []);
+ expect(record.display_phase).not.toBe('commentary');
+ expect(record.text).toBe(notice.text);
+ expect(record.process?.filter(item => item.event?.stream !== 'runtime')).toEqual(notice.process);
+ await (await import('../../../src/main/features/conversation-history-client')).closeConversationHistoryWorker();
+ expect((await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1)).records[0]).toEqual(record);
+ expect((await cache.readConversationHistoryWindowAtMessage(TEST_UID, sourceFile, notice.id, 1))?.records[0]).toEqual(record);
+ expect(fs.readFileSync(sourceFile, 'utf8')).toBe(original);
+ });
+
+ it.each(['inline', 'paged', 'already-timed', 'wrong-source', 'dispatch-source'])(
+ 'fills only the missing interruption clock without duplicating saved process: %s', async shape => {
+ const saved = Array.from({ length: shape === 'paged' ? 1200 : 1 }, (_, i) => ({ type: 'progress', text: `Saved step ${i}` }));
+ const clock = { type: 'event', event: { stream: 'runtime', data: { phase: 'interrupted', duration_ms: 7000 } } };
+ writeRows([
+ { ...message('source'), from: shape === 'dispatch-source' ? 'commander' : 'user',
+ ...(shape === 'dispatch-source' ? { dispatch: true, to: ['codex-agent'] } : {}), ts: '2026-10-17T01:00:00Z' },
+ { ...message('interrupted'), from: 'codex-agent', ts: '2026-10-17T02:00:00Z',
+ source_message_id: 'source', system_kind: 'reply_interrupted', process: [...saved, ...(shape === 'already-timed' ? [clock] : [])] },
+ ]);
+ const original = fs.readFileSync(sourceFile, 'utf8');
+ const paths = await import('../../../src/main/paths');
+ const run = paths.localAgentRunDir(TEST_UID, '123456abcdef');
+ fs.mkdirSync(run, { recursive: true });
+ fs.writeFileSync(path.join(run, 'meta.json'), JSON.stringify({ cid: 'canonical', agentId: 'codex-agent', cli: 'codex',
+ currentMessageId: shape === 'wrong-source' ? 'different-source' : 'source',
+ startedAt: '2026-10-17T01:00:01Z', endedAt: '2026-10-17T01:00:11Z', durationMs: 10000 }));
+ fs.writeFileSync(path.join(run, 'events.jsonl'), JSON.stringify({ type: 'tool-event', phase: 'result', tool: 'bash', callId: 'duplicate', output: 'Duplicate' }) + '\n');
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const { records: [record] } = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1);
+ const clocks = record.process?.filter(item => item.event?.stream === 'runtime') || [];
+ expect(clocks).toEqual(shape === 'wrong-source' ? [] : [shape === 'already-timed' ? clock : {
+ type: 'event', event: { stream: 'runtime', data: { phase: 'interrupted', duration_ms: 10000 } },
+ }]);
+ const items: any[] = record.process_parts?.length ? [] : record.process || [];
+ for (const part of record.process_parts || []) {
+ if (!('ref' in part)) throw new Error('Expected a saved process page');
+ let cursor: number | null = 0;
+ do {
+ const page = await cache.readConversationProcessPage(TEST_UID, sourceFile, part.ref, cursor, record.id);
+ items.push(...page.items); cursor = page.nextCursor;
+ } while (cursor !== null);
+ }
+ expect(items.filter(item => item.type === 'progress')).toEqual(saved);
+ expect(JSON.stringify(items)).not.toContain('Duplicate');
+ await (await import('../../../src/main/features/conversation-history-client')).closeConversationHistoryWorker();
+ expect((await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1)).records[0]).toEqual(record);
+ expect(fs.readFileSync(sourceFile, 'utf8')).toBe(original);
+ });
+
+ it.each(['measured', 'estimated', 'missing', 'overlap'])(
+ 'recovers an interruption clock across identified attempts without counting downtime: %s', async timing => {
+ writeRows([
+ { ...message('source'), from: 'user', ts: '2026-10-17T01:00:00Z' },
+ { ...message('interrupted'), from: 'codex-agent', ts: '2026-10-17T04:00:00Z', system_kind: 'reply_interrupted' },
+ ]);
+ const paths = await import('../../../src/main/paths');
+ for (const [id, startedAt, endedAt, durationMs] of [
+ ['123456abcdef', '2026-10-17T01:00:01Z', '2026-10-17T01:00:11Z', 10000],
+ ['abcdef123456', timing === 'overlap' ? '2026-10-17T01:00:06Z' : '2026-10-17T03:00:00Z',
+ timing === 'overlap' ? '2026-10-17T01:00:16Z' : '2026-10-17T03:00:05Z', timing === 'overlap' ? 10000 : 5000],
+ ] as const) {
+ const run = paths.localAgentRunDir(TEST_UID, id);
+ fs.mkdirSync(run, { recursive: true });
+ const last = id === 'abcdef123456';
+ fs.writeFileSync(path.join(run, 'meta.json'), JSON.stringify({ cid: 'canonical', agentId: 'codex-agent', cli: 'codex',
+ currentMessageId: 'source', startedAt, ...(!last || timing === 'measured' || timing === 'overlap' ? { endedAt, durationMs } : {}) }));
+ const file = path.join(run, 'events.jsonl');
+ fs.writeFileSync(file, timing === 'missing' && last ? '' : JSON.stringify({ type: 'tool-event', phase: 'result', tool: 'bash', callId: id, output: 'Saved' }) + '\n');
+ fs.utimesSync(file, new Date(endedAt), new Date(endedAt));
+ }
+ const cache = await import('../../../src/main/features/conversation_history_cache');
+ const { records: [record] } = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 1);
+ expect(record.process?.filter(item => item.event?.stream === 'runtime') || []).toEqual(timing === 'missing' ? [] : [{
+ type: 'event', event: { stream: 'runtime', data: { phase: 'interrupted', duration_ms: 15000,
+ ...(timing === 'estimated' ? { duration_estimated: true } : {}) } },
+ }]);
+ expect(record.process_parts).toHaveLength(timing === 'missing' ? 1 : 2);
+ expect(record.system_kind).toBe('reply_interrupted');
+ });
+
it('prefers the notice actor archive when a delegated CLI question is the last visible activity', async () => {
writeRows([
{ ...message('user-1'), from: 'user', to: ['commander'], ts: '2026-10-17T01:00:00Z' },
@@ -568,13 +675,15 @@ describe('conversation history projection cache', () => {
const cache = await import('../../../src/main/features/conversation_history_cache');
await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
const entry = onlyCacheEntry();
- fs.rmSync(path.join(entry, 'latest-page-v10.json'));
+ fs.rmSync(path.join(entry, 'latest-page-v12.json'));
fs.writeFileSync(path.join(entry, 'latest-page.json'), JSON.stringify({ version: 4, unrelated: 'x'.repeat(1024 * 1024) }));
fs.writeFileSync(path.join(entry, 'latest-page-v5.json'), JSON.stringify({ version: 5, unrelated: 'x'.repeat(1024 * 1024) }));
fs.writeFileSync(path.join(entry, 'latest-page-v6.json'), JSON.stringify({ version: 6, unrelated: 'x'.repeat(1024 * 1024) }));
fs.writeFileSync(path.join(entry, 'latest-page-v7.json'), JSON.stringify({ version: 7, unrelated: 'x'.repeat(1024 * 1024) }));
fs.writeFileSync(path.join(entry, 'latest-page-v8.json'), JSON.stringify({ version: 8, unrelated: 'x'.repeat(1024 * 1024) }));
fs.writeFileSync(path.join(entry, 'latest-page-v9.json'), JSON.stringify({ version: 9, unrelated: 'x'.repeat(1024 * 1024) }));
+ fs.writeFileSync(path.join(entry, 'latest-page-v10.json'), JSON.stringify({ version: 10, unrelated: 'x'.repeat(1024 * 1024) }));
+ fs.writeFileSync(path.join(entry, 'latest-page-v11.json'), JSON.stringify({ version: 11, unrelated: 'x'.repeat(1024 * 1024) }));
const next = await cache.readConversationHistoryPage(TEST_UID, sourceFile, 10);
expect(next.records.map(record => record.id)).toEqual(['latest']);
expect(fs.existsSync(path.join(entry, 'latest-page.json'))).toBe(false);
@@ -583,7 +692,9 @@ describe('conversation history projection cache', () => {
expect(fs.existsSync(path.join(entry, 'latest-page-v7.json'))).toBe(false);
expect(fs.existsSync(path.join(entry, 'latest-page-v8.json'))).toBe(false);
expect(fs.existsSync(path.join(entry, 'latest-page-v9.json'))).toBe(false);
- expect(fs.statSync(path.join(entry, 'latest-page-v10.json')).size).toBeLessThan(4096);
+ expect(fs.existsSync(path.join(entry, 'latest-page-v10.json'))).toBe(false);
+ expect(fs.existsSync(path.join(entry, 'latest-page-v11.json'))).toBe(false);
+ expect(fs.statSync(path.join(entry, 'latest-page-v12.json')).size).toBeLessThan(4096);
});
it('keeps the answer available during a process-cache write failure and recovers its details', async () => {
@@ -634,7 +745,7 @@ describe('conversation history projection cache', () => {
);
expect(page.nextCursor).not.toBeNull();
const cacheEntry = onlyCacheEntry();
- const latestPageFile = path.join(cacheEntry, 'latest-page-v10.json');
+ const latestPageFile = path.join(cacheEntry, 'latest-page-v12.json');
const cached = JSON.parse(fs.readFileSync(latestPageFile, 'utf8'));
expect(cached.records).toHaveLength(10);
expect(fs.statSync(latestPageFile).size).toBeLessThan(canonicalBytes / 20);
@@ -667,7 +778,7 @@ describe('conversation history projection cache', () => {
const result = (page.records[0].process as any[])[0].event.data;
expect(result.output).toBeUndefined();
expect(result.outputPath).toBeUndefined();
- expect(fs.statSync(path.join(onlyCacheEntry(), 'latest-page-v10.json')).size).toBeLessThan(4_000);
+ expect(fs.statSync(path.join(onlyCacheEntry(), 'latest-page-v12.json')).size).toBeLessThan(4_000);
const canonical = JSON.parse(fs.readFileSync(sourceFile, 'utf8').trim());
expect(canonical.process[0].event.data.output).toEqual(structuredOutput);
@@ -702,7 +813,7 @@ describe('conversation history projection cache', () => {
const extended = await readConversationHistoryPage(TEST_UID, sourceFile, 2);
expect(extended.records.map((record) => record.id)).toEqual(['m3', 'm4']);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v10.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v12.json'), 'utf8'));
expect(cached.records.map((entry: any) => entry.record.id)).toEqual(['m3', 'm4']);
});
@@ -735,7 +846,7 @@ describe('conversation history projection cache', () => {
expect(expanded.records.map((record) => record.id)).toEqual(
Array.from({ length: 8 }, (_, index) => `m${index + 5}`),
);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v10.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v12.json'), 'utf8'));
expect(cached.records).toHaveLength(8);
});
@@ -753,7 +864,7 @@ describe('conversation history projection cache', () => {
expect(whole.records.map((record) => record.id)).toEqual(
Array.from({ length: 30 }, (_, index) => `m${index + 1}`),
);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v10.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v12.json'), 'utf8'));
expect(cached.records).toHaveLength(10);
});
@@ -768,7 +879,7 @@ describe('conversation history projection cache', () => {
);
expect(pages.every((page) => page.records.length === 10)).toBe(true);
- const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v10.json'), 'utf8'));
+ const cached = JSON.parse(fs.readFileSync(path.join(onlyCacheEntry(), 'latest-page-v12.json'), 'utf8'));
expect(cached.records).toHaveLength(10);
});
diff --git a/test/main/features/group_chat/bus-integration.test.ts b/test/main/features/group_chat/bus-integration.test.ts
index c2b61bba..a92eac08 100644
--- a/test/main/features/group_chat/bus-integration.test.ts
+++ b/test/main/features/group_chat/bus-integration.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
import * as os from 'node:os';
import * as path from 'node:path';
import AdmZip from 'adm-zip';
@@ -10,12 +11,13 @@ import { SCHEMA_DESCRIPTION_SOFT_BUDGET_TOKENS } from '../../../../src/core-agen
const retryInfoLog = vi.hoisted(() => vi.fn());
const warningLog = vi.hoisted(() => vi.fn());
+const hostErrorLog = vi.hoisted(() => vi.fn());
const correctionModel = vi.hoisted(() => vi.fn(async (_input: any): Promise<string> => ''));
vi.mock('../../../../src/main/model/core-agent/runner', async (importOriginal) => ({
...(await importOriginal<any>()), completeSkillCreationCorrection: correctionModel,
}));
vi.mock('../../../../src/main/logger', () => ({
- createLogger: () => ({ debug: vi.fn(), info: retryInfoLog, warn: warningLog, error: vi.fn() }),
+ createLogger: () => ({ debug: vi.fn(), info: retryInfoLog, warn: warningLog, error: hostErrorLog }),
}));
/**
@@ -67,12 +69,14 @@ function _resetStreamGates(): void {
const _recordedCalls = vi.hoisted(() => [] as Array<{
sid: string;
message: string;
+ systemPrompt: string;
model: string;
// True when the bus asked this call to resume the still-open active turn
// instead of opening a new one — the in-turn channel retry contract.
resumeActiveTurn: boolean;
executionDeadlineAt: number;
nested: boolean;
+ outputDelivery?: 'final' | 'process';
// Tool names offered to this turn. Lets tests assert the Commander/named
// Agent/anonymous-worker capability split.
extraToolNames: string[];
@@ -114,19 +118,25 @@ const _recordedToolResults = vi.hoisted(() => [] as Array<{
executionTimeoutOwner?: string;
}>);
const _receivedSteers: string[] = [];
+// Observe the real turn-context resolver at the deterministic provider seam.
+// No automation run facts are manufactured by this probe.
+let _modelTurnProbe: ((opts: any) => Promise<void>) | undefined;
vi.mock('../../../../src/main/model/client', () => ({
async *streamChatWithModel(opts: any) {
+ if (_modelTurnProbe) await _modelTurnProbe(opts);
const sid = opts.sessionId || '';
const model = _selectedModel.value;
_recordedCalls.push({
sid,
message: String(opts.message || ''),
+ systemPrompt: String(opts.systemPrompt || ''),
model,
terminalCorrectionAttached: typeof opts.terminalTextGuard === 'function',
resumeActiveTurn: !!opts.resumeActiveTurn,
executionDeadlineAt: opts.executionDeadlineAt,
nested: !!opts.nested,
+ outputDelivery: opts.outputDelivery,
extraToolNames: (Array.isArray(opts.extraTools) ? opts.extraTools : []).map((t: any) => String(t?.name || '')),
browserTool: opts.extraTools?.find((tool: any) => tool.name === 'inner_browser'),
extraToolContracts: (Array.isArray(opts.extraTools) ? opts.extraTools : []).map((tool: any) => ({
@@ -208,6 +218,10 @@ vi.mock('../../../../src/main/model/client', () => ({
continue;
}
// Host task callbacks as the real todo_tasks tool reports them.
+ if (ev?.type === '__artifact_saved__') {
+ opts.onArtifactCreated?.(ev.artifact);
+ continue;
+ }
if (ev?.type === '__todo_saved__') {
opts.onTodoTaskSaved?.(ev.taskId, ev.projectId || '', ev.content || '');
continue;
@@ -271,6 +285,7 @@ beforeEach(async () => {
correctionModel.mockReset().mockResolvedValue('');
retryInfoLog.mockClear();
warningLog.mockClear();
+ hostErrorLog.mockClear();
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-int-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
prevTestGlobalSkillsRoot = process.env.ORKAS_TEST_GLOBAL_SKILLS_ROOT;
@@ -282,9 +297,12 @@ beforeEach(async () => {
_recordedCalls.length = 0;
_recordedToolResults.length = 0;
_receivedSteers.length = 0;
+ _modelTurnProbe = undefined;
modelAbortMock.mockClear();
modelAbortMock.mockReturnValue(0);
cidsToDrop.clear();
+ const shutdown = (globalThis as any)[Symbol.for('orkas.group_chat.bus.shutdown')];
+ if (shutdown) { shutdown.started = false; shutdown.pending = undefined; }
vi.resetModules();
const users = await import('../../../../src/main/features/users');
users.activateUser(TEST_UID);
@@ -382,6 +400,199 @@ async function seedDisabledSkill() {
enabled.setSkillEnabled(TEST_UID, 'arxiv-reader', false);
}
+describe('group_chat bus integration › automation first-turn facts', () => {
+ let restoreBrowserBinding: () => void;
+ beforeEach(async () => {
+ await import('../../../../src/main/features/group_chat');
+ const webAssist = await import('../../../../src/main/features/web_assist');
+ // This host fixture has no Electron window. Use the supported unbound
+ // path; browser attachment has its own owning feature coverage.
+ const binding = vi.spyOn(webAssist, 'bindHostStartedWebAssistConversation').mockReturnValue(false);
+ restoreBrowserBinding = () => binding.mockRestore();
+ }, 60_000);
+ afterEach(() => { restoreBrowserBinding?.(); });
+
+ it.each(['commander', 'named-agent'])('prepares first and subsequent run context before %s execution, even before send returns', async recipient => {
+ const autoTasks = await import('../../../../src/main/features/auto_tasks');
+ const groupChat = await import('../../../../src/main/features/group_chat');
+ const { resolveConversationAssistanceForTurn } = await import('../../../../src/main/features/conversation_assistance_context');
+ const created = await autoTasks.createTask(TEST_UID, {
+ content: 'Compare the current total with the previous run.',
+ schedule: { type: 'daily', hour: 9, minute: 0 },
+ ...(recipient === 'named-agent' ? { recipient: { kind: 'agent' as const, id: AGENT_ID, name: AGENT_NAME } } : {}),
+ });
+ if (!created.ok) throw new Error(created.error);
+ const notePath = autoTasks.handoffNotePath(TEST_UID, created.task);
+ const actualSend = groupChat.send;
+ let observed!: Promise<void>;
+ const send = vi.spyOn(groupChat, 'send').mockImplementation(async input => {
+ const result = await actualSend(input);
+ // A valid send may still be doing post-dispatch work while the actor
+ // assembles its first turn. Force that ordering without a clock race.
+ if (result.ok) await observed;
+ return result;
+ });
+ try {
+ let firstCid = '';
+ for (const runNumber of [1, 2]) {
+ let notify!: () => void;
+ observed = new Promise<void>(resolve => { notify = resolve; });
+ let built: Awaited<ReturnType<typeof resolveConversationAssistanceForTurn>> | undefined;
+ let buildError: unknown;
+ _modelTurnProbe = async opts => {
+ _setScript(opts.sessionId, [{ type: 'final', text: 'Current total checked.' }]);
+ try { built = await resolveConversationAssistanceForTurn(opts.userId, opts.cid, {
+ agentId: opts.agentId, outputDelivery: opts.outputDelivery,
+ }); }
+ catch (error) { buildError = error; }
+ finally { notify(); }
+ };
+ const fired = await autoTasks.runTaskNow(TEST_UID, created.task.id);
+ expect(fired.ok).toBe(true);
+ if (!fired.ok) throw new Error(fired.error);
+ await waitForQuiescent(TEST_UID, fired.cid, 4000);
+ await vi.waitFor(async () => {
+ expect((await autoTasks.getTask(TEST_UID, created.task.id))?.last_run?.status).toBe('completed');
+ });
+ expect(buildError).toBeUndefined();
+ expect(built?.guidance).toContain(`Host facts: run ${runNumber}`);
+ if (runNumber === 1) {
+ expect(built?.guidance).toContain('This is its first run.');
+ expect(built?.readSeeds?.some(seed => seed.path === notePath)).not.toBe(true);
+ firstCid = fired.cid;
+ fs.writeFileSync(notePath, 'Previous total: 42. Next: compare the new total.');
+ } else {
+ expect(built?.guidance).toContain(`its conversation id is ${firstCid}`);
+ expect(built?.guidance).toContain('ended with status completed');
+ expect(built?.guidance).toContain('Previous total: 42.');
+ expect(built?.readSeeds?.some(seed => seed.path === notePath)).toBe(true);
+ }
+ const task = await autoTasks.getTask(TEST_UID, created.task.id);
+ expect(task?.run_count).toBe(runNumber);
+ }
+ expect(_recordedCalls).toHaveLength(2);
+ expect(_recordedCalls.every(call => call.sid.startsWith(recipient === 'named-agent' ? 'gmember-' : 'gconv-'))).toBe(true);
+ expect(hostErrorLog).not.toHaveBeenCalled();
+ expect(warningLog).not.toHaveBeenCalled();
+ } finally {
+ _modelTurnProbe = undefined;
+ send.mockRestore();
+ }
+ }, 20_000);
+
+ it('does not count an automation rejected by the real send boundary', async () => {
+ const autoTasks = await import('../../../../src/main/features/auto_tasks');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const created = await autoTasks.createTask(TEST_UID, {
+ content: 'Run after admission.', schedule: { type: 'daily', hour: 9, minute: 0 },
+ });
+ if (!created.ok) throw new Error(created.error);
+ await bus.prepareForShutdown();
+ expect(await autoTasks.runTaskNow(TEST_UID, created.task.id)).toMatchObject({ ok: false, error: 'send_not_ok' });
+ const task = await autoTasks.getTask(TEST_UID, created.task.id);
+ expect(task?.run_count).toBeUndefined();
+ expect(task?.last_run).toBeUndefined();
+ expect(_recordedCalls).toHaveLength(0);
+ expect(hostErrorLog.mock.calls.map(call => String(call[0]))).toEqual([
+ expect.stringContaining('send failed'),
+ ]);
+ expect(warningLog.mock.calls.map(call => String(call[0]))).toEqual([
+ expect.stringContaining('fire send failed'),
+ ]);
+ });
+
+ it('waits for the run-fact write before starting a model turn', async () => {
+ const autoTasks = await import('../../../../src/main/features/auto_tasks');
+ const storage = await import('../../../../src/main/storage');
+ const created = await autoTasks.createTask(TEST_UID, {
+ content: 'Wait for host facts.', schedule: { type: 'daily', hour: 9, minute: 0 },
+ });
+ if (!created.ok) throw new Error(created.error);
+ let entered!: () => void;
+ const writingStarted = new Promise<void>(resolve => { entered = resolve; });
+ let release!: () => void;
+ const writingAllowed = new Promise<void>(resolve => { release = resolve; });
+ const writeJson = storage.writeJson;
+ const writing = vi.spyOn(storage, 'writeJson').mockImplementation(async (file, value) => {
+ if ((value as any)?.id === created.task.id && (value as any)?.last_run?.status === 'running') {
+ entered();
+ await writingAllowed;
+ }
+ return writeJson(file, value);
+ });
+ _modelTurnProbe = async opts => {
+ _setScript(opts.sessionId, [{ type: 'final', text: 'Started after facts were saved.' }]);
+ };
+ const firing = autoTasks.runTaskNow(TEST_UID, created.task.id);
+ try {
+ await writingStarted;
+ expect(_recordedCalls).toHaveLength(0);
+ release();
+ const fired = await firing;
+ expect(fired.ok).toBe(true);
+ if (!fired.ok) throw new Error(fired.error);
+ await waitForQuiescent(TEST_UID, fired.cid, 4000);
+ expect(_recordedCalls).toHaveLength(1);
+ expect(hostErrorLog).not.toHaveBeenCalled();
+ expect(warningLog).not.toHaveBeenCalled();
+ } finally {
+ release();
+ await firing;
+ writing.mockRestore();
+ }
+ });
+
+ it('keeps execution available when run-fact storage fails, without retrying or inventing facts', async () => {
+ const autoTasks = await import('../../../../src/main/features/auto_tasks');
+ const storage = await import('../../../../src/main/storage');
+ const { resolveConversationAssistanceForTurn } = await import('../../../../src/main/features/conversation_assistance_context');
+ const created = await autoTasks.createTask(TEST_UID, {
+ content: 'Execute even without optional continuity facts.', schedule: { type: 'daily', hour: 9, minute: 0 },
+ });
+ if (!created.ok) throw new Error(created.error);
+ const writeJson = storage.writeJson;
+ let failedWrites = 0;
+ const writing = vi.spyOn(storage, 'writeJson').mockImplementation(async (file, value) => {
+ if ((value as any)?.id === created.task.id && (value as any)?.last_run?.status === 'running') {
+ failedWrites += 1;
+ throw Object.assign(new Error('fixture run-fact write denied'), { code: 'EACCES' });
+ }
+ return writeJson(file, value);
+ });
+ let guidance: string | undefined;
+ _modelTurnProbe = async opts => {
+ guidance = (await resolveConversationAssistanceForTurn(opts.userId, opts.cid)).guidance;
+ _setScript(opts.sessionId, [{ type: 'final', text: 'Execution remains available.' }]);
+ };
+ try {
+ const fired = await autoTasks.runTaskNow(TEST_UID, created.task.id);
+ expect(fired.ok).toBe(true);
+ if (!fired.ok) throw new Error(fired.error);
+ await waitForQuiescent(TEST_UID, fired.cid, 4000);
+ expect(_recordedCalls).toHaveLength(1);
+ expect(guidance).toBeDefined();
+ expect(guidance).not.toContain('## This automation run');
+ expect(failedWrites).toBe(1);
+ expect((await autoTasks.getTask(TEST_UID, created.task.id))?.run_count).toBeUndefined();
+ expect(hostErrorLog).not.toHaveBeenCalled();
+ expect(warningLog.mock.calls.map(call => String(call[0]))).toEqual([
+ expect.stringContaining('run start record failed'),
+ ]);
+ writing.mockRestore();
+ const recovered = await autoTasks.runTaskNow(TEST_UID, created.task.id);
+ expect(recovered.ok).toBe(true);
+ if (!recovered.ok) throw new Error(recovered.error);
+ await waitForQuiescent(TEST_UID, recovered.cid, 4000);
+ expect(_recordedCalls).toHaveLength(2);
+ expect(guidance).toContain('Host facts: run 1');
+ expect((await autoTasks.getTask(TEST_UID, created.task.id))?.run_count).toBe(1);
+ } finally {
+ _modelTurnProbe = undefined;
+ writing.mockRestore();
+ }
+ });
+});
+
describe('group_chat bus integration › unexpected host-turn failure recovery', () => {
// Cold module transformation is fixture setup, not failure/retry latency.
// On a loaded host it exceeded this case's 10s business-flow budget before
@@ -390,6 +601,78 @@ describe('group_chat bus integration › unexpected host-turn failure recovery',
await import('../../../../src/main/features/group_chat');
}, 60_000);
+ it.each(['catalog', 'bindings'])('stops before inference on %s read failure and retries with the original project scope', async (fault) => {
+ const paths = await import('../../../../src/main/paths');
+ const projects = await import('../../../../src/main/features/projects');
+ const chats = await import('../../../../src/main/features/chats');
+ const agents = await import('../../../../src/main/features/agents');
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const groupChat = await import('../../../../src/main/features/group_chat');
+ const publishing = await import('../../../../src/main/features/runtime_content_publish');
+ const project = await projects.createProject(TEST_UID, 'Scoped recovery');
+ if (!project.ok) throw new Error('Project fixture failed');
+ const pid = project.project.project_id;
+ await projects.addAgentBinding(TEST_UID, pid, AGENT_ID);
+ const outsiderDir = paths.agentDir(TEST_UID, 'unbound-fixture');
+ fs.mkdirSync(outsiderDir, { recursive: true });
+ fs.writeFileSync(path.join(outsiderDir, 'agent.json'), JSON.stringify({ agent_id: 'unbound-fixture', name: 'UnboundFixture' }));
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID, { kind: 'normal', projectId: pid });
+ cidsToDrop.add(cid);
+ const bindingFile = paths.projectBindingsFile(TEST_UID, pid);
+ const before = fs.readFileSync(bindingFile, 'utf8');
+ const target = fault === 'catalog' ? paths.agentDefinitionFile(TEST_UID, AGENT_ID)
+ : bindingFile;
+ let active = false;
+ const read = fs.promises.readFile.bind(fs.promises);
+ const readSpy = vi.spyOn(fs.promises, 'readFile').mockImplementation((...args: any[]) => {
+ if (active && args[0] === target) return Promise.reject(Object.assign(new Error('private fixture read failure'), { code: 'EACCES' }));
+ return (read as any)(...args);
+ });
+ syncBuiltinESMExports();
+ const enter = publishing.enterRuntimeContentTurn;
+ const gateSpy = vi.spyOn(publishing, 'enterRuntimeContentTurn').mockImplementationOnce(async (userId) => {
+ const release = await enter(userId);
+ agents.clearAgentListCache();
+ active = true;
+ return release;
+ });
+ try {
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Complete the scoped task' });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ } finally {
+ active = false;
+ readSpy.mockRestore();
+ syncBuiltinESMExports();
+ gateSpy.mockRestore();
+ }
+ expect(_recordedCalls).toHaveLength(0);
+ expect(_recordedToolResults).toHaveLength(0);
+ const rows = await groupChat.readMessages(TEST_UID, cid);
+ const source = rows.find((row: any) => row.from === 'user')!;
+ const failed = rows.filter((row: any) => row.failure_code === 'worker_turn_exception');
+ expect(failed).toHaveLength(1);
+ expect(failed[0]).toMatchObject({ from: 'commander', source_message_id: source.id, failure_kind: 'runtime' });
+ expect(failed[0].text).toContain('Please try again.');
+ const failures = hostErrorLog.mock.calls.filter(call => call[0] === 'worker turn failed');
+ expect(failures).toHaveLength(1);
+ expect(JSON.stringify(failures)).not.toContain(target);
+ expect(JSON.stringify(failures)).not.toContain('private fixture');
+ _setScript(state.buildGconvSessionId(cid), [{ type: 'final', text: 'Recovered within project' }]);
+ expect(await groupChat.retryFailedTurn({ userId: TEST_UID, cid, failedMessageId: failed[0].id, visibleText: source.text }))
+ .toMatchObject({ ok: true, mode: 'restart' });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ expect(_recordedCalls).toHaveLength(1);
+ expect(_recordedCalls[0].systemPrompt).toContain(`id: ${AGENT_ID}`);
+ expect(_recordedCalls[0].systemPrompt).not.toContain('UnboundFixture');
+ expect(_recordedCalls[0].systemPrompt).not.toContain('(no agents)');
+ expect(_recordedToolResults).toHaveLength(0);
+ expect(fs.readFileSync(bindingFile, 'utf8')).toBe(before);
+ expect(fs.readdirSync(paths.userAgentsDir(TEST_UID)).sort()).toEqual([AGENT_ID, 'unbound-fixture'].sort());
+ expect((await groupChat.readMessages(TEST_UID, cid)).some((row: any) => row.text === 'Recovered within project')).toBe(true);
+ expect((await state.readMembers(TEST_UID, cid)).actors.find(actor => actor.id === 'commander')?.in_flight).not.toBe(true);
+ }, 10_000);
+
// Scenario: the user submits an ordinary Commander task, but the host
// boundary fails before the model turn starts. The transcript must retain
// the request, surface one structured/retryable failure, and remain usable.
@@ -454,6 +737,31 @@ describe('group_chat bus integration › unexpected host-turn failure recovery',
}, 10_000);
});
+it('persists one latest application per identity after correction callbacks and retains separate creations', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+ const events: any[] = [];
+ const unsubscribe = bus.subscribe(TEST_UID, cid, event => { if (event.type === 'artifact_created') events.push(event.artifact); });
+ _setScript(state.buildGconvSessionId(cid), [
+ { type: '__artifact_saved__', artifact: { id: 'one', title: 'Draft', revision: 1 } },
+ { type: '__artifact_saved__', artifact: { id: 'one', title: 'Corrected', revision: 2 } },
+ { type: '__artifact_saved__', artifact: { id: 'one', title: 'Late draft', revision: 1 } },
+ { type: '__artifact_saved__', artifact: { id: 'two', title: 'Second', revision: 1 } },
+ { type: 'final', text: 'Ready' },
+ ]);
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Build the requested apps' });
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ unsubscribe();
+ const messages = fs.readFileSync(path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`), 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(messages.flatMap(message => message.artifacts || [])).toEqual([
+ { id: 'one', title: 'Corrected', revision: 2, agent_id: 'commander' },
+ { id: 'two', title: 'Second', revision: 1, agent_id: 'commander' },
+ ]);
+ expect(events.map(a => a.revision)).toEqual([1, 2, 1]);
+}, 10000);
+
describe('group_chat bus integration › conversation search freshness', () => {
it('makes committed user and assistant messages searchable without a repair scan', async () => {
const cid = newCid();
@@ -484,6 +792,163 @@ describe('group_chat bus integration › conversation search freshness', () => {
});
});
+describe('group_chat bus integration › failed-turn write receipt continuity', () => {
+ it.each([false, true])('archives concurrent turns on application shutdown without replay (unresponsive=%s)', async (unresponsive) => {
+ const chats = await import('../../../../src/main/features/chats');
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const groupChat = await import('../../../../src/main/features/group_chat');
+ const cids = [];
+ for (let index = 0; index < 2; index++) {
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID, { kind: 'normal' });
+ cidsToDrop.add(cid);
+ cids.push(cid);
+ if (unresponsive) _holdStream(`shutdown-${index}`);
+ _setScript(state.buildGconvSessionId(cid), [
+ { type: 'delta', text: `Public partial answer ${index}.` },
+ { type: 'event', event: { stream: 'tool', data: { phase: 'end', id: `saved-${index}`, name: 'call_connector_tool', isError: false, output: `confirmed-${index}` } } },
+ { type: 'event', event: { stream: 'tool', data: { phase: 'start', id: `pending-${index}`, name: 'call_connector_tool', arguments: { action: 'write' } } } },
+ ...(unresponsive ? [{ type: '__wait_for_gate__', name: `shutdown-${index}` }] : [{ type: '__wait_for_abort__' }]),
+ ]);
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: `Import schedule ${index}.` });
+ }
+ await expect.poll(() => cids.every(cid => JSON.stringify(bus.liveDisplaySnapshot(TEST_UID, cid)).includes('pending-'))).toBe(true);
+ await bus.enqueue({ uid: TEST_UID, cid: cids[0], fromActorId: 'user', text: 'Queued work must not run during exit.' });
+ const pending = bus.prepareForShutdown();
+ expect(bus.prepareForShutdown()).toBe(pending);
+ await expect(bus.enqueue({ uid: TEST_UID, cid: cids[0], fromActorId: 'user', text: 'Do not admit new work.' })).rejects.toMatchObject({ code: 'E_APP_SHUTTING_DOWN' });
+ await pending;
+ for (const [index, cid] of cids.entries()) {
+ const rows = await groupChat.readMessages(TEST_UID, cid);
+ const archived = rows.filter(row => row.system_kind === 'reply_interrupted');
+ expect(archived).toHaveLength(1);
+ const toolData = archived.flatMap(row => row.process || []).map(item => item.event?.data).filter(Boolean) as any[];
+ expect(toolData.filter(data => data.id === `saved-${index}` && data.phase === 'end')).toHaveLength(1);
+ expect(toolData.find(data => data.id === `saved-${index}`)?.output).toBe(`confirmed-${index}`);
+ expect(toolData.filter(data => data.id === `pending-${index}` && data.phase === 'start')).toHaveLength(1);
+ expect(toolData.some(data => data.id === `pending-${index}` && data.phase === 'end')).toBe(false);
+ expect(archived[0].source_message_id).toBe(rows.find(row => row.from === 'user')?.id);
+ expect(archived[0].text).not.toContain('Public partial answer');
+ expect(JSON.stringify(archived[0].process)).toContain(`Public partial answer ${index}.`);
+ }
+ _resetStreamGates();
+ for (const cid of cids) {
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ expect((await groupChat.readMessages(TEST_UID, cid)).filter(row => row.system_kind === 'reply_interrupted')).toHaveLength(1);
+ }
+ expect(_recordedCalls).toHaveLength(2);
+ expect(hostErrorLog).not.toHaveBeenCalled();
+ expect(warningLog.mock.calls.map(call => call[0])).toEqual(unresponsive ? [] : ['stream error', 'stream error']);
+ }, 12_000);
+
+ // Provider output is controlled; mapping, segment settlement, JSONL storage,
+ // reload and the next turn's history tool are real. No external calendar runs.
+ it.each([
+ { actor: 'commander', split: 'none', ending: 'error' },
+ { actor: 'agent', split: 'none', ending: 'error' },
+ { actor: 'commander', split: 'before-writes', ending: 'error' },
+ { actor: 'commander', split: 'after-writes', ending: 'error' },
+ { actor: 'commander', split: 'before-writes', ending: 'empty' },
+ { actor: 'commander', split: 'before-writes', ending: 'abort' },
+ ])('retains completed writes for next-turn retrieval: $actor / $split / $ending', async ({ actor, split, ending }) => {
+ const chats = await import('../../../../src/main/features/chats');
+ const { conversation_id: cid } = await chats.createConversation(TEST_UID, { kind: 'normal' });
+ cidsToDrop.add(cid);
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const groupChat = await import('../../../../src/main/features/group_chat');
+ const { mapCoreAgentEvents } = await import('../../../../src/main/model/core-agent/event-mapper');
+ const expectedIds = Array.from({ length: 20 }, (_, index) => `calendar-insert-${index}`);
+ const outputs = expectedIds.map((id, index) => JSON.stringify({ id: `event-${index}`, status: 'confirmed', request_id: id,
+ ...(index === 19 ? { confirmation: 'lessonregistrationreceipt' } : {}),
+ }));
+ async function* completedWrites(): AsyncGenerator<any> {
+ for (const [index, id] of expectedIds.entries()) {
+ yield { type: 'tool_start', id, name: 'call_connector_tool', input: {
+ connector_id: 'fixture-calendar', tool_name: 'create_event', arguments: { title: `Lesson ${index}` },
+ } };
+ yield { type: 'tool_end', id, name: 'call_connector_tool', result: outputs[index], isError: false };
+ }
+ }
+ const writeEvents = [];
+ // Consume a live tool prefix; settlement is supplied by the script below.
+ // Reaching EOF without a terminal event is itself a protocol error.
+ for await (const event of mapCoreAgentEvents(completedWrites(), { nowMs: () => 0, failureTrackingScope: {} })) {
+ expect(event.type).not.toBe('error');
+ writeEvents.push(event);
+ if (event.type === 'event' && event.event.stream === 'tool'
+ && event.event.data?.phase === 'end' && event.event.data?.id === expectedIds[19]) break;
+ }
+ const dispatch = [
+ { type: 'delta', text: 'Ask Writer to check the schedule.' },
+ { type: '__call_tool__', name: 'dispatch_to', input: { to: AGENT_NAME, message: 'Check the schedule.' } },
+ ];
+ if (split !== 'none') _setScript(state.buildGmemberSessionId(cid, AGENT_ID), [{ type: 'final', text: 'Schedule checked.' }]);
+ const failure = { type: 'error', text: 'fixture provider rejected the continuation',
+ failureKind: 'model', failureCode: 'context_overflow', failurePhase: 'compaction', retryExhausted: true,
+ ...(ending === 'abort' ? { aborted: true } : {}),
+ };
+ const sid = actor === 'agent' ? state.buildGmemberSessionId(cid, AGENT_ID) : state.buildGconvSessionId(cid);
+ _setScript(sid, [
+ ...(split === 'before-writes' ? dispatch : []),
+ ...writeEvents,
+ ...(split === 'after-writes' ? dispatch : []),
+ ending === 'empty' ? { type: 'final', text: '' } : failure,
+ ]);
+ const events: any[] = [];
+ const unsubscribe = bus.subscribe(TEST_UID, cid, event => events.push(event));
+ try {
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Import the twenty lessons.',
+ ...(actor === 'agent' ? { forceTo: [AGENT_ID] } : {}),
+ });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ const owner = actor === 'agent' ? AGENT_ID : 'commander';
+ const receiptData = (items: any[]) => items.map(item => item.event)
+ .filter(event => event?.stream === 'tool' && event.data?.phase === 'end' && expectedIds.includes(event.data?.id))
+ .map(event => event.data);
+ const live = receiptData(events.filter(event => event.type === 'process' && event.actor === owner)
+ .map(event => event.data));
+ expect(live.map(data => data.id)).toEqual(expectedIds);
+ const stored = (await groupChat.readMessages(TEST_UID, cid)).filter(row => row.from === owner && !row.dispatch);
+ const receipts = receiptData(stored.flatMap(row => row.process || []));
+ expect.soft(receipts.map(data => data.id), 'every completed write must survive settlement exactly once').toEqual(expectedIds);
+ expect.soft(receipts.map(data => data.output)).toEqual(outputs);
+ if (split === 'before-writes' && ending === 'error') {
+ expect.soft(stored.find(row => receiptData(row.process || []).length)?.failure_code, 'saved receipts must not turn a failed run into success').toBe('context_overflow');
+ }
+ expect(_recordedCalls.filter(call => call.sid === sid)).toHaveLength(1);
+
+ // Start another user turn to exercise the authoritative current boundary.
+ // The fixture does not prescribe whether a real model chooses retrieval.
+ _setScript(sid, [{ type: 'final', text: 'Inspecting the retained execution records.' }]);
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Check prior writes before creating any more.', forceTo: [owner] });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ const rows = await groupChat.readMessages(TEST_UID, cid);
+ const boundary = rows.find(row => row.from === 'user' && row.text === 'Check prior writes before creating any more.')!;
+ const { createChatHistoryTool } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const history = createChatHistoryTool({ userId: TEST_UID, currentCid: cid, currentMessageId: boundary.id, allowedScopes: ['current'] });
+ const read = await history.execute({ action: 'read', scope: 'current', page: { mode: 'latest', count: 30 }, include_process: true, max_tokens: 10000 }, { state: {} } as any);
+ expect(read.isError, read.content).toBeFalsy();
+ expect.soft(expectedIds.filter(id => !read.content.includes(id)), 'next-turn retrieval must retain each successful write').toEqual([]);
+ if (split === 'before-writes' && ending === 'error') {
+ const found = await history.execute({ action: 'search', scope: 'current', query: 'lessonregistrationreceipt' }, { state: {} } as any);
+ expect(found.isError, found.content).toBeFalsy();
+ const locator = JSON.parse(/^ process_read: (.+)$/m.exec(found.content)?.[1] || 'null');
+ expect(locator, 'search must offer a usable process locator for the saved write').toBeTruthy();
+ const exact = await history.execute(locator, { state: {} } as any);
+ expect(exact.isError, exact.content).toBeFalsy();
+ expect(exact.content).toContain(expectedIds[19]);
+ }
+ expect(_recordedCalls.filter(call => call.sid === sid)).toHaveLength(2);
+ expect(_recordedToolResults.filter(result => result.name !== 'dispatch_to')).toHaveLength(0);
+ expect(hostErrorLog).not.toHaveBeenCalled();
+ expect(warningLog.mock.calls.map(call => call[0])).toEqual(ending === 'empty' ? [] : ['stream error']);
+ } finally {
+ unsubscribe();
+ }
+ }, 12_000);
+});
+
describe('group_chat bus integration › memory prose does not control execution', () => {
// The requester removed prose-based memory validation. Neither an explanation
// nor a completion claim may rewrite the reply, mutate memory, or create a
@@ -2757,6 +3222,7 @@ describe('group_chat bus integration › conversation delete cascade', () => {
});
describe('group_chat bus integration › G8d in-process dispatch (run_worker / dispatch_to)', () => {
+
it('settles an anonymous worker cancelled while waiting for capacity without starting it or disturbing holders', async () => {
const { workerSlots } = await import('../../../../src/main/util/locks');
const state = await import('../../../../src/main/features/group_chat/state');
@@ -2971,19 +3437,20 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
// The commander reads the result and synthesises within the SAME turn. The
// mock's `__call_tool__` drives the real tool execute() so the nested run
// actually streams (routed by its gworker/gmember session id).
- it('run_worker (anonymous) runs the worker IN-PROCESS and hands its full result back as the tool result — no roster member, no worker bubble, no lingering worker', async () => {
+ it.each([false, true])('run_worker (anonymous) returns its full private result without roster or session residue (rejected named dispatch first: %s)', async (rejectNamedFirst) => {
const cid = newCid();
const state = await import('../../../../src/main/features/group_chat/state');
const bus = await import('../../../../src/main/features/group_chat/bus');
const paths = await import('../../../../src/main/paths');
- const WORKER_RESULT = 'WORKER-INTERNAL-OUTPUT-7c1d: scanned 42 files, here is the full structured summary the commander needs.';
+ const WORKER_RESULT = JSON.stringify({ status: 'complete', order_count: 3, total_amount: 93, missing: [] });
// Commander's SINGLE turn: call run_worker with NO `to` (anonymous worker),
// then synthesise for the user in the SAME turn. G8d removed the re-wake —
// the worker's result returns as the tool result, in-process, so the
// commander reads it and continues without a second scheduled turn.
_setScript(state.buildGconvSessionId(cid), [
+ ...(rejectNamedFirst ? [{ type: '__call_tool__', name: 'dispatch_to', input: { to: 'Worker', message: 'scan the workspace and summarise' } }] : []),
{ type: '__call_tool__', name: 'run_worker', input: { task: 'scan the workspace and summarise' } },
{ type: 'final', text: 'Done — summarised the workspace for you.' },
]);
@@ -2999,6 +3466,18 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
// 1) The worker actually ran in-process: a gworker session turn fired.
const workerCall = _recordedCalls.find((c) => c.sid.startsWith('gworker-'));
expect(workerCall, 'an in-process worker sub-run should have streamed').toBeTruthy();
+ // Anonymous helpers have a private result recipient, not the named
+ // Agent's user-facing form, memory and handback protocols.
+ expect(workerCall!.systemPrompt).toMatch(/assigned sub-task/i);
+ expect(workerCall!.systemPrompt).toMatch(/blocker/i);
+ expect(workerCall!.systemPrompt).toMatch(/return.*Commander/i);
+ expect(workerCall!.systemPrompt).not.toMatch(/agent-input-form|<handback>|inputs_schema|cross.session memory/i);
+ expect(workerCall!.systemPrompt).toContain('## Runtime injection');
+ expect(workerCall!.systemPrompt).toContain('## User language');
+ expect(workerCall!.systemPrompt).not.toContain('$working_dir');
+ expect(workerCall!.systemPrompt.indexOf('## User language')).toBeGreaterThan(workerCall!.systemPrompt.indexOf('## Runtime injection'));
+ expect(workerCall!.systemPrompt.indexOf('## Current date')).toBeGreaterThan(workerCall!.systemPrompt.indexOf('## User language'));
+ expect(workerCall!.systemPrompt.length).toBeLessThan(1800);
expect(workerCall!.skillListPresent).toBe(true);
expect(workerCall!.skillList).toEqual([]);
expect(workerCall!.extraToolNames).not.toContain('skill_search');
@@ -3266,7 +3745,7 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
expect(commanderTurns, 'commander should run exactly one turn (no re-wake)').toBe(1);
}, 12_000);
- it.each([undefined, 'async'] as const)('Send now guides a dispatched Agent without replacing its task or losing the Commander result (mode: %s)', async (mode) => {
+ it.each([undefined, 'async', 'handoff', 'handoff-resume'] as const)('Send now guides a delegated Agent without replacing its task or losing its result delivery (mode: %s)', async (mode) => {
const cid = newCid();
const chats = await import('../../../../src/main/features/chats');
await chats.createConversation(TEST_UID, { conversationId: cid });
@@ -3276,14 +3755,19 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
const paths = await import('../../../../src/main/paths');
const commanderSid = state.buildGconvSessionId(cid);
const agentSid = state.buildGmemberSessionId(cid, AGENT_ID);
+ const handoff = mode === 'handoff' || mode === 'handoff-resume';
_holdStream('dispatch-steer');
_setScript(commanderSid, [
- { type: '__call_tool__', name: 'dispatch_to', input: {
- to: AGENT_NAME, message: 'Implement the feature.', ...(mode ? { mode } : {}),
+ { type: '__call_tool__', name: handoff ? 'hand_off_to' : 'dispatch_to', input: {
+ to: AGENT_NAME, message: 'Implement the feature.',
+ ...(mode === 'async' ? { mode } : {}),
+ ...(mode === 'handoff-resume' ? { resume: 'Review the completed result.' } : {}),
} },
- { type: 'final', text: 'Commander received the updated result.' },
+ ...(!handoff ? [{ type: 'final', text: 'Commander received the updated result.' }] : []),
]);
- if (mode) _setScript(commanderSid, [{ type: 'final', text: 'Commander received the updated result.' }]);
+ if (mode === 'async' || mode === 'handoff-resume') {
+ _setScript(commanderSid, [{ type: 'final', text: 'Commander received the updated result.' }]);
+ }
_setScript(agentSid, [
{ type: '__wait_for_gate__', name: 'dispatch-steer' },
{ type: '__accept_steer__' },
@@ -3299,6 +3783,7 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
expect(child).toMatchObject({ status: 'running', instruction: 'Implement the feature.' });
await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Discuss the plan first.', forceTo: [AGENT_ID] });
const queued = (await board.listTasks(TEST_UID, cid)).find(task => task.status === 'queued')!;
+ expect(_receivedSteers).toHaveLength(0);
expect(await bus.sendConversationTaskNow(TEST_UID, cid, queued.task_id)).toMatchObject({ ok: true, turn_id: child.turn_id });
_releaseStream('dispatch-steer');
await waitForQuiescent(TEST_UID, cid, 5000);
@@ -3318,7 +3803,17 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
const messages = fs.readFileSync(path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`), 'utf8')
.split('\n').filter(Boolean).map(line => JSON.parse(line));
expect(messages.filter(message => message.from === 'user' && message.text === 'Discuss the plan first.')).toHaveLength(1);
- if (mode) {
+ if (handoff) {
+ expect(messages.filter(message => message.from === AGENT_ID && message.turn_id === child.turn_id
+ && message.text.includes('The proposed implementation is ready for discussion.'))).toHaveLength(1);
+ expect(_recordedCalls.filter(call => call.sid === commanderSid))
+ .toHaveLength(mode === 'handoff-resume' ? 2 : 1);
+ if (mode === 'handoff-resume') {
+ expect(messages.some(message => message.from === 'commander'
+ && message.text === 'Commander received the updated result.')).toBe(true);
+ }
+ expect((await state.readState(TEST_UID, cid)).active_recipient).toBeUndefined();
+ } else if (mode) {
expect(messages.filter(message => message.dispatch && message.to.includes('commander')
&& message.model_text?.includes('The proposed implementation is ready for discussion.'))).toHaveLength(1);
} else {
@@ -3329,7 +3824,7 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
} finally { _releaseStream('dispatch-steer'); }
}, 12000);
- it('cancelling the parent after Send now settles both its dispatched child and absorbed update without replay', async () => {
+ it.each(['dispatch_to', 'hand_off_to'] as const)('cancelling %s after Send now settles the delegated task and absorbed update without replay', async (tool) => {
const cid = newCid();
const chats = await import('../../../../src/main/features/chats');
await chats.createConversation(TEST_UID, { conversationId: cid });
@@ -3340,8 +3835,8 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
const agentSid = state.buildGmemberSessionId(cid, AGENT_ID);
_holdStream('dispatch-steer-cancel');
_setScript(commanderSid, [
- { type: '__call_tool__', name: 'dispatch_to', input: { to: AGENT_NAME, message: 'Work on the feature.' } },
- { type: '__wait_for_abort__' },
+ { type: '__call_tool__', name: tool, input: { to: AGENT_NAME, message: 'Work on the feature.' } },
+ ...(tool === 'dispatch_to' ? [{ type: '__wait_for_abort__' }] : []),
]);
_setScript(agentSid, [
{ type: '__wait_for_gate__', name: 'dispatch-steer-cancel' },
@@ -3360,19 +3855,20 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
_releaseStream('dispatch-steer-cancel');
await vi.waitFor(async () => expect((await board.listTasks(TEST_UID, cid)).find(task => task.task_id === queued.task_id))
.toMatchObject({ status: 'running', absorbed_into_task_id: child.task_id }));
- expect(await bus.cancelConversationTask(TEST_UID, cid, parent.task_id)).toMatchObject({ ok: true });
+ expect(await bus.cancelConversationTask(TEST_UID, cid, tool === 'hand_off_to' ? child.task_id : parent.task_id))
+ .toMatchObject({ ok: true });
await waitForQuiescent(TEST_UID, cid, 5000);
const settled = await board.listTasks(TEST_UID, cid);
- for (const id of [parent.task_id, child.task_id, queued.task_id]) {
+ for (const id of [...(tool === 'dispatch_to' ? [parent.task_id] : []), child.task_id, queued.task_id]) {
expect(settled.find(task => task.task_id === id)?.status).toBe('cancelled');
}
expect(_receivedSteers).toHaveLength(1);
expect(_recordedCalls.filter(call => call.sid === agentSid)).toHaveLength(1);
expect(bus.runtimeSnapshot(TEST_UID, cid).activeTurns).toEqual([]);
- // These are the two expected cancellation diagnostics, not a failed
+ // These are the expected cancellation diagnostics, not a failed
// delivery/retry. Any other warning is an unexpected recovery path.
expect(warningLog.mock.calls.map(call => [call[0], call[1]?.aborted]))
- .toEqual([['stream error', true], ['stream error', true]]);
+ .toEqual(Array.from({ length: tool === 'dispatch_to' ? 2 : 1 }, () => ['stream error', true]));
} finally { _releaseStream('dispatch-steer-cancel'); }
}, 12000);
@@ -3462,6 +3958,7 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
await vi.waitFor(() => expect(bus._cidStateForTest(TEST_UID, cid)).toBeNull());
} else await bus.abort(TEST_UID, cid);
await waitForQuiescent(TEST_UID, cid, 5000);
+ expect(_recordedCalls.find(call => call.sid === state.buildGmemberSessionId(cid, AGENT_ID))?.outputDelivery).toBe('process');
const turns = _recordedCalls.filter(c => c.sid === commander);
expect(turns).toHaveLength(scope === 'child' ? 2 : 1);
if (scope === 'child') expect(turns[1].message).toContain('aborted="true"');
@@ -4540,10 +5037,9 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
&& Array.isArray(event.active_turns)
&& event.active_turns.some((turn: any) => turn.actor === AGENT_ID));
expect(agentActive.length).toBeGreaterThan(0);
- expect(agentActive.every((event: any) => event.active_turns
- .filter((turn: any) => turn.actor === AGENT_ID)
- .every((turn: any) => turn.steerable === false)),
- 'follow-up user input stays FIFO instead of mutating the admitted hand-off run').toBe(true);
+ expect(bus.runtimeSnapshot(TEST_UID, cid).activeTurns).toContainEqual(
+ expect.objectContaining({ actor: AGENT_ID, steerable: true }),
+ );
_releaseStream('terminal-handoff-agent');
await waitForQuiescent(TEST_UID, cid, 4000);
@@ -4657,10 +5153,10 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
'the delegated turn must expose a stable execution start for elapsed-time recovery',
).toBe(true);
expect(
- tutorActive.every((e: any) => e.active_turns
+ tutorActive.some((e: any) => e.active_turns
.filter((t: any) => t.actor === tutorId)
- .every((t: any) => t.steerable === false)),
- 'terminal hand-offs must never advertise active-turn user ingress',
+ .some((t: any) => t.steerable === true)),
+ 'interactive hand-offs expose live input once the runtime is ready',
).toBe(true);
expect(
tutorActive.every((e: any) => !e.active_turns.some((t: any) => t.actor === 'commander')),
@@ -5769,6 +6265,79 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
expect(st.orchestration_ledger).toBeUndefined();
}, 20_000);
+ it.each([false, true])('assigns final delivery from the pending Commander continuation (resume: %s)', async (resume) => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const agentId = 'c6a2b3c4d5e6';
+ await writeInteractiveAgent(agentId, 'DeliveryStudio');
+ const commanderSid = state.buildGconvSessionId(cid);
+ const agentSid = state.buildGmemberSessionId(cid, agentId);
+ _setScript(commanderSid, [
+ { type: '__call_tool__', name: 'hand_off_to', input: {
+ to: 'DeliveryStudio', message: 'Prepare the requested result.',
+ ...(resume ? { resume: 'Finish the remaining comparison.' } : {}),
+ } },
+ { type: 'final', text: 'Over to DeliveryStudio.' },
+ ]);
+ _setScript(agentSid, [{ type: 'final', text: 'Which audience?\n<plan-interaction status="open" />' }]);
+ bus.subscribe(TEST_UID, cid, () => {});
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Prepare the result for me.' });
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ const expected = resume
+ ? 'Return the result to Commander, who will continue the remaining work.'
+ : 'Deliver the final result to the user; completion returns only the conversation floor to Commander.';
+ const opposite = resume
+ ? 'Deliver the final result to the user; completion returns only the conversation floor to Commander.'
+ : 'Return the result to Commander, who will continue the remaining work.';
+ const first = _recordedCalls.find(call => call.sid === agentSid)!;
+ expect(first.message).toContain(expected);
+ expect(first.message).not.toContain(opposite);
+ let current = await state.readState(TEST_UID, cid);
+ expect(current.active_recipient).toBe(agentId);
+ expect(!!current.orchestration_ledger).toBe(resume);
+ expect(_recordedCalls.filter(call => call.sid === commanderSid)).toHaveLength(1);
+ _setScript(agentSid, [{ type: 'final', text: 'RESULT-DELIVERED\n<handback reason="completed_handoff" />' }]);
+ if (resume) _setScript(commanderSid, [{ type: 'final', text: 'COMPARISON-DELIVERED' }]);
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'For new users.' });
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ const agentCalls = _recordedCalls.filter(call => call.sid === agentSid);
+ expect(agentCalls).toHaveLength(2);
+ expect(agentCalls[1].message).toContain(expected);
+ expect(_recordedCalls.filter(call => call.sid === commanderSid)).toHaveLength(resume ? 2 : 1);
+ current = await state.readState(TEST_UID, cid);
+ expect(current.active_recipient).toBeUndefined();
+ expect(current.orchestration_ledger).toBeUndefined();
+ const group = await import('../../../../src/main/features/group_chat');
+ const rows = await group.readMessages(TEST_UID, cid);
+ expect(rows.filter(row => row.from === agentId && row.text === 'RESULT-DELIVERED')).toHaveLength(1);
+ expect(rows.filter(row => row.from === 'commander' && row.text === 'COMPARISON-DELIVERED')).toHaveLength(resume ? 1 : 0);
+ }, 15_000);
+
+ it.each(['interrupted', 'another-agent'] as const)('does not assign Commander continuation from a %s ledger', async (mode) => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const agentId = 'c7a2b3c4d5e6';
+ await writeInteractiveAgent(agentId, 'FloorStudio');
+ await state.setActiveRecipient(TEST_UID, cid, agentId, 'commander_handoff');
+ await state.setOrchestrationLedger(TEST_UID, cid, {
+ status: mode === 'interrupted' ? 'interrupted' : 'waiting_for_agent', blocked_on: 'agent_handoff',
+ owner_agent_id: mode === 'another-agent' ? 'c8a2b3c4d5e6' : agentId,
+ user_goal: 'Another pending workflow.', handoff_message: 'Finish the step.', resume_instruction: 'Continue the workflow.',
+ });
+ const sid = state.buildGmemberSessionId(cid, agentId);
+ _setScript(sid, [{ type: 'final', text: 'Which audience?\n<plan-interaction status="open" />' }]);
+ bus.subscribe(TEST_UID, cid, () => {});
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Prepare the result.' });
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ const call = _recordedCalls.find(call => call.sid === sid)!;
+ expect(call.message).toContain('Deliver the final result to the user; completion returns only the conversation floor to Commander.');
+ expect(call.message).not.toContain('who will continue the remaining work');
+ expect(_recordedCalls.some(call => call.sid === state.buildGconvSessionId(cid))).toBe(false);
+ expect((await state.readState(TEST_UID, cid)).active_recipient).toBe(agentId);
+ }, 15_000);
+
it('keeps an interactive hand-off open until the agent hands back explicitly', async () => {
const cid = newCid();
const state = await import('../../../../src/main/features/group_chat/state');
@@ -5989,6 +6558,7 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
bus.subscribe(TEST_UID, cid, () => {});
await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: '做个视频' });
await waitForQuiescent(TEST_UID, cid, 5000);
+ expect(_recordedCalls.find(call => call.sid === coachSid)?.outputDelivery).toBe('final');
_setScript(coachSid, [{ type: 'final', text: 'Here is the finished video.' }]);
await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: '可以' });
await waitForQuiescent(TEST_UID, cid, 5000);
@@ -7024,6 +7594,11 @@ describe('group_chat bus integration › task terminal boundary', () => {
expect(await waitUntil(() => bus._cidStateForTest(TEST_UID, cid) === null)).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 25));
expect(terminals).toHaveLength(1);
+ const taskBoard = await import('../../../../src/main/features/group_chat/task_board');
+ const tasks = await taskBoard.listTasks(TEST_UID, cid);
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0].status).toBe('cancelled');
+ expect(hostErrorLog.mock.calls).toEqual([]);
unsubscribe();
}, 10_000);
});
@@ -9595,6 +10170,81 @@ describe('group_chat bus integration › D29 planned dispatch', () => {
expect(calls[1]).toContain('KEEP_GOING_WITH_THE_ENDING');
expect(_recordedCalls.some((c) => c.sid === state.buildGconvSessionId(cid))).toBe(false);
}, 15_000);
+
+ // Planning takes seconds before any board row exists. The send must read as
+ // being arranged for that whole window, and every way planning ends must
+ // clear that state: a leftover would keep "arranging" on the board forever.
+ it.each(['planned', 'fallback', 'stopped'] as const)(
+ 'reports the send as being arranged until planning ends (%s)', async (outcome) => {
+ await seedSecondAgent();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const groupChat = await import('../../../../src/main/features/group_chat');
+ const cid = newCid();
+ _setScript(state.buildGmemberSessionId(cid, AGENT_ID), [{ type: 'final', text: 'draft written' }]);
+ _setScript(state.buildGmemberSessionId(cid, SECOND_AGENT_ID), [{ type: 'final', text: 'draft reviewed' }]);
+ _setScript(state.buildGconvSessionId(cid), [{ type: 'final', text: 'work arranged' }]);
+ const events: any[] = [];
+ bus.subscribe(TEST_UID, cid, (ev) => events.push(ev));
+ let planning = false;
+ let finish!: (raw: string) => void;
+ // The planner does not observe Stop here, like a model call still
+ // resolving its provider: Stop alone must settle the arranging state.
+ await installPlanner(() => new Promise<string>((resolve) => {
+ planning = true;
+ finish = resolve;
+ }));
+ const text = `@${AGENT_NAME} write a draft, then @${SECOND_AGENT_NAME} review it`;
+ const send = bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text });
+ expect(await waitUntil(() => planning)).toBe(true);
+ const arranging = (await groupChat.listTasks(TEST_UID, cid)).planning;
+ expect(arranging).toHaveLength(1);
+ expect(arranging[0].preview).toBe(text);
+ expect(events.filter((ev) => ev.type === 'task_created')).toEqual([]);
+
+ if (outcome === 'stopped') {
+ const stopping = bus.abort(TEST_UID, cid);
+ // Stop tears the renderer's streams down first and its board re-reads
+ // at once: the send must not still read as arranging, even before
+ // planning unwinds.
+ expect((await groupChat.listTasks(TEST_UID, cid)).planning).toEqual([]);
+ finish(await planFor([{ assignee: 'a1', part: 'Write the draft' }])());
+ await stopping;
+ } else if (outcome === 'fallback') {
+ finish('not a plan');
+ } else {
+ finish(await planFor([
+ { assignee: 'a1', part: 'Write the draft' },
+ { assignee: 'a2', part: 'Review the draft', after: ['t1'] },
+ ])());
+ }
+ const msg = await send;
+ await waitForQuiescent(TEST_UID, cid, 6000);
+
+ expect(arranging[0].message_id).toBe(msg.id);
+ const lifecycle = events
+ .filter((ev) => ev.type === 'dispatch_planning' || ev.type === 'task_created')
+ .map((ev) => (ev.type === 'task_created'
+ ? `created:${ev.task.assignee}`
+ : `${ev.active ? 'arranging' : 'arranged'}:${ev.message_id === msg.id}`));
+ expect(lifecycle).toEqual({
+ planned: ['arranging:true', `created:${AGENT_ID}`, `created:${SECOND_AGENT_ID}`, 'arranged:true'],
+ fallback: ['arranging:true', 'created:commander', 'arranged:true'],
+ stopped: ['arranging:true', 'arranged:true'],
+ }[outcome]);
+ expect((await groupChat.listTasks(TEST_UID, cid)).planning).toEqual([]);
+ }, 15_000);
+
+ it('never reports a send that needs no planning as being arranged', async () => {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const cid = newCid();
+ const events: any[] = [];
+ bus.subscribe(TEST_UID, cid, (ev) => events.push(ev));
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: `@${AGENT_NAME} write a draft` });
+ await waitForQuiescent(TEST_UID, cid, 6000);
+ expect(events.some((ev) => ev.type === 'task_created')).toBe(true);
+ expect(events.some((ev) => ev.type === 'dispatch_planning')).toBe(false);
+ }, 15_000);
});
describe('group_chat bus integration › chip-set floor before first dispatch', () => {
diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.ts
index 29ebb4de..6ae170d1 100644
--- a/test/main/features/group_chat/bus.test.ts
+++ b/test/main/features/group_chat/bus.test.ts
@@ -203,10 +203,10 @@ vi.mock('../../../../src/main/model/client', () => ({
if (isCommanderTurn && steerDispatchIndex >= 0) {
const data = JSON.parse(Buffer.from(message.slice(steerDispatchIndex + steerDispatchMarker.length)
.split(/\s/, 1)[0], 'base64').toString('utf8'));
- const tool = _opts.extraTools.find((candidate: any) => candidate.name === 'dispatch_to');
+ const tool = _opts.extraTools.find((candidate: any) => candidate.name === (data.tool || 'dispatch_to'));
const result = await tool.execute({ to: AGENT_NAME, message: data.task }, { signal: _opts.abortSignal });
streamProbe.dispatchResults.push(String(result?.content || ''));
- yield { type: 'final', text: 'Commander received the CLI result.' };
+ yield { type: 'final', text: data.tool === 'hand_off_to' ? '' : 'Commander received the CLI result.' };
yield { type: 'done' };
return;
}
@@ -289,6 +289,7 @@ vi.mock('../../../../src/main/model/client', () => ({
const encoded = message.slice(publishedIdx + publishedMarker.length).split(/\s/, 1)[0];
const data = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8'));
for (const p of data.paths || []) await _opts?.onFileWritten?.(p);
+ if (data.holdAfterWrite && streamProbe.slowGate) await streamProbe.slowGate;
const publications = Array.isArray(data.publications)
? data.publications
: [data.published || []];
@@ -2460,6 +2461,79 @@ describe('group_chat bus › enqueue routing + persistence', () => {
}
});
+ it('finalizes only the visible terminal deliverable, leaving supporting files untouched', async () => {
+ const hooks = await import('../../../../src/main/features/produced_output_hooks');
+ const finalized: string[] = [];
+ const unregister = hooks.registerProducedOutputHooks({
+ finalizeFile: async (file) => { finalized.push(file); },
+ });
+ let sourcePath = '';
+ let previewPath = '';
+ let finalPath = '';
+ try {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const cid = 'cid-produced-finalization';
+ sourcePath = path.join(tmpDir, 'workspace', 'report.md');
+ previewPath = path.join(tmpDir, 'workspace', 'preview-cover.png');
+ finalPath = path.join(tmpDir, 'workspace', 'report.pdf');
+ for (const [file, body] of [
+ [sourcePath, '# source'],
+ [previewPath, 'preview'],
+ [finalPath, 'pdf'],
+ ] as const) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, body);
+ }
+
+ await bus.enqueue({
+ uid: TEST_UID,
+ cid,
+ fromActorId: 'user',
+ text: `PRODUCED_FILTER_TEST:${Buffer.from(JSON.stringify({
+ paths: [sourcePath, previewPath, finalPath],
+ })).toString('base64')}`,
+ });
+ await waitForQuiescent(TEST_UID, cid);
+
+ expect(finalized).toEqual([finalPath]);
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('# source');
+ expect(fs.readFileSync(previewPath, 'utf8')).toBe('preview');
+
+ expect(fs.readFileSync(finalPath, 'utf8')).toBe('pdf');
+ } finally {
+ unregister();
+ }
+ });
+
+ it('keeps a generated audio file out of the composer while its producing turn is still running', async () => {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const attachments = await import('../../../../src/main/features/chat_attachments');
+ const layout = await import('../../../../src/main/util/project-layout');
+ const cid = 'cid-live-generated-audio';
+ const audio = path.join(layout.chatAttachmentDirForConversation(TEST_UID, cid), 'narration.mp3');
+ fs.mkdirSync(path.dirname(audio), { recursive: true });
+ fs.writeFileSync(audio, 'generated audio bytes');
+ let release!: () => void;
+ streamProbe.slowGate = new Promise<void>(resolve => { release = resolve; });
+ try {
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user',
+ text: `PUBLISHED_OUTPUT_TEST:${Buffer.from(JSON.stringify({
+ paths: [audio], published: [], holdAfterWrite: true,
+ })).toString('base64')}`,
+ });
+ await vi.waitFor(() => expect(bus._cidStateForTest(TEST_UID, cid)?.producedPaths.has(audio)).toBe(true));
+ await vi.waitFor(() => expect(attachments.listPendingAttachments(TEST_UID, cid)).toEqual([]));
+ expect(attachments.listAttachments(TEST_UID, cid).map(item => item.name)).toEqual(['narration.mp3']);
+ } finally {
+ release();
+ await waitForQuiescent(TEST_UID, cid);
+ streamProbe.slowGate = null;
+ }
+ // Even an intermediate file omitted from the final deliverables remains
+ // an output, never an implicit attachment on the user's next message.
+ expect(attachments.listPendingAttachments(TEST_UID, cid)).toEqual([]);
+ });
+
it('finalizes explicitly published exported videos on terminal delivery', async () => {
const hooks = await import('../../../../src/main/features/produced_output_hooks');
const finalized: string[] = [];
@@ -3128,7 +3202,10 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(rows[1].result_msg_id).toBe(rows[0].result_msg_id);
});
- it.each(['steered', 'queued_followup', 'unavailable'] as const)('Send now into a Commander-dispatched CLI preserves the task and result when ingress is %s', async (mode) => {
+ it.each([
+ ['dispatch_to', 'steered'], ['dispatch_to', 'queued_followup'], ['dispatch_to', 'unavailable'],
+ ['hand_off_to', 'steered'], ['hand_off_to', 'queued_followup'], ['hand_off_to', 'unavailable'],
+ ] as const)('Send now into a %s CLI preserves the task and result when ingress is %s', async (tool, mode) => {
const paths = await import('../../../../src/main/paths');
const agentFile = path.join(paths.agentDir(TEST_UID, AGENT_ID), 'agent.json');
const spec = JSON.parse(fs.readFileSync(agentFile, 'utf8'));
@@ -3144,13 +3221,13 @@ describe('group_chat bus › enqueue routing + persistence', () => {
};
const bus = await import('../../../../src/main/features/group_chat/bus');
const board = await import('../../../../src/main/features/group_chat/task_board');
- const cid = `cid-dispatched-cli-steer-${mode}`;
+ const cid = `cid-${tool}-cli-steer-${mode}`;
cidsToDrop.add(cid);
const chats = await import('../../../../src/main/features/chats');
await chats.createConversation(TEST_UID, { conversationId: cid });
try {
await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user',
- text: `CLI_STEER_DISPATCH_TEST:${Buffer.from(JSON.stringify({ task: 'Implement the CLI feature.' })).toString('base64')}` });
+ text: `CLI_STEER_DISPATCH_TEST:${Buffer.from(JSON.stringify({ tool, task: 'Implement the CLI feature.' })).toString('base64')}` });
await vi.waitFor(() => expect(cliRunMock.calls).toHaveLength(1));
expect(bus.runtimeSnapshot(TEST_UID, cid).activeTurns).toEqual([
expect.objectContaining({ actor: AGENT_ID, steerable: mode !== 'unavailable' }),
@@ -3158,6 +3235,7 @@ describe('group_chat bus › enqueue routing + persistence', () => {
const child = (await board.listTasks(TEST_UID, cid)).find(task => task.created_by === 'commander')!;
await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Discuss the plan first.', forceTo: [AGENT_ID] });
const queued = (await board.listTasks(TEST_UID, cid)).find(task => task.status === 'queued')!;
+ expect(cliRunMock.submittedSteers).toHaveLength(0);
const promotion = await bus.sendConversationTaskNow(TEST_UID, cid, queued.task_id);
if (mode === 'unavailable') {
expect(promotion).toEqual({ ok: false, error: 'turn_not_steerable' });
@@ -3184,13 +3262,15 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(settledChild).toMatchObject({ status: 'done', instruction: 'Implement the CLI feature.' });
expect(update.status).toBe('done');
expect(streamProbe.dispatchResults).toHaveLength(1);
- expect(streamProbe.dispatchResults[0]).toContain('CLI task result.');
+ expect(streamProbe.dispatchResults[0]).toContain(tool === 'hand_off_to' ? '"ok":true' : 'CLI task result.');
expect(cliRunMock.calls).toHaveLength(mode === 'steered' ? 1 : 2);
if (mode === 'steered') expect(update.result_msg_id).toBe(settledChild.result_msg_id);
else expect(cliRunMock.calls[1].prompt).toContain('Discuss the plan first.');
const messages = fs.readFileSync(path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`), 'utf8')
.split('\n').filter(Boolean).map(line => JSON.parse(line));
expect(messages.filter(message => message.from === 'user' && message.text === 'Discuss the plan first.')).toHaveLength(1);
+ expect(messages.filter(message => message.from === AGENT_ID && message.turn_id === child.turn_id
+ && message.text === 'CLI task result.')).toHaveLength(1);
expect(loggerMocks.warn).not.toHaveBeenCalled();
} finally {
cliRunMock.activeIngress = null;
@@ -3785,6 +3865,8 @@ describe('group_chat bus › enqueue routing + persistence', () => {
const cliWireContext = `${cliRunMock.calls[0].systemPrompt || ''}\n${cliRunMock.calls[0].prompt || ''}`;
expect(cliWireContext).toContain('COMMANDER_CLI_LEDGER_ROUTE_TEST');
expect(cliWireContext).toContain('CLI_LEDGER_TASK_TEST');
+ expect(cliRunMock.calls[0].prompt).toContain('Return the result to Commander, who will continue the remaining work.');
+ expect(cliRunMock.calls[0].prompt).not.toContain('completion returns only the conversation floor');
expect(cliRunMock.calls[0].prompt).not.toContain('<referenced-messages>');
expect(cliWireContext.match(/COMMANDER_CLI_LEDGER_ROUTE_TEST/g)).toHaveLength(1);
const resumeInput = streamProbe.messages.find((message) => (
@@ -3840,6 +3922,8 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(cliRunMock.calls).toHaveLength(1);
expect(cliRunMock.calls[0].prompt).toContain('## Return control to commander');
+ expect(cliRunMock.calls[0].prompt).toContain('Deliver the final result to the user; completion returns only the conversation floor to Commander.');
+ expect(cliRunMock.calls[0].prompt).not.toContain('who will continue the remaining work');
expect(cliRunMock.calls[0].prompt).toContain('Use `<handback reason="completed_handoff" />` only to close this routed interaction.');
expect(cliRunMock.calls[0].prompt).not.toContain('primary outcome exceeds');
let floor = await state.readState(TEST_UID, cid);
@@ -5867,6 +5951,76 @@ describe('group_chat bus › enqueue routing + persistence', () => {
});
describe('group_chat bus › abort', () => {
+ it.each(['commander', 'agent', 'codex'])(
+ 'retains the executing %s through terminal persistence so crash recovery keeps its identity', async runtime => {
+ const paths = await import('../../../../src/main/paths');
+ const storage = await import('../../../../src/main/storage');
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const chats = await import('../../../../src/main/features/chats');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const actorId = runtime === 'commander' ? 'commander' : AGENT_ID;
+ if (runtime === 'codex') {
+ const file = path.join(paths.agentDir(TEST_UID, AGENT_ID), 'agent.json');
+ const spec = JSON.parse(fs.readFileSync(file, 'utf8'));
+ spec.runtime = { kind: 'cli', cli: 'codex' };
+ fs.writeFileSync(file, JSON.stringify(spec));
+ }
+ const cid = `cid-persist-owner-${runtime}`;
+ cidsToDrop.add(cid);
+ const mainFile = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ const originalAppend = storage.appendJsonlAtomic;
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let entered = false;
+ const append = vi.spyOn(storage, 'appendJsonlAtomic').mockImplementation(async (...args) => {
+ const row = args[1] as any;
+ if (args[0] === mainFile && row.from === actorId && row.source_message_id) {
+ entered = true;
+ await gate;
+ }
+ return originalAppend(...args);
+ });
+ try {
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', forceTo: [actorId],
+ text: 'NON_CLI_PHASED_TEXT_TEST' });
+ await vi.waitFor(() => expect(entered).toBe(true), { timeout: 5000 });
+ const durable = await state.readState(TEST_UID, cid);
+ expect(bus.runtimeSnapshot(TEST_UID, cid).processing).toBe(true);
+ const input = fs.readFileSync(mainFile, 'utf8').trim().split('\n').map(line => JSON.parse(line)).find(row => row.from === 'user');
+ expect(durable.in_flight_turns?.[actorId]).toMatchObject({
+ source_message_id: input.id, turn_id: expect.any(String),
+ });
+
+ // Replay the actual pre-append disk snapshot under a separate cid:
+ // the recovery fixture supplies no actor that the real run lost.
+ const copy = await chats.createConversation(TEST_UID);
+ cidsToDrop.add(copy.conversation_id);
+ fs.copyFileSync(mainFile, path.join(paths.userChatsDir(TEST_UID), `${copy.conversation_id}.jsonl`));
+ fs.copyFileSync(paths.groupChatMembersFile(TEST_UID, cid), paths.groupChatMembersFile(TEST_UID, copy.conversation_id));
+ fs.writeFileSync(paths.groupChatStateFile(TEST_UID, copy.conversation_id), JSON.stringify({
+ ...durable, last_active_at: new Date(Date.now() - 60_000).toISOString(),
+ }));
+ const journalFile = paths.userRunningConversationsFile(TEST_UID);
+ const journal = JSON.parse(fs.readFileSync(journalFile, 'utf8'));
+ journal.items.push({ conversation_id: copy.conversation_id });
+ fs.writeFileSync(journalFile, JSON.stringify(journal));
+ expect((await chats.sweepStaleProcessing(TEST_UID)).swept).toBe(1);
+ const recovered = fs.readFileSync(path.join(paths.userChatsDir(TEST_UID), `${copy.conversation_id}.jsonl`), 'utf8')
+ .trim().split('\n').map(line => JSON.parse(line));
+ expect(recovered.at(-1)).toMatchObject({ from: actorId, system_kind: 'reply_interrupted', ...durable.in_flight_turns?.[actorId] });
+ expect(durable.in_flight).toEqual([actorId]);
+ } finally {
+ release();
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ append.mockRestore();
+ }
+ expect((await state.readState(TEST_UID, cid)).in_flight).toEqual([]);
+ expect((await state.readState(TEST_UID, cid)).in_flight_turns).toBeUndefined();
+ const rows = fs.readFileSync(mainFile, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ expect(rows.filter(row => row.from === actorId && row.source_message_id)).toHaveLength(1);
+ },
+ );
+
it('flips state.json to aborted + clears the queue', async () => {
const bus = await import('../../../../src/main/features/group_chat/bus');
const state = await import('../../../../src/main/features/group_chat/state');
@@ -6352,7 +6506,7 @@ describe('deferred user-message bubble (queued-until-execution, 2026-08-27)', ()
expect(streamProbe.messages.join('\n')).not.toContain('message that must never send');
});
- it('board send-now persists the queued message at the fold and absorbs its row', async () => {
+ it('board send-now publishes the sent message before model acceptance and later settles its row', async () => {
const bus = await import('../../../../src/main/features/group_chat/bus');
const taskBoard = await import('../../../../src/main/features/group_chat/task_board');
const cid = 'cid-deferred-send-now';
@@ -6369,9 +6523,15 @@ describe('deferred user-message bubble (queued-until-execution, 2026-08-27)', ()
const res = await bus.sendConversationTaskNow(TEST_UID, cid, queued!.task_id);
expect(res).toMatchObject({ ok: true });
- // Send-now IS the start of execution (D21): the message persists right
- // here, while the live turn is still running. The board row survives as
- // the durable record and settles through the absorbed/leftover path.
+ expect(res).toMatchObject({
+ message: { id: queued!.source_msg_id, from: 'user', text: 'fold me into the live turn' },
+ task: { task_id: queued!.task_id, status: 'queued', message_sent_at: expect.any(String) },
+ });
+ const sent = (await taskBoard.listTasks(TEST_UID, cid)).find(t => t.task_id === queued!.task_id)!;
+ expect(sent.message_sent_at).toBeTruthy();
+ expect(sent.absorbed_into_turn_id).toBeUndefined();
+ // Sending persists the bubble while the model is still held. It does
+ // not claim that the runtime consumed the update or started another turn.
expect(await userRows(cid)).toEqual([
'DEFERRED_SLOW_TURN_TEST live',
'fold me into the live turn',
@@ -6393,6 +6553,37 @@ describe('deferred user-message bubble (queued-until-execution, 2026-08-27)', ()
expect(['done', 'stopped', 'failed', 'cancelled']).toContain(promoted?.status);
});
+ it('keeps a send-now row unsent when message persistence fails', async () => {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const taskBoard = await import('../../../../src/main/features/group_chat/task_board');
+ const storage = await import('../../../../src/main/storage');
+ const cid = 'cid-send-now-persist-failure';
+ cidsToDrop.add(cid);
+ let release: () => void = () => {};
+ streamProbe.slowGate = new Promise<void>((resolve) => { release = resolve; });
+ let append: ReturnType<typeof vi.spyOn> | undefined;
+ try {
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'DEFERRED_SLOW_TURN_TEST live' });
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'Unsent correction' });
+ const queued = (await taskBoard.listTasks(TEST_UID, cid)).find(t => t.status === 'queued')!;
+ append = vi.spyOn(storage, 'appendJsonlAtomic').mockRejectedValueOnce(new Error('injected history failure'));
+ expect(await bus.sendConversationTaskNow(TEST_UID, cid, queued.task_id))
+ .toMatchObject({ ok: false, error: 'persist_failed' });
+ const retained = (await taskBoard.listTasks(TEST_UID, cid)).find(t => t.task_id === queued.task_id)!;
+ expect(retained.status).toBe('queued');
+ expect(retained.message_sent_at).toBeUndefined();
+ expect(retained.absorbed_into_turn_id).toBeUndefined();
+ expect(await userRows(cid)).toEqual(['DEFERRED_SLOW_TURN_TEST live']);
+ expect(loggerMocks.warn).toHaveBeenCalledWith('task send-now persist failed', expect.any(Object));
+ await bus.cancelConversationTask(TEST_UID, cid, queued.task_id);
+ } finally {
+ append?.mockRestore();
+ release();
+ streamProbe.slowGate = null;
+ }
+ await waitForQuiescent(TEST_UID, cid, 5000);
+ });
+
it('creates no task when a planned send cannot persist its message', async () => {
const storage = await import('../../../../src/main/storage');
const append = vi.spyOn(storage, 'appendJsonlAtomic')
diff --git a/test/main/features/group_chat/message-display.test.ts b/test/main/features/group_chat/message-display.test.ts
index da0d01d4..a341e83f 100644
--- a/test/main/features/group_chat/message-display.test.ts
+++ b/test/main/features/group_chat/message-display.test.ts
@@ -2,6 +2,15 @@ import { describe, expect, it } from 'vitest';
import { classifyNativeCommentary, normalizeNativeMessageDisplay, commanderMentionDisplayText, stripReservedRoutingMentions } from '../../../../src/main/features/group_chat/message-display';
describe('native transcript classification', () => {
+ it.each([{ process: [] }, { process: [{ type: 'event' as const,
+ event: { stream: 'runtime', data: { phase: 'interrupted', duration_ms: 13374 } } }] }])(
+ 'keeps a structured interruption notice in the reply body regardless of clock availability', ({ process }) => {
+ const record = { id: 'interrupted', ts: '2026-10-26T14:31:24', from: 'codex', to: ['user'],
+ turn_id: 't', source_message_id: 'u', seg: 0, system_kind: 'reply_interrupted' as const,
+ text: 'The previous reply was interrupted.', process };
+ expect(normalizeNativeMessageDisplay(record)).toBe(record);
+ });
+
it('stores commentary once while preserving the original source and tool order', () => {
const record = { id: 'm0', ts: '2026-10-14T00:00:00', from: 'claude', to: ['user'],
turn_id: 't', source_message_id: 'u', seg: 0, text: ' ## Complete report\n原文\n',
diff --git a/test/main/features/group_chat/state.test.ts b/test/main/features/group_chat/state.test.ts
index 874ce4d7..89cbd405 100644
--- a/test/main/features/group_chat/state.test.ts
+++ b/test/main/features/group_chat/state.test.ts
@@ -42,6 +42,46 @@ describe('group_chat state › sessionId builders', () => {
});
});
+describe('group_chat state › durable executing turn identity', () => {
+ it('retains each turn across other state writes and clears only the settled actor', async () => {
+ const state = await import('../../../../src/main/features/group_chat/state');
+ await state.setStatus(TEST_UID, TEST_CID, 'running');
+ const a = { turn_id: 'turn-a', source_message_id: 'source-a' };
+ const b = { turn_id: 'turn-b', source_message_id: 'source-b' };
+ await state.markInFlight(TEST_UID, TEST_CID, 'agent-a', true, a);
+ await state.markInFlight(TEST_UID, TEST_CID, 'agent-b', true, b);
+ await state.markInFlight(TEST_UID, TEST_CID, 'agent-a', true);
+ await state.setActiveRecipient(TEST_UID, TEST_CID, 'agent-b', 'user_selection');
+ vi.resetModules();
+ const reloaded = await import('../../../../src/main/features/group_chat/state');
+ expect(await reloaded.readState(TEST_UID, TEST_CID)).toMatchObject({
+ in_flight: ['agent-a', 'agent-b'], in_flight_turns: { 'agent-a': a, 'agent-b': b },
+ });
+ await reloaded.markInFlight(TEST_UID, TEST_CID, 'agent-a', false);
+ expect(await reloaded.readState(TEST_UID, TEST_CID)).toMatchObject({
+ in_flight: ['agent-b'], in_flight_turns: { 'agent-b': b },
+ });
+ expect((await reloaded.readState(TEST_UID, TEST_CID)).in_flight_turns?.['agent-a']).toBeUndefined();
+ await reloaded.setStatus(TEST_UID, TEST_CID, 'idle');
+ expect((await reloaded.readState(TEST_UID, TEST_CID)).in_flight_turns).toBeUndefined();
+ });
+
+ it('reads legacy and malformed turn metadata without losing the actor roster or retaining foreign entries', async () => {
+ const paths = await import('../../../../src/main/paths');
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const file = paths.groupChatStateFile(TEST_UID, TEST_CID);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ for (const metadata of [undefined, [], 'invalid', { 'agent-a': { turn_id: 'turn-a', source_message_id: 'source-a', extra: 'drop' },
+ 'agent-b': { turn_id: '../bad', source_message_id: 'source-b' }, foreign: { turn_id: 'turn-c', source_message_id: 'source-c' } }]) {
+ fs.writeFileSync(file, JSON.stringify({ version: 1, status: 'running', in_flight: ['agent-a', 'agent-b'], in_flight_turns: metadata }));
+ const current = await state.readState(TEST_UID, TEST_CID);
+ expect(current.in_flight).toEqual(['agent-a', 'agent-b']);
+ expect(current.in_flight_turns).toEqual(metadata && !Array.isArray(metadata) && typeof metadata === 'object'
+ ? { 'agent-a': { turn_id: 'turn-a', source_message_id: 'source-a' } } : undefined);
+ }
+ });
+});
+
describe('group_chat state › addMember + ensureAgentMember', () => {
it('addMember idempotent — second call with same id returns false', async () => {
const s = await import('../../../../src/main/features/group_chat/state');
diff --git a/test/main/features/recycle_bin.test.ts b/test/main/features/recycle_bin.test.ts
index 0e5cf6cf..0166d757 100644
--- a/test/main/features/recycle_bin.test.ts
+++ b/test/main/features/recycle_bin.test.ts
@@ -112,6 +112,13 @@ describe('global recycle bin', () => {
const [restoredRow] = JSON.parse(await fsp.readFile(index, 'utf8'));
expect(restoredRow).toMatchObject({ conversation_id: cid, title: row.title, created_at: row.created_at });
expect(restoredRow.project_id || null).toBe(project ? pid : null);
+ expect(Number.isFinite(Date.parse(restoredRow.restored_at))).toBe(true);
+ const chats = await import('../../../src/main/features/chats');
+ await chats.repairConversationIndex(UID);
+ expect((await chats.listCleanupConversationRows(UID)).map(row => row.conversation_id)).toContain(cid);
+ const [repairedRow] = JSON.parse(await fsp.readFile(index, 'utf8'));
+ expect(repairedRow.restored_at).toBe(restoredRow.restored_at);
+ expect(repairedRow.deleted_at).toBeUndefined();
expect(fs.existsSync(path.join(root, 'chats', `${cid}.jsonl`))).toBe(false);
});
diff --git a/test/renderer/conversation-forget-cid.test.ts b/test/renderer/conversation-forget-cid.test.ts
index 44041c9d..299a70cf 100644
--- a/test/renderer/conversation-forget-cid.test.ts
+++ b/test/renderer/conversation-forget-cid.test.ts
@@ -23,6 +23,8 @@ describe('conversation › _forgetCidRecipient', () => {
// boundary; entries of other conversations must survive.
const globals = {
window: { CliAsyncInput: { forget: vi.fn() } },
+ _taskSurfaceAbortRefreshOwners: new Map(),
+ _forgetConversationRuntime: vi.fn(),
_recipientByCid: { c1: 'agent-a' },
_saveRecipientMap: vi.fn(),
_autoRecipientByCid: new Map([['c1', 1]]),
diff --git a/test/renderer/conversation-keyed-rendering.test.ts b/test/renderer/conversation-keyed-rendering.test.ts
index 671bc480..aac6cd3e 100644
--- a/test/renderer/conversation-keyed-rendering.test.ts
+++ b/test/renderer/conversation-keyed-rendering.test.ts
@@ -263,6 +263,45 @@ const CID = 'c1';
const TURN = 'turn-1';
describe('keyed rendering › durable terminal recovery', () => {
+ it.each([
+ ['same-message', 'upgrading'], ['same-message', 'up_to_date'], ['same-message', 'failure'],
+ ['other-message', 'upgrading'], ['other-actor', 'upgrading'],
+ ])(
+ 'keeps CLI maintenance bound to its failed message during history rebuild: %s / %s', async (scope, state) => {
+ const h = loadRenderer(CID);
+ configureDisplayRecovery(h.context);
+ h.context.document.createDocumentFragment = () => new FakeContainer();
+ const append = h.container.appendChild.bind(h.container);
+ h.container.appendChild = (node: any) => {
+ if (node instanceof FakeContainer) {
+ for (const row of [...node.rows]) append(row);
+ return node;
+ }
+ return append(node);
+ };
+ const control = { dataset: { state, cli: 'codex' } };
+ const old = new FakeNode();
+ old.dataset = { msgId: 'failed-message', fromActor: 'codex-agent', failureCode: 'version_too_old' };
+ const query = old.querySelector.bind(old);
+ old.querySelector = (selector: string): any => selector === '.local-cli-upgrade-control' ? control : query(selector);
+ h.container.appendChild(old);
+ const retained: unknown[] = [];
+ const render = h.context.appendChatMessage;
+ h.context.appendChatMessage = (message: any, scroll: boolean, opts: any) => {
+ retained.push(opts.cliUpgradeControl);
+ return render(message, scroll, opts);
+ };
+ h.context.apiFetch = async () => ({ json: async () => ({ ok: true, history: [{
+ id: scope === 'other-message' ? 'another-message' : 'failed-message',
+ from: scope === 'other-actor' ? 'claude-agent' : 'codex-agent', to: ['user'],
+ text: 'CLI requires an update', ts: '2026-10-26T10:00:00Z',
+ failure_code: 'version_too_old', failure_kind: 'dependency',
+ }], conversation: { processing: false } }) });
+ await h.context.loadConversationHistory(CID, { preserveScroll: true });
+ expect(retained).toEqual([scope === 'same-message' ? control : undefined]);
+ },
+ );
+
it('keeps a saved-task shortcut when an otherwise empty Commander reply hands off the work', () => {
const h = loadRenderer(CID);
const record = { from: 'commander', text: '', process: [{ type: 'event', event: {
diff --git a/test/renderer/conversation-polling.test.ts b/test/renderer/conversation-polling.test.ts
index d4aa7179..5879783e 100644
--- a/test/renderer/conversation-polling.test.ts
+++ b/test/renderer/conversation-polling.test.ts
@@ -62,6 +62,7 @@ describe('conversation polling cancellation', () => {
Date,
pollTimers: new Map(),
pollInFlight: new Map(),
+ pendingConvs: new Map(),
pollMsgCounts: new Map([['c1', 1]]),
setInterval(fn: () => Promise<void>) {
nextTimer += 1;
@@ -118,6 +119,7 @@ describe('conversation polling cancellation', () => {
Date,
pollTimers: new Map(),
pollInFlight: new Map(),
+ pendingConvs: new Map(),
pollMsgCounts: new Map([['c1', 1]]),
setInterval(fn: () => Promise<void>) {
nextTimer += 1;
@@ -175,6 +177,7 @@ describe('conversation polling cancellation', () => {
Date,
pollTimers: new Map(),
pollInFlight: new Map(),
+ pendingConvs: new Map(),
pollMsgCounts: new Map(),
setInterval(fn: () => Promise<void>) {
callbacks.set(1, fn);
@@ -236,6 +239,7 @@ describe('conversation polling stays out of live rendering', () => {
Date,
pollTimers: new Map(),
pollInFlight: new Map(),
+ pendingConvs: new Map(),
pollMsgCounts: new Map(),
setInterval(fn: () => Promise<void>) {
nextTimer += 1;
@@ -319,6 +323,92 @@ describe('conversation polling stays out of live rendering', () => {
'/api/conversations/c1/history?limit=10',
]);
});
+
+ it('leaves an admitted user tail to its still-live send instead of reporting interruption', async () => {
+ const { context, callbacks, recovered } = runPollContext([
+ { ok: true, processing: false },
+ ]);
+ const live = { controller: { isBusy: () => true } };
+ context.pendingConvs.set('c1', live);
+ context.apiFetch = async (url: string) => ({
+ ok: true,
+ json: async () => url.includes('/runtime?')
+ ? { ok: true, processing: false }
+ : { ok: true, history: [{ id: 'u2', from: 'user', text: 'follow-up' }] },
+ });
+ context.startPolling('c1');
+ await callbacks.get(1)!();
+
+ expect(recovered).toEqual([]);
+ expect(context.pendingConvs.get('c1')).toBe(live);
+ expect(context.pollTimers.has('c1')).toBe(true);
+ expect(context.pollInFlight.has('c1')).toBe(false);
+
+ // The same timer must still recover a completed reply after the send dies.
+ live.controller.isBusy = () => false;
+ context.apiFetch = async (url: string) => ({
+ ok: true,
+ json: async () => url.includes('/runtime?')
+ ? { ok: true, processing: false }
+ : { ok: true, history: HISTORY },
+ });
+ await callbacks.get(1)!();
+ expect(recovered).toHaveLength(1);
+ expect(recovered[0][1]).toMatchObject({ id: 'a1' });
+ });
+
+ it.each(['runtime', 'history'])('discards a %s read when a newer send replaces its pending owner', async (stage) => {
+ const { context, callbacks, recovered } = runPollContext([
+ { ok: true, processing: false },
+ ]);
+ const delayed = deferred<any>();
+ const readStarted = deferred<void>();
+ const newer = { controller: { isBusy: () => true } };
+ context.pendingConvs.set('c1', {});
+ context.apiFetch = async (url: string) => ({
+ ok: true,
+ json: () => {
+ if (url.includes('/runtime?') === (stage === 'runtime')) {
+ readStarted.resolve();
+ return delayed.promise;
+ }
+ return Promise.resolve(url.includes('/runtime?')
+ ? { ok: true, processing: false }
+ : { ok: true, history: HISTORY });
+ },
+ });
+ context.startPolling('c1');
+ const tick = callbacks.get(1)!();
+ await readStarted.promise;
+ context.pendingConvs.set('c1', newer);
+ delayed.resolve(stage === 'runtime'
+ ? { ok: true, processing: false }
+ : { ok: true, history: HISTORY });
+ await tick;
+
+ expect(recovered).toEqual([]);
+ expect(context.pollTimers.has('c1')).toBe(true);
+ expect(context.pendingConvs.get('c1')).toBe(newer);
+ expect(context.pollInFlight.has('c1')).toBe(false);
+ });
+
+ it.each([undefined, { controller: { abort: vi.fn() } }, { controller: { isBusy: () => false } }])(
+ 'still reports a lost user tail without an active primary send (%j)', async (state) => {
+ const { context, callbacks, recovered } = runPollContext([{ ok: true, processing: false }]);
+ if (state) context.pendingConvs.set('c1', state);
+ context.apiFetch = async (url: string) => ({
+ ok: true,
+ json: async () => url.includes('/runtime?')
+ ? { ok: true, processing: false }
+ : { ok: true, history: [{ id: 'u1', from: 'user', text: 'lost' }] },
+ });
+ context.startPolling('c1');
+ await callbacks.get(1)!();
+
+ expect(recovered).toEqual([['c1', 'chat.reply_interrupted', true]]);
+ expect(context.pollTimers.has('c1')).toBe(false);
+ },
+ );
});
describe('conversation polling history reconcile', () => {
@@ -347,7 +437,7 @@ describe('conversation polling history reconcile', () => {
context._onPolledResponse('c1', { id: 'a1', from: 'commander', text: 'done' });
- expect(historyLoads).toEqual([['c1', { preserveScroll: true }]]);
+ expect(historyLoads).toEqual([['c1', { preserveScroll: true, refreshDisplay: true }]]);
});
it('preserves scroll when a richer persisted final message needs reconciliation', () => {
@@ -371,7 +461,7 @@ describe('conversation polling history reconcile', () => {
form: { title: 'Follow-up' },
});
- expect(historyLoads).toEqual([['c1', { preserveScroll: true }]]);
+ expect(historyLoads).toEqual([['c1', { preserveScroll: true, refreshDisplay: true }]]);
});
it('settles a background terminal repair without touching the visible transcript', async () => {
diff --git a/test/renderer/conversation-produced-chips.test.ts b/test/renderer/conversation-produced-chips.test.ts
index 73db6850..ee9f7baf 100644
--- a/test/renderer/conversation-produced-chips.test.ts
+++ b/test/renderer/conversation-produced-chips.test.ts
@@ -327,7 +327,7 @@ describe('chat video layout', () => {
expect(styleSource).not.toContain('.chat-msg-attach-video-shell');
});
- it('wires expanded markdown and floating-player surfaces to the shared playback toggle', () => {
+ it('wires expanded markdown surfaces to the shared playback toggle', () => {
expect(source).not.toContain('data-chat-video-playback-surface="attachment_bubble"');
expect(utilsSource).toContain('data-chat-video-playback-surface="markdown_bubble"');
// Local and URL viewer entry points are exercised through their real DOM
diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.ts
index f63befe0..6cc53e93 100644
--- a/test/renderer/conversation-sidebar.test.ts
+++ b/test/renderer/conversation-sidebar.test.ts
@@ -9054,6 +9054,31 @@ function setupConversationStatusController(context: any, cid = 'c1', options = {
}
describe('conversation controller settlement', () => {
+ it.each([{ superseded: false, observerOnly: false }, { superseded: false, observerOnly: true }, { superseded: true, observerOnly: true }])('reconciles idle recovery without retiring a newer pending state ($superseded, observer controller: $observerOnly)', async ({ superseded, observerOnly }) => {
+ const context = loadConversationRenderer();
+ setupRunningObserverTestContext(context);
+ if (observerOnly) vm.runInContext(`
+ const observer = { abort() {} };
+ _convChatCtrls.set('c1', observer);
+ _groupObserverReservations.set('c1', observer);
+ pendingConvs.get('c1').controller = observer;
+ `, context);
+ const order: string[] = [];
+ let release: (response: any) => void = () => {};
+ context.apiFetch = () => new Promise(resolve => { release = resolve; });
+ context._recoverObservedConversationHistory = async () => { order.push('canonical reply'); return true; };
+ context._stopGroupEventObserver = () => order.push('stop observer');
+ context._settleDanglingActorPlaceholders = () => {};
+ context._removeEmptyStreamingPlaceholder = () => {};
+ context._syncTaskBoardForRuntimeState = () => {};
+ context._finishStreamingMsg = () => order.push('finish');
+ const syncing = context._syncPendingActorsFromRuntime('c1', { allowController: true });
+ if (superseded) context.pendingConvs.set('c1', { controller: null, aborted: false });
+ release({ json: async () => ({ ok: true, processing: false, active_turns: [], in_flight: [] }) });
+ await syncing;
+ expect(order).toEqual(superseded ? [] : ['canonical reply', 'stop observer', 'finish']);
+ });
+
it('restores a rejected send before snapshot cleanup and ignores stale controllers', () => {
const context = loadConversationRenderer();
const { hooks, msg } = setupConversationStatusController(context, 'c1', { restoreComposerOnFailure: true });