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.

Avoid false interruption bubbles during live turns

wyt14d788fb360b
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 03cec9aa..82efe906 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -51,6 +51,13 @@ import {
import { limitNameDisplayText } from '../util/name-limit';
const log = createLogger('chats');
+// A boot-time stale-state sweep may run twice: once before the first window
+// and again as a deferred cross-user maintenance pass. Only a state whose
+// activity predates this main-process module can belong to a previous crash.
+// Without this cutoff, the deferred pass can wake several minutes later while
+// a newly-started long VideoStudio turn is legitimately running and manufacture
+// a false "reply interrupted" message in the middle of that live bubble.
+const PROCESS_BOOT_CUTOFF_MS = Date.now();
import * as search from './search';
import {
ensureRunningConversationRegistry,
@@ -2178,6 +2185,9 @@ export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swe
candidates.push(...await _conversationStateCandidates(uid));
}
}
+ // Loaded lazily to avoid the chats ↔ bus module cycle during startup. The
+ // CJS path deliberately shares the same in-memory runtime map as send().
+ const bus = require('./group_chat/bus') as typeof import('./group_chat/bus');
await _runBounded(candidates, 32, async ({ uid, cid, file }) => {
try {
const raw = JSON.parse(await fsp.readFile(file, 'utf8'));
@@ -2185,6 +2195,18 @@ export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swe
if (pruneJournalRows) await untrackRunningConversation(uid, cid);
return;
}
+ 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
+ // never stale startup residue, even if this deferred sweep was queued
+ // before the user started the turn.
+ return;
+ }
+ if (!bus.isQuiescent(uid, cid)) {
+ // Belt-and-braces for legacy/malformed timestamps and turn-start races:
+ // live in-memory work always wins over disk maintenance.
+ return;
+ }
await setStatus(uid, cid, 'idle');
const interruptedActors = Array.isArray(raw.in_flight)
? raw.in_flight.filter((actorId: unknown): actorId is string => safeId(actorId))
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 68921456..912630a7 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -4883,7 +4883,7 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
if (!cid || cid !== currentCid || !Array.isArray(rawMessages)) return false;
const container = document.getElementById('chat-history');
if (!container) return false;
- let changed = false;
+ let changed = _removeSupersededInterruptionBubbles(container) > 0;
try { await _refreshGroupMembers(cid); } catch (_) { /* best effort */ }
const visible = _collapseSupersededInterruptionRecords(
rawMessages.filter((gm) => _isVisibleGroupHistoryRecord(gm) && gm.from !== 'user'),
@@ -4904,11 +4904,18 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {
changed = true;
continue;
}
+ // An uncorrelated interruption row can be stale while a newer exact turn
+ // for the same actor is live (or can itself be a false row from deferred
+ // boot maintenance). Do not append a second bubble mid-stream. Once the
+ // runtime settles, normal history reconciliation either removes the row as
+ // superseded by the final message or renders it when it was genuine.
+ if (_shouldDeferInterruptedHistoryRecord(cid, gm)) continue;
const legacy = _groupMsgToLegacy(gm);
const bubble = appendChatMessage(legacy, true, { cid, archive: true });
if (bubble) bubble.dataset.fromActor = String(gm.from || '');
changed = true;
}
+ if (_removeSupersededInterruptionBubbles(container) > 0) changed = true;
if (changed) {
try { if (window.ConversationInfo) window.ConversationInfo.refreshFiles(cid); } catch (_) {}
_scheduleConversationInfoFileRefresh(cid);
@@ -8015,26 +8022,50 @@ function _previousChatMessage(el) {
}
function _removeSupersededInterruptionBubbles(container) {
- if (!container?.querySelectorAll) return;
+ if (!container?.querySelectorAll) return 0;
const pendingByActor = new Map();
+ const liveByActor = new Set();
+ let removed = 0;
const messages = Array.from(container.querySelectorAll(':scope > .chat-message'));
for (const el of messages) {
if (_hasChatMessageClass(el, 'user')) {
pendingByActor.clear();
+ liveByActor.clear();
continue;
}
if (!_hasChatMessageClass(el, 'assistant')) continue;
const actor = String(el.dataset.fromActor || el.dataset.from || '');
if (el.dataset.systemKind === 'reply_interrupted') {
+ // A boot-maintenance race used to append a false interruption below a
+ // still-running placeholder. Never show that as a second bubble. The
+ // polling path defers the record too; this DOM guard repairs an already
+ // mounted row from an earlier poll without discarding the process rail.
+ if (liveByActor.has(actor)) {
+ el.remove();
+ removed += 1;
+ continue;
+ }
const previous = pendingByActor.get(actor);
- if (previous?.parentElement === container) previous.remove();
+ if (previous?.parentElement === container) {
+ previous.remove();
+ removed += 1;
+ }
pendingByActor.set(actor, el);
continue;
}
const superseded = pendingByActor.get(actor);
- if (superseded?.parentElement === container) superseded.remove();
+ if (superseded?.parentElement === container) {
+ superseded.remove();
+ removed += 1;
+ }
pendingByActor.delete(actor);
+ if (el.dataset.placeholder === '1' && el.dataset.finalized !== '1') {
+ liveByActor.add(actor);
+ } else {
+ liveByActor.delete(actor);
+ }
}
+ return removed;
}
function _isLivePlaceholderMessage(el) {
@@ -9660,22 +9691,46 @@ function _consumeActorPlaceholder(cid, actorId, turnId, opts = {}) {
// 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.
+// actor execution recorded on the message itself. General actor-only fallback
+// is intentionally forbidden: an old interruption status can share a sender
+// with a newly resumed VideoStudio turn. The sole legacy exception is a real
+// boot-recovery interruption claiming an actor-only placeholder that itself has
+// no turn id; it cannot collide with a process-driven, turn-keyed live bubble.
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;
+ if (!actorId) return null;
+ const systemKind = _groupMessageSystemKind(gm);
+ if (systemKind === 'reply_interrupted') {
+ if (turnId) {
+ return _consumeActorPlaceholder(cid, actorId, turnId, { allowActorFallback: false });
+ }
+ // Old state.json files persisted only `in_flight`, so a genuine boot
+ // recovery placeholder has the actor-only key and no turn id. Claim only
+ // that exact legacy placeholder. A newly resumed/process-driven turn is
+ // keyed by turn id and must never be finalized by this uncorrelated row.
+ const legacy = _groupPlaceholders.get(_phKey(cid, actorId));
+ if (!legacy?.parentElement || legacy.dataset.finalized === '1'
+ || _normaliseTurnId(legacy.dataset.turnId)) return null;
+ return _consumeActorPlaceholder(cid, actorId, undefined, { allowActorFallback: false });
+ }
+ if (systemKind || !turnId) return null;
return _consumeActorPlaceholder(cid, actorId, turnId, { allowActorFallback: false });
}
+function _shouldDeferInterruptedHistoryRecord(cid, gm) {
+ if (_groupMessageSystemKind(gm) !== 'reply_interrupted') return false;
+ const actorId = String(gm?.from || gm?._from || '');
+ if (!actorId) return false;
+ for (const [key, ph] of _groupPlaceholders.entries()) {
+ if (!key.startsWith(`${cid}:`)) continue;
+ if (String(ph?.dataset?.fromActor || '') !== actorId) continue;
+ if (ph?.dataset?.finalized === '1') continue;
+ if (ph?.parentElement) return true;
+ }
+ return 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 d76826c1..0ef64f0c 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -1196,6 +1196,29 @@ describe('chats › autoTitle on first send', () => {
});
describe('chats › sweepStaleProcessing', () => {
+ const staleActiveAt = () => new Date(Date.now() - 60_000).toISOString();
+
+ it('does not interrupt a conversation that started in the current process before the deferred sweep', async () => {
+ const chats = await loadChats();
+ const conv = await chats.createConversation(TEST_UID);
+ const stateFile = path.join(
+ tmpDir, TEST_UID, 'cloud', 'chats', conv.conversation_id, 'state.json');
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify({
+ version: 1,
+ status: 'running',
+ last_active_at: new Date().toISOString(),
+ in_flight: ['79df9cc89f5f'],
+ }));
+
+ expect((await chats.sweepStaleProcessing()).swept).toBe(0);
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf8')).status).toBe('running');
+ expect(fs.readFileSync(
+ path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`),
+ 'utf8',
+ )).toBe('');
+ });
+
it('uses the indexed active-user fallback once when the journal is missing', async () => {
const chats = await loadChats();
const active = await chats.createConversation(TEST_UID);
@@ -1208,7 +1231,7 @@ describe('chats › sweepStaleProcessing', () => {
const file = path.join(tmpDir, uid, 'cloud', 'chats', cid, 'state.json');
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, JSON.stringify({
- version: 1, status: 'running', last_active_at: new Date().toISOString(), in_flight: ['commander'],
+ version: 1, status: 'running', last_active_at: staleActiveAt(), in_flight: ['commander'],
}));
}
@@ -1233,7 +1256,7 @@ describe('chats › sweepStaleProcessing', () => {
const file = path.join(tmpDir, TEST_UID, 'cloud', 'chats', cid, 'state.json');
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, JSON.stringify({
- version: 1, status: 'running', last_active_at: new Date().toISOString(), in_flight: [],
+ version: 1, status: 'running', last_active_at: staleActiveAt(), in_flight: [],
}));
}
const paths = await import('../../../src/main/paths');
@@ -1262,7 +1285,7 @@ describe('chats › sweepStaleProcessing', () => {
tmpDir, TEST_UID, 'cloud', 'chats', conv.conversation_id, 'state.json');
fs.mkdirSync(path.dirname(stateFile), { recursive: true });
fs.writeFileSync(stateFile, JSON.stringify({
- version: 1, status: 'running', last_active_at: new Date().toISOString(), in_flight: [],
+ version: 1, status: 'running', last_active_at: staleActiveAt(), in_flight: [],
}));
const paths = await import('../../../src/main/paths');
const journal = paths.userRunningConversationsFile(TEST_UID);
@@ -1283,7 +1306,7 @@ describe('chats › sweepStaleProcessing', () => {
const stateFile = path.join(tmpDir, TEST_UID, 'cloud', 'chats', conv.conversation_id, 'state.json');
fs.mkdirSync(path.dirname(stateFile), { recursive: true });
fs.writeFileSync(stateFile, JSON.stringify({
- version: 1, status: 'running', last_active_at: new Date().toISOString(), in_flight: ['79df9cc89f5f'],
+ version: 1, status: 'running', last_active_at: staleActiveAt(), in_flight: ['79df9cc89f5f'],
}));
fs.writeFileSync(path.join(path.dirname(stateFile), 'members.json'), JSON.stringify({
version: 1,
diff --git a/test/renderer/conversation-placeholder-consume.test.ts b/test/renderer/conversation-placeholder-consume.test.ts
index fc91e11e..14aa6d19 100644
--- a/test/renderer/conversation-placeholder-consume.test.ts
+++ b/test/renderer/conversation-placeholder-consume.test.ts
@@ -121,15 +121,17 @@ function loadPlaceholderHelpers(): {
opts?: { allowActorFallback?: boolean },
) => FakePlaceholder | null;
consumeHistory: (cid: string, gm: Record<string, unknown>) => FakePlaceholder | null;
+ deferHistory: (cid: string, gm: Record<string, unknown>) => boolean;
key: (cid: string, actorId: string, turnId?: string) => string;
} {
const fns = [
'const _groupPlaceholders = new Map();',
extractFunction('_normaliseTurnId'),
extractFunction('_phKey'),
+ extractFunction('_groupMessageSystemKind'),
extractFunctionUntil('_consumeActorPlaceholder', '_consumePlaceholderForHistoryRecord'),
extractFunctionUntil('_consumePlaceholderForHistoryRecord', '_finalizeActorPlaceholder'),
- '({ placeholders: _groupPlaceholders, consume: _consumeActorPlaceholder, consumeHistory: _consumePlaceholderForHistoryRecord, key: _phKey });',
+ '({ placeholders: _groupPlaceholders, consume: _consumeActorPlaceholder, consumeHistory: _consumePlaceholderForHistoryRecord, deferHistory: _shouldDeferInterruptedHistoryRecord, key: _phKey });',
].join('\n');
return vm.runInNewContext(fns, {});
}
@@ -174,7 +176,7 @@ function loadInterruptionHelpers() {
].join('\n'), { Map }) as {
systemKind: (message: Record<string, unknown>) => string;
collapse: (messages: Array<Record<string, unknown>>) => Array<Record<string, unknown>>;
- removeBubbles: (container: FakeHistoryContainer) => void;
+ removeBubbles: (container: FakeHistoryContainer) => number;
};
}
@@ -228,7 +230,7 @@ describe('conversation actor placeholder consume', () => {
});
it('does not let an uncorrelated polled row consume a live same-actor turn', () => {
- const { placeholders, consumeHistory, key } = loadPlaceholderHelpers();
+ const { placeholders, consumeHistory, deferHistory, key } = loadPlaceholderHelpers();
const active = new FakePlaceholder({ fromActor: 'video-studio', turnId: 'turn-live' });
placeholders.set(key('cid-1', 'video-studio', 'turn-live'), active);
@@ -237,6 +239,11 @@ describe('conversation actor placeholder consume', () => {
from: 'video-studio',
system_kind: 'reply_interrupted',
})).toBeNull();
+ expect(deferHistory('cid-1', {
+ id: 'interruption-row',
+ from: 'video-studio',
+ system_kind: 'reply_interrupted',
+ })).toBe(true);
expect(consumeHistory('cid-1', {
id: 'legacy-row-without-turn',
from: 'video-studio',
@@ -245,6 +252,25 @@ describe('conversation actor placeholder consume', () => {
expect(placeholders.get(key('cid-1', 'video-studio', 'turn-live'))).toBe(active);
});
+ it('claims a genuine boot interruption only from its actor-only legacy placeholder', () => {
+ const { placeholders, consumeHistory, key } = loadPlaceholderHelpers();
+ const interrupted = new FakePlaceholder({ fromActor: 'video-studio' });
+ const resumed = new FakePlaceholder({ fromActor: 'video-studio', turnId: 'turn-live' });
+ placeholders.set(key('cid-old', 'video-studio'), interrupted);
+ placeholders.set(key('cid-live', 'video-studio', 'turn-live'), resumed);
+ const status = {
+ id: 'interruption-row',
+ from: 'video-studio',
+ system_kind: 'reply_interrupted',
+ };
+
+ expect(consumeHistory('cid-old', status)).toBe(interrupted);
+ expect(interrupted.dataset.finalized).toBe('1');
+ expect(consumeHistory('cid-live', status)).toBeNull();
+ expect(resumed.dataset.finalized).toBeUndefined();
+ expect(placeholders.get(key('cid-live', 'video-studio', 'turn-live'))).toBe(resumed);
+ });
+
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' });
@@ -380,6 +406,53 @@ describe('conversation interruption bubble collapse', () => {
expect(history.messages).toHaveLength(1);
});
+ it('does not append a false interruption below a currently running VideoStudio bubble', () => {
+ const { placeholders, consumeHistory, deferHistory, key } = loadPlaceholderHelpers();
+ const { removeBubbles } = loadInterruptionHelpers();
+ const history = new FakeHistoryContainer();
+ const live = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ {
+ fromActor: 'video-studio',
+ placeholder: '1',
+ turnId: 'turn-that-kept-running',
+ },
+ ['read_file · 完成', 'video_studio · 完成', '正在整理当前轮工具上下文'],
+ );
+ history.append(live);
+ placeholders.set(key('cid-video', 'video-studio', 'turn-that-kept-running'), live);
+ const falseInterruption = {
+ id: 'false-boot-status',
+ from: 'video-studio',
+ system_kind: 'reply_interrupted',
+ };
+
+ // This is the exact screenshot order: the live bubble already exists,
+ // then deferred boot maintenance writes an uncorrelated interruption.
+ const claimed = consumeHistory('cid-video', falseInterruption);
+ expect(claimed).toBeNull();
+ expect(deferHistory('cid-video', falseInterruption)).toBe(true);
+ if (!claimed && !deferHistory('cid-video', falseInterruption)) {
+ history.append(new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ { fromActor: 'video-studio', systemKind: 'reply_interrupted' },
+ ));
+ }
+
+ expect(live.dataset.finalized).toBeUndefined();
+ expect(history.messages).toEqual([live]);
+
+ // Also repair a row mounted by an older renderer before this guard ran.
+ const alreadyMounted = new FakeChatMessage(
+ ['chat-message', 'assistant'],
+ { fromActor: 'video-studio', systemKind: 'reply_interrupted' },
+ );
+ history.append(alreadyMounted);
+ expect(removeBubbles(history)).toBe(1);
+ expect(alreadyMounted.removed).toBe(true);
+ expect(history.messages).toEqual([live]);
+ });
+
it('collapses an interruption loaded from an older page against a newer same-actor bubble', () => {
const { removeBubbles } = loadInterruptionHelpers();
const history = new FakeHistoryContainer();