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(desktop): 修复任务完成后仍显示运行中 (#4468)

Dashdfc5264b811a
diff --git a/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts b/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts
index f7b6ecfb2a..c53bb0ab57 100644
--- a/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts
+++ b/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts
@@ -253,7 +253,7 @@ describe('collapsed project attention wiring', () => {
expect(automationGroupSource).not.toMatch(/useRemoteSessionActivityRevision\s*\(/);
expect(automationGroupSource).toMatch(/useSessionsAttentionKindMap\(groupSessionIds\)/);
expect(automationGroupSource).toMatch(/useSessionsAttentionUrgencyIdSet\(groupSessionIds\)/);
- expect(automationGroupSource).toMatch(/useRemoteSessionsPhaseMap\(groupSessionIds\)/);
+ expect(automationGroupSource).toMatch(/useRemoteSessionsPhaseMap\(group.sessions\)/);
});
it('opens the unread-failed session from a collapsed red group header', () => {
diff --git a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
index 325162be18..b4f114dbf1 100644
--- a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
+++ b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
@@ -108,7 +108,7 @@ describe('Projects sidebar section', () => {
'const remoteActivityRevision = useRemoteSessionActivityRevision()',
);
expect(projectsSectionSource).toContain(
- 'const activity = getRemoteSessionActivity(session.id)',
+ 'const activity = getRemoteSessionActivity(session.id, session.deviceLinkDeviceId)',
);
// running / needs-interaction / error / completed-unread 各归其档。
expect(projectsSectionSource).toMatch(
diff --git a/apps/desktop/src/renderer/__tests__/railActivityOrigin.test.ts b/apps/desktop/src/renderer/__tests__/railActivityOrigin.test.ts
new file mode 100644
index 0000000000..ffe12613a4
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/railActivityOrigin.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, expect, it } from 'vitest';
+
+import {
+ applyRemoteSessionActivity,
+ clearRemoteSessionActivity,
+} from '@/features/device-link/remoteSessionActivityStore';
+import { aggregateRailActivity } from '@/features/cc-agent/sidebar/railActivity';
+import { railPanelStore, type RailLampSession } from '@/features/cc-agent/sidebar/railPanelStore';
+
+afterEach(() => {
+ clearRemoteSessionActivity();
+ railPanelStore.setLampScope(null);
+});
+
+const aggregate = (rows: readonly RailLampSession[]) =>
+ aggregateRailActivity(rows, new Set(), new Set(), new Map(), new Set());
+
+it('keeps both same-ID device rows through panel publication and aggregation', () => {
+ const a = { id: 'same', deviceLinkDeviceId: 'a' };
+ const b = { id: 'same', deviceLinkDeviceId: 'b' };
+ applyRemoteSessionActivity('a', { sessionId: 'same', phase: 'running' });
+ railPanelStore.setLampScope({ projectSessions: [a, b], dialogueSessions: [b] });
+ const scope = railPanelStore.getSnapshot().lampScope!;
+ expect(aggregate(scope.projectSessions).running).toBe(true);
+ expect(aggregate(scope.dialogueSessions).running).toBe(false);
+ expect(aggregate([b, a]).running).toBe(true);
+ applyRemoteSessionActivity('b', { sessionId: 'same', phase: 'completed', attention: false });
+ expect(aggregate(scope.projectSessions).running).toBe(true);
+ applyRemoteSessionActivity('a', { sessionId: 'same', phase: 'completed', attention: false });
+ expect(aggregate(scope.projectSessions).running).toBe(false);
+});
+
+it('publishes a source-only scope change but keeps equal snapshots stable', () => {
+ const scope = {
+ projectSessions: [{ id: 'same', deviceLinkDeviceId: 'a' }],
+ dialogueSessions: [],
+ };
+ railPanelStore.setLampScope(scope);
+ const first = railPanelStore.getSnapshot();
+ railPanelStore.setLampScope({ ...scope, projectSessions: [{ ...scope.projectSessions[0] }] });
+ expect(railPanelStore.getSnapshot()).toBe(first);
+ railPanelStore.setLampScope({
+ ...scope,
+ projectSessions: [{ id: 'same', deviceLinkDeviceId: 'b' }],
+ });
+ expect(railPanelStore.getSnapshot()).not.toBe(first);
+ applyRemoteSessionActivity('a', { sessionId: 'same', phase: 'running' });
+ expect(aggregate(railPanelStore.getSnapshot().lampScope!.projectSessions).running).toBe(false);
+ expect(aggregate([{ id: 'same' }]).running).toBe(false);
+});
diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
index 97f8ffd8e2..6322a943de 100644
--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
@@ -289,7 +289,7 @@ describe('refreshRemoteDeviceSessions retry', () => {
await refreshRemoteDeviceSessions(d);
- expect(getRemoteSessionActivity(bot.id)?.phase).toBe('running');
+ expect(getRemoteSessionActivity(bot.id, d)?.phase).toBe('running');
expect(remoteProjectsStore.getDeviceSessions(d)[0]).toMatchObject({ runtimeEffective });
remoteProjectsStore.applyPatch(d, bot.id, { effort: 'high', listPreview: 'reply received' });
expect(remoteProjectsStore.getDeviceSessions(d)[0]).toMatchObject({
@@ -320,7 +320,7 @@ describe('refreshRemoteDeviceSessions retry', () => {
expect(invoke).toHaveBeenCalledTimes(2);
expect(remoteProjectsStore.getDeviceSessions(d)[0]?.model).toBe('gpt-6-astra');
- expect(getRemoteSessionActivity(bot.id)?.phase).toBe('running');
+ expect(getRemoteSessionActivity(bot.id, d)?.phase).toBe('running');
expect(remoteProjectsStore.getDeviceSessions(other)[0]?.deviceLinkConnectionStatus).toBe(
'connected',
);
@@ -346,7 +346,7 @@ describe('refreshRemoteDeviceSessions retry', () => {
await refreshRemoteDeviceSessions(d, 'MacBook', { snapshotMode: 'replace' });
- expect(getRemoteSessionActivity(bot.id)).toBeUndefined();
+ expect(getRemoteSessionActivity(bot.id, d)).toBeUndefined();
expect(remoteProjectsStore.getDeviceSessions(d, 'active')).toHaveLength(0);
expect(remoteProjectsStore.getDeviceSessions(d)).toHaveLength(
terminal === 'archived' ? 1 : 0,
@@ -743,7 +743,7 @@ describe('refreshRemoteDeviceSessions retry', () => {
});
expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
- expect(getRemoteSessionActivity('stale-archived')).toBeUndefined();
+ expect(getRemoteSessionActivity('stale-archived', d)).toBeUndefined();
expect(invoke).toHaveBeenCalledTimes(1);
});
@@ -772,7 +772,7 @@ describe('refreshRemoteDeviceSessions retry', () => {
expect(remoteProjectsStore.getDeviceSessions(d, 'archived')).toEqual([
expect.objectContaining({ id: 'stale-archived', status: 'archived' }),
]);
- expect(getRemoteSessionActivity('stale-archived')).toBeUndefined();
+ expect(getRemoteSessionActivity('stale-archived', d)).toBeUndefined();
});
it('周期满窗口补查 active 行时回填窗口外会话的权威元数据', async () => {
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts
index 449836e81e..670552b733 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts
@@ -28,7 +28,10 @@ describe('remoteSessionActivityStore', () => {
phase: 'running',
compactDetail: 'run tests',
});
- expect(getRemoteSessionActivity('s1')).toMatchObject({ phase: 'running', attention: false });
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toMatchObject({
+ phase: 'running',
+ attention: false,
+ });
applyRemoteSessionActivity('dev-1', {
sessionId: 's1',
@@ -37,7 +40,7 @@ describe('remoteSessionActivityStore', () => {
interactionKind: 'ask_user_question',
attention: true,
});
- expect(getRemoteSessionActivity('s1')).toMatchObject({
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toMatchObject({
phase: 'needs-interaction',
interactionKind: 'ask_user_question',
});
@@ -49,7 +52,10 @@ describe('remoteSessionActivityStore', () => {
compactDetail: '',
attention: true,
});
- expect(getRemoteSessionActivity('s1')).toMatchObject({ phase: 'completed', attention: true });
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toMatchObject({
+ phase: 'completed',
+ attention: true,
+ });
// 出错未读:保留(右槽红点)
applyRemoteSessionActivity('dev-1', {
@@ -58,7 +64,10 @@ describe('remoteSessionActivityStore', () => {
compactDetail: '',
attention: true,
});
- expect(getRemoteSessionActivity('s1')).toMatchObject({ phase: 'error', attention: true });
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toMatchObject({
+ phase: 'error',
+ attention: true,
+ });
// 已读收尾包(attention=false 终态)→ 删除,行回落时间
applyRemoteSessionActivity('dev-1', {
@@ -67,7 +76,7 @@ describe('remoteSessionActivityStore', () => {
compactDetail: '',
attention: false,
});
- expect(getRemoteSessionActivity('s1')).toBeUndefined();
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toBeUndefined();
});
it('classifies only in-flight phases as active turns', () => {
@@ -110,7 +119,7 @@ describe('remoteSessionActivityStore', () => {
applyRemoteSessionActivity('dev-1', null);
applyRemoteSessionActivity('dev-1', { phase: 'running' });
applyRemoteSessionActivity('dev-1', { sessionId: 's1', phase: 'nope' });
- expect(getRemoteSessionActivity('s1')).toBeUndefined();
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toBeUndefined();
});
it('sweeps entries per device and per session', () => {
@@ -118,11 +127,11 @@ describe('remoteSessionActivityStore', () => {
applyRemoteSessionActivity('dev-2', { sessionId: 's2', phase: 'running', compactDetail: '' });
removeRemoteSessionActivityForDevice('dev-1');
- expect(getRemoteSessionActivity('s1')).toBeUndefined();
- expect(getRemoteSessionActivity('s2')).toMatchObject({ phase: 'running' });
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toBeUndefined();
+ expect(getRemoteSessionActivity('s2', 'dev-2')).toMatchObject({ phase: 'running' });
- removeRemoteSessionActivityEntry('s2');
- expect(getRemoteSessionActivity('s2')).toBeUndefined();
+ removeRemoteSessionActivityEntry('s2', 'dev-2');
+ expect(getRemoteSessionActivity('s2', 'dev-2')).toBeUndefined();
});
it('drops unread completed/error mirrors but keeps an in-flight remote turn', () => {
@@ -143,18 +152,54 @@ describe('remoteSessionActivityStore', () => {
phase: 'running',
compactDetail: '',
});
- dropStaleRemoteTerminalActivity('done');
- dropStaleRemoteTerminalActivity('err');
- dropStaleRemoteTerminalActivity('run');
- expect(getRemoteSessionActivity('done')).toBeUndefined();
- expect(getRemoteSessionActivity('err')).toBeUndefined();
- expect(getRemoteSessionActivity('run')).toMatchObject({ phase: 'running' });
+ dropStaleRemoteTerminalActivity('done', 'dev-1');
+ dropStaleRemoteTerminalActivity('err', 'dev-1');
+ dropStaleRemoteTerminalActivity('run', 'dev-1');
+ expect(getRemoteSessionActivity('done', 'dev-1')).toBeUndefined();
+ expect(getRemoteSessionActivity('err', 'dev-1')).toBeUndefined();
+ expect(getRemoteSessionActivity('run', 'dev-1')).toMatchObject({ phase: 'running' });
});
it('keeps snapshot reference stable when payload content is unchanged', () => {
applyRemoteSessionActivity('dev-1', { sessionId: 's1', phase: 'running', compactDetail: 'x' });
- const first = getRemoteSessionActivity('s1');
+ const first = getRemoteSessionActivity('s1', 'dev-1');
applyRemoteSessionActivity('dev-1', { sessionId: 's1', phase: 'running', compactDetail: 'x' });
- expect(getRemoteSessionActivity('s1')).toBe(first);
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toBe(first);
+ });
+ it('isolates local tasks and identical session IDs on different devices', () => {
+ applyRemoteSessionActivity('a', { sessionId: 'same', phase: 'running' });
+ applyRemoteSessionActivity('b', { sessionId: 'same', phase: 'error', attention: true });
+ expect(getRemoteSessionActivity('same', undefined)).toBeUndefined();
+ expect(getRemoteSessionActivity('same', null)).toBeUndefined();
+ expect(getRemoteSessionActivity('same', 'a')?.phase).toBe('running');
+ expect(getRemoteSessionActivity('same', 'b')?.phase).toBe('error');
+ expect(getRemoteSessionActivity('same', 'unknown')).toBeUndefined();
+
+ applyRemoteSessionActivity('b', { sessionId: 'same', phase: 'completed', attention: false });
+ expect(getRemoteSessionActivity('same', 'b')).toBeUndefined();
+ expect(getRemoteSessionActivity('same', 'a')?.phase).toBe('running');
+ removeRemoteSessionActivityEntry('same', 'b');
+ expect(getRemoteSessionActivity('same', 'a')?.phase).toBe('running');
+ });
+
+ it('scopes starting cleanup and device removal to the matching device', () => {
+ for (const deviceId of ['a', 'b']) {
+ applyRemoteSessionActivity(deviceId, {
+ sessionId: 'same',
+ phase: 'completed',
+ attention: true,
+ });
+ }
+ dropStaleRemoteTerminalActivity('same', undefined);
+ expect(getRemoteSessionActivity('same', 'a')).toBeDefined();
+ dropStaleRemoteTerminalActivity('same', 'a');
+ expect(getRemoteSessionActivity('same', 'a')).toBeUndefined();
+ expect(getRemoteSessionActivity('same', 'b')).toBeDefined();
+ applyRemoteSessionActivity('a', { sessionId: 'same', phase: 'running' });
+ removeRemoteSessionActivityForDevice('b');
+ expect(getRemoteSessionActivity('same', 'a')?.phase).toBe('running');
+ expect(getRemoteSessionActivity('same', 'b')).toBeUndefined();
+ clearRemoteSessionActivity();
+ expect(getRemoteSessionActivity('same', 'a')).toBeUndefined();
});
});
diff --git a/apps/desktop/src/renderer/__tests__/sessionAttentionStoreIntent.test.ts b/apps/desktop/src/renderer/__tests__/sessionAttentionStoreIntent.test.ts
index 296eb1e2a6..e4bd4caae9 100644
--- a/apps/desktop/src/renderer/__tests__/sessionAttentionStoreIntent.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionAttentionStoreIntent.test.ts
@@ -297,7 +297,7 @@ describe('clearSystemSessionAttention 的远程路由', () => {
'notification:clear-session-attention',
['rs1', 'passive'],
);
- removeRemoteSessionActivityEntry('rs1');
+ removeRemoteSessionActivityEntry('rs1', 'dev1');
});
it('aborts in-flight retries when new unread arrives, then re-queues as passive', async () => {
@@ -331,7 +331,7 @@ describe('clearSystemSessionAttention 的远程路由', () => {
'notification:clear-session-attention',
['rs1', 'passive'],
);
- removeRemoteSessionActivityEntry('rs1');
+ removeRemoteSessionActivityEntry('rs1', 'dev1');
} finally {
vi.useRealTimers();
}
@@ -382,7 +382,7 @@ describe('clearSystemSessionAttention 的远程路由', () => {
['rs1', 'explicit'],
);
- removeRemoteSessionActivityEntry('rs1');
+ removeRemoteSessionActivityEntry('rs1', 'dev1');
});
it('a sync already in flight at enqueue time does not release the receipt', () => {
diff --git a/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts b/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts
index 21202d6ff8..9df1522606 100644
--- a/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts
@@ -8,6 +8,10 @@ import {
clearRemoteSessionActivity,
getRemoteSessionActivity,
} from '@/features/device-link/remoteSessionActivityStore';
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ getSessionDeviceId: (id: string) => (id === 's1' ? 'dev-1' : undefined),
+}));
+
import {
absorbSessionStarting,
clearSessionStarting,
@@ -63,7 +67,7 @@ describe('sessionStartingStore', () => {
attention: true,
});
markSessionStarting('s1');
- expect(getRemoteSessionActivity('s1')).toBeUndefined();
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toBeUndefined();
expect([...getStartingSessionIds()]).toEqual(['s1']);
applyRemoteSessionActivity('dev-1', {
@@ -73,7 +77,7 @@ describe('sessionStartingStore', () => {
attention: true,
});
markSessionStarting('s1');
- expect(getRemoteSessionActivity('s1')).toMatchObject({ phase: 'completed' });
+ expect(getRemoteSessionActivity('s1', 'dev-1')).toMatchObject({ phase: 'completed' });
absorbSessionStarting(['s1']);
expect([...getStartingSessionIds()]).toEqual([]);
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 238ddb7a2c..2c1ee8e63e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1102,7 +1102,7 @@ export function CCAgentSessionView({
// 交互时,session 行天然是 startedAt > endedAt,不能把这个正常在飞窗口误判成
// 「应用退出中断」。直接门控首帧,再锁存本次视图,避免 activity 终态与 ended patch
// 先后到达时横幅闪现。
- const remoteSessionActivity = useRemoteSessionActivity(sessionId ?? '');
+ const remoteSessionActivity = useRemoteSessionActivity(sessionId ?? '', remoteDeviceId);
const remoteTurnActive = isRemoteSessionActivityActive(remoteSessionActivity);
// device-link 远程会话:非选中行镜像**被控端自己的全局模型预设**。先 pull 一次,再订阅
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 007608d85f..0d42a80f69 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -1137,7 +1137,8 @@ function ExpandedView({
notifications: sidebarNotifications,
attentionKinds,
urgentSessionIds: urgentSet,
- remotePhaseOf: (sessionId) => getRemoteSessionActivity(sessionId)?.phase,
+ remotePhaseOf: (sessionId, deviceId) =>
+ getRemoteSessionActivity(sessionId, deviceId)?.phase,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容
[
@@ -2100,7 +2101,10 @@ function ExpandedView({
// true 但内容更新」的场景(前一次收尾包丢失 / 延迟时,新 completed/error/
// needs-interaction 到来布尔值不变)。attention 回落不计——那通常是本回执生效后
// relay 推回的收尾包,重发只是无谓 invoke。
- const activeRemoteActivity = useRemoteSessionActivity(viewedSessionId ?? '');
+ const activeRemoteActivity = useRemoteSessionActivity(
+ viewedSessionId ?? '',
+ getSessionDeviceId(viewedSessionId ?? ''),
+ );
const activeRemoteAttention = activeRemoteActivity?.attention === true;
const activeRemoteActivitySig = activeRemoteActivity
? `${activeRemoteActivity.phase}|${activeRemoteActivity.attention === true ? 1 : 0}|${activeRemoteActivity.interactionKind ?? ''}|${activeRemoteActivity.compactDetail}`
@@ -4112,11 +4116,8 @@ function RailPanels({
// RailNav 的段灯据此聚合(review P2「灯绕过筛选/截断」两条的根治)。
useEffect(() => {
railPanelStore.setLampScope({
- projectSessionIds: [
- ...projects.flatMap((p) => p.sessions.map((sess) => sess.id)),
- ...unclassified.map((sess) => sess.id),
- ],
- dialogueSessionIds: dialogues.map((sess) => sess.id),
+ projectSessions: [...projects.flatMap((p) => p.sessions), ...unclassified],
+ dialogueSessions: dialogues,
});
}, [projects, unclassified, dialogues]);
@@ -4270,10 +4271,10 @@ function RailPanels({
if (tone && (!best || rank[tone] > rank[best])) best = tone;
};
for (const s of list) {
- if (runningSessionIds.has(s.id)) running = true;
+ if (!s.deviceLinkDeviceId && runningSessionIds.has(s.id)) running = true;
// 远程会话灯语与 rail 段灯同源(remoteLampOf):本地 running/attention
// 对被控端后台会话是盲区,不并入会出现「段灯亮、项目行不亮」(codex review)。
- const remote = remoteLampOf(s.id);
+ const remote = remoteLampOf(s.id, s.deviceLinkDeviceId);
if (remote) {
if (remote.running) running = true;
consider(remote.tone);
@@ -4302,7 +4303,7 @@ function RailPanels({
const panelNotifications = useMemo(() => {
const remoteIds: string[] = [];
const collect = (list: readonly Session[]) => {
- for (const s of list) if (remoteLampOf(s.id)) remoteIds.push(s.id);
+ for (const s of list) if (remoteLampOf(s.id, s.deviceLinkDeviceId)) remoteIds.push(s.id);
};
collect(dialogues);
collect(unclassified);
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 e007f882c3..ec69f2d2e2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -164,7 +164,7 @@ export const AutomationSessionGroupItem = memo(function AutomationSessionGroupIt
);
const groupAttentionKinds = useSessionsAttentionKindMap(groupSessionIds);
const groupUrgentSessionIds = useSessionsAttentionUrgencyIdSet(groupSessionIds);
- const groupRemotePhases = useRemoteSessionsPhaseMap(groupSessionIds);
+ const groupRemotePhases = useRemoteSessionsPhaseMap(group.sessions);
const collapsedAttention = useMemo(
() =>
resolveCollapsedAttention({
@@ -223,8 +223,13 @@ export const AutomationSessionGroupItem = memo(function AutomationSessionGroupIt
const latestUrgentFromSchedule = useSessionAttentionUrgency(latestSessionId ?? '');
const latestChatKind = useSessionAttentionKind(latestSessionId ?? '');
const latestLocalActivity = useAgentIslandActivity(latestSessionId ?? '');
- const latestRemoteActivity = useRemoteSessionActivity(latestSessionId ?? '');
- const latestLiveActivity = latestRemoteActivity ?? latestLocalActivity;
+ const latestRemoteActivity = useRemoteSessionActivity(
+ latestSessionId ?? '',
+ latestSession?.deviceLinkDeviceId,
+ );
+ const latestLiveActivity = latestSession?.deviceLinkDeviceId
+ ? latestRemoteActivity
+ : latestLocalActivity;
const scheduleId = group.scheduleId;
// 「已停止」= paused(用户主动暂停)+ expired(计划到期不再触发);两者对用户体验
// 而言都是「不会再自动跑」,视觉上都在 Timer chip 上叠 Pause 徽标,并在 tooltip
@@ -233,7 +238,9 @@ export const AutomationSessionGroupItem = memo(function AutomationSessionGroupIt
const hasVisibleChildren = visibleSessions.length > 0;
// running / loading 也只看最新那条:组头 vendor mark 呼吸 + Timer chip 呼吸 + 右侧
// spinner 都据此,与最新 session 子行一致(需求:「loading 状态和最新的 session 保持一致」)。
- const isRunning = latestSessionId != null && runningSessionIds.has(latestSessionId);
+ const isRunning = latestSessionId != null && latestSession?.deviceLinkDeviceId
+ ? latestRemoteActivity?.phase === 'running'
+ : latestSessionId != null && runningSessionIds.has(latestSessionId);
const primaryActivityIso = latestSession?.updatedAt;
const hasActiveHidden =
activeSessionId != null &&
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
index 9988f5abb8..dea1c527d7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
@@ -24,7 +24,6 @@ import { cn } from '@/lib/utils';
import type { Session } from '@/lib/ccAgent.types';
import type { AttentionKind } from '@/lib/sessionAttentionStore';
import {
- getRemoteSessionActivity,
useRemoteSessionActivityRevision,
} from '@/features/device-link/remoteSessionActivityStore';
import { AttentionDot } from '@/components/sidebar/AttentionDot';
@@ -37,8 +36,10 @@ import { projectIdentityKeyForSession } from '../lib/projectGrouping';
import { getSessionDisplayTitle } from '../lib/sessionDisplayTitle';
import { SessionStatusIcon } from './SessionStatusIcon';
import { formatSidebarTime } from '../lib/formatSidebarTime';
-import { railPanelStore, type RailPanelSection } from './railPanelStore';
+import { railPanelStore, type RailLampSession, type RailPanelSection } from './railPanelStore';
import { resolveSessionCardBody } from './sessionCardPreview';
+import { aggregateRailActivity, dotToneOf, remoteLampOf } from './railActivity';
+export { remoteLampOf } from './railActivity';
/** 预览卡宽度(px)——旧 RailFlyout 同宽。 */
const PREVIEW_WIDTH = 208;
@@ -63,8 +64,6 @@ export interface RailNavProps {
onReorderPinned: (newOrderIds: string[]) => void;
}
-const TONE_RANK: Record<AttentionKind, number> = { error: 3, awaiting: 2, done: 1 };
-
/** 置顶瓷砖短标签:拉丁首词 ≤7 字符,否则 CJK 取前 4 字(CSS ellipsis 兜底)。 */
function pinnedTileLabel(title: string): string {
const trimmed = title.trim();
@@ -73,35 +72,6 @@ function pinnedTileLabel(title: string): string {
return trimmed.slice(0, 4);
}
-function dotToneOf(
- id: string,
- notifications: ReadonlySet<string>,
- attentionKinds: ReadonlyMap<string, AttentionKind>,
- urgentSessionIds: ReadonlySet<string>,
-): AttentionKind | null {
- if (!notifications.has(id)) return null;
- const kind = attentionKinds.get(id);
- if (kind === 'error' || urgentSessionIds.has(id)) return 'error';
- if (kind === 'awaiting') return 'awaiting';
- return 'done';
-}
-
-/** device-link 远程会话的灯语补充:本地 running/attention 链路对被控端后台会话
- * 是盲区,SessionItem 行内状态由 remoteSessionActivityStore 驱动 —— rail 聚合灯
- * 与置顶瓷砖必须并入同一镜像,否则远程会话「行亮而入口不亮」(codex review)。
- * phase → 灯语映射与 SessionItem.remoteRightStatus 同一张表;镜像里 completed/
- * error 条目仅在未读(attention)期间存在,存在即未读。 */
-export function remoteLampOf(id: string): { running: boolean; tone: AttentionKind | null } | null {
- const remote = getRemoteSessionActivity(id);
- if (!remote) return null;
- if (remote.phase === 'running') return { running: true, tone: null };
- return {
- running: false,
- tone:
- remote.phase === 'error' ? 'error' : remote.phase === 'needs-interaction' ? 'awaiting' : 'done',
- };
-}
-
interface PreviewState {
session: Session;
anchorRight: number;
@@ -230,24 +200,10 @@ export function RailNav({
// store,不是 React 状态,必须靠版本号入依赖才能跟上被控端 relay 推送)。
const remoteActivityRevision = useRemoteSessionActivityRevision();
- const aggregateIds = useCallback(
- (ids: readonly string[]) => {
- let running = false;
- let best: AttentionKind | null = null;
- const consider = (tone: AttentionKind | null) => {
- if (tone && (!best || TONE_RANK[tone] > TONE_RANK[best])) best = tone;
- };
- for (const id of ids) {
- if (runningSessionIds.has(id)) running = true;
- consider(dotToneOf(id, notifications, attentionKinds, urgentSessionIds));
- const remote = remoteLampOf(id);
- if (remote) {
- if (remote.running) running = true;
- consider(remote.tone);
- }
- }
- return { running, dotTone: best };
- },
+ const aggregateSessions = useCallback(
+ (rows: readonly RailLampSession[]) => aggregateRailActivity(
+ rows, runningSessionIds, notifications, attentionKinds, urgentSessionIds,
+ ),
// eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 remoteLampOf 读到的整表内容
[runningSessionIds, notifications, attentionKinds, urgentSessionIds, remoteActivityRevision],
);
@@ -275,17 +231,17 @@ export function RailNav({
// 挂载,lampScope 照常发布)。
const projectsAgg = useMemo(
() =>
- aggregateIds(
- panelState.lampScope?.projectSessionIds ?? projectLampSessions.map((s) => s.id),
+ aggregateSessions(
+ panelState.lampScope?.projectSessions ?? projectLampSessions,
),
- [aggregateIds, panelState.lampScope, projectLampSessions],
+ [aggregateSessions, panelState.lampScope, projectLampSessions],
);
const dialoguesAgg = useMemo(
() =>
- aggregateIds(
- panelState.lampScope?.dialogueSessionIds ?? dialogueLampSessions.map((s) => s.id),
+ aggregateSessions(
+ panelState.lampScope?.dialogueSessions ?? dialogueLampSessions,
),
- [aggregateIds, panelState.lampScope, dialogueLampSessions],
+ [aggregateSessions, panelState.lampScope, dialogueLampSessions],
);
const [preview, setPreview] = useState<PreviewState | null>(null);
@@ -329,8 +285,10 @@ export function RailNav({
renderItem={(session) => {
const isActive = session.id === activeSessionId;
// 置顶瓷砖与聚合灯同口径:远程会话的 running/未读并入远程活动镜像。
- const remoteLamp = remoteLampOf(session.id);
- const isRunning = runningSessionIds.has(session.id) || remoteLamp?.running === true;
+ const remoteLamp = remoteLampOf(session.id, session.deviceLinkDeviceId);
+ const isRunning =
+ (session.deviceLinkDeviceId == null && runningSessionIds.has(session.id)) ||
+ remoteLamp?.running === true;
const hasUnread = notifications.has(session.id) || remoteLamp?.tone != null;
// 瓷砖短标签、aria-label、悬浮预览卡都用同一个显示标题:置顶一条刚建的会话时
// 原始标题是内部哨兵,原样用会让 rail 上出现 "New Maker"(短标签甚至会截成 "New")。
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 66eb6ee8ca..e8608aafaf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -171,17 +171,17 @@ export const SessionCard = memo(function SessionCard({
// 本地 attention 链路,与 SessionItem 完全一致。
const attentionKind = useSessionAttentionKind(session.id);
const isUrgentFromContext = useSessionAttentionUrgency(session.id);
- const remoteActivity = useRemoteSessionActivity(session.id);
+ const remoteActivity = useRemoteSessionActivity(session.id, session.deviceLinkDeviceId);
const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
const sessionActivity = projectSidebarSessionActivity({
interruption: session,
sessionId: session.id,
title: session.title,
recordStatus: session.status,
- liveActivity: remoteActivity ?? islandActivity,
+ liveActivity: session.deviceLinkDeviceId ? remoteActivity : islandActivity,
attentionKind,
isUrgentFromContext: isUrgentFromContext || remoteSchedule?.hasUnreadFailedRun === true,
- isRunning,
+ isRunning: session.deviceLinkDeviceId ? remoteActivity?.phase === 'running' : isRunning,
hasAttentionNotification: hasAttentionNotification || remoteSchedule?.hasUnreadRun === true,
});
const leftIconRunning = sessionActivity.currentTurnActive === true;
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 f47451e8d8..0583e4ab70 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -401,17 +401,17 @@ export const SessionItem = memo(function SessionItem({
// device-link 远程会话行:本地 attention/running 链路对被控端后台会话是盲区,状态改由
// 被控端灵动岛 relay 的活动镜像驱动(remoteSessionActivityStore,按行精准订阅;本地
// 会话恒 undefined 零开销)。镜像只保留活跃态与未读终态,映射与本地五档同一张色表。
- const remoteActivity = useRemoteSessionActivity(session.id);
+ const remoteActivity = useRemoteSessionActivity(session.id, session.deviceLinkDeviceId);
const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
const sessionActivity = projectSidebarSessionActivity({
interruption: session,
sessionId: session.id,
title: session.title,
recordStatus: session.status,
- liveActivity: remoteActivity ?? islandActivity,
+ liveActivity: session.deviceLinkDeviceId ? remoteActivity : islandActivity,
attentionKind,
isUrgentFromContext: isUrgentFromContext || remoteSchedule?.hasUnreadFailedRun === true,
- isRunning,
+ isRunning: session.deviceLinkDeviceId ? remoteActivity?.phase === 'running' : isRunning,
hasAttentionNotification: hasAttentionNotification || remoteSchedule?.hasUnreadRun === true,
});
const leftIconRunning = sessionActivity.currentTurnActive === true;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts
index eba9c481a3..ae41d72ff6 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts
@@ -1,9 +1,22 @@
// @vitest-environment jsdom
import { createElement, type ReactNode } from 'react';
-import { cleanup, createEvent, fireEvent, render, screen, within } from '@testing-library/react';
+import {
+ act,
+ cleanup,
+ createEvent,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ applyRemoteSessionActivity,
+ clearRemoteSessionActivity,
+} from '@/features/device-link/remoteSessionActivityStore';
+
import { SessionCard } from '../SessionCard';
import { sessionCardVisualCases } from '../__fixtures__/sessionCardVisualCases';
import { SPLIT_GROUP_SESSION_MIME } from '../../splitGroupDnd';
@@ -214,6 +227,7 @@ function sessionRowEl(): HTMLElement {
describe('SessionCard visual cases', () => {
beforeEach(() => {
+ clearRemoteSessionActivity();
mocks.navigate.mockReset();
mocks.dropdownMenuOpen = false;
mocks.boundSchedulesBySession.clear();
@@ -937,4 +951,45 @@ describe('SessionCard visual cases', () => {
),
).toBe(true);
});
+ it.each(['card', 'list'] as const)('keeps %s status scoped to the task origin', (variant) => {
+ const base = sessionCardVisualCases[0];
+ const session = { ...base.session, id: 'origin-regression', deviceLinkDeviceId: undefined };
+ applyRemoteSessionActivity('other', { sessionId: session.id, phase: 'running' });
+ const view = renderCase(base.id, {
+ session,
+ variant,
+ isRunning: false,
+ hasAttentionNotification: false,
+ });
+ expect(sessionRowEl().querySelector('.session-status-breathing')).toBeNull();
+ view.unmount();
+
+ // The remote row must not fall back to a same-ID local activity either.
+ mocks.runningDetailBySession.set(session.id, 'local turn is running');
+ renderCase(base.id, {
+ session: { ...session, deviceLinkDeviceId: 'target' },
+ variant,
+ isRunning: false,
+ hasAttentionNotification: false,
+ });
+ expect(sessionRowEl().querySelector('.session-status-breathing')).toBeNull();
+ act(() => applyRemoteSessionActivity('target', { sessionId: session.id, phase: 'running' }));
+ expect(sessionRowEl().querySelector('.session-status-breathing')).not.toBeNull();
+ act(() =>
+ applyRemoteSessionActivity('other', {
+ sessionId: session.id,
+ phase: 'completed',
+ attention: false,
+ }),
+ );
+ expect(sessionRowEl().querySelector('.session-status-breathing')).not.toBeNull();
+ act(() =>
+ applyRemoteSessionActivity('target', {
+ sessionId: session.id,
+ phase: 'completed',
+ attention: false,
+ }),
+ );
+ expect(sessionRowEl().querySelector('.session-status-breathing')).toBeNull();
+ });
});
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 2cbd1b9771..1ec235faa8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
@@ -10,12 +10,18 @@ export type CollapsedAttentionTone = 'error' | 'done';
export type CollapsedProjectAttentionTone = CollapsedAttentionTone;
interface CollapsedAttentionInput {
- sessions: readonly ({ id: string } & SessionInterruptionState)[];
+ sessions: readonly ({
+ id: string;
+ deviceLinkDeviceId?: string | null;
+ } & SessionInterruptionState)[];
runningSessionIds: ReadonlySet<string>;
notifications: ReadonlySet<string>;
attentionKinds: ReadonlyMap<string, AttentionKind>;
urgentSessionIds: ReadonlySet<string>;
- remotePhaseOf: (sessionId: string) => RemoteSessionActivityPhase | undefined;
+ remotePhaseOf: (
+ sessionId: string,
+ deviceId?: string | null,
+ ) => RemoteSessionActivityPhase | undefined;
}
export interface CollapsedAttentionSummary {
@@ -61,7 +67,7 @@ export function resolveCollapsedAttention({
errorSessionIds.push(session.id);
continue;
}
- const remotePhase = remotePhaseOf(session.id);
+ const remotePhase = remotePhaseOf(session.id, session.deviceLinkDeviceId);
if (remotePhase) {
if (remotePhase === 'error') errorSessionIds.push(session.id);
else if (remotePhase === 'completed') hasDone = true;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/railActivity.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/railActivity.ts
new file mode 100644
index 0000000000..3288c8d6ec
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/railActivity.ts
@@ -0,0 +1,66 @@
+import type { AttentionKind } from '@/lib/sessionAttentionStore';
+import { getRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
+import type { RailLampSession } from './railPanelStore';
+
+const TONE_RANK: Record<AttentionKind, number> = { error: 3, awaiting: 2, done: 1 };
+
+export function dotToneOf(
+ id: string,
+ notifications: ReadonlySet<string>,
+ attentionKinds: ReadonlyMap<string, AttentionKind>,
+ urgentSessionIds: ReadonlySet<string>,
+): AttentionKind | null {
+ if (!notifications.has(id)) return null;
+ const kind = attentionKinds.get(id);
+ if (kind === 'error' || urgentSessionIds.has(id)) return 'error';
+ if (kind === 'awaiting') return 'awaiting';
+ return 'done';
+}
+
+/** device-link 远程会话的灯语补充:本地 running/attention 链路对被控端后台会话
+ * 是盲区,SessionItem 行内状态由 remoteSessionActivityStore 驱动 —— rail 聚合灯
+ * 与置顶瓷砖必须并入同一镜像,否则远程会话「行亮而入口不亮」(codex review)。
+ * phase → 灯语映射与 SessionItem.remoteRightStatus 同一张表;镜像里 completed/
+ * error 条目仅在未读(attention)期间存在,存在即未读。 */
+export function remoteLampOf(
+ id: string,
+ deviceId: string | null | undefined,
+): { running: boolean; tone: AttentionKind | null } | null {
+ const remote = getRemoteSessionActivity(id, deviceId);
+ if (!remote) return null;
+ if (remote.phase === 'running') return { running: true, tone: null };
+ return {
+ running: false,
+ tone:
+ remote.phase === 'error'
+ ? 'error'
+ : remote.phase === 'needs-interaction'
+ ? 'awaiting'
+ : 'done',
+ };
+}
+
+/** 保留每行设备来源,禁止聚合前降为仅含任务 ID 的映射。 */
+export function aggregateRailActivity(
+ rows: readonly RailLampSession[],
+ runningSessionIds: ReadonlySet<string>,
+ notifications: ReadonlySet<string>,
+ attentionKinds: ReadonlyMap<string, AttentionKind>,
+ urgentSessionIds: ReadonlySet<string>,
+): { running: boolean; dotTone: AttentionKind | null } {
+ let running = false;
+ let best: AttentionKind | null = null;
+ const consider = (tone: AttentionKind | null) => {
+ if (tone && (!best || TONE_RANK[tone] > TONE_RANK[best])) best = tone;
+ };
+ for (const { id, deviceLinkDeviceId } of rows) {
+ if (!deviceLinkDeviceId && runningSessionIds.has(id)) running = true;
+ consider(dotToneOf(id, notifications, attentionKinds, urgentSessionIds));
+ const remote = remoteLampOf(id, deviceLinkDeviceId);
+ if (remote) {
+ if (remote.running) running = true;
+ consider(remote.tone);
+ }
+ }
+ return { running, dotTone: best };
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/railPanelStore.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/railPanelStore.ts
index 83008411b2..85ead2473e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/railPanelStore.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/railPanelStore.ts
@@ -38,9 +38,14 @@ export interface RailPanelState {
lampScope: RailLampScope | null;
}
+export interface RailLampSession {
+ id: string;
+ deviceLinkDeviceId?: string | null;
+}
+
export interface RailLampScope {
- projectSessionIds: readonly string[];
- dialogueSessionIds: readonly string[];
+ projectSessions: readonly RailLampSession[];
+ dialogueSessions: readonly RailLampSession[];
}
/** hover 桥接:指针离开瓷砖/面板后的收回宽限(与 peek 抽屉同量级)。 */
@@ -146,10 +151,10 @@ export const railPanelStore = {
(prev == null && scope == null) ||
(prev != null &&
scope != null &&
- prev.projectSessionIds.length === scope.projectSessionIds.length &&
- prev.dialogueSessionIds.length === scope.dialogueSessionIds.length &&
- prev.projectSessionIds.every((id, i) => id === scope.projectSessionIds[i]) &&
- prev.dialogueSessionIds.every((id, i) => id === scope.dialogueSessionIds[i]));
+ prev.projectSessions.length === scope.projectSessions.length &&
+ prev.dialogueSessions.length === scope.dialogueSessions.length &&
+ prev.projectSessions.every((session, i) => session.id === scope.projectSessions[i].id && session.deviceLinkDeviceId === scope.projectSessions[i].deviceLinkDeviceId) &&
+ prev.dialogueSessions.every((session, i) => session.id === scope.dialogueSessions[i].id && session.deviceLinkDeviceId === scope.dialogueSessions[i].deviceLinkDeviceId));
if (same) return;
emit({ ...state, lampScope: scope });
},
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
index 0cf9217590..c0a71545e7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
@@ -429,7 +429,7 @@ export function ProjectsSection({
notifications,
attentionKinds,
urgentSessionIds: urgentSet,
- remotePhaseOf: (sessionId) => getRemoteSessionActivity(sessionId)?.phase,
+ remotePhaseOf: (sessionId, deviceId) => getRemoteSessionActivity(sessionId, deviceId)?.phase,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容
[runningSessionIds, notifications, attentionKinds, urgentSet, remoteActivityRevision],
@@ -444,7 +444,7 @@ export function ProjectsSection({
if (kind === 'awaiting' || kind === 'error') waiting.add(sessionId);
}
const considerRemote = (session: Session) => {
- const activity = getRemoteSessionActivity(session.id);
+ const activity = getRemoteSessionActivity(session.id, session.deviceLinkDeviceId);
if (!activity) return; // 本地会话 / 无活动条目:一次 Map 查找即返回
if (activity.phase === 'running') {
running.add(session.id);
@@ -495,7 +495,7 @@ export function ProjectsSection({
useEffect(() => {
const settled = new Set<string>();
const considerRemote = (session: Session) => {
- if (isRemoteSessionActivityActive(getRemoteSessionActivity(session.id))) {
+ if (isRemoteSessionActivityActive(getRemoteSessionActivity(session.id, session.deviceLinkDeviceId))) {
settled.add(session.id);
}
};
diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
index eb5f548bf4..e95cf1b08f 100644
--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
@@ -369,7 +369,7 @@ async function probeMissingSessionStatuses(
if (result.errorCode === 'NOT_FOUND') {
terminalIds.add(result.sessionId);
remoteProjectsStore.applyPatch(deviceId, result.sessionId, { status: 'deleted' });
- removeRemoteSessionActivityEntry(result.sessionId);
+ removeRemoteSessionActivityEntry(result.sessionId, deviceId);
continue;
}
if (!result.value || typeof result.value !== 'object') continue;
@@ -381,7 +381,7 @@ async function probeMissingSessionStatuses(
status: session.status,
updatedAt: session.updatedAt,
});
- removeRemoteSessionActivityEntry(result.sessionId);
+ removeRemoteSessionActivityEntry(result.sessionId, deviceId);
continue;
}
// sessions:get 返回缺席行时同样是权威快照,回填 title / pinnedAt / model 等
@@ -452,7 +452,8 @@ async function runRefreshRemoteDeviceSessions(
if (status === 'archived' || sessions.length < LIST_LIMIT) {
if (status === 'active') {
for (const session of missingSessions) {
- if (session.source !== 'bot') removeRemoteSessionActivityEntry(session.id);
+ if (session.source !== 'bot')
+ removeRemoteSessionActivityEntry(session.id, deviceId);
}
}
remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
diff --git a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
index 2ec917bf55..1f4f5c4df7 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
@@ -15,7 +15,7 @@
* 不喂系统级 attention(dock 角标 / 通知)—— 通知职责归被控端本机,控制端只做行内可视。
*
* ⚠️ 性能不变量(与 sessionAttentionStore 同款):SessionItem 逐行挂载,订阅必须是
- * 按 sessionId 的稳定引用精准订阅(条目对象未替换时快照引用不变),禁止整表订阅。
+ * 按 deviceId + sessionId 的稳定引用精准订阅(条目对象未替换时快照引用不变),禁止整表订阅。
*/
import { useMemo, useSyncExternalStore } from 'react';
@@ -38,47 +38,60 @@ export function isRemoteSessionActivityActive(
return activity?.phase === 'running' || activity?.phase === 'needs-interaction';
}
-const listeners = new Set<() => void>();
-/** sessionId → 活动条目(引用稳定,内容变化才替换)。 */
-const activityMap = new Map<string, RemoteSessionActivity>();
-/** sessionId → deviceId(设备移除时按设备清扫)。 */
-const sessionDeviceIndex = new Map<string, string>();
+const listeners = new Set<(deviceId?: string, sessionId?: string) => void>();
+/** deviceId → sessionId → 活动条目;本地任务没有 deviceId,不读取远程缓存。 */
+const activityByDevice = new Map<string, Map<string, RemoteSessionActivity>>();
/** 整表变更版本号(聚合消费方作依赖用;activityMap 本体是可变引用,不能当快照)。 */
let revision = 0;
-function emit(): void {
+function emit(deviceId?: string, sessionId?: string): void {
revision++;
- for (const l of listeners) l();
+ for (const l of listeners) l(deviceId, sessionId);
}
function isPhase(value: unknown): value is RemoteSessionActivityPhase {
- return value === 'running' || value === 'needs-interaction' || value === 'completed' || value === 'error';
+ return (
+ value === 'running' ||
+ value === 'needs-interaction' ||
+ value === 'completed' ||
+ value === 'error'
+ );
}
function sameActivity(a: RemoteSessionActivity, b: RemoteSessionActivity): boolean {
- return a.phase === b.phase
- && a.compactDetail === b.compactDetail
- && a.interactionKind === b.interactionKind
- && a.attention === b.attention;
+ return (
+ a.phase === b.phase &&
+ a.compactDetail === b.compactDetail &&
+ a.interactionKind === b.interactionKind &&
+ a.attention === b.attention
+ );
}
-export function subscribeRemoteSessionActivity(listener: () => void): () => void {
+export function subscribeRemoteSessionActivity(
+ listener: (deviceId?: string, sessionId?: string) => void,
+): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
-export function getRemoteSessionActivity(sessionId: string): RemoteSessionActivity | undefined {
- return activityMap.get(sessionId);
+export function getRemoteSessionActivity(
+ sessionId: string,
+ deviceId: string | null | undefined,
+): RemoteSessionActivity | undefined {
+ return deviceId ? activityByDevice.get(deviceId)?.get(sessionId) : undefined;
}
/** Hook —— 按 sessionId 精准订阅(本地会话恒为 undefined,零开销)。 */
-export function useRemoteSessionActivity(sessionId: string): RemoteSessionActivity | undefined {
+export function useRemoteSessionActivity(
+ sessionId: string,
+ deviceId: string | null | undefined,
+): RemoteSessionActivity | undefined {
return useSyncExternalStore(
subscribeRemoteSessionActivity,
- () => activityMap.get(sessionId),
- () => activityMap.get(sessionId),
+ () => getRemoteSessionActivity(sessionId, deviceId),
+ () => getRemoteSessionActivity(sessionId, deviceId),
);
}
@@ -88,12 +101,12 @@ export function useRemoteSessionActivity(sessionId: string): RemoteSessionActivi
* 组外条目变化、以及组内 detail 类变化都不会触发重渲染 —— 别改成整表 revision
* 逐行用(会退化成整表订阅,违反文件头的性能不变量)。 */
export function useRemoteSessionsPhaseMap(
- sessionIds: readonly string[],
+ sessions: readonly { id: string; deviceLinkDeviceId?: string | null }[],
): ReadonlyMap<string, RemoteSessionActivityPhase> {
const getSnapshot = (): string => {
let key = '';
- for (const id of sessionIds) {
- const phase = activityMap.get(id)?.phase;
+ for (const { id, deviceLinkDeviceId } of sessions) {
+ const phase = getRemoteSessionActivity(id, deviceLinkDeviceId)?.phase;
if (phase) key += `${id}:${phase}|`;
}
return key;
@@ -127,11 +140,11 @@ export function applyRemoteSessionActivity(deviceId: string, payload: unknown):
if (typeof payload !== 'object' || payload === null) return;
const p = payload as Record<string, unknown>;
const sessionId = typeof p.sessionId === 'string' ? p.sessionId : '';
- if (!sessionId || !isPhase(p.phase)) return;
+ if (!deviceId || !sessionId || !isPhase(p.phase)) return;
const attention = p.attention === true;
const keep = p.phase === 'running' || p.phase === 'needs-interaction' || attention;
if (!keep) {
- removeRemoteSessionActivityEntry(sessionId);
+ removeRemoteSessionActivityEntry(sessionId, deviceId);
return;
}
const next: RemoteSessionActivity = {
@@ -141,43 +154,48 @@ export function applyRemoteSessionActivity(deviceId: string, payload: unknown):
interactionKind: typeof p.interactionKind === 'string' ? p.interactionKind : undefined,
attention,
};
- sessionDeviceIndex.set(sessionId, deviceId);
+ let activityMap = activityByDevice.get(deviceId);
+ if (!activityMap) {
+ activityMap = new Map();
+ activityByDevice.set(deviceId, activityMap);
+ }
const current = activityMap.get(sessionId);
if (current && sameActivity(current, next)) return;
activityMap.set(sessionId, next);
- emit();
+ emit(deviceId, sessionId);
}
/** 刚发送时丢掉上一轮 completed/error 镜像。running / needs-interaction 是本轮活档,保留。 */
-export function dropStaleRemoteTerminalActivity(sessionId: string): void {
- const activity = activityMap.get(sessionId);
+export function dropStaleRemoteTerminalActivity(
+ sessionId: string,
+ deviceId: string | null | undefined,
+): void {
+ const activity = getRemoteSessionActivity(sessionId, deviceId);
if (!activity) return;
if (activity.phase !== 'completed' && activity.phase !== 'error') return;
- removeRemoteSessionActivityEntry(sessionId);
+ removeRemoteSessionActivityEntry(sessionId, deviceId);
}
/** 单会话清除(被控端删除 / 归档该会话时由 sessions:patched 路由调用)。 */
-export function removeRemoteSessionActivityEntry(sessionId: string): void {
- sessionDeviceIndex.delete(sessionId);
- if (activityMap.delete(sessionId)) emit();
-}
-
-/** 设备级清扫(设备被移除 / 撤销 / 关被控)。瞬时 disconnected 不调用 —— 保留快照与
- * remoteProjectsStore.markDeviceDisconnected 的"网络抖动不清列表"语义对齐。 */
+export function removeRemoteSessionActivityEntry(
+ sessionId: string,
+ deviceId: string | null | undefined,
+): void {
+ if (!deviceId) return;
+ const activityMap = activityByDevice.get(deviceId);
+ if (!activityMap?.delete(sessionId)) return;
+ if (activityMap.size === 0) activityByDevice.delete(deviceId);
+ emit(deviceId, sessionId);
+}
+
+/** 设备移除时只清理该设备;瞬时断线仍保留快照。 */
export function removeRemoteSessionActivityForDevice(deviceId: string): void {
- let changed = false;
- for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {
- if (indexedDeviceId !== deviceId) continue;
- sessionDeviceIndex.delete(sessionId);
- changed = activityMap.delete(sessionId) || changed;
- }
- if (changed) emit();
+ if (activityByDevice.delete(deviceId)) emit(deviceId);
}
/** 全清(登出 / device-link stopped)。 */
export function clearRemoteSessionActivity(): void {
- sessionDeviceIndex.clear();
- if (activityMap.size === 0) return;
- activityMap.clear();
+ if (activityByDevice.size === 0) return;
+ activityByDevice.clear();
emit();
}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 42314cd670..7d53713ff2 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -8685,7 +8685,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
// controller while this renderer still owns an offline outbox.
// Retire it at the authoritative push boundary so reconnect
// cannot dispatch into a task that no longer exists.
- removeRemoteSessionActivityEntry(p.sessionId);
+ removeRemoteSessionActivityEntry(p.sessionId, push.deviceId);
_purgeSession(p.sessionId);
break;
}
@@ -8693,7 +8693,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
mirrorSessionFields(p.sessionId, p.patch);
// 会话在被控端被删除 / 归档 → 同步清掉活动镜像,避免孤儿状态点。
if (terminal) {
- removeRemoteSessionActivityEntry(p.sessionId);
+ removeRemoteSessionActivityEntry(p.sessionId, push.deviceId);
}
}
break;
diff --git a/apps/desktop/src/renderer/lib/sessionAttentionStore.ts b/apps/desktop/src/renderer/lib/sessionAttentionStore.ts
index 105446adcc..6e073c49e5 100644
--- a/apps/desktop/src/renderer/lib/sessionAttentionStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionAttentionStore.ts
@@ -136,17 +136,24 @@ function attentionEraOf(sessionId: string): number {
return attentionEraBySession.get(sessionId) ?? 0;
}
-function remoteActivitySigOf(sessionId: string): string {
- const activity = getRemoteSessionActivity(sessionId);
+function remoteActivitySigOf(sessionId: string, deviceId = getSessionDeviceId(sessionId)): string {
+ const activity = getRemoteSessionActivity(sessionId, deviceId);
if (!activity) return 'none';
return `${activity.phase}\u0000${activity.attention ? 1 : 0}\u0000${activity.compactDetail}`;
}
-function rebasePendingReceiptsOnNewAttention(): void {
+function rebasePendingReceiptsOnNewAttention(
+ changedDeviceId?: string,
+ changedSessionId?: string,
+): void {
const watched = new Set([...pendingRemoteReceipts.keys(), ...inflightReceiptSessions.keys()]);
for (const sessionId of watched) {
- const attention = getRemoteSessionActivity(sessionId)?.attention === true;
- const sig = remoteActivitySigOf(sessionId);
+ if (changedSessionId && sessionId !== changedSessionId) continue;
+ // Origin can disappear during bootstrap. A pending receipt must still become
+ // conservative when new unread arrives; read that event's exact device shard.
+ const deviceId = getSessionDeviceId(sessionId) ?? changedDeviceId;
+ const attention = getRemoteSessionActivity(sessionId, deviceId)?.attention === true;
+ const sig = remoteActivitySigOf(sessionId, deviceId);
const prevSig = pendingActivitySigSeen.get(sessionId) ?? sig;
if (attention && sig !== prevSig) {
attentionEraBySession.set(sessionId, attentionEraOf(sessionId) + 1);
@@ -225,7 +232,7 @@ function flushPendingRemoteReceipt(sessionId: string): void {
// 镜像缺条目(推送丢失 / 未达)时回落消息层终止错误探针:探到 error 同样按下不发,
// 等用户处置横幅产生的 explicit-action 放行,fail-safe。告警一直不处置就一直挂着
// (对应「未处理」语义正确),开销是一个 Map 条目。
- const activity = getRemoteSessionActivity(sessionId);
+ const activity = getRemoteSessionActivity(sessionId, getSessionDeviceId(sessionId));
const errorUnread = activity
? activity.phase === 'error' && activity.attention
: remoteTerminalErrorProbe?.(sessionId) === true;
diff --git a/apps/desktop/src/renderer/lib/sessionStartingStore.ts b/apps/desktop/src/renderer/lib/sessionStartingStore.ts
index 1e3e1776ba..60e8c5b8d3 100644
--- a/apps/desktop/src/renderer/lib/sessionStartingStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionStartingStore.ts
@@ -14,6 +14,7 @@
import { useEffect, useSyncExternalStore } from 'react';
+import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
import { dropStaleRemoteTerminalActivity } from '@/features/device-link/remoteSessionActivityStore';
/** 发送失败 / 状态一直不到时的兜底;正常路径应在 agent 开跑时就被吸收。 */
@@ -55,7 +56,7 @@ export function markSessionStarting(sessionId: string): void {
if (!already) {
// 先丢掉上一轮远程终态,再置 starting。否则 absorb 会把旧 completed/error
// 当成新权威立刻清掉。重复 mark 只刷新 TTL,不能再删本轮新到达的终态。
- dropStaleRemoteTerminalActivity(sessionId);
+ dropStaleRemoteTerminalActivity(sessionId, getSessionDeviceId(sessionId));
startingIds.add(sessionId);
}
clearTimer(sessionId);