diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md
index 6d7d04187f..767f94ec1a 100644
--- a/docs/interactive-capabilities/README.md
+++ b/docs/interactive-capabilities/README.md
@@ -27,9 +27,9 @@ OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, a
- Generated per-item interaction audit: `docs/interactive-capabilities/technical/product-control-open-audit.json`
- Generated low-level audit map: `docs/interactive-capabilities/technical/tauri-command-map.json`
-说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **705** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。
+说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **706** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。
-Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **705** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes.
+Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **706** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes.
## 控制边界 / Control boundary
diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json
index 2501934ccc..b17a2f36a8 100644
--- a/docs/interactive-capabilities/technical/tauri-command-map.json
+++ b/docs/interactive-capabilities/technical/tauri-command-map.json
@@ -2,10 +2,10 @@
"schemaVersion": 2,
"generatedFrom": "src/shared/interactive-capabilities/catalog.json",
"catalogDigest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575",
- "commandCount": 705,
+ "commandCount": 706,
"coverage": {
- "commandCount": 705,
- "documentedCommandCount": 644,
+ "commandCount": 706,
+ "documentedCommandCount": 645,
"implementationCommandCount": 61,
"implementationDigest": "fdb6f78b009b95270d26834349aade36e0987553167f325a9c674a085b876a2d"
},
@@ -4806,6 +4806,22 @@
"signature": "fn git_get_status( state: State<'_, AppState>, mut request: GitRepositoryRequest, ) -> Result",
"remoteWorkspacePolicy": "RemoteRouted"
},
+ {
+ "id": "git_get_tracked_change_count",
+ "moduleId": "git",
+ "capabilityId": "feature.git",
+ "capabilityIds": [
+ "feature.git"
+ ],
+ "documentedItemIds": [
+ "feature.git:status-diff"
+ ],
+ "visibility": "documented",
+ "rustPath": "git_get_tracked_change_count",
+ "sourceFile": "src/apps/desktop/src/api/git_api.rs",
+ "signature": "fn git_get_tracked_change_count( state: State<'_, AppState>, request: GitTrackedChangeCountRequest, ) -> Result
+ );
+}
diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx
index cb0e1beb28..89cb1f1a74 100644
--- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx
@@ -29,6 +29,7 @@ vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: {
releaseSessionHistoryCompletionAfterInitialPaint: () => false,
extendSessionHistoryWindow: () => null,
loadSessionTurnWindow: (...args: unknown[]) => fixture.loadTurnWindow(...args),
+ loadPreviousSessionTurnWindow: (...args: unknown[]) => fixture.loadTurnWindow(...args),
activateSessionHistoryWindow: () => fixture.cached,
} }));
vi.mock('../../store/modernFlowChatStore', async importOriginal => {
diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx
index 5579c2a5ab..9c67658944 100644
--- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx
+++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx
@@ -2183,11 +2183,13 @@ export const ModernFlowChatContainer: React.FC = (
setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'loading' }));
let viewportPreparationStarted = false;
try {
- const result = await flowChatStore.loadSessionTurnWindow(sessionId, targetOrdinal, {
- source: 'prefetch',
- before: direction === 'before' ? 12 : 4,
- after: direction === 'after' ? 12 : 1,
- });
+ const result = direction === 'before'
+ ? await flowChatStore.loadPreviousSessionTurnWindow(sessionId, targetOrdinal)
+ : await flowChatStore.loadSessionTurnWindow(sessionId, targetOrdinal, {
+ source: 'prefetch',
+ before: 4,
+ after: 12,
+ });
if (!result.isCurrent || !isCurrent()) {
recordHistoryPagingEvent(sessionId, 'outcome_cancelled', {
direction,
@@ -2789,6 +2791,7 @@ export const ModernFlowChatContainer: React.FC = (
key={surfaceScope.key('welcome', surfaceScope.epoch,
activeSession?.sessionId ?? '', activeSession?.draft?.workspaceId ?? '')}
session={activeSession}
+ isActive={isViewportActive}
onQuickAction={(command) => {
window.dispatchEvent(new CustomEvent('fill-chat-input', {
detail: { message: command, sessionId: activeSession?.sessionId }
diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
index 95827eb2c6..fe491ac25e 100644
--- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
+++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts
@@ -6678,7 +6678,7 @@ describe('FlowChatStore historical session hydration state', () => {
expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledTimes(1);
});
- it.each(['local', 'ssh'])('opens %s history with one Turn and warms an adjacent range only after paint without replacing the tail', async location => {
+ it.each(['local', 'ssh'])('opens %s history with one Turn and shares the post-paint warm-up with older paging', async location => {
const catalog = createTurnCatalog(100);
const session = createSession({ sessionId: 'history-1', isHistorical: true, historyState: 'metadata-only',
...(location === 'ssh' ? { remoteConnectionId: 'ssh-host', remoteSshHost: 'host.example' } : {}),
@@ -6690,8 +6690,8 @@ describe('FlowChatStore historical session hydration state', () => {
});
apiMocks.loadSessionTurnWindow.mockResolvedValueOnce({
status: 'ready', catalogRevision: catalog.revision, totalTurnCount: 100,
- startOrdinal: 98, endOrdinalExclusive: 100, targetTurnId: 'turn-98',
- turns: [98, 99].map(index => createPersistedTurn(index)),
+ startOrdinal: 94, endOrdinalExclusive: 99, targetTurnId: 'turn-98',
+ turns: [94, 95, 96, 97, 98].map(index => createPersistedTurn(index)),
});
flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]), activeSessionId: session.sessionId }));
await flowChatStore.loadSessionHistory(session.sessionId);
@@ -6700,9 +6700,13 @@ describe('FlowChatStore historical session hydration state', () => {
const tail = flowChatStore.getState().sessions.get(session.sessionId)!.dialogTurns;
expect(tail.map(turn => turn.id)).toEqual(['turn-99']);
flowChatStore.releaseSessionHistoryCompletionAfterInitialPaint(session.sessionId);
+ await expect(flowChatStore.loadPreviousSessionTurnWindow(session.sessionId, 98)).resolves.toMatchObject({
+ status: 'ready',
+ range: { startOrdinal: 94, endOrdinalExclusive: 100 },
+ });
await flushAsyncWork();
expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledTimes(1);
- expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledWith(expect.objectContaining({ targetStorageTurnIndex: 98, before: 0, after: 1 }));
+ expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledWith(expect.objectContaining({ targetStorageTurnIndex: 98, before: 12, after: 1 }));
expect(flowChatStore.getState().sessions.get(session.sessionId)!.dialogTurns).toBe(tail);
expect(flowChatStore.getSessionHistoryViewState(session.sessionId)?.activeRange).toBeNull();
expect(flowChatStore.hasPendingSessionHistoryCompletion(session.sessionId)).toBe(false);
diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts
index 4c7f35d029..ccf03b053b 100644
--- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts
+++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts
@@ -3716,6 +3716,18 @@ export class FlowChatStore {
}
}
+ public loadPreviousSessionTurnWindow(
+ sessionId: string,
+ targetOrdinal: number,
+ ): Promise {
+ // The tail warm-up and the older boundary must share the same request.
+ return this.loadSessionTurnWindow(sessionId, targetOrdinal, {
+ source: 'prefetch',
+ before: 12,
+ after: 1,
+ });
+ }
+
public async loadSessionTurnWindow(
sessionId: string,
targetOrdinal: number,
@@ -3917,6 +3929,8 @@ export class FlowChatStore {
request.workspaceId ? '' : request.remoteSshHost ?? '',
request.targetStorageTurnIndex,
request.catalog.revision,
+ request.originalTargetTurnId ?? '',
+ request.includeInternal ? 'internal' : 'public',
request.before,
request.after,
);
@@ -4103,7 +4117,7 @@ export class FlowChatStore {
const first = canonicalSessionTurns(session)[0];
const firstOrdinal = session.turnCatalog.entries.find(entry => entry.turnId === first?.id)?.ordinal;
if (firstOrdinal !== undefined && firstOrdinal > 0) {
- void this.loadSessionTurnWindow(sessionId, firstOrdinal - 1, { before: 0, after: 1, source: 'prefetch' })
+ void this.loadPreviousSessionTurnWindow(sessionId, firstOrdinal - 1)
.catch(error => {
if (!isSurfaceChangedError(error)) log.debug('Adjacent session history prefetch stopped', { sessionId, error });
});
diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts
index a22bafa49a..ba63634da5 100644
--- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts
+++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts
@@ -1,6 +1,6 @@
// Generated by scripts/generate-interactive-capabilities.mjs; do not edit.
// Source: openbitfun_product_domains::remote_surface (Product Operation Registry).
-export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:416c934dda520065" as const;
+export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:a7e5f2b6b738cb96" as const;
/**
* Registered Tauri commands the Peer Device controller keeps on the controller
@@ -217,6 +217,7 @@ export const PEER_HOST_CAPABILITY_IDS = [
"user_question_interaction_v1",
"ssh_none_auth_v1",
"terminal_cursor_replay_v1",
+ "git_tracked_change_count_v1",
] as const;
export type PeerHostCapabilityId = (typeof PEER_HOST_CAPABILITY_IDS)[number];
@@ -272,6 +273,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly<
"user_question_response",
"user_question_interaction_v1",
"ssh_none_auth_v1",
+ "git_tracked_change_count_v1",
],
cli: [
"model_routing_v1",
@@ -300,6 +302,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly<
"user_question_response",
"user_question_interaction_v1",
"terminal_cursor_replay_v1",
+ "git_tracked_change_count_v1",
],
};
diff --git a/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts b/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts
index e1b7ac47e1..0537eac8e0 100644
--- a/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts
+++ b/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts
@@ -230,6 +230,12 @@ export interface GitTrustOutcome {
}
export class GitAPI {
+ async getTrackedChangeCount(workspaceId: string): Promise {
+ return invokePrepared('git_get_tracked_change_count', async () => ({
+ request: { workspaceId },
+ }), { timeout: 8_000 });
+ }
+
private repositoryProbeCache = new Map{{fileCount}} changed file hasn’t been committed.",
+ "workspaceChanges_other": "The workspace is stirring. {{fileCount}} changed files haven’t been committed.",
"openingWorkspace": "Let's get to work in {{workspace}}.",
"openingMorning": "Good morning. The day starts with you.",
"openingAfternoon": "Good afternoon. Let's make today a little more interesting.",
diff --git a/src/web-ui/src/locales/en-US/panels/files.json b/src/web-ui/src/locales/en-US/panels/files.json
index 4373226ffd..9a783dabad 100644
--- a/src/web-ui/src/locales/en-US/panels/files.json
+++ b/src/web-ui/src/locales/en-US/panels/files.json
@@ -99,7 +99,8 @@
"loadingFileTree": "Loading file tree..."
},
"empty": {
- "selectWorkspace": "File tree will be displayed after selecting a workspace"
+ "selectWorkspace": "File tree will be displayed after selecting a workspace",
+ "directoryUnavailable": "The selected directory is unavailable."
},
"dialog": {
"newFile": {
diff --git a/src/web-ui/src/locales/en-US/scenes/project-resources.json b/src/web-ui/src/locales/en-US/scenes/project-resources.json
index 85deac09b1..efecc7aa17 100644
--- a/src/web-ui/src/locales/en-US/scenes/project-resources.json
+++ b/src/web-ui/src/locales/en-US/scenes/project-resources.json
@@ -33,7 +33,6 @@
"primary": "Primary directory",
"related": "Associated directory",
"openDirectory": "Open directory {{name}}",
- "editDirectory": "Edit directory {{name}}",
"scrollPrevious": "Previous directories",
"scrollNext": "Next directories",
"add": "Add directory",
diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json
index f88cd70512..c89a682dca 100644
--- a/src/web-ui/src/locales/zh-CN/common.json
+++ b/src/web-ui/src/locales/zh-CN/common.json
@@ -400,6 +400,7 @@
"duplicateEmpty": "请发送消息后再复制该会话。",
"duplicateRunning": "请等待当前对话结束后再复制该会话。",
"duplicateDispatchUnsupported": "运行在其他设备上的会话无法复制。",
+ "dispatchMutationUnsupported": "请在任务所属设备上归档或删除此会话。",
"openStorageDirectory": "打开会话存储目录",
"openStorageDirectoryFailed": "打开会话存储目录失败",
"storageDirectoryDesktopOnly": "仅支持打开存储在当前桌面实例上的会话目录。",
@@ -407,7 +408,7 @@
"exportMarkdown": "导出为 Markdown",
"exportMarkdownFull": "导出完整过程",
"exportMarkdownResult": "导出结果",
- "delete": "删除",
+ "delete": "删除会话",
"deleteConfirmTitle": "删除会话",
"deleteConfirmMessage": "会话及其子会话将被永久删除,无法恢复。",
"confirmEdit": "确认",
diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json
index 5634798531..41dae38327 100644
--- a/src/web-ui/src/locales/zh-CN/flow-chat.json
+++ b/src/web-ui/src/locales/zh-CN/flow-chat.json
@@ -3505,6 +3505,8 @@
},
"welcome": {
"openingWorkspace": "在 {{workspace}},开工。",
+ "workspaceChanges_one": "工作区有动静,{{fileCount}} 个文件改了还没提交。",
+ "workspaceChanges_other": "工作区有动静,{{fileCount}} 个文件改了还没提交。",
"openingMorning": "早安,今天由你开场。",
"openingAfternoon": "下午好,给今天加点意思。",
"openingEvening": "晚上好,按你的节奏来。",
diff --git a/src/web-ui/src/locales/zh-CN/panels/files.json b/src/web-ui/src/locales/zh-CN/panels/files.json
index 32486c52ca..3ed45f1ca9 100644
--- a/src/web-ui/src/locales/zh-CN/panels/files.json
+++ b/src/web-ui/src/locales/zh-CN/panels/files.json
@@ -99,7 +99,8 @@
"loadingFileTree": "正在加载文件树..."
},
"empty": {
- "selectWorkspace": "选择工作区后将显示文件树"
+ "selectWorkspace": "选择工作区后将显示文件树",
+ "directoryUnavailable": "所选目录不可用。"
},
"dialog": {
"newFile": {
diff --git a/src/web-ui/src/locales/zh-CN/scenes/project-resources.json b/src/web-ui/src/locales/zh-CN/scenes/project-resources.json
index 0aacbf79b0..a545c39efd 100644
--- a/src/web-ui/src/locales/zh-CN/scenes/project-resources.json
+++ b/src/web-ui/src/locales/zh-CN/scenes/project-resources.json
@@ -33,7 +33,6 @@
"primary": "主目录",
"related": "关联目录",
"openDirectory": "打开目录 {{name}}",
- "editDirectory": "编辑目录 {{name}}",
"scrollPrevious": "查看前面的目录",
"scrollNext": "查看后面的目录",
"add": "添加目录",
diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json
index d3f655f8b2..ece3f565b2 100644
--- a/src/web-ui/src/locales/zh-TW/common.json
+++ b/src/web-ui/src/locales/zh-TW/common.json
@@ -400,6 +400,7 @@
"duplicateEmpty": "請傳送訊息後再複製該會話。",
"duplicateRunning": "請等待目前對話結束後再複製該會話。",
"duplicateDispatchUnsupported": "執行在其他裝置上的會話無法複製。",
+ "dispatchMutationUnsupported": "請在任務所屬裝置上歸檔或刪除此會話。",
"openStorageDirectory": "開啟會話儲存目錄",
"openStorageDirectoryFailed": "開啟會話儲存目錄失敗",
"storageDirectoryDesktopOnly": "僅支援開啟儲存在目前桌面執行個體上的會話目錄。",
@@ -407,7 +408,7 @@
"exportMarkdown": "匯出為 Markdown",
"exportMarkdownFull": "匯出完整過程",
"exportMarkdownResult": "匯出結果",
- "delete": "刪除",
+ "delete": "刪除會話",
"deleteConfirmTitle": "刪除會話",
"deleteConfirmMessage": "會話及其子會話將被永久刪除,無法復原。",
"confirmEdit": "確認",
diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json
index fbe36338c7..55b8dd356d 100644
--- a/src/web-ui/src/locales/zh-TW/flow-chat.json
+++ b/src/web-ui/src/locales/zh-TW/flow-chat.json
@@ -3504,6 +3504,8 @@
}
},
"welcome": {
+ "workspaceChanges_one": "工作區有動靜,{{fileCount}} 個檔案改了還沒提交。",
+ "workspaceChanges_other": "工作區有動靜,{{fileCount}} 個檔案改了還沒提交。",
"openingWorkspace": "在 {{workspace}},開工。",
"openingMorning": "早安,今天由你開場。",
"openingAfternoon": "下午好,給今天加點意思。",
diff --git a/src/web-ui/src/locales/zh-TW/panels/files.json b/src/web-ui/src/locales/zh-TW/panels/files.json
index 71e0d02a44..bc3b9e4bf3 100644
--- a/src/web-ui/src/locales/zh-TW/panels/files.json
+++ b/src/web-ui/src/locales/zh-TW/panels/files.json
@@ -99,7 +99,8 @@
"loadingFileTree": "正在載入檔案樹..."
},
"empty": {
- "selectWorkspace": "選擇工作區後將顯示檔案樹"
+ "selectWorkspace": "選擇工作區後將顯示檔案樹",
+ "directoryUnavailable": "所選目錄無法使用。"
},
"dialog": {
"newFile": {
diff --git a/src/web-ui/src/locales/zh-TW/scenes/project-resources.json b/src/web-ui/src/locales/zh-TW/scenes/project-resources.json
index 54f2e50e93..645ef3f0c0 100644
--- a/src/web-ui/src/locales/zh-TW/scenes/project-resources.json
+++ b/src/web-ui/src/locales/zh-TW/scenes/project-resources.json
@@ -33,7 +33,6 @@
"primary": "主目錄",
"related": "關聯目錄",
"openDirectory": "開啟目錄 {{name}}",
- "editDirectory": "編輯目錄 {{name}}",
"scrollPrevious": "查看前面的目錄",
"scrollNext": "查看後面的目錄",
"add": "新增目錄",
diff --git a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts
index 6d105b5704..ca96270261 100644
--- a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts
+++ b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts
@@ -206,4 +206,26 @@ describe('ExplorerController startup observability', () => {
expect(unwatchSrc).toHaveBeenCalledTimes(1);
expect(provider.watch).not.toHaveBeenCalled();
});
+
+ it('does not restart watchers when a directory read finishes after leaving its tree', async () => {
+ let finishDirectory!: (nodes: Awaited>) => void;
+ const unwatch = vi.fn();
+ const provider: ExplorerFileSystemProvider = {
+ getChildren: vi.fn(({ path }) => path === '/reference'
+ ? Promise.resolve([{ path: '/reference/docs', name: 'docs', isDirectory: true }])
+ : new Promise(resolve => { finishDirectory = resolve; })),
+ watch: vi.fn(() => unwatch),
+ };
+ const controller = new ExplorerController(provider);
+ await controller.configure({ rootPath: '/reference', workspaceId: 'project' });
+
+ const expansion = controller.expandFolderLazy('/reference/docs');
+ controller.dispose();
+ expect(unwatch).toHaveBeenCalled();
+ vi.mocked(provider.watch).mockClear();
+ finishDirectory([]);
+ await expansion;
+
+ expect(provider.watch).not.toHaveBeenCalled();
+ });
});
diff --git a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts
index 23702bf12b..95d1ea915d 100644
--- a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts
+++ b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts
@@ -610,7 +610,7 @@ export class ExplorerController {
private syncWatchers(): void {
const rootPath = this.config.rootPath;
- if (!rootPath || !this.config.enableAutoWatch) {
+ if (this.disposed || !rootPath || !this.config.enableAutoWatch) {
this.stopWatchers();
return;
}
@@ -663,6 +663,6 @@ export class ExplorerController {
}
private isGenerationCurrent(generation: number, rootPath: string): boolean {
- return generation === this.generation && pathsEquivalentFs(this.config.rootPath ?? '', rootPath);
+ return !this.disposed && generation === this.generation && pathsEquivalentFs(this.config.rootPath ?? '', rootPath);
}
}
diff --git a/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx
new file mode 100644
index 0000000000..a8e5c8ef5e
--- /dev/null
+++ b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { activateSurface } from '@/infrastructure/peer-device/deviceSurface';
+import { gitEventService } from '../services/GitEventService';
+import { useTrackedChangeCount } from './useTrackedChangeCount';
+
+const mocks = vi.hoisted(() => ({
+ getTrackedChangeCount: vi.fn<(id: string) => Promise>(),
+ peer: vi.fn(),
+ desktop: true,
+}));
+vi.mock('@/infrastructure/api/service-api/GitAPI', () => ({
+ gitAPI: { getTrackedChangeCount: mocks.getTrackedChangeCount },
+ gitWorkspaceKey: ({ workspaceId }: { workspaceId: string }) => workspaceId,
+}));
+vi.mock('@/infrastructure/peer-device/peerDeviceContextState', () => ({
+ usePeerDeviceModeOptional: mocks.peer,
+}));
+vi.mock('@/infrastructure/runtime', () => ({ isTauriRuntime: () => mocks.desktop }));
+
+function Count({ id, remote = false }: { id: string; remote?: boolean }) {
+ return ;
+}
+
+async function advance(ms: number) {
+ await act(async () => { await vi.advanceTimersByTimeAsync(ms); });
+}
+
+describe('welcome tracked change count', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+ activateSurface('local');
+ vi.useFakeTimers();
+ mocks.getTrackedChangeCount.mockReset();
+ mocks.peer.mockReturnValue(null);
+ mocks.desktop = true;
+ container = document.createElement('div');
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ vi.useRealTimers();
+ });
+
+ it('coalesces visible readers, caches the result and never polls', async () => {
+ mocks.getTrackedChangeCount.mockResolvedValue(3);
+ await act(async () => root.render(<>>));
+ expect(mocks.getTrackedChangeCount).not.toHaveBeenCalled();
+ await advance(200);
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledExactlyOnceWith('same');
+ expect(container.textContent).toBe('33');
+
+ await act(async () => root.render(null));
+ await act(async () => root.render());
+ await advance(200);
+ expect(container.textContent).toBe('3');
+ await advance(60_000);
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1);
+ });
+
+ it('refreshes after a scoped operation and ignores its superseded in-flight count', async () => {
+ let finishFirst!: (count: number) => void;
+ mocks.getTrackedChangeCount.mockImplementationOnce(() => new Promise(resolve => { finishFirst = resolve; }))
+ .mockResolvedValue(1);
+ await act(async () => root.render());
+ await advance(200);
+ await act(async () => gitEventService.emit('operation:completed', {
+ repositoryPath: { workspaceId: 'repo' }, timestamp: new Date(), operationType: 'commit',
+ description: 'Commit',
+ }));
+ await advance(200);
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1);
+ await act(async () => finishFirst(8));
+ expect(container.textContent).toBe('');
+ await advance(200);
+ expect(container.textContent).toBe('1');
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(2);
+ });
+
+ it('gates old peers and ignores a response from a previous device activation', async () => {
+ let finishLocal!: (count: number) => void;
+ mocks.getTrackedChangeCount.mockImplementationOnce(() => new Promise(resolve => { finishLocal = resolve; }))
+ .mockResolvedValue(2);
+ await act(async () => root.render());
+ await advance(200);
+ await act(async () => activateSurface('peer'));
+ await act(async () => finishLocal(99));
+ await advance(200);
+ expect(container.textContent).toBe('');
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1);
+
+ mocks.peer.mockReturnValue({ attachments: [{ deviceId: 'peer', health: 'ready',
+ capabilities: { gitTrackedChangeCountV1: true, hostKind: 'cli' },
+ }] });
+ await act(async () => root.render());
+ await advance(200);
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1);
+
+ await act(async () => root.render());
+ await advance(200);
+ expect(container.textContent).toBe('2');
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(2);
+ });
+
+ it('discards an old workspace result and refreshes an inactive workspace on return after a Git operation', async () => {
+ let finishOld!: (count: number) => void;
+ mocks.getTrackedChangeCount.mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; }))
+ .mockResolvedValueOnce(2).mockResolvedValueOnce(0);
+ await act(async () => root.render());
+ await advance(200);
+ await act(async () => root.render());
+ await advance(200);
+ await act(async () => finishOld(99));
+ expect(container.textContent).toBe('2');
+
+ await act(async () => root.render(null));
+ await act(async () => gitEventService.emit('operation:completed', {
+ repositoryPath: { workspaceId: 'current' }, timestamp: new Date(), operationType: 'commit',
+ description: 'Commit',
+ }));
+ await advance(200);
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(2);
+ await act(async () => root.render());
+ await advance(200);
+ expect(container.textContent).toBe('0');
+ expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts
new file mode 100644
index 0000000000..6805d2f35d
--- /dev/null
+++ b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts
@@ -0,0 +1,113 @@
+import { useEffect, useState, useSyncExternalStore } from 'react';
+import { gitAPI } from '@/infrastructure/api/service-api/GitAPI';
+import { getActiveSurfaceScope, isLocalSurface, onSurfaceActivated, type SurfaceScope } from '@/infrastructure/peer-device/deviceSurface';
+import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState';
+import { isTauriRuntime } from '@/infrastructure/runtime';
+import { BoundedResourceCache } from '@/shared/utils/BoundedResourceCache';
+import { gitEventService } from '../services/GitEventService';
+
+const REFRESH_DELAY_MS = 150;
+const CACHE_TTL_MS = 30_000;
+const ERROR_TTL_MS = 5_000;
+type Count = number | null;
+type PendingCount = { invalidated: boolean; result: Promise };
+
+const cache = new BoundedResourceCache(64, 64);
+const pending = new Map();
+
+function invalidate(key: string) {
+ cache.delete(key);
+ const request = pending.get(key);
+ if (request) request.invalidated = true;
+}
+
+// A Git action in a different scene can invalidate a cached welcome count.
+function invalidateWorkspaceCount({ data }: { data: { repositoryPath: { workspaceId: string } } }) {
+ const surface = getActiveSurfaceScope();
+ invalidate(surface.key('tracked-changes', surface.epoch, data.repositoryPath.workspaceId));
+}
+
+const stopOperationInvalidation = gitEventService.on('operation:completed', invalidateWorkspaceCount);
+const stopBranchInvalidation = gitEventService.on('branch:changed', invalidateWorkspaceCount);
+import.meta.hot?.dispose(() => {
+ stopOperationInvalidation();
+ stopBranchInvalidation();
+ cache.clear();
+});
+
+function readCount(key: string, workspaceId: string, surface: SurfaceScope): Promise {
+ const cached = cache.get(key);
+ if (cached && cached.expiresAt > Date.now()) return Promise.resolve(cached.count);
+ const existing = pending.get(key);
+ if (existing) return existing.result;
+
+ const request: PendingCount = {
+ invalidated: false,
+ result: gitAPI.getTrackedChangeCount(workspaceId)
+ .catch(() => null)
+ .then(count => {
+ if (request.invalidated || !surface.isCurrent()) return undefined;
+ cache.set(key, { count, expiresAt: Date.now() + (count === null ? ERROR_TTL_MS : CACHE_TTL_MS) });
+ return count;
+ })
+ .finally(() => pending.delete(key)),
+ };
+ pending.set(key, request);
+ return request.result;
+}
+
+/** A visible welcome page reads one number without registering Git polling demand. */
+export function useTrackedChangeCount(workspaceId: string, remoteWorkspace: boolean): Count {
+ const surface = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope);
+ const peer = usePeerDeviceModeOptional();
+ const attachment = peer?.attachments.find(item => item.deviceId === surface.surfaceId);
+ const supported = isLocalSurface(surface.surfaceId) ? isTauriRuntime()
+ : attachment?.health === 'ready' && attachment.capabilities?.gitTrackedChangeCountV1 === true
+ && !(remoteWorkspace && attachment.capabilities.hostKind === 'cli');
+ const key = surface.key('tracked-changes', surface.epoch, workspaceId);
+ const [snapshot, setSnapshot] = useState<{ key: string; count: Count }>();
+
+ useEffect(() => {
+ if (!supported) {
+ invalidate(key);
+ setSnapshot(undefined);
+ return;
+ }
+ let active = true;
+ let timer: ReturnType | undefined;
+ let revision = 0;
+ const canRead = () => active && surface.isCurrent() && document.visibilityState !== 'hidden';
+ const refresh = () => {
+ clearTimeout(timer);
+ const currentRevision = ++revision;
+ if (!canRead()) return;
+ timer = setTimeout(async () => {
+ if (!canRead()) return;
+ const count = await readCount(key, workspaceId, surface);
+ if (!canRead() || currentRevision !== revision) return;
+ // An operation invalidated this scan while it was in flight.
+ if (count === undefined) {
+ refresh();
+ return;
+ }
+ setSnapshot(previous => previous?.key === key && previous.count === count ? previous : { key, count });
+ }, REFRESH_DELAY_MS);
+ };
+ const scope = { repositoryPath: { workspaceId } };
+ const stopOperations = gitEventService.on('operation:completed', refresh, scope);
+ const stopBranchChanges = gitEventService.on('branch:changed', refresh, scope);
+ window.addEventListener('focus', refresh);
+ document.addEventListener('visibilitychange', refresh);
+ refresh();
+ return () => {
+ active = false;
+ clearTimeout(timer);
+ stopOperations();
+ stopBranchChanges();
+ window.removeEventListener('focus', refresh);
+ document.removeEventListener('visibilitychange', refresh);
+ };
+ }, [key, supported, surface, workspaceId]);
+
+ return supported && snapshot?.key === key ? snapshot.count : null;
+}