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.

Prevent duplicate chat bubbles during recovery

wyt6128496b9a0f
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 2a9a7fd2..03cec9aa 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -2200,6 +2200,7 @@ export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swe
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.',
};
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index fc963d3e..3c693002 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -688,9 +688,10 @@ function activeTurnsForState(state: CidState): ActiveTurn[] {
});
}
turns.sort((a, b) => a.order - b.order);
- return turns.map(({ actor, turn_id, started_at_ms }) => ({
+ return turns.map(({ actor, turn_id, msg_id, started_at_ms }) => ({
actor,
turn_id,
+ ...(msg_id ? { msg_id } : {}),
started_at_ms,
}));
}
@@ -1166,6 +1167,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
...(params.dispatch ? { dispatch: true } : {}),
...(params.seg !== undefined ? { seg: params.seg } : {}),
...(params.process && params.process.length ? { process: params.process } : {}),
+ ...(params.turn_id ? { turn_id: params.turn_id } : {}),
};
// Persist: main jsonl + each recipient + sender (so sender sees own history
diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.ts
index 88db8fca..a46d4741 100644
--- a/src/main/features/group_chat/visibility.ts
+++ b/src/main/features/group_chat/visibility.ts
@@ -62,6 +62,14 @@ export interface GroupMessage {
unknown_mentions?: string[];
/** Plain `@token` list (raw text mentions). */
mentions?: string[];
+ /** Stable actor-execution id that produced this record. Live process,
+ * terminal bus events, persisted history and renderer placeholders all use
+ * this value to refer to the same reply. Older records may omit it. */
+ turn_id?: string;
+ /** Host-generated status records are not model replies. Kept explicit so
+ * recovery/reconciliation never claims a live actor placeholder merely
+ * because the status row has the same sender. */
+ system_kind?: 'reply_interrupted';
/** Markdown text body. */
text: string;
/** Internal model-facing text. UI renders `text`; workers use this when
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 178c71b1..68921456 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -2361,6 +2361,54 @@ function _normalizeCreatedSkills(gm) {
return null;
}
+function _groupMessageSystemKind(gm) {
+ const explicit = String(gm?.system_kind || gm?._system_kind || '');
+ if (explicit) return explicit;
+ // Compatibility for interruption rows written by the first release that
+ // persisted them without an explicit discriminator. `model_text` is a
+ // stable host-authored English protocol string regardless of UI locale.
+ const modelText = String(gm?.model_text || '');
+ if (modelText.startsWith('The previous assistant run was interrupted by an application exit or crash')) {
+ return 'reply_interrupted';
+ }
+ return '';
+}
+
+// An interruption status is useful while the old turn is genuinely stopped.
+// Once the same actor continues without another visible user message, the
+// status has been superseded and must not remain as a second assistant bubble.
+// Keep this record-level pass shared by cold history, polling and reconcile so
+// those paths agree about which persisted rows should have DOM nodes.
+function _collapseSupersededInterruptionRecords(records) {
+ if (!Array.isArray(records) || !records.length) return [];
+ const out = [];
+ const pendingByActor = new Map();
+ for (const gm of records) {
+ if (!gm) continue;
+ const actor = String(gm.from || gm._from || '');
+ const isUser = actor === 'user' || gm.role === 'user';
+ if (isUser) {
+ pendingByActor.clear();
+ out.push(gm);
+ continue;
+ }
+ if (_groupMessageSystemKind(gm) === 'reply_interrupted') {
+ const previousIndex = pendingByActor.get(actor);
+ if (previousIndex !== undefined) out[previousIndex] = null;
+ pendingByActor.set(actor, out.length);
+ out.push(gm);
+ continue;
+ }
+ const supersededIndex = pendingByActor.get(actor);
+ if (supersededIndex !== undefined) {
+ out[supersededIndex] = null;
+ pendingByActor.delete(actor);
+ }
+ out.push(gm);
+ }
+ return out.filter(Boolean);
+}
+
function _groupMsgToLegacy(gm) {
if (!gm || typeof gm !== 'object') return gm;
if (gm.role !== undefined) return gm; // already legacy shape
@@ -2391,6 +2439,8 @@ function _groupMsgToLegacy(gm) {
...(Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length ? { marketplace_requests: gm.marketplace_requests } : {}),
...(gm.plan_announcement ? { _plan_announcement: true } : {}),
...(Array.isArray(gm.process) && gm.process.length ? { process: gm.process } : {}),
+ ...(gm.turn_id ? { _turn_id: gm.turn_id } : {}),
+ ...(_groupMessageSystemKind(gm) ? { _system_kind: _groupMessageSystemKind(gm) } : {}),
};
return out;
}
@@ -2427,6 +2477,10 @@ function _syncRenderedGroupMessageIdentity(el, message) {
if (msgId && !el.dataset.msgId) el.dataset.msgId = String(msgId);
const from = message.from || message._from;
if (from && !el.dataset.fromActor) el.dataset.fromActor = String(from);
+ const turnId = message.turn_id || message.turnId || message._turn_id;
+ if (turnId && !el.dataset.turnId) el.dataset.turnId = String(turnId);
+ const systemKind = message.system_kind || message._system_kind;
+ if (systemKind && !el.dataset.systemKind) el.dataset.systemKind = String(systemKind);
const tsInput = message.ts || message.time;
if (tsInput) {
el.dataset.ts = String(_msTs(tsInput));
@@ -4519,8 +4573,10 @@ async function _loadOlderConversationHistory(cid, before) {
const knownIds = new Set(Array.from(container.querySelectorAll('.chat-message[data-msg-id]'))
.map((el) => el.dataset.msgId)
.filter(Boolean));
- const page = (Array.isArray(data.history) ? data.history : [])
- .filter((gm) => gm && !gm.dispatch && (!gm.id || !knownIds.has(String(gm.id))))
+ const page = _collapseSupersededInterruptionRecords(
+ (Array.isArray(data.history) ? data.history : [])
+ .filter((gm) => gm && !gm.dispatch && (!gm.id || !knownIds.has(String(gm.id)))),
+ )
.map(_groupMsgToLegacy)
.sort((a, b) => _msTs(a && a.time) - _msTs(b && b.time));
const fragment = document.createDocumentFragment();
@@ -4531,6 +4587,7 @@ async function _loadOlderConversationHistory(cid, before) {
}));
if (row) container.insertBefore(fragment, row);
else container.insertBefore(fragment, container.firstChild);
+ _removeSupersededInterruptionBubbles(container);
_setLoadEarlierHistory(container, cid, data.next_cursor);
// The user deliberately requested older history, so reveal the new page
// rather than preserving the previous top loader as the viewport anchor.
@@ -4620,8 +4677,9 @@ async function loadConversationHistory(cid, opts = {}) {
// agent's visibility slice still carries dispatches so the agent has the
// dispatch text in its own context.
const renderStartedAt = performance.now();
- const visibleGroupHistory = (data.history || [])
- .filter(_isVisibleGroupHistoryRecord);
+ const visibleGroupHistory = _collapseSupersededInterruptionRecords(
+ (data.history || []).filter(_isVisibleGroupHistoryRecord),
+ );
const history = visibleGroupHistory
.map(_groupMsgToLegacy)
// Defensive sort by ts: jsonl is append-ordered (already chronological),
@@ -4806,7 +4864,9 @@ function _scheduleHistoryReconcileAfterStream(cid, opts = {}) {
const res = await apiFetch(_historyRequestUrl(cid));
const data = await res.json();
if (!data.ok || !Array.isArray(data.history)) return;
- const visible = data.history.filter(_isVisibleGroupHistoryRecord);
+ const visible = _collapseSupersededInterruptionRecords(
+ data.history.filter(_isVisibleGroupHistoryRecord),
+ );
for (const gm of visible.slice(-8)) {
if (!gm || !gm.id) continue;
const el = _findRenderedMessageForHistoryRecord(container, gm);
@@ -4825,7 +4885,9 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
if (!container) return false;
let changed = false;
try { await _refreshGroupMembers(cid); } catch (_) { /* best effort */ }
- const visible = rawMessages.filter((gm) => _isVisibleGroupHistoryRecord(gm) && gm.from !== 'user');
+ const visible = _collapseSupersededInterruptionRecords(
+ rawMessages.filter((gm) => _isVisibleGroupHistoryRecord(gm) && gm.from !== 'user'),
+ );
for (const gm of visible) {
if (!gm.id) continue;
const existing = _findRenderedMessageForHistoryRecord(container, gm);
@@ -4836,7 +4898,7 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
}
continue;
}
- const ph = _consumeActorPlaceholder(cid, String(gm.from || ''));
+ const ph = _consumePlaceholderForHistoryRecord(cid, gm);
if (ph && ph.parentElement) {
_finalizeActorPlaceholder(ph, gm, cid, true);
changed = true;
@@ -5474,6 +5536,8 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
if (typeof opts.msgIndex === 'number') msgDiv.dataset.msgIndex = String(opts.msgIndex);
if (message._msg_id) msgDiv.dataset.msgId = String(message._msg_id);
if (message._from) msgDiv.dataset.fromActor = String(message._from);
+ if (message._turn_id) msgDiv.dataset.turnId = String(message._turn_id);
+ if (message._system_kind) msgDiv.dataset.systemKind = String(message._system_kind);
msgDiv.dataset.ts = String(_msTs(message.time));
if (role === 'user') {
msgDiv.dataset.retryContent = String(rawContent || '');
@@ -7950,6 +8014,29 @@ function _previousChatMessage(el) {
return prev || null;
}
+function _removeSupersededInterruptionBubbles(container) {
+ if (!container?.querySelectorAll) return;
+ const pendingByActor = new Map();
+ const messages = Array.from(container.querySelectorAll(':scope > .chat-message'));
+ for (const el of messages) {
+ if (_hasChatMessageClass(el, 'user')) {
+ pendingByActor.clear();
+ continue;
+ }
+ if (!_hasChatMessageClass(el, 'assistant')) continue;
+ const actor = String(el.dataset.fromActor || el.dataset.from || '');
+ if (el.dataset.systemKind === 'reply_interrupted') {
+ const previous = pendingByActor.get(actor);
+ if (previous?.parentElement === container) previous.remove();
+ pendingByActor.set(actor, el);
+ continue;
+ }
+ const superseded = pendingByActor.get(actor);
+ if (superseded?.parentElement === container) superseded.remove();
+ pendingByActor.delete(actor);
+ }
+}
+
function _isLivePlaceholderMessage(el) {
return _hasChatMessageClass(el, 'assistant')
&& el?.dataset?.placeholder === '1'
@@ -9445,6 +9532,9 @@ function _setPlaceholderActor(ph, actorId, opts = {}) {
ph.style.display = 'none';
}
}
+ if (actorId && ph.parentElement) {
+ _removeSupersededInterruptionBubbles(ph.parentElement);
+ }
}
function _refreshActorPlaceholders(cid, actorId) {
@@ -9528,12 +9618,13 @@ function _ensureActorPlaceholder(cid, actorId, fallbackPh, turnId, triggerMsgId,
return ph;
}
-function _consumeActorPlaceholder(cid, actorId, turnId) {
+function _consumeActorPlaceholder(cid, actorId, turnId, opts = {}) {
const tid = _normaliseTurnId(turnId);
+ const allowActorFallback = opts.allowActorFallback !== false;
const k = _phKey(cid, actorId, tid);
let ph = _groupPlaceholders.get(k);
_groupPlaceholders.delete(k);
- if (!ph && tid) {
+ if (!ph && tid && allowActorFallback) {
const legacyK = _phKey(cid, actorId);
const legacyPh = _groupPlaceholders.get(legacyK);
if (legacyPh && legacyPh.parentElement && legacyPh.dataset.finalized !== '1'
@@ -9542,7 +9633,7 @@ function _consumeActorPlaceholder(cid, actorId, turnId) {
_groupPlaceholders.delete(legacyK);
}
}
- if (!ph) {
+ if (!ph && allowActorFallback) {
// Segment/final events should carry the same turn id that seeded the live
// placeholder, but reconnect/runtime recovery paths can leave the DOM with
// only actor identity. Do not strand a same-actor live bubble in "writing"
@@ -9567,6 +9658,24 @@ function _consumeActorPlaceholder(cid, actorId, turnId) {
return ph || null;
}
+// Polling/history reconciliation has no terminal bus-event envelope to prove
+// which live placeholder a persisted row belongs to. Only claim the exact
+// actor execution recorded on the message itself. Actor-only fallback is
+// intentionally forbidden here: a boot-time interruption status uses the same
+// sender as a newly resumed VideoStudio (or other long-running) turn, and the
+// old fallback finalized the current placeholder with that stale status. Later
+// process events then created another placeholder, visibly splitting one reply
+// across multiple bubbles. Legacy records without `turn_id` are appended as
+// canonical history rows; their live placeholder is resolved by the terminal
+// bus event or the normal end-of-stream history reconcile.
+function _consumePlaceholderForHistoryRecord(cid, gm) {
+ if (gm?.system_kind || gm?._system_kind) return null;
+ const actorId = String(gm?.from || gm?._from || '');
+ const turnId = _normaliseTurnId(gm?.turn_id || gm?.turnId || gm?._turn_id);
+ if (!actorId || !turnId) return null;
+ return _consumeActorPlaceholder(cid, actorId, turnId, { allowActorFallback: false });
+}
+
// Transform a streaming placeholder bubble into its finalized form:
// freeze the process rail (keep visible + collapsed by default),
// render markdown into [data-role="final"], append produced-files chip /
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index 180f7505..d76826c1 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -1308,6 +1308,7 @@ describe('chats › sweepStaleProcessing', () => {
expect.objectContaining({
from: '79df9cc89f5f',
to: ['user'],
+ system_kind: 'reply_interrupted',
text: expect.any(String),
model_text: expect.stringContaining('interrupted'),
}),
diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.ts
index 72af7493..d262f571 100644
--- a/test/main/features/group_chat/bus.test.ts
+++ b/test/main/features/group_chat/bus.test.ts
@@ -526,7 +526,7 @@ describe('group_chat bus › enqueue routing + persistence', () => {
});
try {
- await bus.enqueue({
+ const trigger = await bus.enqueue({
uid: TEST_UID, cid: TEST_CID, fromActorId: 'user',
text: 'ACTIVE_TURN_TEST',
});
@@ -541,6 +541,7 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(running.activeTurns[0]).toMatchObject({
actor: 'commander',
turn_id: processEv.turn_id,
+ msg_id: trigger.id,
started_at_ms: expect.any(Number),
});
expect(running.activeTurns[0].started_at_ms).toBeLessThanOrEqual(Date.now());
@@ -553,6 +554,13 @@ describe('group_chat bus › enqueue routing + persistence', () => {
const finalEv = events.find((ev) => ev.type === 'message' && ev.turn_end && ev.msg?.from === 'commander');
expect(finalEv?.turn_id).toBe(processEv.turn_id);
+ expect(finalEv?.msg?.turn_id).toBe(processEv.turn_id);
+ const paths = await import('../../../../src/main/paths');
+ const persisted = fs.readFileSync(
+ path.join(paths.userChatsDir(TEST_UID), `${TEST_CID}.jsonl`),
+ 'utf8',
+ ).trim().split('\n').map((line) => JSON.parse(line));
+ expect(persisted.find((row) => row.id === finalEv?.msg?.id)?.turn_id).toBe(processEv.turn_id);
expect(bus.runtimeSnapshot(TEST_UID, TEST_CID).activeTurns).toEqual([]);
} finally {
streamGate.releaseActiveTurn?.();
diff --git a/test/renderer/conversation-placeholder-consume.test.ts b/test/renderer/conversation-placeholder-consume.test.ts
index f8c9d4d8..fc91e11e 100644
--- a/test/renderer/conversation-placeholder-consume.test.ts
+++ b/test/renderer/conversation-placeholder-consume.test.ts
@@ -32,13 +32,61 @@ function extractFunctionUntil(name: string, nextName: string): string {
class FakePlaceholder {
dataset: Record<string, string>;
- parentElement = {};
+ parentElement: any = {};
constructor(dataset: Record<string, string>) {
this.dataset = { ...dataset };
}
}
+class FakeChatMessage extends FakePlaceholder {
+ readonly classList: { contains: (name: string) => boolean };
+ readonly processLines: string[];
+ removed = false;
+
+ constructor(
+ classes: string[],
+ dataset: Record<string, string>,
+ processLines: string[] = [],
+ ) {
+ super(dataset);
+ const names = new Set(classes);
+ this.classList = { contains: (name: string) => names.has(name) };
+ this.processLines = processLines;
+ }
+
+ remove() {
+ this.removed = true;
+ this.parentElement?.removeChild(this);
+ this.parentElement = null;
+ }
+}
+
+class FakeHistoryContainer {
+ messages: FakeChatMessage[] = [];
+
+ append(...messages: FakeChatMessage[]) {
+ for (const message of messages) {
+ message.parentElement = this;
+ this.messages.push(message);
+ }
+ }
+
+ prepend(message: FakeChatMessage) {
+ message.parentElement = this;
+ this.messages.unshift(message);
+ }
+
+ removeChild(message: FakeChatMessage) {
+ this.messages = this.messages.filter((candidate) => candidate !== message);
+ }
+
+ querySelectorAll(selector: string) {
+ if (selector !== ':scope > .chat-message') throw new Error(`unexpected selector: ${selector}`);
+ return this.messages.slice();
+ }
+}
+
class FakeDanglingPlaceholder {
parentElement: Record<string, never> | null = {};
removed = false;
@@ -66,15 +114,22 @@ class FakeDanglingPlaceholder {
function loadPlaceholderHelpers(): {
placeholders: Map<string, FakePlaceholder>;
- consume: (cid: string, actorId: string, turnId?: string) => FakePlaceholder | null;
+ consume: (
+ cid: string,
+ actorId: string,
+ turnId?: string,
+ opts?: { allowActorFallback?: boolean },
+ ) => FakePlaceholder | null;
+ consumeHistory: (cid: string, gm: Record<string, unknown>) => FakePlaceholder | null;
key: (cid: string, actorId: string, turnId?: string) => string;
} {
const fns = [
'const _groupPlaceholders = new Map();',
extractFunction('_normaliseTurnId'),
extractFunction('_phKey'),
- extractFunction('_consumeActorPlaceholder'),
- '({ placeholders: _groupPlaceholders, consume: _consumeActorPlaceholder, key: _phKey });',
+ extractFunctionUntil('_consumeActorPlaceholder', '_consumePlaceholderForHistoryRecord'),
+ extractFunctionUntil('_consumePlaceholderForHistoryRecord', '_finalizeActorPlaceholder'),
+ '({ placeholders: _groupPlaceholders, consume: _consumeActorPlaceholder, consumeHistory: _consumePlaceholderForHistoryRecord, key: _phKey });',
].join('\n');
return vm.runInNewContext(fns, {});
}
@@ -108,6 +163,21 @@ function loadActivityHelpers() {
};
}
+function loadInterruptionHelpers() {
+ return vm.runInNewContext([
+ extractFunctionUntil('_groupMessageSystemKind', '_collapseSupersededInterruptionRecords'),
+ extractFunctionUntil('_collapseSupersededInterruptionRecords', '_groupMsgToLegacy'),
+ extractFunction('_isChatMessageEl'),
+ extractFunction('_hasChatMessageClass'),
+ extractFunction('_removeSupersededInterruptionBubbles'),
+ '({ systemKind: _groupMessageSystemKind, collapse: _collapseSupersededInterruptionRecords, removeBubbles: _removeSupersededInterruptionBubbles });',
+ ].join('\n'), { Map }) as {
+ systemKind: (message: Record<string, unknown>) => string;
+ collapse: (messages: Array<Record<string, unknown>>) => Array<Record<string, unknown>>;
+ removeBubbles: (container: FakeHistoryContainer) => void;
+ };
+}
+
function loadSettleHelper(
placeholders: Map<string, FakeDanglingPlaceholder>,
orphans: FakeDanglingPlaceholder[],
@@ -157,6 +227,41 @@ describe('conversation actor placeholder consume', () => {
expect(placeholders.get(key('cid-1', 'agent-1', 'turn-2'))).toBe(agent);
});
+ it('does not let an uncorrelated polled row consume a live same-actor turn', () => {
+ const { placeholders, consumeHistory, key } = loadPlaceholderHelpers();
+ const active = new FakePlaceholder({ fromActor: 'video-studio', turnId: 'turn-live' });
+ placeholders.set(key('cid-1', 'video-studio', 'turn-live'), active);
+
+ expect(consumeHistory('cid-1', {
+ id: 'interruption-row',
+ from: 'video-studio',
+ system_kind: 'reply_interrupted',
+ })).toBeNull();
+ expect(consumeHistory('cid-1', {
+ id: 'legacy-row-without-turn',
+ from: 'video-studio',
+ })).toBeNull();
+ expect(active.dataset.finalized).toBeUndefined();
+ expect(placeholders.get(key('cid-1', 'video-studio', 'turn-live'))).toBe(active);
+ });
+
+ it('claims a polled terminal row only for its exact persisted turn id', () => {
+ const { placeholders, consumeHistory, key } = loadPlaceholderHelpers();
+ const old = new FakePlaceholder({ fromActor: 'video-studio', turnId: 'turn-old' });
+ const active = new FakePlaceholder({ fromActor: 'video-studio', turnId: 'turn-live' });
+ placeholders.set(key('cid-1', 'video-studio', 'turn-old'), old);
+ placeholders.set(key('cid-1', 'video-studio', 'turn-live'), active);
+
+ expect(consumeHistory('cid-1', {
+ id: 'terminal-row',
+ from: 'video-studio',
+ turn_id: 'turn-old',
+ })).toBe(old);
+ expect(old.dataset.finalized).toBe('1');
+ expect(active.dataset.finalized).toBeUndefined();
+ expect(placeholders.get(key('cid-1', 'video-studio', 'turn-live'))).toBe(active);
+ });
+
it('keeps process-bearing abort placeholders until the persisted message consumes them', () => {
const processPlaceholder = new FakeDanglingPlaceholder(2);
const emptyPlaceholder = new FakeDanglingPlaceholder(0);
@@ -189,6 +294,139 @@ describe('conversation actor placeholder consume', () => {
});
});
+describe('conversation interruption bubble collapse', () => {
+ it('recognizes legacy host-authored interruption rows', () => {
+ const { systemKind } = loadInterruptionHelpers();
+ expect(systemKind({
+ model_text: 'The previous assistant run was interrupted by an application exit or crash before it produced a complete reply.',
+ })).toBe('reply_interrupted');
+ });
+
+ it('removes a superseded same-actor interruption without crossing a user message', () => {
+ const { collapse } = loadInterruptionHelpers();
+ const interruption = { id: 'status', from: 'video-studio', system_kind: 'reply_interrupted' };
+ const resumed = { id: 'answer', from: 'video-studio', turn_id: 'turn-2' };
+
+ expect(collapse([interruption, resumed]).map((row) => row.id)).toEqual(['answer']);
+ expect(collapse([
+ interruption,
+ { ...interruption, id: 'status-new' },
+ resumed,
+ ]).map((row) => row.id)).toEqual(['answer']);
+ expect(collapse([
+ interruption,
+ { id: 'user-2', from: 'user' },
+ resumed,
+ ]).map((row) => row.id)).toEqual(['status', 'user-2', 'answer']);
+ });
+
+ it('keeps exactly one VideoStudio bubble through stale polling, resumed progress, and terminal persistence', () => {
+ const { placeholders, consumeHistory, key } = loadPlaceholderHelpers();
+ const { removeBubbles } = loadInterruptionHelpers();
+ const history = new FakeHistoryContainer();
+ const staleInterruptions = Array.from({ length: 6 }, (_, index) => new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ {
+ fromActor: 'video-studio',
+ msgId: `interruption-${index + 1}`,
+ systemKind: 'reply_interrupted',
+ },
+ ));
+ const progressLines = [
+ 'Captured frame 841/4950.',
+ 'Captured frame 901/4950.',
+ 'Captured frame 1681/4950.',
+ ];
+ const live = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ {
+ fromActor: 'video-studio',
+ placeholder: '1',
+ turnId: 'video-turn-live',
+ },
+ progressLines,
+ );
+ history.append(...staleInterruptions, live);
+ placeholders.set(key('cid-video', 'video-studio', 'video-turn-live'), live);
+
+ // Startup polling can replay one or several interruption rows written by
+ // earlier app exits. None may finalize the currently resumed actor turn.
+ for (const interruption of staleInterruptions) {
+ expect(consumeHistory('cid-video', {
+ id: interruption.dataset.msgId,
+ from: 'video-studio',
+ system_kind: 'reply_interrupted',
+ })).toBeNull();
+ }
+ expect(live.dataset.finalized).toBeUndefined();
+ expect(placeholders.get(key('cid-video', 'video-studio', 'video-turn-live'))).toBe(live);
+
+ // Learning the resumed placeholder's actor identity performs the same DOM
+ // cleanup as the production renderer. Even repeated crashes must not leave
+ // a stack of assistant bubbles above the continuing progress rail.
+ removeBubbles(history);
+ expect(history.messages).toEqual([live]);
+ expect(staleInterruptions.every((message) => message.removed)).toBe(true);
+ expect(live.processLines).toEqual(progressLines);
+
+ live.processLines.push('Captured frame 4921/4950.');
+ expect(consumeHistory('cid-video', {
+ id: 'video-final',
+ from: 'video-studio',
+ turn_id: 'video-turn-live',
+ })).toBe(live);
+ expect(live.dataset.finalized).toBe('1');
+ expect(live.processLines.at(-1)).toBe('Captured frame 4921/4950.');
+ expect(history.messages).toHaveLength(1);
+ });
+
+ it('collapses an interruption loaded from an older page against a newer same-actor bubble', () => {
+ const { removeBubbles } = loadInterruptionHelpers();
+ const history = new FakeHistoryContainer();
+ const resumed = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ { fromActor: 'video-studio', msgId: 'resumed-answer', turnId: 'turn-2' },
+ );
+ history.append(resumed);
+
+ // Older-history paging prepends records after the newer page is already
+ // mounted. The record-only collapse cannot see across that page boundary,
+ // so the DOM pass must remove the stale bubble.
+ const olderInterruption = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ { fromActor: 'video-studio', msgId: 'old-status', systemKind: 'reply_interrupted' },
+ );
+ history.prepend(olderInterruption);
+ removeBubbles(history);
+
+ expect(olderInterruption.removed).toBe(true);
+ expect(history.messages).toEqual([resumed]);
+ });
+
+ it('preserves a genuine prior-turn interruption when a user message starts the resumed turn', () => {
+ const { removeBubbles } = loadInterruptionHelpers();
+ const history = new FakeHistoryContainer();
+ const interrupted = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ { fromActor: 'video-studio', msgId: 'prior-status', systemKind: 'reply_interrupted' },
+ );
+ const user = new FakeChatMessage(
+ ['chat-message', 'user'],
+ { msgId: 'continue-request' },
+ );
+ const resumed = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ { fromActor: 'video-studio', msgId: 'next-answer', turnId: 'turn-next' },
+ );
+ history.append(interrupted, user, resumed);
+
+ removeBubbles(history);
+
+ expect(interrupted.removed).toBe(false);
+ expect(history.messages).toEqual([interrupted, user, resumed]);
+ });
+});
+
describe('conversation activity elapsed clock', () => {
it('hydrates a replacement placeholder from the stable backend turn start', () => {
const { normalise, seed } = loadActivityHelpers();