Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(session): 修复手机任务红点残留与恢复状态不一致 (#4942)
Chris Zhangf66afa34f234
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.tsindex 558bf3a6bd..78ca227391 100644--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts@@ -366,6 +366,40 @@ describe('active runtime summary projection', () => {expect(rows[0].capabilities.availableModels[0].description).toHaveLength(120_000);});+ it('keeps only the canonical activity flags needed to clear stale mobile dots', () => {+ const projected = __testing.projectInvokeResultForTunnel(+ 'maker:list-active', [{+ ...rows[0], activityPhase: 'running', activityAttention: false,+ }, {+ ...rows[1], activityPhase: 'idle', activityAttention: false,+ }], false, [{ summary: true }],+ );+ expect(projected).toEqual([{+ sessionId: 'session-0', isTurnRunning: true,+ activityPhase: 'running', activityAttention: false,+ }, {+ sessionId: 'session-1', isTurnRunning: false,+ activityPhase: 'idle', activityAttention: false,+ }]);+ });++ it('preserves the opt-in complete snapshot envelope while projecting its runtime rows', () => {+ const projected = __testing.projectInvokeResultForTunnel(+ 'maker:list-active', { format: 'active-sessions-v2', sessions: rows },+ false, [{ summary: true, snapshotVersion: 2 }],+ );+ expect(projected).toEqual({ format: 'active-sessions-v2', sessions: [+ { sessionId: 'session-0', isTurnRunning: true },+ { sessionId: 'session-1', isTurnRunning: false },+ ] });+ expect(__testing.projectInvokeResultForTunnel(+ 'maker:list-active', rows, false, [{ summary: true, snapshotVersion: 2 }],+ )).toEqual([+ { sessionId: 'session-0', isTurnRunning: true },+ { sessionId: 'session-1', isTurnRunning: false },+ ]);+ });+it.each([[], [null], [{ summary: false }], [{ summary: 'true' }]])('preserves the complete response for legacy or non-opt-in callers (%j)', (...args) => {expect(__testing.projectInvokeResultForTunnel('maker:list-active', rows, false, args))diff --git a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.tsindex 85e1b12021..54e0fece33 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts@@ -55,6 +55,15 @@ it('fails closed for incomplete batch results, rejects hidden gets and clears aexpect(batch).toHaveBeenCalledTimes(1);});+it('filters hidden runtime rows inside a complete active-session snapshot', async () => {+ setRemoteBotSessionLookup(async (id) => id === 'hidden' ? 'hidden' : 'ordinary');+ expect(await projectRemoteSessionResult('maker:list-active', {+ format: 'active-sessions-v2', sessions: [+ { sessionId: 'visible' }, { sessionId: 'hidden' },+ ],+ })).toEqual({ format: 'active-sessions-v2', sessions: [{ sessionId: 'visible' }] });+});+it('filters batch detail reads using the shared fresh visibility lookup', async () => {let hidden = false;diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 14701eda83..3d59ff4f55 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -569,12 +569,25 @@ function projectInvokeResultForTunnel(const options = args[0];if (channel === 'maker:list-active' && options && typeof options === 'object'&& !Array.isArray(options) && 'summary' in options && options.summary === true- && Array.isArray(result)) {- return result.map((item: unknown) => {+ && (Array.isArray(result) || (+ 'snapshotVersion' in options && options.snapshotVersion === 2+ && result && typeof result === 'object' && !Array.isArray(result)+ && 'format' in result && result.format === 'active-sessions-v2'+ && 'sessions' in result && Array.isArray(result.sessions)+ ))) {+ const complete = !Array.isArray(result);+ const rows = complete ? (result as { sessions: unknown[] }).sessions : result;+ const projected = rows.map((item: unknown) => {if (!item || typeof item !== 'object' || Array.isArray(item)) return item;const row = item as Record<string, unknown>;- return { sessionId: row.sessionId, isTurnRunning: row.isTurnRunning };+ return {+ sessionId: row.sessionId,+ isTurnRunning: row.isTurnRunning,+ ...(typeof row.activityPhase === 'string' && typeof row.activityAttention === 'boolean'+ ? { activityPhase: row.activityPhase, activityAttention: row.activityAttention } : {}),+ };});+ return complete ? { format: 'active-sessions-v2', sessions: projected } : projected;}if (channel === 'maker:schedule:list-sidebar-index-runs') {return capScheduleSidebarIndexForTunnel(result);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex b62bbc38d5..ba4ff0ae43 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -15872,14 +15872,32 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions));});- ipcMain.handle(MAKER_INVOKE.LIST_ACTIVE, () => {- return maker.listActiveSessions().map((s) => ({- sessionId: s.id,- agentKind: s.agentKind,- workDir: s.workDir,- capabilities: s.capabilities,- isTurnRunning: s.isTurnRunning(),- }));+ ipcMain.handle(MAKER_INVOKE.LIST_ACTIVE, (_event, options?: unknown) => {+ const activityService = getAgentIslandService();+ const activityById = new Map(activityService?.getSessionActivitySnapshots()+ .map((activity) => [activity.sessionId, activity] as const) ?? []);+ const sessions = maker.listActiveSessions().map((s) => {+ const activity = activityById.get(s.id);+ return {+ sessionId: s.id,+ agentKind: s.agentKind,+ workDir: s.workDir,+ capabilities: s.capabilities,+ isTurnRunning: s.isTurnRunning(),+ ...(activityService ? {+ activityPhase: activity?.phase ?? 'idle',+ activityAttention: activity?.attention ?? false,+ } : {}),+ };+ });+ // Only an opted-in controller may treat an absent runtime as idle. Legacy+ // callers keep the array response and its original absence semantics.+ if (options && typeof options === 'object' && !Array.isArray(options)+ && (options as Record<string, unknown>).summary === true+ && (options as Record<string, unknown>).snapshotVersion === 2) {+ return { format: 'active-sessions-v2', sessions };+ }+ return sessions;});ipcMain.handle(diff --git a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.tsindex 0ffbebc11e..adf99dce5e 100644--- a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts@@ -304,6 +304,23 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {expect(window.electronAPI.maker.schedule.listSidebarIndexRuns).toHaveBeenCalledTimes(1);});+ it('clears recovered failure urgency on completion without opening or marking the task read', async () => {+ const runs = [indexRun({ runId: 'failure', status: 'failed', readAt: undefined, firedAt: 10 })];+ stubApiWithRuns(runs);+ const { result } = renderHook(() => useAutomationScheduleSessionIndex());+ await waitFor(() => expect(result.current.get('session-1')?.hasUnreadFailedRun).toBe(true));++ runs.push(indexRun({ runId: 'success', status: 'success', readAt: undefined, firedAt: 20 }));+ await act(async () => {+ scheduleEventListener?.({ type: 'completed', scheduleId: 'schedule-1', runId: 'success', sessionId: 'session-1' });+ });+ await waitFor(() => expect(result.current.get('session-1')).toMatchObject({+ hasUnreadFailedRun: false, hasFailedRun: false, hasUnreadRun: true,+ unreadRunIds: ['success'], unreadFailedRunIds: [],+ }));+ expect(runs[0].readAt).toBeUndefined();+ });+it('keeps a recovered warning cleared after reopening the task', async () => {stubApiWithRuns([indexRun({ runId: 'read-failure', status: 'failed', readAt: 30, firedAt: 10 }),diff --git a/apps/desktop/src/renderer/__tests__/scheduleRecoveryStatus.test.ts b/apps/desktop/src/renderer/__tests__/scheduleRecoveryStatus.test.tsnew file mode 100644index 0000000000..05e250abfb--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/scheduleRecoveryStatus.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { projectScheduleSidebarIndex } from '@/features/scheduler/lib/projectScheduleSidebarIndex';+import type { ScheduleSidebarIndexRun } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';+import { projectSidebarSessionActivity, resolveSidebarRightStatus } from '@/features/cc-agent/sidebar/sidebarRightStatus';++const failure: ScheduleSidebarIndexRun = {+ runId: 'failure', scheduleId: 'schedule', scheduleName: 'Check',+ scheduleStatus: 'active', sessionId: 'task', status: 'failed', firedAt: 1,+};+const success: ScheduleSidebarIndexRun = { ...failure, runId: 'success', status: 'success', firedAt: 2 };++function status(runs: ScheduleSidebarIndexRun[], liveError = false) {+ const info = projectScheduleSidebarIndex(runs).get('task')!;+ return {+ info,+ dot: resolveSidebarRightStatus(projectSidebarSessionActivity({+ sessionId: 'task', attentionKind: undefined,+ liveActivity: liveError ? { phase: 'error', attention: true } : undefined,+ isUrgentFromContext: info.hasUnreadFailedRun,+ hasAttentionNotification: info.hasUnreadRun,+ isRunning: false,+ })),+ };+}++describe('task status after schedule recovery', () => {+ it.each([false, true])('retires an old failure after success, independent of arrival order (reversed=%s)', (reversed) => {+ const rows = [failure, success];+ const { info, dot } = status(reversed ? rows.reverse() : rows);+ expect(info.latestFailedRun).toBeUndefined();+ expect(dot).toBe('done');+ expect(info.unreadRunIds).toEqual(['success']);+ expect(info.unreadFailedRunIds).toEqual([]);+ expect(info.latestUnreadFailedRunId).toBeUndefined();+ });++ it('does not turn recovered unread history into a new completion badge after the success was read', () => {+ const { info, dot } = status([failure, { ...success, readAt: 3 }]);+ expect(info.hasUnreadRun).toBe(false);+ expect(dot).toBe('time');+ });++ it('honors host recovery even when the successful run is absent from the lightweight snapshot', () => {+ expect(status([{ ...failure, failureRecovered: true }]).dot).toBe('time');+ });++ it('keeps real failures red: no recovery, another schedule success, and a new failure after success', () => {+ for (const rows of [[failure], [failure, { ...success, scheduleId: 'other' }],+ [failure, success, { ...failure, runId: 'new-failure', firedAt: 3 }]]) {+ expect(status(rows).dot).toBe('error');+ }+ });++ it('does not clear the actual task error when its background schedule recovers', () => {+ expect(status([failure, success], true).dot).toBe('error');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/scheduleUnreadRunCounts.test.ts b/apps/desktop/src/renderer/__tests__/scheduleUnreadRunCounts.test.tsnew file mode 100644index 0000000000..6b224ac0fc--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/scheduleUnreadRunCounts.test.ts@@ -0,0 +1,69 @@+// @vitest-environment jsdom+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import type { Schedule, SchedulerEvent } from '@cindy/maker-scheduler';+import { useScheduleUnreadRunCounts } from '@/features/scheduler/hooks/useScheduleUnreadRunCounts';+import type { ScheduleSidebarIndexRun } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';++function run(overrides: Partial<ScheduleSidebarIndexRun>): ScheduleSidebarIndexRun {+ return {+ runId: 'failure', scheduleId: 'schedule-1', scheduleName: 'Schedule',+ scheduleStatus: 'active', status: 'failed', firedAt: 10, ...overrides,+ };+}++function mountCounts(runs: ScheduleSidebarIndexRun[]) {+ let listener: ((event: SchedulerEvent) => void) | undefined;+ vi.stubGlobal('electronAPI', { maker: { schedule: {+ listSidebarIndexRuns: vi.fn().mockResolvedValue({ runs }),+ onEvent: vi.fn((callback: (event: SchedulerEvent) => void) => {+ listener = callback;+ return () => { listener = undefined; };+ }),+ } } });+ const schedules = [{ id: 'schedule-1' }, { id: 'schedule-2' }] as Schedule[];+ return {+ ...renderHook(() => useScheduleUnreadRunCounts(schedules)),+ complete: () => listener?.({ type: 'completed', scheduleId: 'schedule-1', runId: 'success', sessionId: 'session-1' }),+ };+}++afterEach(() => vi.unstubAllGlobals());++it('clears recovered failures on completion while retaining unread success until read', async () => {+ const runs = [run({})];+ const view = mountCounts(runs);+ await waitFor(() => expect(view.result.current.get('schedule-1')).toBe(1));++ runs.unshift(run({ runId: 'success', status: 'success', firedAt: 20 }));+ await act(async () => view.complete());+ expect(view.result.current.get('schedule-1')).toBe(1);++ runs[0].readAt = 30;+ await act(async () => view.complete());+ expect(view.result.current.get('schedule-1') ?? 0).toBe(0);+ expect(runs[1].readAt).toBeUndefined();++ runs.push(run({ runId: 'new-failure', status: 'interrupted', firedAt: 40 }));+ await act(async () => view.complete());+ expect(view.result.current.get('schedule-1')).toBe(1);+});++it('honors host recovery flags without requiring the success row or a session binding', async () => {+ const view = mountCounts([+ run({ failureRecovered: true }),+ run({ runId: 'unread-success', status: 'success', scheduleId: 'schedule-2' }),+ ]);+ await waitFor(() => expect(view.result.current.get('schedule-2')).toBe(1));+ expect(view.result.current.get('schedule-1') ?? 0).toBe(0);+});++it('keeps real failures when another schedule succeeds and ignores hidden schedules', async () => {+ const view = mountCounts([+ run({}),+ run({ runId: 'other-success', status: 'success', scheduleId: 'schedule-2', firedAt: 20, readAt: 30 }),+ run({ runId: 'hidden-failure', scheduleId: 'hidden' }),+ ]);+ await waitFor(() => expect(view.result.current.get('schedule-1')).toBe(1));+ expect(view.result.current.size).toBe(1);+});diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.tsindex 88e8ce532e..ac375c534e 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts@@ -3,7 +3,7 @@ import type { Schedule, SchedulerEvent } from '@cindy/maker-scheduler';import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { createLogger } from '@/lib/logger';-import { isUnreadScheduleRun } from '../lib/runUnread';+import { activeScheduleFailures, isUnreadScheduleRun } from '@cindy/maker-shared/schedule-model';import { loadScheduleSidebarIndexRuns } from '../lib/scheduleSidebarIndexRuns';import { subscribeScheduleRunReadSync } from '../lib/scheduleRunReadSync';@@ -33,10 +33,13 @@ export function useScheduleUnreadRunCounts(const runs = await loadScheduleSidebarIndexRuns();if (refreshSeqRef.current !== seq) return;+ const activeFailures = activeScheduleFailures(runs.map((run) => ({ ...run, id: run.runId })));const next = new Map<string, number>();for (const run of runs) {if (!visibleScheduleIds.has(run.scheduleId)) continue;if (!isUnreadScheduleRun(run)) continue;+ // Recovered failures remain unread in history, but no longer light task indicators.+ if (run.status !== 'success' && !activeFailures.has(run.runId)) continue;next.set(run.scheduleId, (next.get(run.scheduleId) ?? 0) + 1);}setCounts(next);diff --git a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.tsindex b1ff99c6f6..dd8713313e 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts@@ -16,9 +16,10 @@ export function projectScheduleSidebarIndex(const existing = next.get(run.sessionId);const unreadRunIds = existing?.unreadRunIds ? [...existing.unreadRunIds] : [];const unreadFailedRunIds = existing?.unreadFailedRunIds ? [...existing.unreadFailedRunIds] : [];- // 只对未读 run 累加(与 isUnreadScheduleRun 对齐)。failed / interrupted- // 未读 run 拉高本 session 的 urgency 让侧栏涂红而不是涂绿。- const isRunUnread = isUnreadScheduleRun(run);+ // Match the in-task warning: recovered failures stay in history, but must+ // not keep a red dot (or become a false completion dot after recovery).+ const isUnreadFailure = activeFailures.has(run.runId) && isUnreadFailedScheduleRun(run);+ const isRunUnread = isUnreadScheduleRun(run) && (run.status === 'success' || isUnreadFailure);if (isRunUnread) unreadRunIds.push(run.runId);let latestFailedRun = existing?.latestFailedRun;if (activeFailures.has(run.runId)) {@@ -27,7 +28,7 @@ export function projectScheduleSidebarIndex(latestFailedRun = candidate;}let latestUnreadFailedRunId = existing?.latestUnreadFailedRunId;- if (isUnreadFailedScheduleRun(run)) {+ if (isUnreadFailure) {unreadFailedRunIds.push(run.runId);const firedAt = run.firedAt ?? 0;if (firedAt >= (latestUnreadFailedFiredAt.get(run.sessionId) ?? Number.NEGATIVE_INFINITY)) {diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex d6bcd49cbd..473688a859 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -3548,7 +3548,7 @@ export default function SessionScreen() {commitRead('active', fetchActiveSessionSnapshot, (activeSessionSnapshot) => {remoteSessionStore.setActiveSessionSnapshots(deviceId,- Array.isArray(activeSessionSnapshot.activeSessions) ? activeSessionSnapshot.activeSessions : [],+ activeSessionSnapshot.activeSessions,activeSessionSnapshot.activityEpochAtFetchStart,);}),diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex 7d238f9c3e..e6318d6bbb 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -433,8 +433,8 @@ describe('mobile home desktop-first surface', () => {expect(source).toContain('saveDeviceIdentityCache(result.cache)');expect(source).toContain('loadDeviceSessionScheduleIndex(deviceId, invoke,');expect(source).toContain('replaceSessionScheduleIndexEntries(');- expect(source).toContain("invoke<unknown[]>(device.deviceId, 'maker:list-active', [");- expect(source).toContain("{ summary: true }");+ expect(source).toContain("invoke<unknown>(device.deviceId, 'maker:list-active', [");+ expect(source).toContain("{ summary: true, snapshotVersion: 2 }");expect(source).toContain('if (isOptionalActiveSessionSnapshotError(err)) return null;');expect(source).toContain('function isOptionalActiveSessionSnapshotError(error: unknown): boolean');expect(source).toContain('if (isAccessRevokedError(error) || isDeviceOfflineError(error)) return false;');diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex af4a512dbf..abfcb5e9a4 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -443,7 +443,7 @@ describe("mobile maker transport", () => {{deviceId: "dev-1",channel: "maker:list-active",- args: [{ summary: true }],+ args: [{ summary: true, snapshotVersion: 2 }],},]);});diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex d7c7a88885..db7865e3d6 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -2747,6 +2747,59 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.isSessionRunning('s2')).toBe(true);});+ it('reconciles a missed error-clear push from an authoritative active activity snapshot', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1', phase: 'error', attention: true,+ });+ expect(remoteSessionStore.getSessionLiveActivity('s1')).toMatchObject({ phase: 'error', attention: true });++ // 旧主机没有活动字段,运行标记本身不足以判定旧错误已读。+ remoteSessionStore.setActiveSessionSnapshots('dev-1', [{ sessionId: 's1', isTurnRunning: true }]);+ expect(remoteSessionStore.getSessionLiveActivity('s1')).toMatchObject({ phase: 'error', attention: true });++ remoteSessionStore.setActiveSessionSnapshots('dev-1', [{+ sessionId: 's1', isTurnRunning: true,+ activityPhase: 'running', activityAttention: false,+ }]);+ expect(remoteSessionStore.getSessionLiveActivity('s1')).toMatchObject({ phase: 'running', attention: false });+ expect(remoteSessionStore.isSessionRunning('s1')).toBe(true);++ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1', phase: 'running', attention: false, workingPhase: 'testing',+ });+ remoteSessionStore.setActiveSessionSnapshots('dev-1', [{+ sessionId: 's1', isTurnRunning: true,+ activityPhase: 'running', activityAttention: false,+ }]);+ expect(remoteSessionStore.getSessionLiveActivity('s1')?.workingPhase).toBe('testing');+ });++ it('does not let a delayed activity snapshot erase a newer error push', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const epoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();+ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1', phase: 'error', attention: true,+ });+ remoteSessionStore.setActiveSessionSnapshots('dev-1', [{+ sessionId: 's1', isTurnRunning: false,+ activityPhase: 'completed', activityAttention: false,+ }], epoch);+ expect(remoteSessionStore.getSessionLiveActivity('s1')).toMatchObject({ phase: 'error', attention: true });+ });++ it('clears a cached error when the host explicitly reports no remaining activity', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1', phase: 'error', attention: true,+ });+ remoteSessionStore.setActiveSessionSnapshots('dev-1', [{+ sessionId: 's1', isTurnRunning: false,+ activityPhase: 'idle', activityAttention: false,+ }]);+ expect(remoteSessionStore.getSessionLiveActivity('s1')).toBeNull();+ });+it('does not treat an absent active-session row as an idle assertion', () => {vi.useFakeTimers();try {@@ -2769,6 +2822,45 @@ describe('remoteSessionStore', () => {}});+ it('clears a missed error and stale running state for a runtime absent from a complete snapshot', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.setDeviceSessions('dev-2', 'Mac mini', [session('s2')]);+ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1', phase: 'error', attention: true,+ });+ remoteSessionStore.applySessionActivity('dev-2', {+ sessionId: 's2', phase: 'error', attention: true,+ });+ remoteSessionStore.setSessionRunning('s1', true);++ // A legacy host also returns an empty array, without claiming completeness.+ remoteSessionStore.setActiveSessionSnapshots('dev-1', []);+ expect(remoteSessionStore.getSessionLiveActivity('s1')).toMatchObject({ phase: 'error', attention: true });+ expect(remoteSessionStore.isSessionRunning('s1')).toBe(true);++ remoteSessionStore.setActiveSessionSnapshots('dev-1', {+ format: 'active-sessions-v2', sessions: [],+ });++ expect(remoteSessionStore.getSessionLiveActivity('s1')).toBeNull();+ expect(remoteSessionStore.isSessionRunning('s1')).toBe(false);+ expect(remoteSessionStore.getSessionLiveActivity('s2')).toMatchObject({ phase: 'error', attention: true });+ });++ it('does not let a delayed complete snapshot clear a newer activity push', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const epoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();+ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1', phase: 'error', attention: true,+ });++ remoteSessionStore.setActiveSessionSnapshots('dev-1', {+ format: 'active-sessions-v2', sessions: [],+ }, epoch);++ expect(remoteSessionStore.getSessionLiveActivity('s1')).toMatchObject({ phase: 'error', attention: true });+ });+it('clears stale reconnect progress from an active snapshot without erasing newer retry events', () => {remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.tsindex 79252474a5..324c05ab7a 100644--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts@@ -18,6 +18,7 @@ import {SCHEDULE_INDEX_THROTTLE_TTL_MS,} from '@/session/scheduleIndex';import type { RemoteSessionScheduleInfo } from '@/session/sessionList';+import { resolveMobileSessionRightStatus } from '@/session/sessionRightStatus';import { markSessionScheduleRunsRead } from '@/session/scheduleRunRead';function makerWithSchedules(@@ -35,6 +36,31 @@ function makerWithSchedules(}describe('scheduleIndex', () => {+ it.each(['lightweight', 'legacy'] as const)('reconciles recovered failure dots with task details through %s reads', async (source) => {+ const failure = { id: 'failure', runId: 'failure', scheduleId: 'sched-1', scheduleName: 'Check',+ scheduleStatus: 'active', sessionId: 'task', status: 'failed', firedAt: 1 };+ const success = { ...failure, id: 'success', runId: 'success', status: 'success', firedAt: 2 };+ const rows = [failure, success];+ const maker = makerWithSchedules(async (id) => id === 'sched-1' ? rows : []);+ const load = async () => source === 'lightweight'+ ? loadLightweightSessionScheduleIndex('device', vi.fn().mockResolvedValue({ runs: rows }))+ : loadSessionScheduleIndex(maker);+ const dot = (info: RemoteSessionScheduleInfo) => resolveMobileSessionRightStatus({+ livePhase: undefined, liveAttention: false, pendingInteractionCount: 0, running: false,+ scheduleUnreadCount: info.unreadCount, scheduleHasUnreadFailedRun: info.hasUnreadFailedRun,+ });+ const recovered = (await load()).get('task')!;+ expect(recovered.latestFailedRun).toBeUndefined();+ expect(dot(recovered)).toBe('done');+ expect(recovered.unreadRunIds).toEqual(['success']);++ // A fresh failure must still be visible both in the task and on its row.+ rows.push({ ...failure, id: 'new-failure', runId: 'new-failure', firedAt: 3 });+ const failed = (await load()).get('task')!;+ expect(failed.latestFailedRun?.runId).toBe('new-failure');+ expect(dot(failed)).toBe('error');+ });+it.each([false, true])('peer recovery invalidates only its success or pending snapshot (pending=%s)', async (pending) => {resetScheduleIndexThrottleForTesting();let finish!: (value: Map<string, RemoteSessionScheduleInfo>) => void;diff --git a/apps/mobile/src/__tests__/scheduleModel.test.ts b/apps/mobile/src/__tests__/scheduleModel.test.tsindex 29c485a9f2..b9072764a0 100644--- a/apps/mobile/src/__tests__/scheduleModel.test.ts+++ b/apps/mobile/src/__tests__/scheduleModel.test.ts@@ -167,7 +167,8 @@ describe('schedule model', () => {const runs = [run({ id: 'running', status: 'running', readAt: undefined }),run({ id: 'failed', status: 'failed', errorMsg: 'boom', readAt: undefined }),- run({ id: 'read', status: 'success', readAt: NOW }),+ // 这条已读成功发生在失败之前,不构成恢复。+ run({ id: 'read', status: 'success', firedAt: NOW - 120_000, readAt: NOW }),];expect(countUnreadRuns(runs, NOW)).toBe(1);diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex f8621d72ea..7baa719571 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -322,6 +322,11 @@ export interface MobileActiveSessionSnapshot {isTurnRunning?: boolean;}+export type MobileActiveSessionSnapshotResult = MobileActiveSessionSnapshot[] | {+ format: 'active-sessions-v2';+ sessions: MobileActiveSessionSnapshot[];+};+/** 被控端视角的模型单价(USD / 百万 token,同桌面 useModelPricing 形状)。 */export interface MobileModelPrice {inputUsdPerMtok: number;@@ -516,7 +521,7 @@ export interface MobileMakerTransport {createOpts?: CreateSessionOptions,sendOpts?: SendOptions,): Promise<{ accepted: true } | { accepted: false; reason?: string }>;- listActiveSessions(): Promise<MobileActiveSessionSnapshot[]>;+ listActiveSessions(): Promise<MobileActiveSessionSnapshotResult>;/*** 切模型。可选第 3 参 providerId = 同时切来源(被控端按其路由 + 持久化 provider_id)。* 不传 providerId = 老 2 参语义,不动会话当前来源选择。@@ -957,7 +962,7 @@ export function createMobileMakerTransport({call("local-db:messages:around-client-id", [sessionId, clientId, opts]),send: (sessionId, message, createOpts, sendOpts) =>call("maker:send", [sessionId, message, createOpts, sendOpts]),- listActiveSessions: () => call("maker:list-active", [{ summary: true }]),+ listActiveSessions: () => call("maker:list-active", [{ summary: true, snapshotVersion: 2 }]),setModel: async (sessionId, model, providerId, selection) => {const wireArgs = selection? [sessionId, model, providerId ?? null, null, selection]diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex f90368faaf..c94b1a3750 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -808,8 +808,8 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newSassertCurrentScope();const epoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();// Old hosts ignore this optional projection and still return the full snapshot.- const active = await invoke<unknown[]>(device.deviceId, 'maker:list-active', [- { summary: true },+ const active = await invoke<unknown>(device.deviceId, 'maker:list-active', [+ { summary: true, snapshotVersion: 2 },]).catch((err) => {if (isOptionalActiveSessionSnapshotError(err)) return null;throw err;@@ -844,7 +844,7 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newSdevice.name,nextSessions,);- if (Array.isArray(activeSessions)) {+ if (activeSessions !== null) {remoteSessionStore.setActiveSessionSnapshots(device.deviceId,activeSessions,diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 28934e1a03..ece865d361 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -4069,26 +4069,36 @@ export const remoteSessionStore = {setActiveSessionSnapshots(deviceId: string,- list: readonly unknown[],+ response: unknown,activityEpochAtFetchStart = makerActivityEpoch,): void {- // `maker:list-active` returns only currently active sessions. Absence is not- // an idle assertion: the request can have started before a turn and complete- // after a live delta, or a stale reconnect response can race a newer push.- // Only explicit boolean states in the snapshot may change a session's run- // state; terminal maker/activity events remain the idle authority.- const snapshotStates = new Map<string, boolean>();+ // Only the opted-in v2 envelope asserts a complete runtime list. Legacy+ // arrays can come from old hosts, where absence must retain its old meaning.+ const completeResponse = isRecord(response) && response.format === 'active-sessions-v2'+ && Array.isArray(response.sessions) ? response : null;+ const list: readonly unknown[] = completeResponse+ ? completeResponse.sessions as unknown[]+ : (Array.isArray(response) ? response : []);+ const snapshotStates = new Map<string, {+ running: boolean;+ activityPhase: string | null;+ activityAttention: unknown;+ }>();for (const item of list) {if (!isRecord(item)) continue;const sessionId = readString(item, 'sessionId');if (sessionId && typeof item.isTurnRunning === 'boolean') {const indexedDeviceId = sessionDeviceIndex.get(sessionId);if (indexedDeviceId && indexedDeviceId !== deviceId) continue;- snapshotStates.set(sessionId, item.isTurnRunning);+ snapshotStates.set(sessionId, {+ running: item.isTurnRunning,+ activityPhase: readString(item, 'activityPhase'),+ activityAttention: item.activityAttention,+ });}}let changed = false;- for (const [sessionId, running] of snapshotStates) {+ for (const [sessionId, { running, activityPhase, activityAttention }] of snapshotStates) {if (!running) {changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;changed = writeMakerTurnRunning(sessionId, false) || changed;@@ -4096,6 +4106,25 @@ export const remoteSessionStore = {const current = readSessionRunStatus(sessionId);const hasNewerMakerActivity = (sessionMakerActivityEpochs.get(sessionId) ?? 0)> activityEpochAtFetchStart;+ // A fresh host snapshot can repair a missed activity clear while the phone was+ // backgrounded. Old hosts omit these optional fields, so keep their push-only path.+ if (!hasNewerMakerActivity && typeof activityAttention === 'boolean'+ && (isRemoteSessionLiveActivityPhase(activityPhase) || activityPhase === 'idle')) {+ if (activityPhase === 'running' || activityPhase === 'needs-interaction'+ || (activityAttention && activityPhase !== 'idle')) {+ const previous = sessionLiveActivity.get(sessionId);+ changed = writeSessionLiveActivity(sessionId, {+ sessionId,+ phase: activityPhase,+ compactDetail: previous?.phase === activityPhase ? previous.compactDetail : '',+ workingPhase: previous?.phase === activityPhase ? previous.workingPhase : undefined,+ interactionKind: previous?.phase === activityPhase ? previous.interactionKind : undefined,+ attention: activityAttention,+ }) || changed;+ } else {+ changed = deleteSessionLiveActivity(sessionId) || changed;+ }+ }const next = clearLiveGenerationOnWideRunStart(current, {...current,isRunning: running,@@ -4105,6 +4134,25 @@ export const remoteSessionStore = {});changed = writeSessionRunStatus(sessionId, next) || changed;}+ if (completeResponse) {+ for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {+ if (indexedDeviceId !== deviceId || snapshotStates.has(sessionId)+ || (sessionMakerActivityEpochs.get(sessionId) ?? 0) > activityEpochAtFetchStart) continue;+ // A runtime absent from a complete host snapshot has ended. Do not+ // discard a newer live push that arrived while this read was in flight.+ changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;+ changed = writeMakerTurnRunning(sessionId, false) || changed;+ changed = deleteSessionLiveActivity(sessionId) || changed;+ const current = readSessionRunStatus(sessionId);+ changed = writeSessionRunStatus(sessionId, {+ ...current,+ isRunning: false,+ reconnectAttempt: null,+ sideTaskRunning: false,+ startedAt: null,+ }) || changed;+ }+ }if (changed) emit();},@@ -4506,6 +4554,7 @@ export const remoteSessionStore = {const sessionId = readString(payload, 'sessionId');const phase = readString(payload, 'phase');if (!sessionId || !isRemoteSessionLiveActivityPhase(phase)) return;+ markSessionMakerActivity(sessionId);const compactDetail = typeof payload.compactDetail === 'string' ? payload.compactDetail : '';let changed = false;if (phase === 'running' || phase === 'needs-interaction') {diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex b4a71260ec..142fd94372 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -67,10 +67,27 @@ Mobile 未新增卡片入口。服务端无需改动。`omarchyMenu`;缺省保留旧工具栏,不向旧主机发送新动作。旧端的 `desktop` 语义不变。工作区切换作用于采集屏幕,菜单使用本机固定入口,所有操作沿用控制 lease 与撤权检查。+## 手机首页会话活动快照++现有 `maker:list-active` 的可选 `{ summary: true }` 响应在运行标记之外增加+`activityPhase` / `activityAttention` 两个可选字段。被控端从现有会话活动投影提供这两个+状态字段;活动服务已就绪但该会话不在活动账本中时,明确返回 `idle` / `false`,不下发活动正文。+手机首页拿到明确字段时修正本地可能漏掉收尾推送的红点;读取期间+若收到更新的活动推送,仍以推送为准。旧被控端不提供字段时,手机保留原有推送路径;旧控制端+忽略新增字段。未新增 channel、relay 类型、持久化状态或权限。++新版手机可选请求 `{ summary: true, snapshotVersion: 2 }`。新版被控端只对该请求返回+`{ format: 'active-sessions-v2', sessions: [...] }`,表示运行时列表完整;手机据此将仍在任务+列表、但已不在运行时列表的同设备任务活动状态清为 idle。读取期间有更新的活动推送时,+不得用旧快照覆盖。旧被控端忽略新参数并返回原数组;手机遇到数组时不根据缺席清除。+旧控制端仍请求、接收原数组。该扩展不修改 relay、授权或持久化格式。+## 自动化检查恢复投影运行状态和已读回执保留历史事实。当前警告只保留未被**同一自动化**更新成功运行恢复的失败;-另一自动化成功不能清除它。检查受阻与实际执行失败分别显示;原有运行历史页面保持不变。+另一自动化成功不能清除它。任务列表红点与任务内警告共用此恢复判定;已恢复的失败即使+历史记录仍未读,也不再贡献任务列表红点或完成未读点。新的失败与真实任务终止错误仍须+正常标红。检查受阻与实际执行失败分别显示;原有运行历史页面及其已读状态保持不变。轻量侧栏协议新增可选 `failureKind` / `failureRecovered`,旧端忽略,新端缺省按普通失败处理。前置检查仍遵守 exit 0 放行、exit 2 跳过、其他值阻止执行。脚本可在 stdout 单独输出一行diff --git a/packages/maker-shared/src/__tests__/scheduleModel.test.ts b/packages/maker-shared/src/__tests__/scheduleModel.test.tsindex 78239c75dc..b0657c281f 100644--- a/packages/maker-shared/src/__tests__/scheduleModel.test.ts+++ b/packages/maker-shared/src/__tests__/scheduleModel.test.ts@@ -166,6 +166,39 @@ describe('schedule model', () => {});});+ it('counts only active failures in mobile schedule rows and overview', () => {+ const olderFailure = run({ id: 'failure', status: 'failed', firedAt: NOW - 120_000 });+ const recovered = [+ olderFailure,+ run({ id: 'success', status: 'success', firedAt: NOW - 60_000, readAt: NOW }),+ ];+ const currentSchedule = schedule({});+ const overview = (runs: RemoteScheduleRun[]) => summarizeAutomationOverview(+ [currentSchedule], new Map([[currentSchedule.id, runs]]), NOW,+ ).unreadRunCount;++ expect(countUnreadRuns(recovered, NOW)).toBe(0);+ expect(summarizeSchedule(currentSchedule, recovered, NOW).unreadCount).toBe(0);+ expect(overview(recovered)).toBe(0);+ expect(olderFailure.readAt).toBeUndefined();+ expect(summarizeRun(olderFailure, NOW).unread).toBe(true);++ const unreadSuccess = recovered.map((item) => item.id === 'success'+ ? { ...item, readAt: undefined } : item);+ expect(countUnreadRuns(unreadSuccess, NOW)).toBe(1);+ expect(overview(unreadSuccess)).toBe(1);++ const otherScheduleSuccess = run({+ id: 'other-success', scheduleId: 'sched-2', status: 'success',+ firedAt: NOW - 30_000, readAt: NOW,+ });+ expect(countUnreadRuns([olderFailure, otherScheduleSuccess], NOW)).toBe(1);++ const newFailure = run({ id: 'new-failure', status: 'interrupted', firedAt: NOW - 15_000 });+ expect(countUnreadRuns([...recovered, newFailure], NOW)).toBe(1);+ expect(overview([...recovered, newFailure])).toBe(1);+ });+it('folds repeated persistent-session runs by session id', () => {const displayRuns = displayRunsForMobile([run({ id: 'old-same-session', sessionId: 's1', firedAt: NOW - 2000 }),@@ -183,7 +216,7 @@ describe('schedule model', () => {const runs = [run({ id: 'running', status: 'running', readAt: undefined }),run({ id: 'failed', status: 'failed', errorMsg: 'boom', readAt: undefined }),- run({ id: 'read', status: 'success', readAt: NOW }),+ run({ id: 'read', status: 'success', readAt: NOW, firedAt: NOW - 120_000 }),];expect(countUnreadRuns(runs, NOW)).toBe(1);diff --git a/packages/maker-shared/src/scheduleModel.ts b/packages/maker-shared/src/scheduleModel.tsindex f9cc943031..c91ac9fde9 100644--- a/packages/maker-shared/src/scheduleModel.ts+++ b/packages/maker-shared/src/scheduleModel.ts@@ -124,7 +124,9 @@ export function displayRunsForMobile(list: readonly RemoteScheduleRun[]): Remote}export function countUnreadRuns(list: readonly RemoteScheduleRun[], now = Date.now()): number {- return list.filter((run) => isUnreadRun(run, now)).length;+ const activeFailures = activeScheduleFailures(list);+ return list.filter((run) => isUnreadRun(run, now)+ && (run.status === 'success' || activeFailures.has(run.id))).length;}export function summarizeAutomationOverview(diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.tsindex 9df52e6571..f5d24d2d15 100644--- a/packages/maker-shared/src/sessionList.ts+++ b/packages/maker-shared/src/sessionList.ts@@ -643,7 +643,12 @@ export function buildSessionScheduleIndex(const firedAt = toMillis(run.firedAt);const existing = index.get(run.sessionId);const unreadRunIds = existing ? [...existing.unreadRunIds] : [];- if (isUnreadScheduleRun(run)) unreadRunIds.push(run.id);+ // A recovered failure remains in history, but no longer represents an+ // unread task result. Use the same recovery set as the in-task notice.+ const isUnreadFailure = activeFailures.has(run.id) && isUnreadFailedScheduleRun(run);+ if (isUnreadScheduleRun(run) && (run.status === 'success' || isUnreadFailure)) {+ unreadRunIds.push(run.id);+ }const candidate = activeFailures.has(run.id) ? { runId: run.id, firedAt, scheduleId: run.scheduleId, failureKind: classifyScheduleFailure(run) } : undefined;const latestFailedRun = candidate && (!existing?.latestFailedRun || compareFailedScheduleRuns(candidate, existing.latestFailedRun) > 0)? candidate : existing?.latestFailedRun;@@ -657,7 +662,7 @@ export function buildSessionScheduleIndex(unreadRunIds,unreadCount: unreadRunIds.length,latestFailedRun,- hasUnreadFailedRun: existing?.hasUnreadFailedRun === true || isUnreadFailedScheduleRun(run),+ hasUnreadFailedRun: existing?.hasUnreadFailedRun === true || isUnreadFailure,running,latestRunAt: Math.max(existing?.latestRunAt ?? 0, firedAt),});