Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote): 同步应用退出后的中断红点

Dash5d814b5c5536
diff --git a/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts
index 533911d96f..739a216365 100644
--- a/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts
@@ -8,14 +8,62 @@
import { afterEach, describe, expect, it } from 'vitest';
import { sessionToCamel, setSessionRuntimeProjector, type SessionRowWithCount } from '../mapper';
+import { setSessionInterruptionBootAtForTests } from '../sessionInterruptionBoot';
+import { projectSessionActivity } from '@cindy/maker-shared/session-activity';
afterEach(() => {
setSessionRuntimeProjector(null);
+ setSessionInterruptionBootAtForTests(Date.now());
});
-function sessionRow(
- overrides: Partial<SessionRowWithCount>,
-): SessionRowWithCount {
+describe('host interruption evidence on serialized session rows', () => {
+ it('restores a pre-boot alert without activity history and clears with existing ended patches', () => {
+ setSessionInterruptionBootAtForTests(2000);
+ const session = sessionToCamel(
+ sessionRow({ source: 'desktop', activeTurnStartedAt: 1000, lastTurnEndedAt: 900 }),
+ );
+ expect(session.interruptedTurnStartedAt).toBe(1000);
+ const project = (interruption: typeof session) =>
+ projectSessionActivity({ sessionId: session.id, interruption, attention: false });
+ expect(project(session)).toMatchObject({ phase: 'error', attention: true });
+ // Viewing sends a read receipt, not a turn-ended patch.
+ expect(project({ ...session })).toMatchObject({ phase: 'error', attention: true });
+ expect(project({ ...session, lastTurnEndedAt: 1000 })).toMatchObject({
+ phase: 'idle',
+ attention: false,
+ });
+ expect(project({ ...session, clearedAt: new Date(1000).toISOString() })).toMatchObject({
+ phase: 'idle',
+ attention: false,
+ });
+ expect(project({ ...session, activeTurnStartedAt: 2500 })).toMatchObject({
+ phase: 'idle',
+ attention: false,
+ });
+ });
+
+ it.each([
+ { activeTurnStartedAt: 2000 },
+ { activeTurnStartedAt: 2500 },
+ { lastTurnEndedAt: 1000 },
+ { clearedAt: 1000 },
+ { status: 'archived' },
+ { status: 'deleted' },
+ { source: 'unknown' },
+ ])('does not mark a live, handled or hidden task: %j', (patch) => {
+ setSessionInterruptionBootAtForTests(2000);
+ const session = sessionToCamel(
+ sessionRow({
+ source: 'desktop',
+ activeTurnStartedAt: 1000,
+ ...patch,
+ } as Partial<SessionRowWithCount>),
+ );
+ expect(session.interruptedTurnStartedAt).toBeNull();
+ });
+});
+
+function sessionRow(overrides: Partial<SessionRowWithCount>): SessionRowWithCount {
const base = {
id: 's-1',
title: 'New Maker',
diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.ts
index fb9fa0a2ae..9404cd8889 100644
--- a/apps/desktop/src/main/localDb/mapper.ts
+++ b/apps/desktop/src/main/localDb/mapper.ts
@@ -8,6 +8,9 @@
*/
import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+import { hasPendingSessionInterruption } from '@cindy/maker-shared/session-activity';
+import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';
+import { getSessionInterruptionBootAt } from './sessionInterruptionBoot';
import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';
import { markdownPreviewText } from '../../shared/markdownPreviewText.js';
@@ -274,6 +277,19 @@ export function sessionToCamel(row: SessionRowWithCount): Session {
),
summary: row.summary ?? null,
};
+ // Only the owning host can distinguish a pre-boot interruption from a live
+ // turn. Keep the generation so existing ended/clear patches revoke it without
+ // another query; a normal read acknowledgement must not revoke this evidence.
+ const candidate = { ...base, interruptedTurnStartedAt: base.activeTurnStartedAt };
+ base.interruptedTurnStartedAt =
+ row.source != null &&
+ DESKTOP_VISIBLE_SESSION_SOURCES.includes(
+ row.source as (typeof DESKTOP_VISIBLE_SESSION_SOURCES)[number],
+ ) &&
+ (base.activeTurnStartedAt ?? Infinity) < getSessionInterruptionBootAt() &&
+ hasPendingSessionInterruption(candidate)
+ ? base.activeTurnStartedAt
+ : null;
return sessionRuntimeProjector ? { ...base, ...sessionRuntimeProjector(base) } : base;
}
diff --git a/apps/desktop/src/main/localDb/sessionActiveTurn.ts b/apps/desktop/src/main/localDb/sessionActiveTurn.ts
index 22a51fc58d..c8845ac31d 100644
--- a/apps/desktop/src/main/localDb/sessionActiveTurn.ts
+++ b/apps/desktop/src/main/localDb/sessionActiveTurn.ts
@@ -52,6 +52,10 @@
import { and, desc, eq, gt, inArray, isNull, lt, sql } from 'drizzle-orm';
import { getDbClient } from './client/current';
+import {
+ getSessionInterruptionBootAt,
+ setSessionInterruptionBootAtForTests,
+} from './sessionInterruptionBoot';
import { messages, sessions } from './schema';
import { createLogger } from '../logger';
import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';
@@ -329,11 +333,9 @@ function enqueueEndedWrite(sessionId: string, endedAt: number, notifyContext: un
* 检测不到(PR #879 review P1,两个 reviewer 独立指出)。现在把边界下沉进查询本身,
* 调用时机不再影响正确性。
*/
-let _bootAtMs = Date.now();
-
/** 测试专用:定格「本进程启动时刻」,让中断判定不依赖真实时钟。 */
export function _setBootAtMsForTests(ms: number): void {
- _bootAtMs = ms;
+ setSessionInterruptionBootAtForTests(ms);
}
/**
@@ -360,11 +362,13 @@ export async function listInterruptedPendingRows(): Promise<
gt(sessions.activeTurnStartedAt, sql`COALESCE(${sessions.lastTurnEndedAt}, 0)`),
gt(sessions.activeTurnStartedAt, sql`COALESCE(${sessions.clearedAt}, 0)`),
// 只认「开始于本进程启动之前」的 turn —— 排除正在跑的(见 _bootAtMs 注释)。
- lt(sessions.activeTurnStartedAt, _bootAtMs),
+ lt(sessions.activeTurnStartedAt, getSessionInterruptionBootAt()),
),
);
// startedAt 必非 null(上面的 gt/lt 比较已排除),类型收窄用于批量处置的 CAS。
- return rows.flatMap((r) => (r.startedAt == null ? [] : [{ sessionId: r.id, startedAt: r.startedAt }]));
+ return rows.flatMap((r) =>
+ r.startedAt == null ? [] : [{ sessionId: r.id, startedAt: r.startedAt }],
+ );
}
/** 同上,只要会话 id —— 红点首拉用。 */
@@ -612,5 +616,5 @@ export function _resetSessionActiveTurnStateForTests(): void {
// bootAt 一并重置:它在模块 import 时定格,而用例常以「相对 now 的 startedAt」
// 造数据 —— 文件内前置用例的累计耗时一旦超过该相对差,后续用例的中断判定就会
// 因 startedAt >= bootAt 静默翻转(时钟脆弱)。每个用例重新定基消除顺序耦合。
- _bootAtMs = Date.now();
+ setSessionInterruptionBootAtForTests(Date.now());
}
diff --git a/apps/desktop/src/main/localDb/sessionInterruptionBoot.ts b/apps/desktop/src/main/localDb/sessionInterruptionBoot.ts
new file mode 100644
index 0000000000..2c162d99a6
--- /dev/null
+++ b/apps/desktop/src/main/localDb/sessionInterruptionBoot.ts
@@ -0,0 +1,11 @@
+/** One host boot boundary for the pending-alert query and session serialization. */
+let bootAtMs = Date.now();
+
+export function getSessionInterruptionBootAt(): number {
+ return bootAtMs;
+}
+
+/** Test-only: keep query and serialized interruption evidence on the same clock. */
+export function setSessionInterruptionBootAtForTests(value: number): void {
+ bootAtMs = value;
+}
diff --git a/apps/desktop/src/renderer/__tests__/remoteInterruptedAttention.test.ts b/apps/desktop/src/renderer/__tests__/remoteInterruptedAttention.test.ts
new file mode 100644
index 0000000000..fdf0555ddf
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteInterruptedAttention.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+import {
+ projectSidebarSessionActivity,
+ resolveSidebarRightStatus,
+} from '../features/cc-agent/sidebar/sidebarRightStatus';
+import { resolveCollapsedAttention } from '../features/cc-agent/sidebar/projectCollapsedAttention';
+
+const interruption = {
+ status: 'active',
+ activeTurnStartedAt: 1000,
+ interruptedTurnStartedAt: 1000,
+ lastTurnEndedAt: 900,
+};
+
+describe('persisted interruption on remote Desktop', () => {
+ it('keeps the red dot after reading without relying on the local notification store', () => {
+ const input = {
+ sessionId: 'remote',
+ interruption,
+ attentionKind: undefined,
+ isUrgentFromContext: false,
+ isRunning: false,
+ hasAttentionNotification: false,
+ };
+ expect(resolveSidebarRightStatus(projectSidebarSessionActivity(input))).toBe('error');
+ expect(
+ resolveSidebarRightStatus(
+ projectSidebarSessionActivity({
+ ...input,
+ interruption: { ...interruption, lastTurnEndedAt: 1000 },
+ }),
+ ),
+ ).toBe('time');
+ });
+
+ it('exposes an older interrupted child in collapsed projects and automation groups', () => {
+ const input = {
+ sessions: [{ id: 'old', ...interruption }, { id: 'new' }],
+ runningSessionIds: new Set<string>(),
+ notifications: new Set<string>(),
+ attentionKinds: new Map(),
+ urgentSessionIds: new Set<string>(),
+ remotePhaseOf: () => undefined,
+ };
+ expect(resolveCollapsedAttention(input)).toEqual({ tone: 'error', errorSessionIds: ['old'] });
+ expect(
+ resolveCollapsedAttention({
+ ...input,
+ sessions: [{ id: 'old', ...interruption, lastTurnEndedAt: 1000 }],
+ }),
+ ).toEqual({ tone: null, errorSessionIds: [] });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index e448908bbe..e007f882c3 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -252,6 +252,7 @@ export const AutomationSessionGroupItem = memo(function AutomationSessionGroupIt
// 只是档位改由整组决定。
const latestHasNotification = latestSessionId != null && notifications.has(latestSessionId);
const groupActivity = projectSidebarSessionActivity({
+ interruption: latestSession,
sessionId: latestSessionId ?? '',
title: latestSession?.title,
recordStatus: latestSession?.status,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index d214721ea1..66eb6ee8ca 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -174,6 +174,7 @@ export const SessionCard = memo(function SessionCard({
const remoteActivity = useRemoteSessionActivity(session.id);
const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
const sessionActivity = projectSidebarSessionActivity({
+ interruption: session,
sessionId: session.id,
title: session.title,
recordStatus: session.status,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index 34152fe31c..f47451e8d8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -404,6 +404,7 @@ export const SessionItem = memo(function SessionItem({
const remoteActivity = useRemoteSessionActivity(session.id);
const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
const sessionActivity = projectSidebarSessionActivity({
+ interruption: session,
sessionId: session.id,
title: session.title,
recordStatus: session.status,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
index df8e396845..2cbd1b9771 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
@@ -1,4 +1,8 @@
import type { AttentionKind } from '@/lib/sessionAttentionStore';
+import {
+ hasPendingSessionInterruption,
+ type SessionInterruptionState,
+} from '@cindy/maker-shared/session-activity';
import type { RemoteSessionActivityPhase } from '@/features/device-link/remoteSessionActivityStore';
export type CollapsedAttentionTone = 'error' | 'done';
@@ -6,7 +10,7 @@ export type CollapsedAttentionTone = 'error' | 'done';
export type CollapsedProjectAttentionTone = CollapsedAttentionTone;
interface CollapsedAttentionInput {
- sessions: readonly { id: string }[];
+ sessions: readonly ({ id: string } & SessionInterruptionState)[];
runningSessionIds: ReadonlySet<string>;
notifications: ReadonlySet<string>;
attentionKinds: ReadonlyMap<string, AttentionKind>;
@@ -49,6 +53,10 @@ export function resolveCollapsedAttention({
const errorSessionIds: string[] = [];
for (const session of sessions) {
+ if (hasPendingSessionInterruption(session)) {
+ errorSessionIds.push(session.id);
+ continue;
+ }
if (urgentSessionIds.has(session.id)) {
errorSessionIds.push(session.id);
continue;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
index 83558c2ae1..9bf73d1132 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
@@ -1,6 +1,7 @@
import {
projectSessionActivity,
type SessionActivitySnapshot,
+ type SessionInterruptionState,
} from '@cindy/maker-shared/session-activity';
import type { AttentionKind } from '@/lib/sessionAttentionStore';
@@ -9,6 +10,7 @@ export { resolveSessionRightStatus as resolveSidebarRightStatus } from '@cindy/m
export type { SessionRightStatus as SidebarRightStatusKind } from '@cindy/maker-shared/session-activity';
export interface SidebarRightStatusInput {
+ interruption?: SessionInterruptionState;
sessionId: string;
title?: string | null;
recordStatus?: SessionActivitySnapshot['recordStatus'];
@@ -37,6 +39,7 @@ export interface SidebarRightStatusInput {
/** Collapse local/remote live state and legacy attention fallbacks into one model. */
export function projectSidebarSessionActivity({
+ interruption,
sessionId,
title,
recordStatus,
@@ -51,6 +54,7 @@ export function projectSidebarSessionActivity({
const awaitingAttention = hasAttentionNotification && attentionKind === 'awaiting';
const doneAttention = hasAttentionNotification && !errorAttention && !awaitingAttention;
return projectSessionActivity({
+ interruption,
sessionId,
recordStatus: liveActivity?.recordStatus ?? recordStatus,
title,
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index 0ceefd1eb9..ce7bf1e497 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -299,6 +299,8 @@ export interface Session {
* 消费方按 null 兜底(不提示)。
*/
activeTurnStartedAt?: number | null;
+ /** Host-confirmed pre-boot interruption generation; absent on older hosts. */
+ interruptedTurnStartedAt?: number | null;
lastTurnEndedAt?: number | null;
/**
* worktree-parallel-sessions: 本 session 绑定的 git worktree 绝对路径(null = 无 worktree)。
diff --git a/apps/mobile/src/__tests__/sessionRightStatus.test.ts b/apps/mobile/src/__tests__/sessionRightStatus.test.ts
index ee8dfcde26..90e45ce9d4 100644
--- a/apps/mobile/src/__tests__/sessionRightStatus.test.ts
+++ b/apps/mobile/src/__tests__/sessionRightStatus.test.ts
@@ -17,6 +17,35 @@ const base = {
scheduleUnreadCount: 0,
} as const;
+it('shows the host interruption without live activity, survives read ACK and clears on resolution', () => {
+ const interruption = {
+ status: 'active',
+ activeTurnStartedAt: 1000,
+ interruptedTurnStartedAt: 1000,
+ lastTurnEndedAt: 900,
+ };
+ expect(resolveMobileSessionRightStatus({ ...base, interruption })).toBe('error');
+ expect(
+ resolveMobileSessionRightStatus({
+ ...base,
+ interruption,
+ liveAttention: false,
+ }),
+ ).toBe('error');
+ expect(
+ resolveMobileSessionRightStatus({
+ ...base,
+ interruption: { ...interruption, lastTurnEndedAt: 1000 },
+ }),
+ ).toBe('time');
+ expect(
+ resolveMobileSessionRightStatus({
+ ...base,
+ interruption: { ...interruption, interruptedTurnStartedAt: undefined },
+ }),
+ ).toBe('time');
+});
+
describe('resolveMobileSessionRightStatus', () => {
it('error 未读压过一切(含 running 与待处理交互)', () => {
expect(resolveMobileSessionRightStatus({
diff --git a/apps/mobile/src/session/sessionRightStatus.ts b/apps/mobile/src/session/sessionRightStatus.ts
index 1b8e5d80b0..fe2252a5b5 100644
--- a/apps/mobile/src/session/sessionRightStatus.ts
+++ b/apps/mobile/src/session/sessionRightStatus.ts
@@ -16,18 +16,30 @@
* 即使 liveActivity 缺失(relay 断连)也能点亮 awaiting。
* - scheduleUnreadCount / scheduleHasUnreadFailedRun:同桌面自动化运行账本。
*/
-import { projectSessionActivity, resolveSessionRightStatus, resolveCollapsedGroupRightStatus, type SessionRightStatus } from '@cindy/maker-shared/session-activity';
+import {
+ projectSessionActivity,
+ resolveSessionRightStatus,
+ resolveCollapsedGroupRightStatus,
+ type SessionRightStatus,
+ type SessionInterruptionState,
+} from '@cindy/maker-shared/session-activity';
type SessionRow = import('@cindy/maker-shared/session-list').RemoteSessionListItem;
export type MobileSessionRightStatus = SessionRightStatus;
export function latestMobileSessionRow(item: SessionRow): SessionRow {
- return item.automationGroup?.items.reduce((a, b) =>
- Date.parse(b.session.userSendAt ?? b.session.updatedAt ?? b.session.createdAt) > Date.parse(a.session.userSendAt ?? a.session.updatedAt ?? a.session.createdAt) ? b : a,
- ) ?? item;
+ return (
+ item.automationGroup?.items.reduce((a, b) =>
+ Date.parse(b.session.userSendAt ?? b.session.updatedAt ?? b.session.createdAt) >
+ Date.parse(a.session.userSendAt ?? a.session.updatedAt ?? a.session.createdAt)
+ ? b
+ : a,
+ ) ?? item
+ );
}
export interface MobileSessionRightStatusInput {
+ interruption?: SessionInterruptionState;
/** liveActivity.phase(缺失 = 无 relay 数据)。 */
livePhase: 'running' | 'needs-interaction' | 'completed' | 'error' | undefined;
/** liveActivity.attention === true(未读标志,main 侧维护已读语义)。 */
@@ -42,6 +54,7 @@ export interface MobileSessionRightStatusInput {
}
export function resolveMobileSessionRightStatus({
+ interruption,
livePhase,
liveAttention,
pendingInteractionCount,
@@ -49,14 +62,21 @@ export function resolveMobileSessionRightStatus({
scheduleUnreadCount,
scheduleHasUnreadFailedRun = false,
}: MobileSessionRightStatusInput): MobileSessionRightStatus {
- return resolveSessionRightStatus(projectSessionActivity({
- sessionId: '',
- livePhase,
- running,
- waitingForUser: pendingInteractionCount > 0,
- terminal: scheduleHasUnreadFailedRun ? 'error' : scheduleUnreadCount > 0 ? 'completed' : null,
- attention: liveAttention || pendingInteractionCount > 0 || scheduleUnreadCount > 0 || scheduleHasUnreadFailedRun,
- }));
+ return resolveSessionRightStatus(
+ projectSessionActivity({
+ interruption,
+ sessionId: '',
+ livePhase,
+ running,
+ waitingForUser: pendingInteractionCount > 0,
+ terminal: scheduleHasUnreadFailedRun ? 'error' : scheduleUnreadCount > 0 ? 'completed' : null,
+ attention:
+ liveAttention ||
+ pendingInteractionCount > 0 ||
+ scheduleUnreadCount > 0 ||
+ scheduleHasUnreadFailedRun,
+ }),
+ );
}
/** Group header mirrors the latest run; collapsed errors remain discoverable. */
@@ -67,14 +87,17 @@ export function resolveMobileSessionRowStatus(
): { status: MobileSessionRightStatus; target: import('@cindy/maker-shared/session-list').RemoteSessionListItem } {
const children = item.automationGroup?.items;
const latest = latestMobileSessionRow(item);
- const statusOf = (row: typeof item, isRunning: boolean) => resolveMobileSessionRightStatus({
- livePhase: row.liveActivity?.phase,
- liveAttention: row.liveActivity?.attention === true,
- pendingInteractionCount: row.pendingInteractionCount,
- running: isRunning || row.liveActivity?.phase === 'running' || row.scheduleInfo?.running === true,
- scheduleUnreadCount: row.scheduleInfo?.unreadCount ?? 0,
- scheduleHasUnreadFailedRun: row.scheduleInfo?.hasUnreadFailedRun,
- });
+ const statusOf = (row: typeof item, isRunning: boolean) =>
+ resolveMobileSessionRightStatus({
+ interruption: row.session,
+ livePhase: row.liveActivity?.phase,
+ liveAttention: row.liveActivity?.attention === true,
+ pendingInteractionCount: row.pendingInteractionCount,
+ running:
+ isRunning || row.liveActivity?.phase === 'running' || row.scheduleInfo?.running === true,
+ scheduleUnreadCount: row.scheduleInfo?.unreadCount ?? 0,
+ scheduleHasUnreadFailedRun: row.scheduleInfo?.hasUnreadFailedRun,
+ });
const error = children?.find((row) => statusOf(row, false) === 'error');
const hasDone = children?.some((row) => statusOf(row, false) === 'done');
return {
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index c6146939d0..6018b40a09 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -59,6 +59,8 @@ export interface RemoteSession {
* 原样透出,startedAt > endedAt 且未被 /clear 越过 = 上次 turn 因应用退出被中断,
* 见桌面 sessionActiveTurn.ts)。老被控端缺省 → 判定恒不命中,banner 不出现。 */
activeTurnStartedAt?: number | null;
+ /** Host-confirmed pre-boot interruption generation; absent on older hosts. */
+ interruptedTurnStartedAt?: number | null;
lastTurnEndedAt?: number | null;
status: RemoteSessionStatus;
agentKind: 'cc' | 'codex' | 'pi';
diff --git a/packages/maker-shared/src/__tests__/sessionInterruption.test.ts b/packages/maker-shared/src/__tests__/sessionInterruption.test.ts
new file mode 100644
index 0000000000..43ca8a6c73
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/sessionInterruption.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { hasPendingSessionInterruption } from '../sessionActivity.js';
+import { groupAutomationListItems, toRemoteSessionListItem } from '../sessionList.js';
+
+describe('shared persisted interruption projection', () => {
+ const interrupted = {
+ status: 'active', activeTurnStartedAt: 1000, interruptedTurnStartedAt: 1000,
+ lastTurnEndedAt: 900,
+ };
+
+ it('requires host evidence and keeps resolutions independent of the viewing device clock', () => {
+ expect(hasPendingSessionInterruption(interrupted)).toBe(true);
+ for (const patch of [
+ { interruptedTurnStartedAt: undefined }, { interruptedTurnStartedAt: NaN },
+ { activeTurnStartedAt: 2000 }, { lastTurnEndedAt: 1000 },
+ { clearedAt: new Date(1000).toISOString() }, { status: 'archived' },
+ ]) expect(hasPendingSessionInterruption({ ...interrupted, ...patch })).toBe(false);
+ });
+
+ it('makes an older interrupted automation the collapsed group target until handled', () => {
+ const base = { agentKind: 'cc', createdAt: new Date(1000).toISOString(), updatedAt: new Date(1000).toISOString(), model: '', title: 'Patrol', workingDir: null, source: 'scheduler', status: 'active' };
+ const old = { ...base, ...interrupted, id: 'old' };
+ const latest = { ...base, id: 'latest', updatedAt: new Date(3000).toISOString() };
+ const group = (prior: typeof old) => groupAutomationListItems([toRemoteSessionListItem(prior), toRemoteSessionListItem(latest)], 4000)[0];
+ expect(group(old).automationGroup?.primarySessionId).toBe('old');
+ expect(group({ ...old, lastTurnEndedAt: 1000 }).automationGroup?.primarySessionId).toBe('latest');
+ });
+});
diff --git a/packages/maker-shared/src/sessionActivity.ts b/packages/maker-shared/src/sessionActivity.ts
index 17e6bb993f..e022e9089a 100644
--- a/packages/maker-shared/src/sessionActivity.ts
+++ b/packages/maker-shared/src/sessionActivity.ts
@@ -79,6 +79,7 @@ export interface SessionActivityTransition {
}
export interface SessionActivityProjectionInput {
+ interruption?: SessionInterruptionState;
sessionId: string;
recordStatus?: SessionRecordStatus;
title?: string | null;
@@ -96,6 +97,29 @@ export interface SessionActivityProjectionInput {
gracefulStopState?: SessionGracefulStopState;
}
+/** Optional host evidence; old hosts omit it. Read receipts do not dismiss alerts. */
+export interface SessionInterruptionState {
+ interruptedTurnStartedAt?: number | null;
+ activeTurnStartedAt?: number | null;
+ lastTurnEndedAt?: number | null;
+ clearedAt?: string | null;
+ status?: string;
+}
+
+export function hasPendingSessionInterruption(
+ session: SessionInterruptionState | undefined,
+): boolean {
+ const started = session?.interruptedTurnStartedAt;
+ if (!session || typeof started !== 'number' || !Number.isFinite(started) || started <= 0)
+ return false;
+ return (
+ session.status === 'active' &&
+ session.activeTurnStartedAt === started &&
+ started > (session.lastTurnEndedAt ?? 0) &&
+ started > (session.clearedAt ? Date.parse(session.clearedAt) : 0)
+ );
+}
+
const WORKFLOW_RULES: readonly {
key: string;
waitingOn?: SessionWorkflowWaitTarget;
@@ -155,16 +179,17 @@ function resolvePhase(input: SessionActivityProjectionInput): SessionActivityPha
export function projectSessionActivity(
input: SessionActivityProjectionInput,
): SessionActivitySnapshot {
+ const interrupted = hasPendingSessionInterruption(input.interruption);
return {
sessionId: input.sessionId,
- phase: resolvePhase(input),
+ phase: interrupted ? 'error' : resolvePhase(input),
currentTurnActive: input.running === true || input.livePhase === 'running',
...(input.recordStatus ? { recordStatus: input.recordStatus } : {}),
startedAtMs: input.startedAtMs ?? null,
lastActivityAtMs: input.lastActivityAtMs ?? null,
currentActionSummary: input.currentActionSummary?.trim() || null,
...(input.interactionKind ? { interactionKind: input.interactionKind } : {}),
- attention: input.attention === true,
+ attention: interrupted || input.attention === true,
workflow: sessionWorkflowFromTitle(input.title),
turnGeneration: input.turnGeneration ?? null,
gracefulStopState: input.gracefulStopState ?? 'none',
diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.ts
index 8933b116f4..ae2db837d7 100644
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@ -2,6 +2,7 @@ import { messageContentToPreview } from './messageNormalize.js';
import { stripTrailingPathSeparators } from './pathText.js';
import { presentationDate, presentationText, type PresentationLocalizer } from './presentationLocalization.js';
import { isSyntheticTriggerText } from './syntheticTrigger.js';
+import { hasPendingSessionInterruption, type SessionInterruptionState } from './sessionActivity.js';
import type { RemoteSchedule, RemoteScheduleRun } from './scheduleTypes.js';
import { toMillis, isUnreadScheduleRun, isUnreadFailedScheduleRun } from './scheduleModel.js';
import { sessionCollaborationLabel, sessionWorktreeLabel } from './sessionIdentity.js';
@@ -9,7 +10,7 @@ import { isDefaultDraftSessionTitle } from './sessionTitle.js';
import { getSessionListCollapseView } from './sessionListCollapse.js';
import { collapseWorktreeDirForGrouping } from './worktreePaths.js';
-export interface RemoteSessionListSessionLike {
+export interface RemoteSessionListSessionLike extends SessionInterruptionState {
_count?: { messages?: number } | null;
agentKind: 'cc' | 'codex' | string;
createdAt: string;
@@ -518,10 +519,14 @@ function remoteSessionListItemExemptFromCollapse(
/** 需关注:等待处理交互 / 自动化未读 run / live activity 请求关注。 */
function remoteSessionListItemNeedsAttention(item: RemoteSessionListItem): boolean {
+ if (hasPendingSessionInterruption(item.session)) return true;
if (item.pendingInteractionCount > 0) return true;
if ((item.scheduleInfo?.unreadCount ?? 0) > 0) return true;
const live = item.liveActivity;
- return !!live && (live.attention === true || live.phase === 'needs-interaction' || live.phase === 'error');
+ return (
+ !!live &&
+ (live.attention === true || live.phase === 'needs-interaction' || live.phase === 'error')
+ );
}
function remoteSessionListItemIsRunning(
@@ -639,7 +644,7 @@ export function buildSessionScheduleIndex(
const isLatest = !existing || firedAt >= existing.latestRunAt;
index.set(run.sessionId, {
scheduleId: isLatest ? scheduleId : existing.scheduleId,
- scheduleName: isLatest ? (schedule?.name || scheduleId) : existing.scheduleName,
+ scheduleName: isLatest ? schedule?.name || scheduleId : existing.scheduleName,
scheduleStatus: isLatest ? schedule?.status : existing.scheduleStatus,
allSchedulesStopped: false,
unreadRunIds,
@@ -680,7 +685,9 @@ function matchesStatusFilter(
): boolean {
if (filter === 'all') return session.status !== 'deleted';
if (filter === 'waiting') {
- return session.status !== 'deleted' && (options.pendingInteractionIndex?.get(session.id) ?? 0) > 0;
+ return (
+ session.status !== 'deleted' && (options.pendingInteractionIndex?.get(session.id) ?? 0) > 0
+ );
}
if (filter === 'automation') {
return session.status !== 'deleted' && isAutomationSession(session, options.scheduleIndex);
@@ -864,7 +871,8 @@ function toAutomationGroupListItem(
// 组行的活动时间取组内最新一条,不跟随 primary —— primary 可能是较旧的未读 / 运行中 run,
// 用它的时间会让上游(首页项目卡 latestActivityAt、日期分桶、行右侧时间)把整组排成旧活动。
const latestActivityAt = group.reduce(
- (latest, item) => (item.lastActivityAt.localeCompare(latest) > 0 ? item.lastActivityAt : latest),
+ (latest, item) =>
+ item.lastActivityAt.localeCompare(latest) > 0 ? item.lastActivityAt : latest,
primary.lastActivityAt,
);
return {
@@ -913,9 +921,14 @@ function toAutomationGroupListItem(
* 与桌面折叠组一致:未读失败优先,其余打开最新运行;等待交互仍在展开子行显示。
*/
function pickAutomationPrimaryItem(group: readonly RemoteSessionListItem[]): RemoteSessionListItem {
- return group.find((item) => item.scheduleInfo?.hasUnreadFailedRun
- || (item.liveActivity?.phase === 'error' && item.liveActivity.attention))
- ?? group.reduce((a, b) => lastActivity(b.session) > lastActivity(a.session) ? b : a);
+ return (
+ group.find(
+ (item) =>
+ hasPendingSessionInterruption(item.session) ||
+ item.scheduleInfo?.hasUnreadFailedRun ||
+ (item.liveActivity?.phase === 'error' && item.liveActivity.attention),
+ ) ?? group.reduce((a, b) => (lastActivity(b.session) > lastActivity(a.session) ? b : a))
+ );
}
function mergeScheduleInfo(group: readonly RemoteSessionListItem[]): RemoteSessionScheduleInfo | null {
@@ -968,11 +981,13 @@ function isSearchablePreviewMessage(message: RemoteMessage): boolean {
// 消息流渲染成「已自动继续」分隔卡,预览同样不能把它当用户消息展示——按文本
// 过滤不可行(用户真发「继续」是合法消息),只认落库标记。
if (message.role === 'user' && message.agentMeta?.autoResume === true) return false;
- return message.role === 'user'
- || message.role === 'assistant'
- || message.role === 'system'
- || message.role === 'ask_user'
- || message.role === 'plan_review';
+ return (
+ message.role === 'user' ||
+ message.role === 'assistant' ||
+ message.role === 'system' ||
+ message.role === 'ask_user' ||
+ message.role === 'plan_review'
+ );
}
export function sessionRowMessagePreview(session: RemoteSession): string | null {