@keyou007/agent-bot 0.1.27-alpha.2 → 0.1.27-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +78 -13
  3. package/README.zh.md +78 -13
  4. package/assets/agent-bot.ico +0 -0
  5. package/assets/roboto-mono-OFL.txt +93 -0
  6. package/assets/roboto-mono-latin.woff2 +0 -0
  7. package/assets/workspace-drafts.js +88 -0
  8. package/assets/workspace-sessions.js +1935 -232
  9. package/assets/workspace.css +360 -35
  10. package/assets/workspace.js +2115 -249
  11. package/dist/cli/SelfUpdateObserver.js +124 -0
  12. package/dist/cli/SelfUpdateObserver.js.map +1 -0
  13. package/dist/cli/SelfUpdateRunner.js +267 -70
  14. package/dist/cli/SelfUpdateRunner.js.map +1 -1
  15. package/dist/cli/SelfUpdater.js +54 -15
  16. package/dist/cli/SelfUpdater.js.map +1 -1
  17. package/dist/cli/controlProtocol.js.map +1 -1
  18. package/dist/cli/help.js +6 -0
  19. package/dist/cli/help.js.map +1 -1
  20. package/dist/cli.js +85 -6
  21. package/dist/cli.js.map +1 -1
  22. package/dist/codex/CodexEventMapper.js +29 -5
  23. package/dist/codex/CodexEventMapper.js.map +1 -1
  24. package/dist/codex/CodexRuntime.js +3 -0
  25. package/dist/codex/CodexRuntime.js.map +1 -1
  26. package/dist/feishu/CardRenderer.js +45 -13
  27. package/dist/feishu/CardRenderer.js.map +1 -1
  28. package/dist/feishu/ConsoleFeishuClient.js +4 -0
  29. package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
  30. package/dist/feishu/FeishuMarkdown.js +2 -14
  31. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  32. package/dist/feishu/FeishuMessageClient.js +9 -0
  33. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  34. package/dist/feishu/FeishuTurnPresenter.js +26 -14
  35. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  36. package/dist/index.js +47 -12
  37. package/dist/index.js.map +1 -1
  38. package/dist/local-files/DiagramPreview.js +11 -6
  39. package/dist/local-files/DiagramPreview.js.map +1 -1
  40. package/dist/local-files/GitDiffPreview.js +40 -10
  41. package/dist/local-files/GitDiffPreview.js.map +1 -1
  42. package/dist/local-files/LiveMarkup.js +104 -0
  43. package/dist/local-files/LiveMarkup.js.map +1 -0
  44. package/dist/local-files/LocalFileViewerServer.js +219 -129
  45. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  46. package/dist/local-files/MarkdownExport.js +54 -0
  47. package/dist/local-files/MarkdownExport.js.map +1 -0
  48. package/dist/local-files/PreviewCodeFont.js +11 -0
  49. package/dist/local-files/PreviewCodeFont.js.map +1 -0
  50. package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
  51. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  52. package/dist/local-files/ToolCommandDisplay.js +111 -0
  53. package/dist/local-files/ToolCommandDisplay.js.map +1 -0
  54. package/dist/local-files/TurnPreviewPage.js +23 -269
  55. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  56. package/dist/local-files/WorkspaceFileEvents.js +206 -0
  57. package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
  58. package/dist/local-files/WorkspaceFiles.js +79 -3
  59. package/dist/local-files/WorkspaceFiles.js.map +1 -1
  60. package/dist/local-files/WorkspaceImages.js +15 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +20 -5
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +881 -79
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +105 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +13 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +28 -21
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +229 -92
  73. package/dist/proxy/ProxySessionController.js.map +1 -1
  74. package/dist/proxy/TaskMetadata.js +86 -0
  75. package/dist/proxy/TaskMetadata.js.map +1 -0
  76. package/dist/scheduling/ScheduleCards.js +10 -4
  77. package/dist/scheduling/ScheduleCards.js.map +1 -1
  78. package/dist/scheduling/ScheduleCommand.js +4 -0
  79. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  80. package/dist/scheduling/ScheduledTaskStore.js +51 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +18 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +145 -19
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +143 -36
  87. package/dist/state/TurnPreviewJournal.js.map +1 -1
  88. package/dist/state/TurnToolText.js +172 -0
  89. package/dist/state/TurnToolText.js.map +1 -0
  90. package/dist/state/migrations.js +4 -0
  91. package/dist/state/migrations.js.map +1 -1
  92. package/dist/supervision/SafeRestartNotifier.js +9 -6
  93. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  94. package/dist/terminal/TerminalPage.js +5 -0
  95. package/dist/terminal/TerminalPage.js.map +1 -1
  96. package/dist/updates/AutomaticUpdatePreparer.js +63 -12
  97. package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
  98. package/dist/updates/ManualUpdateController.js +7 -2
  99. package/dist/updates/ManualUpdateController.js.map +1 -1
  100. package/dist/utils/promptAttachments.js +20 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/toolTimestamp.js +6 -0
  103. package/dist/utils/toolTimestamp.js.map +1 -0
  104. package/npm-shrinkwrap.json +2 -2
  105. package/package.json +1 -1
  106. package/skills/agent-bot/SKILL.md +23 -2
  107. package/src/cli/SelfUpdateObserver.ts +111 -0
  108. package/src/cli/SelfUpdateRunner.ts +271 -85
  109. package/src/cli/SelfUpdater.ts +53 -16
  110. package/src/cli/controlProtocol.ts +1 -0
  111. package/src/cli/help.ts +6 -0
  112. package/src/cli.ts +71 -5
  113. package/src/codex/CodexEventMapper.ts +25 -5
  114. package/src/codex/CodexRuntime.ts +4 -0
  115. package/src/feishu/CardRenderer.ts +48 -13
  116. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  117. package/src/feishu/FeishuMarkdown.ts +2 -14
  118. package/src/feishu/FeishuMessageClient.ts +10 -0
  119. package/src/feishu/FeishuTurnPresenter.ts +22 -8
  120. package/src/feishu/types.ts +1 -0
  121. package/src/index.ts +47 -12
  122. package/src/local-files/DiagramPreview.ts +11 -6
  123. package/src/local-files/GitDiffPreview.ts +38 -10
  124. package/src/local-files/LiveMarkup.ts +103 -0
  125. package/src/local-files/LocalFileViewerServer.ts +207 -132
  126. package/src/local-files/MarkdownExport.ts +54 -0
  127. package/src/local-files/PreviewCodeFont.ts +12 -0
  128. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  129. package/src/local-files/ToolCommandDisplay.ts +104 -0
  130. package/src/local-files/TurnPreviewPage.ts +23 -254
  131. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  132. package/src/local-files/WorkspaceFiles.ts +72 -5
  133. package/src/local-files/WorkspaceImages.ts +10 -0
  134. package/src/local-files/WorkspacePage.ts +20 -5
  135. package/src/local-files/WorkspaceSessions.ts +811 -82
  136. package/src/local-files/WorkspaceTimeline.ts +109 -0
  137. package/src/presentation/OutboundRouter.ts +15 -4
  138. package/src/presentation/TurnStateReducer.ts +27 -18
  139. package/src/presentation/turnViewTypes.ts +2 -0
  140. package/src/proxy/ProxySessionController.ts +226 -77
  141. package/src/proxy/TaskMetadata.ts +81 -0
  142. package/src/runtime/types.ts +2 -1
  143. package/src/scheduling/ScheduleCards.ts +10 -4
  144. package/src/scheduling/ScheduleCommand.ts +4 -0
  145. package/src/scheduling/ScheduledTaskStore.ts +54 -9
  146. package/src/scheduling/types.ts +24 -4
  147. package/src/state/StateStore.ts +157 -20
  148. package/src/state/TurnPreviewJournal.ts +138 -34
  149. package/src/state/TurnToolText.ts +156 -0
  150. package/src/state/migrations.ts +4 -0
  151. package/src/supervision/SafeRestartNotifier.ts +9 -6
  152. package/src/terminal/TerminalPage.ts +5 -0
  153. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  154. package/src/updates/ManualUpdateController.ts +8 -3
  155. package/src/utils/promptAttachments.ts +24 -0
  156. package/src/utils/toolTimestamp.ts +5 -0
@@ -2,15 +2,66 @@
2
2
  const apiBase = document.body.dataset.workspaceUrl;
3
3
  const project = document.body.dataset.project;
4
4
  const root = document.body.dataset.root || '';
5
+ const workspacePageTitle = document.title;
6
+ const workspaceRevision = document.body.dataset.workspaceRevision;
7
+ const workspaceInstance = document.body.dataset.workspaceInstance;
8
+ const workspaceScript = document.getElementById('workspace-script')?.getAttribute('src');
5
9
  const appBase = document.body.dataset.workspaceApp;
10
+ const applePlatform = /^(?:Mac|iPhone|iPad|iPod)/iu.test(navigator.userAgentData?.platform || navigator.platform || '');
11
+ const embedded = document.body.hasAttribute('data-workspace-embedded');
6
12
  const historyScope = appBase ? new URL(appBase,window.location.href).href : apiBase;
7
13
  const isWindowsRoot = base => /^[a-z]:/iu.test(base) || base.startsWith(String.fromCharCode(92));
8
14
  const projectPath = (value, base = root) => isWindowsRoot(base) ? value?.replaceAll('\\','/').toLowerCase() : value;
9
15
  const stored = key => { try { return JSON.parse(window.localStorage?.getItem(key) || 'null'); } catch { return null; } };
10
- const chatAnchor = value => value?.bottom === true ? {bottom:true} :
11
- typeof value?.turn === 'string' && value.turn.length <= 200 && Number.isSafeInteger(value.offset) && Math.abs(value.offset) < 10_000_000
12
- ? {turn:value.turn,offset:value.offset} : undefined;
16
+ const chatOffset = value => Number.isSafeInteger(value) && Math.abs(value) < 10_000_000;
17
+ const chatAnchor = value => {
18
+ if (value?.bottom === true) return {bottom:true};
19
+ if (typeof value?.turn !== 'string' || value.turn.length > 200 || !chatOffset(value.offset)) return;
20
+ const anchor = {turn:value.turn,offset:value.offset}, target = value.target;
21
+ if (typeof target?.row === 'string' && target.row.length <= 512 && chatOffset(target.offset)) {
22
+ const part = Number.isSafeInteger(target.part) && target.part >= 0 && target.part < 4096 ? target.part : undefined;
23
+ anchor.target = {row:target.row,offset:target.offset,part};
24
+ }
25
+ return anchor;
26
+ };
13
27
  const put = (key,value) => { try { window.localStorage?.setItem(key,JSON.stringify(value)); } catch {} };
28
+ const themeKey = 'agentbot-workspace-theme';
29
+ const treeCacheKey = 'agentbot-workspace-directory-cache-v1', treeCacheAge = 30 * 60_000;
30
+ const conserveData = () => {
31
+ const network = window.navigator?.connection;
32
+ return Boolean(network?.saveData || network?.type === 'cellular' || ['slow-2g','2g','3g'].includes(network?.effectiveType)
33
+ || window.matchMedia?.('(pointer: coarse)').matches);
34
+ };
35
+ class DirectoryCache {
36
+ constructor() {
37
+ this.pages = new Map(); this.size = 0;
38
+ if (embedded) return;
39
+ try {
40
+ const saved = window.sessionStorage?.getItem(treeCacheKey);
41
+ if (saved && saved.length <= 600_000) for (const [key,item] of JSON.parse(saved)) {
42
+ if (item?.at > Date.now()-treeCacheAge && Array.isArray(item.data?.entries)) this.set(key,item.data,item.at,item.etag);
43
+ }
44
+ } catch {}
45
+ }
46
+ get(key) {
47
+ const item = this.pages.get(key); if (!item || item.at <= Date.now()-treeCacheAge) return;
48
+ this.pages.delete(key); this.pages.set(key,item); return item;
49
+ }
50
+ set(key,data,at = Date.now(),etag) {
51
+ const size = JSON.stringify([key,{data,at,etag}]).length;
52
+ if (size > 200_000) return;
53
+ this.size += size - (this.pages.get(key)?.size || 0);
54
+ this.pages.delete(key); this.pages.set(key,{data,at,etag,size});
55
+ while (this.pages.size > 160 || this.size > 550_000) {
56
+ const first = this.pages.keys().next().value; this.size -= this.pages.get(first).size; this.pages.delete(first);
57
+ }
58
+ }
59
+ persist() {
60
+ if (embedded) return;
61
+ try { window.sessionStorage?.setItem(treeCacheKey,JSON.stringify([...this.pages].map(([key,{data,at,etag}]) => [key,{data,at,etag}]))); } catch {}
62
+ }
63
+ clear() { this.pages.clear(); this.size = 0; this.persist(); }
64
+ }
14
65
  const choice = (value, values, fallback) => {
15
66
  if (value === undefined || value === null) return fallback;
16
67
  if (!values.includes(value)) throw new Error('页面状态中的选项无效。'); return value;
@@ -22,7 +73,13 @@
22
73
  const relativePath = (value, empty = false) => {
23
74
  if (typeof value !== 'string' || (!empty && !value) || value.includes('\0') || /^[\\/]|^[a-z]:/iu.test(value) || value.split(/[\\/]/u).includes('..')) throw new Error('页面状态中的路径无效。'); return value;
24
75
  };
25
- const tabKinds = ['file','diff','new','web','terminal'];
76
+ const tabKinds = embedded ? ['file','diff'] : ['file','diff','new','web','terminal','directory'];
77
+ const localDirectoryPrefix = 'local-';
78
+ const isLocalDirectory = id => id.startsWith(localDirectoryPrefix);
79
+ const directoryEntry = (kind, value) => kind === 'directory' && value != null ? relativePath(value) : undefined;
80
+ const previewSource = (kind,value) => appBase && ['file','diff'].includes(kind) && /^[a-f0-9]{32}$/u.test(value || '') ? value : undefined;
81
+ const previewKey = (kind,path,source) => (source ? source+':' : '')+kind+':'+path;
82
+ const localAddress = value => /^(?:file:|[a-z]:[\\/]|\\\\|\/(?!\/))/iu.test(value);
26
83
  const webAddress = value => {
27
84
  const url = new URL(value);
28
85
  if (!['http:','https:'].includes(url.protocol) || url.username || url.password || url.origin === window.location.origin || value.length > 4096) throw new Error('仅支持不含账号密码的外部 HTTP / HTTPS 网址。');
@@ -35,21 +92,31 @@
35
92
  const local = /^localhost$|[.]localhost$|^\[[a-f0-9:]+\]$|^[0-9]+(?:[.][0-9]+){3}$/iu.test(host);
36
93
  return webAddress((local?'http://':'https://')+value.replace(/^\/\//u,''));
37
94
  };
95
+ const parseAddressLine = value => {
96
+ const suffix = /:(\d+)$/u.exec(value);
97
+ if (!suffix) return;
98
+ const line = Number(suffix[1]);
99
+ if (Number.isSafeInteger(line) && line > 0) return {path:value.slice(0,suffix.index),hash:'#L'+line};
100
+ };
38
101
  const fileAddress = (value, root) => {
39
102
  const windowsRoot = isWindowsRoot(root);
40
- if (/^https?:|^\/\//iu.test(value) || /^[^\s/\\:@]+:[0-9]+(?:[/?#]|$)|^\[[a-f0-9:]+\](?::[0-9]+)?(?:[/?#]|$)/iu.test(value)) return;
41
- if (/^[a-z][a-z0-9+.-]*:/iu.test(value) && !/^file:|^[a-z]:[\\/]/iu.test(value)) throw new Error('仅支持项目文件或 HTTP / HTTPS 网址。');
42
- const hashIndex = value.indexOf('#'), hash = hashIndex < 0?undefined:value.slice(hashIndex);
43
- let path = hashIndex < 0?value:value.slice(0,hashIndex);
103
+ if (/^https?:|^\/\/|^\[[a-f0-9:]+\](?::[0-9]+)?(?:[/?#]|$)/iu.test(value)) return;
104
+ const hashIndex = value.indexOf('#'), line = hashIndex < 0 && !value.startsWith(':') ? parseAddressLine(value) : undefined;
105
+ if (!line && /^[^\s/\\:@]+:[0-9]+(?:[/?#]|$)/u.test(value)) return;
106
+ let path = line?.path ?? (hashIndex < 0 ? value : value.slice(0,hashIndex));
107
+ if (/^[a-z][a-z0-9+.-]*:/iu.test(path) && !/^file:|^[a-z]:[\\/]/iu.test(path)) throw new Error('仅支持项目文件或 HTTP / HTTPS 网址。');
108
+ const suffix = value.slice(path.length), hash = line?.hash ?? (suffix || undefined);
44
109
  if (/^file:/iu.test(path)) { const url = new URL(path); if (url.host && url.host !== 'localhost') throw new Error('仅支持项目内的本地文件。'); path = decodeURIComponent(url.pathname).replace(/^\/([a-z]:)/iu,'$1'); }
45
110
  path = path.replaceAll('\\','/'); const base = root.replaceAll('\\','/').replace(/\/$/u,'');
46
111
  if (/^[a-z]:|^\//iu.test(path)) {
47
112
  if (!projectPath(path,root).startsWith(projectPath(base,root)+'/')) throw new Error('文件必须位于当前项目目录内。'); path = path.slice(base.length+1);
48
113
  }
49
114
  relativePath(path,true); if (windowsRoot && /[<>:"|?*]/u.test(path)) return; const trailing = path.endsWith('/'); path = path.split('/').filter(part => part && part !== '.').join('/'); if (trailing && path) path += '/';
50
- return {path,hash,literal:hash && !/^file:/iu.test(value) && (!windowsRoot || !/[<>:"|?*]/u.test(path+hash))?path+hash:undefined};
115
+ const literal = suffix && !/^file:/iu.test(value) && (!windowsRoot || !/[<>:"|?*]/u.test(path+suffix)) ? path+suffix : undefined;
116
+ return {path,hash,literal,query:line ? path : literal || path};
51
117
  };
52
118
  const tabPath = (value, kind) => {
119
+ if (kind === 'directory') { if (!/^(?:local-)?[a-f0-9]{32}$/u.test(value)) throw new Error('目录标识无效。'); return value; }
53
120
  if (kind === 'web') return webAddress(value);
54
121
  if (kind === 'new' || kind === 'terminal') { if (typeof value !== 'string' || !/^[a-f0-9]{16}$/u.test(value)) throw new Error('标签标识无效。'); return value; }
55
122
  return relativePath(value);
@@ -74,6 +141,8 @@
74
141
  const url = new URL(href), params = url.searchParams;
75
142
  const entry = params.get('entry'), kind = choice(params.get('kind'),tabKinds,'file'), mode = choice(params.get('mode'),['all','staged','unstaged'],'all');
76
143
  const route = {pane:choice(params.get('pane'),['tasks','chat','files'],'files'),listMode:choice(params.get('list'),['files','changes'],'files'),view:choice(params.get('view'),['list','content'],entry?'content':'list'),tab:entry?{id:params.has('tab')?tabId(params.get('tab')):undefined,path:tabPath(entry,kind),kind,mode,original:params.has('original')?relativePath(params.get('original')):undefined}:null};
144
+ if (route.tab) route.tab.directoryEntry = directoryEntry(kind,params.get('directoryFile'));
145
+ if (route.tab) route.tab.source = previewSource(kind,params.get('sourceDir'));
77
146
  let extra = {v:1}; const encoded = url.hash.startsWith('#workspace=');
78
147
  if (encoded) {
79
148
  extra = JSON.parse(decodeURIComponent(url.hash.slice(11)));
@@ -86,15 +155,17 @@
86
155
  if (!value || typeof value !== 'object') throw new Error('链接中的文件标签无效。');
87
156
  const kind = choice(value.kind,tabKinds,'file');
88
157
  const path = tabPath(value.path,kind);
89
- const tab = {id:value.id===undefined?resolveId?.(kind,path) || instanceId():tabId(value.id),path,kind,mode:choice(value.mode,['all','staged','unstaged'],'all'),original:value.original===undefined?undefined:relativePath(value.original),scrollTop:offset(value.scrollTop),scrollLeft:offset(value.scrollLeft),hash:undefined,requestedHash:undefined};
158
+ const source = previewSource(kind,value.source);
159
+ const tab = {id:value.id===undefined?resolveId?.(kind,path,source) || instanceId():tabId(value.id),path,kind,source,mode:choice(value.mode,['all','staged','unstaged'],'all'),original:value.original===undefined?undefined:relativePath(value.original),scrollTop:offset(value.scrollTop),scrollLeft:offset(value.scrollLeft),hash:undefined,requestedHash:undefined};
160
+ tab.directoryEntry = directoryEntry(kind,value.directoryEntry);
90
161
  for (const key of ['hash','requestedHash']) if (value[key] !== undefined) { if (typeof value[key] !== 'string' || !value[key].startsWith('#')) throw new Error('链接中的文件锚点无效。'); tab[key] = value[key]; }
91
162
  tabs.push(tab);
92
163
  }
93
164
  }
94
165
  if (route.tab) {
95
- let active = tabs.find(tab => route.tab.id?tab.id===route.tab.id:tab.path === route.tab.path && tab.kind === route.tab.kind);
96
- if (!active) { active = {...route.tab,id:route.tab.id || resolveId?.(kind,route.tab.path) || instanceId(),scrollTop:0,scrollLeft:0}; tabs.push(active); }
97
- Object.assign(active,{path:route.tab.path,kind:route.tab.kind,mode:route.tab.mode,original:route.tab.original}); route.tab.id = active.id;
166
+ let active = tabs.find(tab => route.tab.id?tab.id===route.tab.id:tab.path === route.tab.path && tab.kind === route.tab.kind && tab.source === route.tab.source);
167
+ if (!active) { active = {...route.tab,id:route.tab.id || resolveId?.(kind,route.tab.path,route.tab.source) || instanceId(),scrollTop:0,scrollLeft:0}; tabs.push(active); }
168
+ Object.assign(active,route.tab,{id:active.id}); route.tab.id = active.id;
98
169
  if (!encoded && url.hash) active.hash = active.requestedHash = url.hash;
99
170
  route.tab.hash = active.hash;
100
171
  }
@@ -111,10 +182,10 @@
111
182
  const layout = {};
112
183
  for (const key of ['sidebar','chat','explorer']) if (extra.layout?.[key] !== undefined) { const value = offset(extra.layout[key]); if (value > 4000) throw new Error('面板宽度无效。'); layout[key] = value; }
113
184
  for (const key of ['sidebarCollapsed','filesCollapsed','explorerCollapsed']) if (extra.layout?.[key] !== undefined) { if (typeof extra.layout[key] !== 'boolean') throw new Error('面板折叠状态无效。'); layout[key] = extra.layout[key]; }
114
- const recentTabs = extra.recentTabs ?? [], keys = new Map(tabs.flatMap(tab => [[tab.id,tab.id],[tab.kind+':'+tab.path,tab.id]]));
185
+ const recentTabs = extra.recentTabs ?? [], keys = new Map(tabs.flatMap(tab => [[tab.id,tab.id],[previewKey(tab.kind,tab.path,tab.source),tab.id]]));
115
186
  if (new Set(tabs.map(tab => tab.id)).size !== tabs.length) throw new Error('链接中的标签标识重复。');
116
187
  if (!Array.isArray(recentTabs) || recentTabs.some(key => typeof key !== 'string' || !keys.has(key))) throw new Error('链接中的标签浏览顺序无效。');
117
- return {route,tabs,trees,scroll,layout,recentTabs:[...new Set(recentTabs.map(key => keys.get(key)))]};
188
+ return {route,tabs,trees,treeDirectory:previewSource('file',extra.treeDirectory),scroll,layout,recentTabs:[...new Set(recentTabs.map(key => keys.get(key)))]};
118
189
  };
119
190
  const element = (tag, text, className) => {
120
191
  const node = document.createElement(tag);
@@ -125,6 +196,7 @@
125
196
  const icons = {
126
197
  tasks: '<path d="m3 6 2 2 4-4M12 6h9M3 13h3M12 13h9M3 20h3M12 20h9"/>',
127
198
  chat: '<path d="M21 11a8 8 0 0 1-8 8H8l-5 3V11a8 8 0 0 1 8-8h2a8 8 0 0 1 8 8Z"/>',
199
+ annotation: '<path d="M5 4h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-9l-5 4v-4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/><path d="M9 10h6m-3-3v6"/>',
128
200
  folder: '<path d="M3 7V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/>',
129
201
  tree: '<rect x="3" y="2" width="6" height="5" rx="1"/><path d="M6 7v13h6M6 12h6"/><rect x="12" y="9" width="9" height="6" rx="1"/><rect x="12" y="17" width="9" height="6" rx="1"/>',
130
202
  file: '<path d="M14 2H5a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9Z M14 2v7h7M8 13h8M8 17h8"/>',
@@ -136,6 +208,7 @@
136
208
  up: '<path d="M12 20V4m-6 6 6-6 6 6"/>',
137
209
  down: '<path d="M12 4v16m-6-6 6 6 6-6"/>',
138
210
  close: '<path d="m6 6 12 12M6 18 18 6"/>',
211
+ check: '<path d="m5 12 4 4L19 6"/>',
139
212
  download: '<path d="M12 3v12m-5-5 5 5 5-5M4 16v5h16v-5"/>',
140
213
  send: '<path d="m22 2-7 20-4-9-9-4Z M22 2 11 13"/>',
141
214
  lock: '<rect x="5" y="10" width="14" height="11" rx="2"/><path d="M8 10V6a4 4 0 0 1 8 0v4M12 14v3"/>',
@@ -146,8 +219,15 @@
146
219
  explorer: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/>',
147
220
  web: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a17 17 0 0 1 0 18 17 17 0 0 1 0-18Z"/>',
148
221
  terminal: '<rect x="2" y="3" width="20" height="18" rx="2"/><path d="m6 8 4 4-4 4M13 16h5"/>',
222
+ pencil: '<path d="m14 6 4 4M4 20l4.5-1 11-11a2.8 2.8 0 0 0-4-4l-11 11Z"/>',
223
+ trash: '<path d="M4 7h16M9 7V4h6v3m3 0-1 13H7L6 7m4 3v7m4-7v7"/>',
224
+ plug: '<path d="M9 3v5m6-5v5M6 8h12v3a6 6 0 0 1-12 0Zm6 9v4"/>',
225
+ tool: '<path d="M14 6l4 4 3-3a6 6 0 0 1-7 8l-5 5a2.8 2.8 0 1 1-4-4l5-5a6 6 0 0 1 8-7Z"/>',
149
226
  external: '<path d="M14 3h7v7M21 3 10 14M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"/>',
150
227
  locate: '<circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/>',
228
+ search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4.5 4.5"/>',
229
+ sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5"/>',
230
+ moon: '<path d="M21 14a9 9 0 0 1-11-11 9 9 0 1 0 11 11Z"/>',
151
231
  'file-javascript': '<g stroke="none"><g transform="matrix(0.5 0 0 0.5 3 -16)"><g><path fill="currentColor" stroke="none" d="M 12.65625 59.96094 Q 12.65625 64.94141 10.1953125 67.70508 Q 7.734375 70.46875 3.6328125 70.46875 Q 1.7187501 70.46875 0.48828125 70.01953 L 0.48828125 65.64453 Q 1.6015626 66.40625 3.359375 66.40625 Q 8.0078125 66.40625 8.0078125 59.21875 L 8.0078125 41.992188 L 12.65625 41.992188 L 12.65625 59.96094 Z M 18.027344 68.88672 L 18.027344 64.10156 Q 18.671875 64.6875 19.560547 65.15625 Q 20.449219 65.625 21.445313 65.947266 Q 22.441406 66.26953 23.437498 66.44531 Q 24.433596 66.62109 25.27344 66.62109 Q 28.203125 66.62109 29.638672 65.64453 Q 31.074219 64.66797 31.074219 62.812496 Q 31.074219 61.816406 30.595705 61.083984 Q 30.117188 60.351566 29.257813 59.746094 Q 28.398438 59.140625 27.236328 58.58398 Q 26.074219 58.027348 24.746094 57.421875 Q 23.320313 56.660156 22.089844 55.878906 Q 20.859375 55.097656 19.951172 54.15039 Q 19.042969 53.203125 18.52539 52.01172 Q 18.007813 50.820313 18.007813 49.21875 Q 18.007813 47.246094 18.896484 45.791016 Q 19.785156 44.335938 21.240234 43.38867 Q 22.69531 42.441406 24.550781 41.98242 Q 26.406248 41.523438 28.339842 41.523438 Q 32.734375 41.523438 34.746094 42.51953 L 34.746094 47.109375 Q 32.36328 45.39062 28.613281 45.39062 Q 27.578125 45.39062 26.552734 45.585934 Q 25.527344 45.781246 24.716797 46.230465 Q 23.90625 46.679684 23.398438 47.382816 Q 22.890623 48.085938 22.890623 49.08203 Q 22.890623 50.01953 23.28125 50.703125 Q 23.671875 51.386723 24.423828 51.953125 Q 25.175783 52.51953 26.259766 53.05664 Q 27.34375 53.59375 28.769531 54.218754 Q 30.234375 54.98047 31.533201 55.820313 Q 32.83203 56.660156 33.81836 57.67578 Q 34.804688 58.691406 35.38086 59.931644 Q 35.95703 61.171875 35.95703 62.753906 Q 35.95703 64.88281 35.097656 66.34766 Q 34.23828 67.8125 32.783203 68.73047 Q 31.328125 69.64844 29.433596 70.05859 Q 27.539063 70.46875 25.429688 70.46875 Q 24.72656 70.46875 23.701172 70.36133 Q 22.675781 70.25391 21.601563 70.04883 Q 20.527344 69.84375 19.570313 69.55078 Q 18.613281 69.25781 18.027344 68.88672 Z" /></g></g></g>',
152
232
  'file-typescript': '<g stroke="none"><g transform="matrix(0.46511627906976744 0 0 0.46511627906976744 2 -14.046511627906975)"><g><path fill="currentColor" stroke="none" d="M 21.425781 45.9375 L 13.378907 45.9375 L 13.378907 70 L 8.730469 70 L 8.730469 45.9375 L 0.70312494 45.9375 L 0.70312494 41.992188 L 21.425781 41.992188 L 21.425781 45.9375 Z M 24.238283 68.88672 L 24.238283 64.10156 Q 24.882813 64.6875 25.771484 65.15625 Q 26.660158 65.625 27.65625 65.947266 Q 28.652344 66.26953 29.648438 66.44531 Q 30.644531 66.62109 31.484375 66.62109 Q 34.414063 66.62109 35.84961 65.64453 Q 37.285156 64.66797 37.285156 62.812496 Q 37.285156 61.816406 36.80664 61.083984 Q 36.328125 60.351566 35.46875 59.746094 Q 34.609375 59.140625 33.447266 58.58398 Q 32.285156 58.027348 30.957031 57.421875 Q 29.531252 56.660156 28.300781 55.878906 Q 27.070313 55.097656 26.16211 54.15039 Q 25.253906 53.203125 24.736328 52.01172 Q 24.21875 50.820313 24.21875 49.21875 Q 24.21875 47.246094 25.107422 45.791016 Q 25.996094 44.335938 27.451172 43.38867 Q 28.90625 42.441406 30.761717 41.98242 Q 32.617188 41.523438 34.55078 41.523438 Q 38.945313 41.523438 40.95703 42.51953 L 40.95703 47.109375 Q 38.57422 45.39062 34.82422 45.39062 Q 33.789063 45.39062 32.76367 45.585934 Q 31.738281 45.781246 30.927734 46.230465 Q 30.117188 46.679684 29.609375 47.382816 Q 29.101563 48.085938 29.101563 49.08203 Q 29.101563 50.01953 29.492188 50.703125 Q 29.882813 51.386723 30.634766 51.953125 Q 31.386719 52.51953 32.470703 53.05664 Q 33.554688 53.59375 34.98047 54.218754 Q 36.445313 54.98047 37.74414 55.820313 Q 39.04297 56.660156 40.029297 57.67578 Q 41.015625 58.691406 41.591797 59.931644 Q 42.16797 61.171875 42.16797 62.753906 Q 42.16797 64.88281 41.308594 66.34766 Q 40.44922 67.8125 38.99414 68.73047 Q 37.539063 69.64844 35.64453 70.05859 Q 33.75 70.46875 31.640625 70.46875 Q 30.9375 70.46875 29.91211 70.36133 Q 28.88672 70.25391 27.8125 70.04883 Q 26.738281 69.84375 25.78125 69.55078 Q 24.824217 69.25781 24.238283 68.88672 Z" /></g></g></g>',
153
233
  'file-cpp': '<g stroke="none"><g transform="matrix(0.5333333333333333 0 0 0.5333333333333333 1.8000000000000007 -17.866666666666667)"><g><path fill="currentColor" stroke="none" d="M 22.988281 68.828125 Q 19.824219 70.46875 15.1171875 70.46875 Q 9.0234375 70.46875 5.3515625 66.62109 Q 1.6796875 62.773438 1.6796875 56.523438 Q 1.6796875 49.804688 5.8105464 45.664063 Q 9.941406 41.523438 16.25 41.523438 Q 20.3125 41.523438 22.988281 42.67578 L 22.988281 47.285156 Q 20.15625 45.60547 16.738281 45.60547 Q 12.187499 45.60547 9.365234 48.515625 Q 6.5429688 51.42578 6.5429688 56.289066 Q 6.5429688 60.91797 9.1796875 63.66211 Q 11.816405 66.40625 16.113281 66.40625 Q 20.078125 66.40625 22.988281 64.53125 L 22.988281 68.828125 Z" /></g></g><path d="M16.3 10.2v4.2m-1.45-2.1h2.9M21.3 10.2v4.2m-1.45-2.1h2.9" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round" opacity="1" /></g>',
@@ -188,7 +268,332 @@
188
268
  };
189
269
  const iconControl = (tag, name, label, className = '') => {
190
270
  const node = element(tag,undefined,'icon-control '+className); node.append(icon(name));
191
- node.title = label; node.setAttribute('aria-label',label); return node;
271
+ node.dataset.tooltip = label; node.setAttribute('aria-label',label); return node;
272
+ };
273
+ const selectionElement = node => node.nodeType === 1 ? node : node.parentElement;
274
+ const sameRange = (a,b) => a.startContainer === b.startContainer && a.endContainer === b.endContainer
275
+ && a.startOffset === b.startOffset && a.endOffset === b.endOffset;
276
+ const annotationAnchor = (range,root,kind) => {
277
+ const prefix = document.createRange(); prefix.selectNodeContents(root);
278
+ prefix.setEnd(range.startContainer,range.startOffset);
279
+ return {kind,start:prefix.toString().length,text:range.toString()};
280
+ };
281
+ const restoreAnnotationRange = (root,anchor) => {
282
+ if (!root || typeof anchor?.text !== 'string' || !anchor.text || anchor.text.length > 100_000) return;
283
+ const text = root.textContent;
284
+ let start = anchor.start;
285
+ if (!Number.isSafeInteger(start) || start < 0 || !text.startsWith(anchor.text,start)) {
286
+ start = text.indexOf(anchor.text);
287
+ if (start < 0 || start !== text.lastIndexOf(anchor.text)) return;
288
+ }
289
+ const range = document.createRange(), end = start+anchor.text.length;
290
+ const nodes = document.createTreeWalker(root,NodeFilter.SHOW_TEXT);
291
+ let offset = 0, node, started = false;
292
+ while ((node = nodes.nextNode())) {
293
+ const next = offset+node.length;
294
+ if (!started && start < next) { range.setStart(node,start-offset); started = true; }
295
+ if (started && end <= next) { range.setEnd(node,end-offset); return range; }
296
+ offset = next;
297
+ }
298
+ };
299
+ const lineSpan = (first,last) => first === last ? String(first) : `${first}–${last}`;
300
+ const annotationPath = (directory,entry) => {
301
+ const path = directory.replace(/[\\/]$/u,'')+'/'+entry;
302
+ return isWindowsRoot(directory) ? path.replaceAll('/','\\') : path;
303
+ };
304
+ const annotationQuote = ({range,preview,selectedText,directory,tab}) => {
305
+ let quote, line, originalLine;
306
+ if (preview.matches('.code')) {
307
+ const selectedRows = [];
308
+ for (const source of preview.querySelectorAll('.line-text,.diff-text')) {
309
+ if (!range.intersectsNode(source)) continue;
310
+ const portion = range.cloneRange(); portion.selectNodeContents(source);
311
+ if (source.contains(range.startContainer)) portion.setStart(range.startContainer,range.startOffset);
312
+ if (source.contains(range.endContainer)) portion.setEnd(range.endContainer,range.endOffset);
313
+ selectedRows.push({row:source.parentElement,text:portion.toString()});
314
+ }
315
+ const rows = selectedRows.slice(selectedRows.findIndex(row => row.text),selectedRows.findLastIndex(row => row.text)+1);
316
+ quote = rows.map(row => row.text).join('\n');
317
+ const current = rows.map(({row}) => /^L(\d+)$/u.exec(row.id)?.[1]).filter(Boolean);
318
+ if (current.length) line = lineSpan(current[0],current.at(-1));
319
+ if (rows.some(({row}) => row.classList.contains('diff-deletion'))) {
320
+ const original = rows.map(({row}) => row.querySelector('.diff-number')?.textContent).filter(Boolean);
321
+ originalLine = lineSpan(original[0],original.at(-1));
322
+ }
323
+ } else {
324
+ const start = selectionElement(range.startContainer)?.closest('[data-source-start]');
325
+ const end = selectionElement(range.endContainer)?.closest('[data-source-end]');
326
+ if (!start || !end) return;
327
+ line = lineSpan(start.dataset.sourceStart,end.dataset.sourceEnd);
328
+ quote = selectedText;
329
+ }
330
+ if (!quote.trim() || !line && !originalLine) return;
331
+ return {path:annotationPath(directory,tab.path),line,originalLine,quote,
332
+ ...(originalLine && tab.original ? {originalPath:annotationPath(directory,tab.original)} : {})};
333
+ };
334
+ class WorkspaceAnnotations {
335
+ constructor(app) {
336
+ this.app = app;
337
+ this.draftAnnotations = [];
338
+ const button = this.button = iconControl('button','annotation','添加批注','workspace-annotation');
339
+ button.type = 'button'; button.hidden = true;
340
+ button.onpointerdown = event => event.preventDefault();
341
+ button.onclick = () => this.open();
342
+ const form = this.form = element('form',undefined,'workspace-annotation-editor');
343
+ form.hidden = true; form.setAttribute('aria-label','添加批注');
344
+ const input = this.input = element('textarea'); input.rows = 1; input.maxLength = 8000;
345
+ input.placeholder = '写批注…'; input.setAttribute('aria-label','批注内容');
346
+ const actions = this.actions = element('div',undefined,'workspace-annotation-actions');
347
+ const cancel = iconControl('button','close','取消批注'); cancel.type = 'button'; cancel.onclick = () => this.cancel();
348
+ const submit = this.submit = iconControl('button','check','添加到聊天'); submit.type = 'submit';
349
+ const status = this.status = element('small'); status.setAttribute('role','status');
350
+ const measure = this.measure = element('span',undefined,'workspace-annotation-measure'); measure.setAttribute('aria-hidden','true');
351
+ actions.append(cancel,submit); form.append(input,actions,status,measure);
352
+ input.oninput = () => { this.status.textContent = ''; this.grow(); };
353
+ input.onkeydown = event => {
354
+ if (event.isComposing || event.keyCode === 229) return;
355
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.cancel(); }
356
+ if (event.key !== 'Enter') return;
357
+ event.preventDefault(); event.stopPropagation();
358
+ if (event.shiftKey || event.ctrlKey || event.metaKey) {
359
+ if (input.value.length - (input.selectionEnd-input.selectionStart) < input.maxLength) {
360
+ input.setRangeText('\n',input.selectionStart,input.selectionEnd,'end'); this.grow();
361
+ }
362
+ } else this.commit();
363
+ };
364
+ form.onsubmit = event => { event.preventDefault(); this.commit(); };
365
+ form.addEventListener('focusout',event => {
366
+ if (!form.contains(event.relatedTarget)) this.saveOnBlur();
367
+ });
368
+ app.append(button,form);
369
+ this.listeners = new AbortController(); const {signal} = this.listeners;
370
+ document.addEventListener('selectionchange',this.selectionChanged,{signal});
371
+ document.addEventListener('pointerdown',this.beginSelection,{capture:true,signal});
372
+ window.addEventListener('pointerup',this.endSelection,{signal});
373
+ window.addEventListener('pointercancel',this.endSelection,{signal});
374
+ window.addEventListener('blur',this.endSelection,{signal});
375
+ document.addEventListener('keydown',this.extendSelection,{signal});
376
+ document.addEventListener('keyup',this.finishKeyboardSelection,{signal});
377
+ app.addEventListener('scroll',this.refresh,{capture:true,signal});
378
+ window.addEventListener('resize',this.refresh,{signal});
379
+ window.visualViewport?.addEventListener('resize',this.refresh,{signal});
380
+ window.visualViewport?.addEventListener('scroll',this.refresh,{signal});
381
+ if (embedded) window.addEventListener('message',this.result,{signal});
382
+ if (window.CSS?.highlights && typeof MutationObserver === 'function') {
383
+ this.observer = new MutationObserver(records => {
384
+ const preview = this.app.filesPanel?.content, chat = this.app.sessions?.body;
385
+ if (this.draftAnnotations.length && records.some(({target}) => preview?.contains(target) || chat?.contains(target))) this.paintDrafts();
386
+ });
387
+ this.observer.observe(app,{subtree:true,childList:true,characterData:true});
388
+ }
389
+ }
390
+ hideOffer() {
391
+ clearTimeout(this.offerTimer); this.offer = undefined; this.button.hidden = true;
392
+ }
393
+ beginSelection = event => {
394
+ if (event.button !== 0 || this.button.contains(event.target) || this.form.contains(event.target)) return;
395
+ clearTimeout(this.settleTimer); this.touchSettling = event.pointerType === 'touch';
396
+ this.pointer = event.pointerId; this.dismissedRange = undefined; this.hideOffer();
397
+ };
398
+ endSelection = event => {
399
+ if (event.type !== 'blur' && this.pointer !== event.pointerId) return;
400
+ this.pointer = undefined;
401
+ if (event.type === 'blur') {
402
+ clearTimeout(this.settleTimer); this.keyboard = this.touchSettling = false; this.hideOffer(); this.saveOnBlur();
403
+ return;
404
+ }
405
+ this.selectionChanged();
406
+ };
407
+ extendSelection = event => {
408
+ if (!event.shiftKey || !['ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End','PageUp','PageDown'].includes(event.key)
409
+ || event.target.closest?.('textarea,input,[contenteditable=true]')) return;
410
+ this.keyboard = true; this.dismissedRange = undefined; this.hideOffer();
411
+ };
412
+ finishKeyboardSelection = event => {
413
+ if (event.key !== 'Shift' || !this.keyboard) return;
414
+ this.keyboard = false; this.selectionChanged();
415
+ };
416
+ selectionChanged = () => {
417
+ if (this.entry || this.pointer !== undefined || this.keyboard) return;
418
+ if (!this.touchSettling && !window.matchMedia?.('(pointer:coarse)').matches) { this.offerSelection(); return; }
419
+ this.hideOffer(); clearTimeout(this.settleTimer);
420
+ this.settleTimer = setTimeout(() => { this.touchSettling = false; this.offerSelection(); },210);
421
+ };
422
+ offerSelection() {
423
+ if (this.entry) return;
424
+ const selected = this.selection();
425
+ if (selected && (this.offer && sameRange(selected.range,this.offer.range)
426
+ || this.dismissedRange && sameRange(selected.range,this.dismissedRange))) return;
427
+ this.hideOffer();
428
+ this.dismissedRange = undefined;
429
+ if (!selected) return;
430
+ this.offer = {...selected,range:selected.range.cloneRange(),selectedText:window.getSelection().toString()};
431
+ this.refresh();
432
+ this.offerTimer = setTimeout(() => { this.dismissedRange = this.offer?.range; this.hideOffer(); },3000);
433
+ }
434
+ selection() {
435
+ const sessions = this.app.sessions, task = embedded ? this.hostTask : sessions?.annotationTask(), selection = window.getSelection?.();
436
+ if (!selection?.rangeCount || selection.isCollapsed || !task) return;
437
+ const range = selection.getRangeAt(0);
438
+ const start = selectionElement(range.startContainer), end = selectionElement(range.endContainer);
439
+ const chat = sessions?.body;
440
+ if (chat?.contains(range.commonAncestorContainer) && start?.closest('.session-turn-content,.session-outbox') && end?.closest('.session-turn-content,.session-outbox')) {
441
+ const label = start.closest('.session-message')?.getAttribute('aria-label') || (start.closest('[data-tool]') ? '工具输出' : '对话记录');
442
+ const scope = selectionElement(range.commonAncestorContainer)?.closest('.session-turn-content,.session-outbox');
443
+ const turns = [...new Set([start,end].map(node => node.closest('[data-turn]')?.dataset.turn).filter(Boolean))];
444
+ return {range,content:chat,preview:scope || chat,anchorKind:scope?.classList.contains('session-turn-content') ? 'turn' : scope ? 'outbox' : 'chat',
445
+ task,label:'聊天 · '+label,turn:turns.join(' → ') || undefined};
446
+ }
447
+ const files = this.app.filesPanel, tab = files?.tabs.get(files.activeKey);
448
+ if (files?.dataset.view !== 'content' || files.renderedKey !== tab?.key || !['file','diff'].includes(tab?.kind)) return;
449
+ const content = files.content, directory = files.previewRoot(tab.source);
450
+ if (!directory || !content.contains(range.commonAncestorContainer)) return;
451
+ const preview = start?.closest('pre.code,.markdown-body');
452
+ if (!preview || end?.closest('pre.code,.markdown-body') !== preview) return;
453
+ return {range,content,preview,anchorKind:tab.kind,tab,directory,task};
454
+ }
455
+ open() {
456
+ const selected = this.offer;
457
+ if (!selected || this.entry || this.button.hidden) return;
458
+ const {label,turn,selectedText,task,content,range,tab,preview,anchorKind} = selected;
459
+ const annotation = label ? {label,turn,quote:selectedText} : annotationQuote(selected);
460
+ if (!annotation?.quote.trim()) return;
461
+ const anchor = annotationAnchor(range,preview,anchorKind);
462
+ this.entry = {annotation:{...annotation,anchor},task,content,range,tab};
463
+ this.highlight('workspace-annotation-selection',[range]);
464
+ this.hideOffer(); this.form.hidden = false;
465
+ this.grow(); this.input.focus({preventScroll:true});
466
+ }
467
+ grow() {
468
+ this.measure.textContent = this.input.value;
469
+ this.submit.disabled = !this.input.value.trim() || Boolean(this.pending);
470
+ this.refresh();
471
+ }
472
+ saveOnBlur() {
473
+ if (!this.entry || this.pending) return;
474
+ if (this.input.value.trim()) this.commit(); else this.cancel();
475
+ }
476
+ commit() {
477
+ const note = this.input.value.trim(), entry = this.entry;
478
+ if (!entry || !note || this.pending) return;
479
+ const annotation = {...entry.annotation,note};
480
+ if (annotation.quote.length > 100_000) { this.finish('选中的文字过长,请缩小选区后再添加批注。'); return; }
481
+ if (embedded) {
482
+ const request = this.pending = instanceId();
483
+ this.submit.disabled = true;
484
+ this.replyTimer = setTimeout(() => this.finish('未能添加批注,请重试。'),3000);
485
+ window.parent.postMessage({type:'agentbot-workspace-annotate',request,annotation,task:entry.task},window.location.origin);
486
+ } else {
487
+ const error = this.app.sessions.addAnnotation(annotation,entry.task);
488
+ this.finish(error);
489
+ }
490
+ }
491
+ result = event => {
492
+ if (event.source !== window.parent || event.origin !== window.location.origin) return;
493
+ if (event.data?.type === 'agentbot-workspace-annotation-result' && this.pending && event.data.request === this.pending) this.finish(event.data.error);
494
+ if (event.data?.type === 'agentbot-workspace-annotation-drafts') {
495
+ this.hostTask = event.data.task;
496
+ this.draftAnnotations = event.data.annotations;
497
+ this.paintDrafts();
498
+ }
499
+ };
500
+ finish(error) {
501
+ clearTimeout(this.replyTimer); this.pending = undefined;
502
+ if (!error) {
503
+ const selection = window.getSelection();
504
+ if (selection?.rangeCount && this.entry && sameRange(selection.getRangeAt(0),this.entry.range)) selection.removeAllRanges();
505
+ this.cancel(); return;
506
+ }
507
+ this.status.textContent = error; this.grow();
508
+ }
509
+ cancel() {
510
+ if (this.entry) this.dismissedRange = this.entry.range;
511
+ clearTimeout(this.replyTimer); this.pending = this.entry = undefined;
512
+ this.form.hidden = true; this.input.value = this.status.textContent = '';
513
+ this.hideOffer(); this.highlight('workspace-annotation-selection',[]);
514
+ }
515
+ highlight(name,ranges) {
516
+ if (!window.CSS?.highlights || typeof Highlight !== 'function') return;
517
+ if (ranges.length) CSS.highlights.set(name,new Highlight(...ranges)); else CSS.highlights.delete(name);
518
+ }
519
+ updateDrafts(task,attachments) {
520
+ this.draftTask = task;
521
+ this.draftAnnotations = attachments.flatMap(({annotation}) => annotation?.anchor ? [annotation] : []);
522
+ this.paintDrafts();
523
+ for (const tab of this.app.filesPanel?.tabs.values() || []) this.syncFrame(tab);
524
+ }
525
+ syncFrame(tab) {
526
+ if (tab.kind !== 'directory' || !tab.frameReady) return;
527
+ const annotations = this.draftAnnotations.filter(item => item.path).map(({path,anchor}) => ({path,anchor}));
528
+ tab.frame.contentWindow?.postMessage({type:'agentbot-workspace-annotation-drafts',task:this.draftTask,
529
+ annotations},window.location.origin);
530
+ }
531
+ paintDrafts() {
532
+ if (!window.CSS?.highlights) return;
533
+ const files = this.app.filesPanel, tab = files?.tabs.get(files.activeKey), sessions = this.app.sessions;
534
+ const directory = files?.renderedKey === tab?.key && ['file','diff'].includes(tab?.kind) && files.previewRoot(tab.source);
535
+ const file = directory && annotationPath(directory,tab.path);
536
+ const ranges = [];
537
+ for (const {path,turn,anchor} of this.draftAnnotations) {
538
+ let root;
539
+ if (path) {
540
+ if (file !== path || tab.kind !== anchor.kind) continue;
541
+ root = files.content.querySelector('pre.code,.markdown-body');
542
+ } else if (anchor.kind === 'turn') root = sessions?.turnNodes.get(turn)?.content;
543
+ else root = anchor.kind === 'outbox' ? sessions?.outbox : sessions?.body;
544
+ const range = restoreAnnotationRange(root,anchor);
545
+ if (range) ranges.push(range);
546
+ }
547
+ this.highlight('workspace-annotation-draft',ranges);
548
+ }
549
+ hasDraft() {
550
+ if (this.entry) return true;
551
+ for (const tab of this.app.filesPanel?.tabs.values() || []) {
552
+ if (tab.kind === 'directory' && tab.frame?.contentDocument?.querySelector('.workspace-annotation-editor:not([hidden])')) return true;
553
+ }
554
+ return false;
555
+ }
556
+ refresh = () => {
557
+ const entry = this.entry;
558
+ if (entry) {
559
+ this.form.hidden = !entry.content.isConnected || !entry.content.clientHeight
560
+ || Boolean(entry.tab && this.app.filesPanel.tabs.get(this.app.filesPanel.activeKey) !== entry.tab);
561
+ if (!this.form.hidden) this.position(this.form,entry,true);
562
+ } else if (this.offer) this.position(this.button,this.offer,false);
563
+ };
564
+ position(node,{content,range},editing) {
565
+ const bounds = content.getBoundingClientRect(), rect = range.getBoundingClientRect();
566
+ if (!editing && (!rect.width || !rect.height || rect.bottom <= bounds.top || rect.top >= bounds.bottom
567
+ || rect.right <= bounds.left || rect.left >= bounds.right)) { node.hidden = true; return; }
568
+ const viewport = window.visualViewport, gap = 5;
569
+ const leftEdge = viewport?.offsetLeft || 0, topEdge = viewport?.offsetTop || 0;
570
+ const rightEdge = leftEdge+(viewport?.width || document.documentElement.clientWidth);
571
+ const bottomEdge = topEdge+(viewport?.height || document.documentElement.clientHeight);
572
+ node.hidden = false;
573
+ const minLeft = Math.max(bounds.left,leftEdge), maxRight = Math.min(bounds.right,rightEdge);
574
+ const minTop = Math.max(bounds.top,topEdge), maxBottom = Math.min(bounds.bottom,bottomEdge);
575
+ if (editing) {
576
+ const width = Math.min(maxRight-minLeft,Math.max(220,this.measure.scrollWidth+this.actions.offsetWidth+22));
577
+ node.style.width = `${width}px`;
578
+ this.input.style.height = '0px'; this.input.style.height = `${this.input.scrollHeight}px`;
579
+ }
580
+ const {width,height} = node.getBoundingClientRect();
581
+ const left = Math.max(minLeft,Math.min(editing ? rect.left : rect.right-width,maxRight-width));
582
+ const after = rect.bottom+gap, before = rect.top-height-gap;
583
+ const top = after+height <= maxBottom || before < minTop ? after : before;
584
+ node.style.left = `${left}px`;
585
+ node.style.top = `${Math.max(minTop,Math.min(top,maxBottom-height))}px`;
586
+ }
587
+ disconnect() {
588
+ this.listeners.abort(); this.observer?.disconnect(); clearTimeout(this.settleTimer); this.cancel();
589
+ this.highlight('workspace-annotation-draft',[]);
590
+ this.button.remove(); this.form.remove();
591
+ }
592
+ }
593
+ const toolIcons = {
594
+ command:'terminal',execute:'terminal',repl:'terminal',read:'file',edit:'pencil',write:'pencil',file_change:'diff',
595
+ delete:'trash',move:'forward',search:'search',web_search:'search',fetch:'web',mcp:'plug',
596
+ image_view:'file-image',image_generation:'file-image',think:'chat',switch_mode:'branch',
192
597
  };
193
598
  const fileIcon = path => {
194
599
  const name = path.replaceAll('\\','/').split('/').pop().toLowerCase(), extension = name.split('.').pop();
@@ -204,22 +609,23 @@
204
609
  const names = {M:'修改',A:'新增',D:'删除',R:'重命名',C:'复制',T:'类型变化'};
205
610
  const labels = item.conflict ? ['冲突'] : item.untracked ? ['未跟踪'] : [index !== ' ' ? '已暂存 · '+(names[index] || index) : '',worktree !== ' ' ? '未暂存 · '+(names[worktree] || worktree) : ''].filter(Boolean);
206
611
  const status = element('span',item.conflict?'!':item.untracked?'U':index === 'D' || worktree === 'D'?'D':index !== ' '?index:worktree,'change-status');
207
- status.title = labels.join(' / '); status.setAttribute('aria-hidden','true'); status.dataset.kind = item.conflict?'conflict':item.untracked?'untracked':index === 'D' || worktree === 'D'?'deleted':'changed'; return status;
612
+ status.dataset.tooltip = labels.join(' / '); status.setAttribute('aria-hidden','true'); status.dataset.kind = item.conflict?'conflict':item.untracked?'untracked':index === 'D' || worktree === 'D'?'deleted':'changed'; return status;
208
613
  };
209
614
  const lineStats = item => {
210
615
  const stats = element('span',undefined,'tree-line-stats');
211
616
  if (Number.isSafeInteger(item.additions) && Number.isSafeInteger(item.deletions)) {
212
617
  stats.append(element('span','+'+item.additions,'line-additions'),element('span','−'+item.deletions,'line-deletions'));
213
- stats.title = (item.directory?'目录累计':'')+'增加 '+item.additions+' 行,删除 '+item.deletions+' 行'+(item.lineStatsIncomplete?'(部分文件无可用行数,仅累计已统计文本文件)':'');
214
- } else { stats.textContent = '—'; stats.title = '无可用文本行数统计(二进制、超过 2 MiB、读取超时或失败)。'; }
618
+ stats.dataset.tooltip = (item.directory?'目录累计':'')+'增加 '+item.additions+' 行,删除 '+item.deletions+' 行'+(item.lineStatsIncomplete?'(部分文件无可用行数,仅累计已统计文本文件)':'');
619
+ } else { stats.textContent = '—'; stats.dataset.tooltip = '无可用文本行数统计(二进制、超过 2 MiB、读取超时或失败)。'; }
215
620
  stats.setAttribute('aria-hidden','true'); return stats;
216
621
  };
217
622
  const directoryGitStatus = (summary,item) => {
218
623
  if (item.ignored) { summary.classList.add('is-git-ignored'); summary.setAttribute('aria-label',item.name+',Git 已忽略'); }
219
624
  if (!item.changes) return;
220
625
  const count = element('span',String(item.changes),'directory-git-status count-badge'), label = '目录内 '+item.changes+' 个文件有 Git 变更', stats = lineStats(item), metadata = element('span',undefined,'tree-git-meta');
221
- count.title = label; count.setAttribute('aria-hidden','true'); metadata.append(stats,count); summary.append(metadata); summary.setAttribute('aria-label',item.name+(item.ignored?',Git 已忽略':'')+','+label+','+stats.title);
626
+ count.dataset.tooltip = label; count.setAttribute('aria-hidden','true'); metadata.append(stats,count); summary.append(metadata); summary.setAttribute('aria-label',item.name+(item.ignored?',Git 已忽略':'')+','+label+','+stats.dataset.tooltip);
222
627
  };
628
+ const tabStripSelector = '.file-tabs,.explorer-directory-tabs';
223
629
  class WorkspaceScrollbars {
224
630
  constructor(host) {
225
631
  this.host = host; this.hovered = new Set(); this.recent = new Map(); this.entries = new Map(); this.targets = new WeakMap();
@@ -276,7 +682,7 @@
276
682
  wheel = event => {
277
683
  const target = this.targets.get(event.target.closest('.scrollbar-track')); if (!target || event.ctrlKey) return;
278
684
  let x = event.deltaX, y = event.deltaY;
279
- if (target.node.classList.contains('file-tabs') && Math.abs(y) > Math.abs(x) || event.shiftKey && x === 0) { x = y; y = 0; }
685
+ if (target.node.matches(tabStripSelector) && Math.abs(y) > Math.abs(x) || event.shiftKey && x === 0) { x = y; y = 0; }
280
686
  let moved = false;
281
687
  for (const [axis,delta] of [['x',x],['y',y]]) {
282
688
  if (!delta) continue;
@@ -330,7 +736,7 @@
330
736
  if (!entry) {
331
737
  const box = element('div',undefined,'workspace-scrollbar'), x = element('span',undefined,'scrollbar-x'), y = element('span',undefined,'scrollbar-y');
332
738
  const trackX = element('div',undefined,'scrollbar-track scrollbar-track-x'), trackY = element('div',undefined,'scrollbar-track scrollbar-track-y');
333
- box.dataset.region = node.classList.contains('file-tabs') ? 'tabs' : node.classList.contains('content-body') ? 'content' : node.classList.contains('file-navigation') ? 'tree' : 'other';
739
+ box.dataset.region = node.matches(tabStripSelector) ? 'tabs' : node.classList.contains('content-body') ? 'content' : node.classList.contains('file-navigation') ? 'tree' : 'other';
334
740
  box.append(trackX,trackY,x,y); this.layer.append(box); entry = {box,x,y,trackX,trackY}; this.entries.set(node,entry);
335
741
  this.targets.set(trackX,{node,axis:'x'}); this.targets.set(trackY,{node,axis:'y'});
336
742
  }
@@ -362,6 +768,134 @@
362
768
  this.hovered.clear(); this.recent.clear(); this.entries.clear();
363
769
  }
364
770
  }
771
+ const tooltipControls = '[data-tooltip], [data-tooltip-shortcut], [data-tooltip-overflow]';
772
+ function tooltipShortcut(node) {
773
+ if (node.dataset.tooltipShortcut) return node.dataset.tooltipShortcut;
774
+ const shortcuts = (node.getAttribute('aria-keyshortcuts') || '').split(/\s+/u).filter(Boolean);
775
+ const preferred = applePlatform ? 'Meta' : 'Control', alternate = applePlatform ? 'Control' : 'Meta';
776
+ const keys = {Escape:'Esc',ArrowLeft:'←',ArrowRight:'→',ArrowUp:'↑',ArrowDown:'↓',
777
+ ...(applePlatform ? {Control:'⌃',Meta:'⌘',Alt:'⌥',Shift:'⇧'} : {Control:'Ctrl'})};
778
+ return shortcuts.map(shortcut => shortcut.split('+')).filter(parts => !parts.includes(alternate)
779
+ || !shortcuts.includes(parts.map(key => key === alternate ? preferred : key).join('+')))
780
+ .map(parts => parts.map(key => keys[key] || key).join(applePlatform ? '' : '+')).join(' / ');
781
+ }
782
+ class WorkspaceTooltips {
783
+ constructor(host) {
784
+ this.host = host;
785
+ const tip = this.tip = element('div',undefined,'workspace-tooltip');
786
+ tip.id = 'workspace-tooltip-'+instanceId(); tip.setAttribute('role','tooltip'); tip.hidden = true;
787
+ this.topLayer = typeof tip.showPopover === 'function';
788
+ if (this.topLayer) tip.setAttribute('popover','manual');
789
+ this.label = element('span'); this.detail = element('small',undefined,'workspace-tooltip-detail');
790
+ this.shortcut = element('kbd'); tip.append(this.label,this.shortcut,this.detail); host.append(tip);
791
+ this.events = new AbortController();
792
+ const {signal} = this.events;
793
+ for (const type of ['pointerover','pointerout']) host.addEventListener(type,this.pointer,{capture:true,signal});
794
+ host.addEventListener('focusin',this.focus,{signal}); host.addEventListener('focusout',this.blur,{signal});
795
+ host.addEventListener('pointerdown',this.dismiss,{capture:true,signal});
796
+ host.addEventListener('scroll',this.scroll,{capture:true,signal});
797
+ host.addEventListener('click',this.dismiss,{signal});
798
+ window.addEventListener('resize',this.dismiss,{signal}); window.addEventListener('blur',this.dismiss,{signal});
799
+ window.addEventListener('keydown',this.key,{signal});
800
+ this.size = new ResizeObserver(this.render);
801
+ this.changes = new window.MutationObserver(records => {
802
+ if (this.visible && records.some(record => !tip.contains(record.target))) this.render();
803
+ });
804
+ this.changes.observe(host,{subtree:true,childList:true,attributes:true,attributeFilter:['aria-label','aria-keyshortcuts','data-tooltip','data-tooltip-shortcut','data-tooltip-overflow','hidden']});
805
+ }
806
+ control(node) {
807
+ if (!node) return;
808
+ if (this.tip.contains(node)) return this.tip;
809
+ const control = node.closest?.(tooltipControls), nativeTitle = node.closest?.('[title]');
810
+ if (control && this.host.contains(control) && !(nativeTitle && control.contains(nativeTitle))) return control;
811
+ }
812
+ pointer = event => {
813
+ if (event.pointerType === 'touch') return;
814
+ const node = this.control(event.type === 'pointerout' ? event.relatedTarget : event.target);
815
+ if (node === this.pointed) return;
816
+ this.pointed = node;
817
+ if (node === this.tip || node && node === this.visible) { clearTimeout(this.timer); return; }
818
+ const target = node || this.focused;
819
+ if (target) this.schedule(target,node ? 400 : 0);
820
+ else { clearTimeout(this.timer); this.timer = setTimeout(this.dismiss,140); }
821
+ };
822
+ focus = event => {
823
+ const node = this.control(event.target);
824
+ if (node && node !== this.tip && node.matches(':focus-visible')) {
825
+ this.focused = node; this.schedule(node,0);
826
+ }
827
+ };
828
+ blur = event => {
829
+ if (this.focused !== event.target) return;
830
+ this.focused = undefined;
831
+ if (this.pointed && this.pointed !== this.tip) this.schedule(this.pointed,400);
832
+ else if (this.pointed !== this.tip) this.dismiss();
833
+ };
834
+ key = event => { if (event.key === 'Escape') this.dismiss(); };
835
+ scroll = event => {
836
+ const target = this.visible || this.focused;
837
+ if (target && event.target.contains(target)) this.dismiss();
838
+ };
839
+ schedule(node,delay) {
840
+ this.hide(); this.timer = setTimeout(() => {
841
+ this.visible = node; this.render();
842
+ if (this.visible) {
843
+ this.size.observe(node);
844
+ this.autoHide = setTimeout(this.dismiss,2500);
845
+ }
846
+ },delay);
847
+ }
848
+ render = () => {
849
+ const node = this.visible;
850
+ if (!node) return;
851
+ if (!this.host.contains(node) || !node.matches(tooltipControls) || !node.getClientRects().length) { this.dismiss(); return; }
852
+ const label = (node.dataset.tooltip || node.getAttribute('aria-label') || node.textContent).trim();
853
+ if (!label) { this.dismiss(); return; }
854
+ const shortcut = tooltipShortcut(node), detail = node.tooltipDetail?.() || '';
855
+ const overflow = node.dataset.tooltipOverflow;
856
+ if (!shortcut && !detail && overflow !== undefined) {
857
+ const targets = overflow ? [...node.querySelectorAll(overflow)] : [node];
858
+ if (!targets.some(target => target.scrollWidth > target.clientWidth || target.scrollHeight > target.clientHeight)) {
859
+ this.dismiss(); return;
860
+ }
861
+ }
862
+ if (this.label.textContent !== label) this.label.textContent = label;
863
+ if (this.detail.textContent !== detail) this.detail.textContent = detail;
864
+ this.tip.toggleAttribute('data-annotation',node.hasAttribute('data-annotation-tooltip'));
865
+ this.detail.toggleAttribute('hidden',!detail);
866
+ if (this.shortcut.textContent !== shortcut) this.shortcut.textContent = shortcut;
867
+ this.shortcut.toggleAttribute('hidden',!shortcut);
868
+ if (this.tip.hidden) {
869
+ const dialog = this.topLayer && node.closest('dialog[open]');
870
+ if (dialog) dialog.append(this.tip);
871
+ this.tip.hidden = false;
872
+ if (this.topLayer) this.tip.showPopover();
873
+ }
874
+ if (shortcut || detail || node.dataset.tooltip && label !== node.getAttribute('aria-label') && label !== node.textContent.trim()) {
875
+ const ids = (node.getAttribute('aria-describedby') || '').split(/\s+/u).filter(Boolean);
876
+ if (!ids.includes(this.tip.id)) node.setAttribute('aria-describedby',[...ids,this.tip.id].join(' '));
877
+ }
878
+ const anchor = node.getBoundingClientRect(), bubble = this.tip.getBoundingClientRect();
879
+ const left = Math.max(8,Math.min(window.innerWidth-bubble.width-8,anchor.left+(anchor.width-bubble.width)/2));
880
+ const above = anchor.top-bubble.height-7;
881
+ const top = Math.max(8,Math.min(window.innerHeight-bubble.height-8,above >= 8 ? above : anchor.bottom+7));
882
+ if (this.tip.style.left !== left+'px') this.tip.style.left = left+'px';
883
+ if (this.tip.style.top !== top+'px') this.tip.style.top = top+'px';
884
+ };
885
+ dismiss = () => { this.focused = undefined; this.hide(); };
886
+ hide() {
887
+ clearTimeout(this.timer); clearTimeout(this.autoHide);
888
+ const node = this.visible;
889
+ if (!node) return;
890
+ if (this.topLayer && this.tip.matches(':popover-open')) this.tip.hidePopover();
891
+ this.visible = undefined; this.size.disconnect(); this.tip.hidden = true;
892
+ if (this.tip.parentElement !== this.host) this.host.append(this.tip);
893
+ const ids = (node.getAttribute('aria-describedby') || '').split(/\s+/u).filter(id => id && id !== this.tip.id);
894
+ if (ids.length) node.setAttribute('aria-describedby',ids.join(' '));
895
+ else node.removeAttribute('aria-describedby');
896
+ }
897
+ disconnect() { this.dismiss(); this.changes.disconnect(); this.events.abort(); this.tip.remove(); }
898
+ }
365
899
  class WorkspaceTaskList extends HTMLElement {
366
900
  connectedCallback() {
367
901
  this.replaceChildren(element('h2','项目任务','pane-heading'),element('div',project,'workspace-project'),element('div','任务列表将在后续接入。当前页面只浏览这个项目,不创建或切换任务。','workspace-placeholder'));
@@ -378,14 +912,297 @@
378
912
  this.replaceChildren(element('h2','聊天','pane-heading'),body,composer);
379
913
  }
380
914
  }
915
+ const commandPaletteFileLimit = 40;
916
+ const recentCommandLimit = 5, recentCommandKey = 'agentbot-workspace-recent-commands';
917
+ const commandPrefix = /^[>>]/u;
918
+ const paletteShortcuts = {files:'P',commands:'Shift+P'};
919
+ const normalizeCommandText = text => text.normalize('NFKC').trim().toLowerCase();
920
+ class WorkspaceCommandPalette {
921
+ constructor(app) {
922
+ this.app = app;
923
+ this.chinese = /^zh(?:[-_]|$)/iu.test(navigator.language || document.documentElement.lang);
924
+ this.applePlatform = applePlatform;
925
+ this.recentCommandIds = [];
926
+ const dialog = this.dialog = element('dialog',undefined,'workspace-command-palette');
927
+ const close = this.closeButton = iconControl('button','close','关闭命令面板','command-palette-close');
928
+ close.setAttribute('aria-keyshortcuts','Escape'); close.onclick = () => this.close();
929
+ const search = element('div',undefined,'command-palette-search');
930
+ const input = this.input = element('input');
931
+ input.placeholder = '搜索文件名或路径'; input.maxLength = 160; input.autocomplete = 'off'; input.spellcheck = false;
932
+ input.setAttribute('autofocus','');
933
+ input.setAttribute('role','combobox'); input.setAttribute('aria-label','搜索文件'); input.setAttribute('aria-autocomplete','list');
934
+ const body = this.body = element('div',undefined,'command-palette-body');
935
+ const results = this.results = element('div',undefined,'command-palette-results'); results.setAttribute('role','listbox');
936
+ const notice = this.notice = element('div',undefined,'command-palette-notice'); notice.setAttribute('role','status');
937
+ dialog.id = 'command-palette-'+instanceId(); results.id = dialog.id+'-results';
938
+ const shortcuts = Object.values(paletteShortcuts).flatMap(keys => ['Control+'+keys,'Meta+'+keys]);
939
+ dialog.setAttribute('aria-keyshortcuts',shortcuts.join(' ')); input.setAttribute('aria-controls',results.id);
940
+ search.append(input,close);
941
+ body.append(results,notice); dialog.append(search,body);
942
+ dialog.addEventListener('cancel',event => { event.preventDefault(); this.close(); });
943
+ dialog.onpointerdown = event => { this.onBackdrop = event.target === dialog; };
944
+ dialog.onclick = event => { if (this.onBackdrop && event.target === dialog) this.close(); };
945
+ window.visualViewport?.addEventListener('resize',this.updateViewport);
946
+ input.oninput = event => { if (!event.isComposing) this.updateQuery(); };
947
+ input.oncompositionend = () => this.updateQuery();
948
+ input.onkeydown = this.onInputKey;
949
+ app.append(dialog);
950
+ window.addEventListener('keydown',this.onShortcut,true);
951
+ }
952
+ onShortcut = event => {
953
+ if (!(event.ctrlKey || event.metaKey) || event.altKey || event.isComposing || event.key?.toLowerCase() !== 'p') return;
954
+ event.preventDefault(); event.stopPropagation();
955
+ if (!event.repeat) this.open(event.shiftKey ? 'commands' : 'files');
956
+ };
957
+ open(mode = 'files') {
958
+ const opening = !this.dialog.open, commands = commandPrefix.test(this.input.value.trimStart());
959
+ const reset = opening || (mode === 'commands' ? !commands : commands || this.mode !== mode);
960
+ if (reset) {
961
+ this.mode = mode === 'overview' ? 'overview' : 'files';
962
+ this.input.value = mode === 'commands' ? '>' : ''; this.onBackdrop = false;
963
+ }
964
+ if (opening) {
965
+ this.dialog.showModal();
966
+ this.updateViewport();
967
+ }
968
+ if (reset) this.updateQuery();
969
+ this.input.focus({preventScroll:true});
970
+ if (reset && mode === 'commands') this.input.setSelectionRange?.(1,1);
971
+ }
972
+ close() {
973
+ clearTimeout(this.timer); this.search?.abort(); this.search = undefined;
974
+ if (this.dialog.open) this.dialog.close();
975
+ }
976
+ disconnect() {
977
+ window.removeEventListener('keydown',this.onShortcut,true);
978
+ window.visualViewport?.removeEventListener('resize',this.updateViewport);
979
+ this.close();
980
+ }
981
+ updateViewport = () => {
982
+ if (this.dialog.open && window.visualViewport) this.dialog.style.setProperty('--palette-viewport',`${window.visualViewport.height}px`);
983
+ };
984
+ commands() {
985
+ const {filesPanel:files,sessions,themeToggle} = this.app;
986
+ const commands = [{id:'find-file',zh:'查找文件',en:'Go to File',common:true,shortcut:paletteShortcuts.files,run:() => this.open()}];
987
+ const add = (id,zh,en,action,common = false) => commands.push({id,zh,en,run:() => { this.close(); action(); },common});
988
+ if (!embedded) add('new-tab','新建标签','New Tab',() => this.showFiles(panel => panel.openNew()),true);
989
+ if (files.directoryPanel && !files.directoryPending) add('open-folder','打开目录','Open Folder',() => this.showFiles(panel => {
990
+ panel.showList(); panel.showDirectoryChooser(true,true);
991
+ },true),true);
992
+ if (files.treeApi && !files.choosingDirectory) {
993
+ const showList = mode => this.showFiles(panel => { panel.selectList(mode); panel.showList(); },true);
994
+ add('files','查看项目文件','Show File Explorer',() => showList('files'));
995
+ add('git-changes','查看未提交改动','View Git Changes',() => showList('changes'),true);
996
+ add('refresh-files','刷新文件','Refresh Files',() => files.querySelector('.refresh').click());
997
+ }
998
+ if (!files.locateButton.disabled) add('reveal-file','定位当前文件','Reveal Active File in Explorer',
999
+ () => this.showFiles(panel => { void panel.revealCurrentFile(); },true));
1000
+ if (!embedded && sessions?.csrf) add('new-task','新建任务','New Task',() => sessions.openNewTask(),true);
1001
+ if (!embedded && sessions) {
1002
+ add('tasks','打开任务列表','Show Tasks',() => this.app.navigate(() => {
1003
+ this.app.selectPane('tasks');
1004
+ if (this.app.layout.sidebarCollapsed) { this.app.layout.sidebarCollapsed = false; this.app.applyLayout(); }
1005
+ }));
1006
+ add('chat','打开聊天','Show Chat',() => this.app.navigate(() => this.app.selectPane('chat')));
1007
+ }
1008
+ const dark = document.documentElement.dataset.workspaceTheme === 'dark';
1009
+ add('color-theme',themeToggle.getAttribute('aria-label'),dark ? 'Switch to Light Theme' : 'Switch to Dark Theme',() => themeToggle.click(),true);
1010
+ return commands;
1011
+ }
1012
+ readRecentCommands() {
1013
+ const saved = stored(recentCommandKey);
1014
+ return Array.isArray(saved) ? saved.filter(id => typeof id === 'string').slice(0,recentCommandLimit) : this.recentCommandIds;
1015
+ }
1016
+ searchCommands(query) {
1017
+ const commands = this.commands(), byId = new Map(commands.map(command => [command.id,command]));
1018
+ const recent = [...new Set(this.readRecentCommands())].map(id => byId.get(id)).filter(Boolean);
1019
+ const words = normalizeCommandText(query).split(/\s+/u);
1020
+ const matches = command => {
1021
+ const text = normalizeCommandText(command.en+' '+(this.chinese ? command.zh : ''));
1022
+ return words.every(word => text.includes(word));
1023
+ };
1024
+ const all = commands.filter(matches);
1025
+ const primary = query ? [...new Set([...recent,...commands.filter(command => command.common)])].filter(matches) : recent;
1026
+ const primaryLabel = query ? (this.chinese ? '常用命令' : 'Common Commands') : (this.chinese ? '最近使用' : 'Recently Used');
1027
+ const allLabel = query ? (this.chinese ? '全局命令' : 'Global Commands') : (this.chinese ? '所有命令' : 'All Commands');
1028
+ this.render([
1029
+ {items:primary,label:primaryLabel,className:'command-palette-primary'},
1030
+ {items:all,label:allLabel,className:'command-palette-all'},
1031
+ ],all.length ? '' : (this.chinese ? '没有匹配的命令' : 'No matching commands'),true);
1032
+ }
1033
+ describeMode(commands) {
1034
+ const overview = this.mode === 'overview';
1035
+ const dialogLabel = overview ? '命令面板' : '打开文件';
1036
+ this.dialog.setAttribute('aria-label',commands ? (this.chinese ? '搜索命令' : 'Search Commands') : dialogLabel);
1037
+ this.results.setAttribute('aria-label',commands ? (this.chinese ? '命令列表' : 'Commands') : (overview ? '常用命令与文件' : '匹配文件'));
1038
+ const searchLabel = commands ? (this.chinese ? '搜索命令' : 'Search commands') : '搜索文件';
1039
+ this.input.setAttribute('aria-label',searchLabel);
1040
+ this.input.placeholder = commands ? searchLabel : '搜索文件名或路径';
1041
+ const closeLabel = commands && !this.chinese ? 'Close command palette' : '关闭命令面板';
1042
+ this.closeButton.dataset.tooltip = closeLabel; this.closeButton.setAttribute('aria-label',closeLabel);
1043
+ this.dialog.lang = commands && !this.chinese ? 'en' : document.documentElement.lang;
1044
+ }
1045
+ updateQuery() {
1046
+ clearTimeout(this.timer); this.search?.abort();
1047
+ const input = this.input.value.trim(), commands = commandPrefix.test(input);
1048
+ this.describeMode(commands);
1049
+ if (commands) { this.searchCommands(input.slice(1).trim()); return; }
1050
+ const files = this.app.filesPanel, query = input.replaceAll('\\','/');
1051
+ if (!query) {
1052
+ const recent = files.readRecentFiles();
1053
+ if (this.mode === 'overview') {
1054
+ const common = this.commands().filter(command => command.common);
1055
+ common.splice(1,0,{zh:'显示并运行命令',shortcut:paletteShortcuts.commands,run:() => this.open('commands')});
1056
+ this.render([{items:common,label:'常用命令',className:'command-palette-commands'},
1057
+ {items:recent,label:'最近打开的文件',className:'command-palette-recent'}],recent.length ? '' : '没有最近打开的文件');
1058
+ } else this.renderFiles(recent,recent.length ? '' : '没有最近打开的文件');
1059
+ return;
1060
+ }
1061
+ const sources = [...new Set([files.explorerDirectory || undefined,undefined,...(files.directoryPanel?.tabs || []).map(tab => tab.id)])]
1062
+ .filter(source => files.previewApi(source));
1063
+ if (!sources.length) { this.renderFiles([],'请先打开一个项目或目录。'); return; }
1064
+ this.renderFiles([],'正在搜索…');
1065
+ const search = this.search = new AbortController();
1066
+ this.timer = setTimeout(() => this.searchFiles(files,sources,query,search),160);
1067
+ }
1068
+ async searchFiles(files,sources,query,search) {
1069
+ const items = [];
1070
+ let failed = 0, truncated = false;
1071
+ for (let start = 0; start < sources.length && !search.signal.aborted; start += 3) {
1072
+ const batch = sources.slice(start,start+3);
1073
+ const responses = await Promise.allSettled(batch.map(source => files.request(
1074
+ 'address',{query},undefined,undefined,undefined,files.previewApi(source),search.signal)));
1075
+ if (search.signal.aborted || this.app.filesPanel !== files) return;
1076
+ for (const [index,result] of responses.entries()) {
1077
+ if (result.status === 'rejected' || !Array.isArray(result.value.entries)) { failed++; continue; }
1078
+ truncated ||= result.value.truncated;
1079
+ for (const entry of result.value.entries) items.push({path:entry.path,source:batch[index],kind:'file'});
1080
+ }
1081
+ }
1082
+ const normalized = query.toLowerCase();
1083
+ const rank = item => {
1084
+ const path = item.path.toLowerCase(), name = path.split('/').at(-1);
1085
+ return name === normalized || path === normalized ? 0 : name.startsWith(normalized) ? 1 : name.includes(normalized) ? 2 : 3;
1086
+ };
1087
+ items.sort((a,b) => rank(a)-rank(b));
1088
+ const incomplete = truncated || failed || items.length > commandPaletteFileLimit;
1089
+ if (failed === sources.length) this.renderFiles([],'暂时无法搜索文件,请修改查询后重试。');
1090
+ else if (!items.length) this.renderFiles([],incomplete ? '没有匹配的文件,请输入更具体的路径。' : '没有匹配的文件');
1091
+ else this.renderFiles(items.slice(0,commandPaletteFileLimit),incomplete ? '结果可能不完整,请输入更具体的文件名或路径。' : '');
1092
+ }
1093
+ renderFiles(items,status) { this.render([{items}],status); }
1094
+ render(sections,status,localizeCommands = false) {
1095
+ this.items = sections.flatMap(section => section.items);
1096
+ this.options = []; this.results.replaceChildren(); this.body.scrollTop = 0;
1097
+ const hasItems = this.items.length > 0;
1098
+ this.results.hidden = !hasItems;
1099
+ this.notice.hidden = !status;
1100
+ this.notice.textContent = status;
1101
+ this.input.setAttribute('aria-expanded',String(hasItems));
1102
+ for (const {items,label,className} of sections) {
1103
+ if (!items.length) continue;
1104
+ let group = this.results;
1105
+ if (label) {
1106
+ group = element('div',undefined,className); this.results.append(group);
1107
+ group.setAttribute('role','group'); group.setAttribute('aria-label',label);
1108
+ }
1109
+ for (const item of items) {
1110
+ const option = this.renderOption(item,this.options.length,localizeCommands);
1111
+ this.options.push(option); group.append(option);
1112
+ }
1113
+ }
1114
+ this.select(hasItems ? 0 : -1);
1115
+ }
1116
+ renderOption(item,index,localized) {
1117
+ const option = element('button',undefined,'command-palette-option');
1118
+ option.type = 'button'; option.tabIndex = -1; option.setAttribute('role','option'); option.id = this.results.id+'-'+index;
1119
+ if (item.run) {
1120
+ const label = element('span',undefined,'command-palette-command-label');
1121
+ const name = localized && !this.chinese ? item.en : item.zh;
1122
+ label.append(element('span',name,'command-palette-command-name'));
1123
+ if (localized && this.chinese) {
1124
+ const translation = element('span',item.en,'command-palette-translation'); translation.lang = 'en';
1125
+ label.append(translation);
1126
+ }
1127
+ option.append(label);
1128
+ if (item.shortcut) {
1129
+ const keys = this.applePlatform ? ('⌘'+item.shortcut).replace('⌘Shift+','⇧⌘') : 'Ctrl+'+item.shortcut;
1130
+ const badge = element('kbd',keys,'command-palette-shortcut'); badge.setAttribute('aria-hidden','true');
1131
+ option.setAttribute('aria-keyshortcuts',(this.applePlatform ? 'Meta+' : 'Control+')+item.shortcut);
1132
+ option.append(badge);
1133
+ }
1134
+ } else {
1135
+ const files = this.app.filesPanel;
1136
+ const parts = item.path.split('/'), name = parts.pop();
1137
+ const root = files.previewRoot(item.source), scope = files.directoryPanel?.tabs.length || item.source
1138
+ ? root?.split(/[\\/]/u).filter(Boolean).at(-1) : undefined;
1139
+ const path = [scope,...parts].filter(Boolean).join('/');
1140
+ option.dataset.tooltip = root ? root+' · '+item.path : item.path;
1141
+ const label = element('span',undefined,'command-palette-label');
1142
+ label.append(element('span',name,'command-palette-name'));
1143
+ if (path) label.append(element('span',path,'command-palette-path'));
1144
+ option.append(fileIcon(item.path),label);
1145
+ if (item.kind === 'diff') option.append(element('span','改动','command-palette-kind'));
1146
+ }
1147
+ option.onpointerdown = event => { if (event.button === 0 && event.pointerType !== 'touch') event.preventDefault(); };
1148
+ option.onpointerenter = event => { if (event.pointerType !== 'touch') this.select(index); };
1149
+ option.onclick = () => this.accept(index);
1150
+ return option;
1151
+ }
1152
+ select(index,scroll = false) {
1153
+ this.index = index;
1154
+ for (const [position,option] of this.options.entries()) option.setAttribute('aria-selected',String(position === index));
1155
+ const option = this.options[index];
1156
+ if (option) {
1157
+ this.input.setAttribute('aria-activedescendant',option.id);
1158
+ if (scroll) option.scrollIntoView({block:'nearest'});
1159
+ } else this.input.removeAttribute('aria-activedescendant');
1160
+ }
1161
+ onInputKey = event => {
1162
+ if (event.isComposing || event.keyCode === 229) return;
1163
+ if (event.key === 'Enter') { event.preventDefault(); this.accept(this.index); }
1164
+ else if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && this.items.length) {
1165
+ event.preventDefault();
1166
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
1167
+ this.select((this.index+direction+this.items.length)%this.items.length,true);
1168
+ }
1169
+ };
1170
+ accept(index) {
1171
+ const item = this.items[index];
1172
+ if (!item) return;
1173
+ if (item.run) {
1174
+ if (item.id) {
1175
+ this.recentCommandIds = [...new Set([item.id,...this.readRecentCommands()])].slice(0,recentCommandLimit);
1176
+ put(recentCommandKey,this.recentCommandIds);
1177
+ }
1178
+ item.run(); return;
1179
+ }
1180
+ this.close();
1181
+ this.showFiles(files => files.openFile(item.path,item.kind,item.original,undefined,undefined,item.source));
1182
+ this.app.filesPanel.content.focus({preventScroll:true});
1183
+ }
1184
+ showFiles(action, showExplorer = false) {
1185
+ this.app.navigate(() => {
1186
+ this.app.selectPane('files');
1187
+ const layout = this.app.layout;
1188
+ if (layout.filesCollapsed || (showExplorer && layout.explorerCollapsed)) {
1189
+ layout.filesCollapsed = false;
1190
+ if (showExplorer) layout.explorerCollapsed = false;
1191
+ this.app.applyLayout();
1192
+ }
1193
+ action(this.app.filesPanel);
1194
+ });
1195
+ }
1196
+ }
381
1197
  class WorkspaceFiles extends HTMLElement {
382
1198
  connectedCallback() {
383
- this.dataset.noProject = String(!this.fileApi);
384
- this.controllers = new Set(); this.tabs = new Map(); this.views = new Map(); this.activeKey = undefined; this.recentTabs = [];
1199
+ this.dataset.noProject = String(!this.fileApi && !appBase);
1200
+ this.dataset.noPrimary = String(!this.fileApi);
1201
+ this.controllers = new Set(); this.tabs = new Map(); this.views = new Map(); this.localDirectories = new Map(); this.activeKey = undefined; this.recentTabs = [];
385
1202
  this.renderedKey = undefined;
386
1203
  this.dataset.view = 'list'; this.listScrollTop = 0;
387
1204
  this.generation = 0; this.navigationGeneration = 0; this.navigationSequence = 0; this.listMode = 'files';
388
- this.innerHTML = '<div class="file-tabs" role="tablist" aria-label="已打开文件"></div><div class="content-toolbar" hidden></div><div class="file-layout"><section class="file-main"><div class="content-body" role="region" aria-label="文件内容" tabindex="0"><div class="content-empty">从右侧文件树选择文件,或在改动列表中查看 Git 变更。</div></div></section><aside class="file-explorer" aria-label="文件浏览"><div class="file-toolbar"><div class="file-list-switch" role="group" aria-label="文件浏览方式"><button data-list="files" aria-pressed="true">文件</button><button data-list="changes" aria-pressed="false">未提交</button></div><button class="refresh" title="刷新列表和当前文件">刷新</button></div><nav class="file-navigation" aria-label="项目文件"></nav></aside></div>';
1205
+ this.innerHTML = '<div class="file-tabs" role="tablist" aria-label="已打开文件"></div><div class="content-toolbar" hidden></div><div class="file-layout"><section class="file-main"><div class="content-body" role="region" aria-label="文件内容" tabindex="0"><div class="content-empty">从右侧文件树选择文件,或在改动列表中查看 Git 变更。</div></div></section><aside class="file-explorer" aria-label="文件浏览"><div class="file-toolbar"><div class="file-list-switch" role="group" aria-label="文件浏览方式"><button data-list="files" aria-pressed="true">文件</button><button data-list="changes" aria-pressed="false">未提交</button></div><button class="refresh" data-tooltip="刷新列表和当前文件">刷新</button></div><nav class="file-navigation" aria-label="项目文件"></nav></aside></div>';
389
1206
  this.navigation = this.querySelector('.file-navigation'); this.tabBar = this.querySelector('.file-tabs');
390
1207
  const strip = element('div',undefined,'file-tab-strip'); this.tabBar.before(strip); strip.append(this.tabBar);
391
1208
  const actions = element('div',undefined,'tab-actions'), add = iconControl('button','plus','新标签','new-tab');
@@ -411,26 +1228,40 @@
411
1228
  this.navigationForward = iconControl('button','forward','前进','navigation-forward'); this.navigationForward.onclick = () => this.closest('agentbot-workspace').traverseHistory(1);
412
1229
  this.content.addEventListener('scroll',() => this.updateDiffNavigation());
413
1230
  this.diffResize = () => this.updateDiffNavigation(); window.addEventListener('resize',this.diffResize);
1231
+ this.caretResize = new ResizeObserver(() => this.positionPreviewCaret());
1232
+ this.previewSelectionChanged = () => {
1233
+ if (!this.previewCaret) return;
1234
+ const selection = window.getSelection();
1235
+ if (selection && !selection.isCollapsed && (this.content.contains(selection.anchorNode) || this.content.contains(selection.focusNode))) this.clearPreviewCaret();
1236
+ };
1237
+ document.addEventListener('selectionchange',this.previewSelectionChanged);
414
1238
  this.content.onclick = event => {
415
1239
  if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
416
- const link = event.target.closest('a'); if (!link) return;
417
- if (link.dataset.workspaceEntry !== undefined) { event.preventDefault(); this.openFile(link.dataset.workspaceEntry,'file',undefined,new URL(link.href).hash); }
1240
+ const link = event.target.closest('a');
1241
+ if (!link) { this.placePreviewCaret(event); return; }
1242
+ this.clearPreviewCaret();
1243
+ if (link.dataset.workspaceEntry !== undefined) { event.preventDefault(); this.openFile(link.dataset.workspaceEntry,'file',undefined,new URL(link.href).hash,undefined,this.tabs.get(this.activeKey)?.source); }
418
1244
  else if (link.getAttribute('href')?.startsWith('#')) {
419
1245
  event.preventDefault(); this.navigate(() => { const tab = this.tabs.get(this.activeKey); tab.hash = tab.requestedHash = link.getAttribute('href'); this.restoreHash(tab); });
420
1246
  }
421
1247
  };
422
- this.navigationViews = new Map([['files',{node:this.navigation,scrollTop:0,pending:0,ready:false,expanded:new Set(),pages:new Map(),restorePages:new Map(),observers:new Set()}]]);
1248
+ this.navigationViews = new Map([['files',this.createNavigationView(this.navigation)]]);
423
1249
  this.addEventListener('click',this.keepTreeRow,true);
424
1250
  this.addEventListener('mousedown',this.startTreeToggle,true);
425
1251
  this.addEventListener('keydown',this.clearTreePointerFocus,true);
426
1252
  this.addEventListener('scroll',this.trimTreeScroll,true);
1253
+ this.toolbar.onfocusout = () => Promise.resolve().then(() => {
1254
+ const tab = this.tabs.get(this.activeKey);
1255
+ if (tab?.stale) void this.refreshLivePreview(tab);
1256
+ });
427
1257
  const filesButton = this.querySelector('[data-list=files]'), changesButton = this.querySelector('[data-list=changes]');
428
- filesButton.replaceChildren(icon('tree')); filesButton.classList.add('icon-control'); filesButton.title = '项目文件'; filesButton.setAttribute('aria-label','项目文件');
1258
+ filesButton.replaceChildren(icon('tree')); filesButton.classList.add('icon-control'); filesButton.dataset.tooltip = '项目文件'; filesButton.setAttribute('aria-label','项目文件');
429
1259
  const count = element('span',undefined,'count-badge'); count.hidden = true; count.setAttribute('aria-hidden','true');
430
- changesButton.replaceChildren(icon('diff'),count); changesButton.classList.add('icon-control'); changesButton.title = '未提交改动'; changesButton.setAttribute('aria-label','未提交改动');
431
- const refresh = this.querySelector('.refresh'); refresh.replaceChildren(icon('refresh')); refresh.classList.add('icon-control'); refresh.setAttribute('aria-label',refresh.title);
1260
+ changesButton.replaceChildren(icon('diff'),count); changesButton.classList.add('icon-control'); changesButton.dataset.tooltip = '未提交改动'; changesButton.setAttribute('aria-label','未提交改动');
1261
+ const refresh = this.querySelector('.refresh'); refresh.replaceChildren(icon('refresh')); refresh.classList.add('icon-control'); refresh.setAttribute('aria-label',refresh.dataset.tooltip);
432
1262
  this.locateButton = iconControl('button','locate','在列表中定位当前文件','locate-current-file'); refresh.before(this.locateButton); this.locateButton.onclick = () => this.revealCurrentFile();
433
1263
  this.revealMessage = element('div',undefined,'reveal-message'); this.revealMessage.hidden = true; this.revealMessage.setAttribute('role','status'); this.navigation.before(this.revealMessage);
1264
+ if (this.taskId && appBase && !embedded) this.createDirectoryPanel(refresh);
434
1265
  for (const button of this.querySelectorAll('[data-list]')) {
435
1266
  button.onclick = () => this.selectList(button.dataset.list);
436
1267
  }
@@ -438,9 +1269,258 @@
438
1269
  this.saveScroll(); this.loadNavigation(this.listMode,true); const tab = this.tabs.get(this.activeKey); if (tab) this.loadTab(tab,true);
439
1270
  };
440
1271
  this.renderTabs();
441
- if (!this.fileApi) this.content.replaceChildren(element('div','此任务没有可浏览的项目目录。','content-empty'));
1272
+ if (!this.fileApi) {
1273
+ this.content.replaceChildren(element('div','此任务没有主项目目录。','content-empty'));
1274
+ this.notice(this.navigation,'在新标签中输入路径或选择任务目录。');
1275
+ }
1276
+ }
1277
+ placePreviewCaret(event) {
1278
+ this.clearPreviewCaret();
1279
+ const selection = window.getSelection();
1280
+ if (!selection?.isCollapsed || event.detail > 1 || this.renderedKey !== this.activeKey
1281
+ || event.target.closest('button,input,select,textarea,summary,img,svg,.diff-number,.diff-marker')) return;
1282
+ const codeLine = event.target.closest('.code .line'), markdown = event.target.closest('.markdown-body');
1283
+ if (!codeLine && !markdown) return;
1284
+ const {clientX:x,clientY:y} = event;
1285
+ const point = document.caretPositionFromPoint?.(x,y);
1286
+ const range = document.createRange();
1287
+ if (point) { range.setStart(point.offsetNode,point.offset); range.collapse(true); }
1288
+ else {
1289
+ const hit = document.caretRangeFromPoint?.(x,y);
1290
+ if (hit) { range.setStart(hit.startContainer,hit.startOffset); range.collapse(true); }
1291
+ }
1292
+ const text = codeLine?.querySelector('.line-text,.diff-text');
1293
+ if (text && !text.contains(range.startContainer)) {
1294
+ range.selectNodeContents(text);
1295
+ range.collapse(x <= text.getBoundingClientRect().left);
1296
+ }
1297
+ const line = codeLine ?? selectionElement(range.startContainer)?.closest('p,pre,h1,h2,h3,h4,h5,h6,li,td,th,blockquote');
1298
+ if (!line || (!text && (!markdown?.contains(line) || !line.contains(event.target)))) return;
1299
+ this.content.focus({preventScroll:true});
1300
+ selection.removeAllRanges(); selection.addRange(range);
1301
+ this.previewCaret = {line,range,text};
1302
+ line.classList.add('preview-caret-line');
1303
+ this.positionPreviewCaret();
1304
+ this.caretResize.observe(line);
1305
+ }
1306
+ positionPreviewCaret() {
1307
+ const caret = this.previewCaret;
1308
+ if (!caret) return;
1309
+ const {line,range,text} = caret, bounds = line.getBoundingClientRect();
1310
+ if (!this.content.contains(line) || !bounds.height) { this.clearPreviewCaret(); return; }
1311
+ const hit = range.getBoundingClientRect();
1312
+ const rect = hit.height ? hit : text?.getBoundingClientRect();
1313
+ if (!rect?.height) { this.clearPreviewCaret(); return; }
1314
+ const top = rect.top-bounds.top-line.clientTop+line.scrollTop;
1315
+ const left = !hit.height && range.startOffset > 0 ? rect.right : rect.left;
1316
+ line.style.setProperty('--preview-caret-x',`${left-bounds.left-line.clientLeft+line.scrollLeft}px`);
1317
+ line.style.setProperty('--preview-caret-y',`${top}px`);
1318
+ line.style.setProperty('--preview-caret-height',`${rect.height}px`);
1319
+ if (!text) {
1320
+ const height = Math.max(rect.height,parseFloat(getComputedStyle(line).lineHeight) || 0);
1321
+ line.style.setProperty('--preview-band-y',`${top-(height-rect.height)/2}px`);
1322
+ line.style.setProperty('--preview-band-height',`${height}px`);
1323
+ }
1324
+ }
1325
+ clearPreviewCaret() {
1326
+ const caret = this.previewCaret;
1327
+ if (!caret) return;
1328
+ this.previewCaret = undefined;
1329
+ this.caretResize.disconnect();
1330
+ caret.line.classList.remove('preview-caret-line');
1331
+ for (const property of ['--preview-caret-x','--preview-caret-y','--preview-caret-height','--preview-band-y','--preview-band-height']) caret.line.style.removeProperty(property);
1332
+ }
1333
+ directoryApi(directory) {
1334
+ const url = new URL(appBase+'/directory',window.location.href);
1335
+ url.searchParams.set('task',this.taskId); url.searchParams.set('directory',directory);
1336
+ return url.href;
1337
+ }
1338
+ previewApi(source) { return source ? this.directoryApi(source) : this.fileApi; }
1339
+ previewRoot(source) { return source ? this.directoryPanel?.directories.find(item => item.id === source)?.path : this.projectRoot; }
1340
+ get recentFileStorageKey() {
1341
+ return 'agentbot-workspace-recent-files:'+JSON.stringify([embedded ? apiBase : this.taskId || '',projectPath(this.projectRoot,this.projectRoot)]);
1342
+ }
1343
+ readRecentFiles() {
1344
+ const history = this.recentFiles ?? stored(this.recentFileStorageKey);
1345
+ const entries = Array.isArray(history) ? history : [...this.recentTabs].reverse().map(key => this.tabs.get(key));
1346
+ const valid = [];
1347
+ for (const item of entries.slice(0,commandPaletteFileLimit)) {
1348
+ if (!item || !['file','diff'].includes(item.kind) || (item.source && (!previewSource(item.kind,item.source) || !this.previewRoot(item.source)))
1349
+ || !this.previewApi(item.source)) continue;
1350
+ try {
1351
+ valid.push({path:relativePath(item.path),kind:item.kind,source:item.source,original:item.original === undefined?undefined:relativePath(item.original)});
1352
+ } catch {}
1353
+ }
1354
+ return valid;
1355
+ }
1356
+ rememberRecentFile({path,kind,source,original}) {
1357
+ const root = this.previewRoot(source), key = projectPath(path,root);
1358
+ const previous = this.readRecentFiles();
1359
+ this.recentFiles = [{path,kind,source,original},...previous.filter(item => item.source !== source || projectPath(item.path,root) !== key)].slice(0,commandPaletteFileLimit);
1360
+ put(this.recentFileStorageKey,this.recentFiles);
1361
+ }
1362
+ get treeApi() { return this.previewApi(this.explorerDirectory); }
1363
+ get treeRoot() { return this.directoryPanel?.tabs.find(tab => tab.id === this.explorerDirectory)?.path || this.projectRoot; }
1364
+ createDirectoryPanel(refresh) {
1365
+ this.directoryStrip = element('div',undefined,'explorer-directory-tabs');
1366
+ const strip = this.directoryStrip;
1367
+ strip.hidden = true; strip.setAttribute('role','group'); strip.setAttribute('aria-label','目录标签');
1368
+ strip.addEventListener('wheel',event => {
1369
+ if (event.ctrlKey || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return;
1370
+ const left = strip.scrollLeft, scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? strip.clientWidth : 1;
1371
+ strip.scrollLeft = left+event.deltaY*scale;
1372
+ if (strip.scrollLeft !== left) event.preventDefault();
1373
+ },{passive:false});
1374
+ this.addDirectory = iconControl('button','plus','添加目录','add-explorer-directory');
1375
+ this.addDirectory.hidden = true; this.addDirectory.onclick = () => this.showDirectoryChooser(true,true);
1376
+ refresh.before(this.directoryStrip,this.addDirectory);
1377
+ this.addDirectory.after(this.locateButton);
1378
+ this.directoryChooser = element('section',undefined,'explorer-directory-chooser');
1379
+ this.directoryChooser.hidden = true; this.directoryChooser.setAttribute('aria-label','选择目录');
1380
+ const form = element('form',undefined,'explorer-directory-form');
1381
+ this.directoryInput = element('input'); this.directoryInput.placeholder = '输入绝对目录路径'; this.directoryInput.maxLength = 4096; this.directoryInput.required = true;
1382
+ this.directoryInput.autocomplete = 'off'; this.directoryInput.spellcheck = false;
1383
+ this.directoryInput.setAttribute('aria-label','目录路径');
1384
+ this.directorySubmit = element('button','打开'); this.directorySubmit.type = 'submit';
1385
+ form.append(this.directoryInput,this.directorySubmit);
1386
+ form.onsubmit = event => { event.preventDefault(); const address = this.directoryInput.value.trim().replace(/^"(.+)"$/u,'$1'); if (address) void this.directoryAction('open-path',{address}); };
1387
+ this.directoryError = element('div',undefined,'explorer-directory-error'); this.directoryError.setAttribute('role','status'); this.directoryError.hidden = true;
1388
+ this.directoryChoices = element('div',undefined,'explorer-directory-choices');
1389
+ this.directoryChooser.append(form,this.directoryError,element('h3','任务关联目录'),this.directoryChoices);
1390
+ this.directoryChooser.onkeydown = event => {
1391
+ if (event.key === 'Escape' && this.treeApi && !this.directoryPending) {
1392
+ event.preventDefault(); this.showDirectoryChooser(false); this.restoreScroll(); this.addDirectory.focus();
1393
+ }
1394
+ };
1395
+ this.revealMessage.before(this.directoryChooser);
1396
+ }
1397
+ showDirectoryChooser(show, focus = false) {
1398
+ if (!this.directoryPanel) return;
1399
+ this.choosingDirectory = show;
1400
+ this.directoryChooser.hidden = !show; this.directoryError.hidden = true;
1401
+ this.dataset.directoryChooser = String(show);
1402
+ for (const button of this.querySelectorAll('.file-list-switch button')) button.disabled = show;
1403
+ this.renderDirectoryPanel();
1404
+ if (show && focus) this.directoryInput.focus();
1405
+ }
1406
+ renderDirectoryPanel() {
1407
+ if (!this.directoryPanel) return;
1408
+ const {tabs,directories} = this.directoryPanel, strip = this.directoryStrip, left = strip.scrollLeft;
1409
+ const directoryCount = tabs.length + (this.fileApi ? 1 : 0);
1410
+ strip.hidden = directoryCount < 2 && !this.choosingDirectory;
1411
+ this.addDirectory.hidden = Boolean(this.choosingDirectory); strip.replaceChildren();
1412
+ this.addDirectory.disabled = Boolean(this.directoryPending);
1413
+ this.directorySubmit.disabled = Boolean(this.directoryPending);
1414
+ if (strip.hidden) return;
1415
+ const appendTab = (directory, selected, action, close) => {
1416
+ const row = element('div',undefined,'explorer-directory-tab');
1417
+ const button = element('button',directory.name); button.type = 'button';
1418
+ if (directory.path && directory.path !== directory.name) button.dataset.tooltip = directory.path;
1419
+ button.setAttribute('aria-pressed',String(selected)); button.disabled = Boolean(this.directoryPending); button.onclick = action;
1420
+ row.append(button);
1421
+ if (close) {
1422
+ const dismiss = iconControl('button','close','关闭 '+directory.name,'close-explorer-directory');
1423
+ dismiss.disabled = Boolean(this.directoryPending); dismiss.onclick = close; row.append(dismiss);
1424
+ }
1425
+ row.classList.toggle('is-active',selected); strip.append(row);
1426
+ };
1427
+ const activate = directory => {
1428
+ if (directory === this.explorerDirectory) { this.showDirectoryChooser(false); this.restoreScroll(); }
1429
+ else void this.directoryAction('activate',{directory});
1430
+ };
1431
+ if (this.fileApi) appendTab({name:this.projectRoot.split(/[\\/]/u).filter(Boolean).at(-1) || '主目录',path:this.projectRoot},
1432
+ !this.choosingDirectory && !this.explorerDirectory,() => activate(null));
1433
+ for (const tab of tabs) appendTab(tab,!this.choosingDirectory && tab.id === this.explorerDirectory,
1434
+ () => activate(tab.id),() => this.directoryAction('close',{directory:tab.id}));
1435
+ if (this.choosingDirectory) appendTab({name:'选择目录'},true,() => this.directoryInput.focus(),
1436
+ this.treeApi ? () => { this.showDirectoryChooser(false); this.restoreScroll(); } : undefined);
1437
+ strip.scrollLeft = left;
1438
+ const active = strip.querySelector('.is-active');
1439
+ if (active && active.offsetLeft+active.offsetWidth > strip.scrollLeft+strip.clientWidth) strip.scrollLeft = active.offsetLeft+active.offsetWidth-strip.clientWidth;
1440
+ else if (active && active.offsetLeft < strip.scrollLeft) strip.scrollLeft = active.offsetLeft;
1441
+ if (!this.choosingDirectory) return;
1442
+ const choices = new Map([...directories,...(this.taskDirectories || [])].map(item => [item.id,item]));
1443
+ this.directoryChoices.replaceChildren();
1444
+ for (const directory of choices.values()) {
1445
+ if (!directory.path || projectPath(directory.path,this.projectRoot) === projectPath(this.projectRoot,this.projectRoot)) continue;
1446
+ const button = element('button',undefined,'launch-directory'); button.type = 'button';
1447
+ button.dataset.tooltip = directory.path; button.dataset.tooltipOverflow = '.launch-directory-path';
1448
+ const label = element('span',undefined,'launch-directory-label');
1449
+ label.append(element('strong',directory.name),element('span',directory.path,'launch-directory-path'));
1450
+ button.append(icon('folder'),label);
1451
+ if (tabs.some(tab => tab.id === directory.id)) button.append(element('span','已打开','explorer-directory-open'));
1452
+ button.disabled = Boolean(this.directoryPending); button.onclick = () => this.directoryAction('open-recorded',{directory:directory.id});
1453
+ this.directoryChoices.append(button);
1454
+ }
1455
+ if (!this.directoryChoices.childElementCount) this.directoryChoices.append(element('p','暂无关联目录,可输入路径打开。'));
1456
+ }
1457
+ setDirectoryPanel(panel) {
1458
+ if (!panel || !this.directoryStrip) return;
1459
+ const app = this.closest('agentbot-workspace');
1460
+ const changed = (this.explorerDirectory || null) !== panel.active;
1461
+ if (changed && app?.filesPanel === this) { this.saveScroll(); app.persistTrees(); }
1462
+ this.directoryPanel = panel;
1463
+ if (changed) this.switchExplorerDirectory(panel.active);
1464
+ else this.explorerDirectory = panel.active;
1465
+ if (!this.treeApi) this.showDirectoryChooser(true);
1466
+ else this.renderDirectoryPanel();
1467
+ }
1468
+ async directoryAction(action, params) {
1469
+ if (this.directoryPending) return false;
1470
+ const app = this.closest('agentbot-workspace');
1471
+ this.directoryPending = true; this.directoryError.hidden = true; this.renderDirectoryPanel();
1472
+ try {
1473
+ const panel = await app.sessions.fetch('/directory-panel',{body:{task:this.taskId,action,...params}});
1474
+ if (!this.isConnected) return false;
1475
+ this.setDirectoryPanel(panel);
1476
+ if (action === 'open-path') this.directoryInput.value = '';
1477
+ if (action !== 'close' || !this.treeApi) this.showDirectoryChooser(!this.treeApi);
1478
+ this.restoreScroll(); this.queuePersist();
1479
+ return true;
1480
+ } catch (error) {
1481
+ if (!this.isConnected) return false;
1482
+ if (this.choosingDirectory) { this.directoryError.hidden = false; this.directoryError.textContent = error.message; }
1483
+ else { this.revealMessage.hidden = false; this.notice(this.revealMessage,error.message); }
1484
+ return false;
1485
+ } finally {
1486
+ this.directoryPending = false;
1487
+ if (this.isConnected) this.renderDirectoryPanel();
1488
+ }
1489
+ }
1490
+ switchExplorerDirectory(directory) {
1491
+ const app = this.closest('agentbot-workspace'), mode = this.listMode;
1492
+ this.explorerDirectory = directory;
1493
+ this.dataset.noPrimary = String(!this.treeApi);
1494
+ clearTimeout(this.searchTimer); this.searchController?.abort(); this.searchSequence = (this.searchSequence || 0)+1;
1495
+ clearTimeout(this.syncTimer); this.syncTimer = undefined; this.fileChanges = undefined;
1496
+ clearTimeout(this.warmTimer); this.warmTimer = undefined;
1497
+ this.liveReady = false; this.usedDirectoryCache = false; this.summaryRequest = this.changesSummary = undefined;
1498
+ this.revealing = this.pendingFilterTarget = this.pendingTreeTarget = undefined;
1499
+ this.locateButton.removeAttribute('aria-busy'); this.revealMessage.hidden = true;
1500
+ for (const view of this.navigationViews.values()) {
1501
+ view.generation = ++this.navigationSequence;
1502
+ for (const observer of view.observers) observer.disconnect();
1503
+ }
1504
+ const node = this.navigation.cloneNode(false); this.navigation.replaceWith(node); this.navigation = node;
1505
+ this.navigationViews = new Map([[mode,this.createNavigationView(node)]]);
1506
+ this.listScrollTop = 0; this.search.value = ''; this.applyChangesMetadata({totalChanges:0});
1507
+ if (!this.activeKey && this.directoryPanel) this.showExplorerEmpty();
1508
+ if (app?.filesPanel !== this) return;
1509
+ app.initTreeStorage(this.treeRoot,this.taskId);
1510
+ this.restoreTrees(app.treeStates);
1511
+ const view = this.navigationView(mode);
1512
+ this.listScrollTop = (view.query?view.filterScrollTop:view.scrollTop) || 0;
1513
+ this.selectList(mode,false);
1514
+ if (this.treeApi && mode !== 'changes') void this.updateChangesCount();
1515
+ this.updateCurrentFile();
1516
+ app.watchFiles(this);
1517
+ }
1518
+ showExplorerEmpty() {
1519
+ this.content.replaceChildren(element('div',this.treeApi?'选择一个文件或改动。':'此任务没有可浏览的目录。','content-empty'));
442
1520
  }
443
1521
  disconnectedCallback() {
1522
+ document.removeEventListener('selectionchange',this.previewSelectionChanged);
1523
+ this.clearPreviewCaret();
444
1524
  this.removeEventListener('click',this.keepTreeRow,true);
445
1525
  this.removeEventListener('mousedown',this.startTreeToggle,true);
446
1526
  this.removeEventListener('keydown',this.clearTreePointerFocus,true);
@@ -452,13 +1532,14 @@
452
1532
  for (const view of this.navigationViews.values()) for (const observer of view.observers) observer.disconnect();
453
1533
  this.tabs.clear(); this.views.clear();
454
1534
  clearTimeout(this.searchTimer); this.searchController?.abort();
1535
+ clearTimeout(this.syncTimer); clearTimeout(this.warmTimer);
455
1536
  }
456
1537
  navigate(action, replace = false) {
457
1538
  const app = this.closest('agentbot-workspace');
458
1539
  if (app?.filesPanel === this) app.navigate(action,replace);
459
1540
  }
460
1541
  queuePersist() { const app = this.closest('agentbot-workspace'); if (app?.filesPanel === this) app.queuePersist(); }
461
- pathKey(value) { return projectPath(value,this.projectRoot); }
1542
+ pathKey(value) { return projectPath(value,this.treeRoot); }
462
1543
  startTreeToggle = event => {
463
1544
  if (event.button !== 0) return;
464
1545
  const summary = event.target.closest('summary'); if (!summary || !this.navigation.contains(summary)) return;
@@ -473,15 +1554,22 @@
473
1554
  const summary = event.target.closest('summary'); if (!summary || !this.navigation.contains(summary)) return;
474
1555
  this.reserveTreeScroll(this.navigation.scrollTop);
475
1556
  };
476
- trimTreeScroll = event => { if (event.target === this.navigation) this.reserveTreeScroll(this.navigation.scrollTop); };
1557
+ trimTreeScroll = event => {
1558
+ if (event.target !== this.navigation) return;
1559
+ this.reserveTreeScroll(this.navigation.scrollTop);
1560
+ if (this.liveReady) this.resumeDirtyDirectories();
1561
+ };
477
1562
  reserveTreeScroll(top) {
478
1563
  const navigation = this.navigation; if (!navigation.clientHeight) return;
479
1564
  const tree = navigation.querySelector(':scope > .navigation-tree');
480
1565
  if (tree) tree.style.minHeight = top > 0 ? 'calc(100% + '+top+'px)' : '';
481
1566
  }
1567
+ createNavigationView(node) {
1568
+ return {node,scrollTop:0,pending:0,ready:false,expanded:new Set(),pages:new Map(),restorePages:new Map(),observers:new Set(),directories:new Map()};
1569
+ }
482
1570
  navigationView(mode) {
483
1571
  let view = this.navigationViews.get(mode);
484
- if (!view) { view = {node:this.navigation.cloneNode(false),scrollTop:0,pending:0,ready:false,expanded:new Set(),pages:new Map(),restorePages:new Map(),observers:new Set()}; this.navigationViews.set(mode,view); }
1572
+ if (!view) { view = this.createNavigationView(this.navigation.cloneNode(false)); this.navigationViews.set(mode,view); }
485
1573
  return view;
486
1574
  }
487
1575
  restoreTrees(trees) {
@@ -489,7 +1577,7 @@
489
1577
  const saved = trees[mode], view = this.navigationViews.get(mode) || (saved ? this.navigationView(mode) : undefined); if (!view) continue;
490
1578
  const expanded = new Set(saved?.expanded || []);
491
1579
  const changed = [...view.expanded].some(path => !expanded.has(path)) || [...expanded].some(path => !view.expanded.has(path));
492
- const pages = new Map(saved?.pages || []), needsPages = [...pages].some(([entry,count]) => count > (view.pages.get(entry) || 0));
1580
+ const pages = new Map(conserveData() ? [] : saved?.pages || []), needsPages = [...pages].some(([entry,count]) => count > (view.pages.get(entry) || 0));
493
1581
  view.expanded = expanded; view.restorePages = pages; view.scrollTop = saved?.scrollTop || 0;
494
1582
  view.filterScrollTop = saved?.filterScrollTop || 0; view.filterCollapsed = new Set(saved?.filterCollapsed || []);
495
1583
  for (const details of view.node.querySelectorAll('details[data-directory]')) details.open = expanded.has(details.dataset.directory);
@@ -498,13 +1586,13 @@
498
1586
  if ((view.query || '') !== (saved?.query || '')) { view.query = saved?.query || ''; if (view.query && !view.filterNode) view.filterNode = view.node.cloneNode(false); }
499
1587
  }
500
1588
  }
501
- selectList(mode) {
502
- this.navigate(() => {
1589
+ selectList(mode, record = true) {
1590
+ const apply = () => {
503
1591
  if (mode === this.listMode) {
504
1592
  const view = this.navigationView(mode), node = view.query?view.filterNode:view.node;
505
1593
  if (this.navigation !== node) { this.navigation.replaceWith(node); this.navigation = node; }
506
1594
  this.search.value = view.query || ''; if (view.query && view.filterQuery !== view.query) this.filterNavigation(mode);
507
- if (this.fileApi && !view.ready && !view.pending) this.loadNavigation(mode);
1595
+ if (this.treeApi && !view.ready && !view.pending) this.loadNavigation(mode);
508
1596
  return;
509
1597
  }
510
1598
  this.saveScroll(); const previous = this.navigationViews.get(this.listMode);
@@ -515,57 +1603,113 @@
515
1603
  if (view.query && view.filterQuery !== view.query) this.filterNavigation(mode);
516
1604
  this.navigationGeneration = view.generation; this.listScrollTop = view.query ? view.filterScrollTop || 0 : view.scrollTop; this.dataset.view = 'list';
517
1605
  for (const button of this.querySelectorAll('[data-list]')) button.setAttribute('aria-pressed',String(button.dataset.list === mode));
518
- if (this.fileApi && !view.ready && !view.pending) this.loadNavigation(); this.restoreScroll(); this.syncFrames();
1606
+ if (this.treeApi && !view.ready && !view.pending) this.loadNavigation(); this.restoreScroll(); this.syncFrames();
1607
+ if (view.needsSync) this.queueFileSync({reset:true});
519
1608
  this.updateCurrentFile();
520
- });
1609
+ };
1610
+ if (record) this.navigate(apply); else apply();
521
1611
  }
522
- async request(api, params = {}, controller = new AbortController()) {
523
- if (!this.fileApi) throw new Error('此任务没有可浏览的项目目录。');
524
- const url = new URL(this.fileApi); url.searchParams.set('api',api);
1612
+ async request(api, params = {}, controller = new AbortController(), conditional, onEtag, base = this.fileApi, signal) {
1613
+ if (!base) throw new Error('此任务没有可浏览的项目目录。');
1614
+ const url = new URL(base); url.searchParams.set('api',api);
525
1615
  for (const [key,value] of Object.entries(params)) if (value !== undefined) url.searchParams.set(key,String(value));
526
1616
  this.controllers.add(controller);
1617
+ const abort = () => controller.abort();
1618
+ if (signal?.aborted) abort(); else signal?.addEventListener('abort',abort,{once:true});
527
1619
  const timer = setTimeout(() => controller.abort(),15000);
528
1620
  try {
529
- const response = await fetch(url,{signal:controller.signal,credentials:api === 'terminal'?'same-origin':'omit',cache:'no-store'});
1621
+ const response = await fetch(url,{signal:controller.signal,credentials:embedded || api === 'terminal' || base !== this.fileApi?'same-origin':'omit',cache:'no-store',
1622
+ ...(conditional?.etag?{headers:{'if-none-match':conditional.etag}}:{})});
1623
+ if (response.status === 304 && conditional) { onEtag?.(conditional.etag); return conditional.data; }
530
1624
  let data;
531
1625
  try { data = await response.json(); }
532
1626
  catch { throw new Error('服务器返回无效 JSON(HTTP '+response.status+')'); }
533
1627
  if (!response.ok) throw Object.assign(new Error(data.error || '读取失败(HTTP '+response.status+')'),{status:response.status});
1628
+ onEtag?.(response.headers?.get('etag') || undefined);
534
1629
  return data;
535
1630
  } catch (error) {
536
1631
  if (error.name === 'AbortError') throw new Error('读取超时,请重试。');
537
1632
  if (error.name === 'TypeError') throw new Error('网络不可用:'+error.message);
538
1633
  throw error;
539
- } finally { clearTimeout(timer); this.controllers.delete(controller); }
1634
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort',abort); this.controllers.delete(controller); }
1635
+ }
1636
+ requestTree(api, params, controller, conditional, onEtag) {
1637
+ return this.request(api,params,controller,conditional,onEtag,this.treeApi);
540
1638
  }
541
1639
  notice(container, text, retry) {
542
1640
  const message = element('div',text,'navigation-message'+(retry?' error':'')); container.replaceChildren(message);
543
1641
  if (retry) { const button = iconControl('button','refresh','重试'); button.onclick = retry; container.append(button); }
544
1642
  }
545
1643
  async updateChangesCount() {
546
- const generation = this.navigationGeneration;
1644
+ if (conserveData()) { await this.updateChangesSummary(); return; }
1645
+ const view = this.navigationView('changes');
547
1646
  try {
548
- const data = await this.request('changes',{prefetch:1});
549
- if (!this.isConnected || generation !== this.navigationGeneration) return;
550
- const view = this.navigationView('changes'); if (!view.ready && !view.pending && Array.isArray(data.preloaded)) { view.rootData = data; this.cacheMetadata(view,data); }
1647
+ const cached = this.cachedDirectory('changes','',0);
1648
+ const data = cached?.data || await this.requestTree('changes',{prefetch:1});
1649
+ if (this.navigationViews.get('changes') !== view) return;
1650
+ if (cached) this.recheckCachedDirectory(cached,'');
1651
+ if (!this.isConnected || view.ready || view.pending) return;
1652
+ if (!cached && Array.isArray(data.preloaded)) {
1653
+ const app = this.closest('agentbot-workspace');
1654
+ app.directoryCache.set(this.directoryKey('changes','',0),data); app.scheduleCacheSave();
1655
+ }
551
1656
  this.applyChangesMetadata(data);
552
1657
  } catch (error) {
553
- if (this.isConnected && generation === this.navigationGeneration) this.showChangesCountError(error);
1658
+ if (this.isConnected && this.navigationViews.get('changes') === view && !view.ready && !view.pending) this.showChangesCountError(error);
554
1659
  }
555
1660
  }
1661
+ updateChangesSummary() {
1662
+ if (this.summaryRequest) return this.summaryRequest;
1663
+ let etag;
1664
+ const pending = this.requestTree('changes-summary',{},undefined,this.changesSummary,value => { etag = value; })
1665
+ .then(data => {
1666
+ if (this.summaryRequest === pending && this.isConnected && this.listMode !== 'changes') {
1667
+ this.changesSummary = {data,etag}; this.applyChangesMetadata(data);
1668
+ }
1669
+ }).catch(error => { if (this.summaryRequest === pending && this.isConnected && !this.changesSummary && this.listMode !== 'changes') this.showChangesCountError(error); })
1670
+ .finally(() => { if (this.summaryRequest === pending) this.summaryRequest = undefined; });
1671
+ this.summaryRequest = pending;
1672
+ return pending;
1673
+ }
1674
+ directoryKey(mode,entry,page) { return JSON.stringify([this.treeApi,mode,entry,page]); }
1675
+ cachedDirectory(mode,entry,page) {
1676
+ return this.closest('agentbot-workspace').directoryCache.get(this.directoryKey(mode,entry,page));
1677
+ }
1678
+ recheckCachedDirectory(cached,entry) {
1679
+ if (!this.liveReady) { this.usedDirectoryCache = true; return; }
1680
+ if (cached.at < (this.lastFileChange || 0) || Date.now()-cached.at > 15_000) this.queueFileSync(entry?{paths:[entry]}:{reset:true});
1681
+ }
1682
+ fetchDirectory(mode,entry,page,force = false) {
1683
+ const key = this.directoryKey(mode,entry,page), app = this.closest('agentbot-workspace');
1684
+ this.directoryReads ??= new Map();
1685
+ if (!force && this.directoryReads.has(key)) return this.directoryReads.get(key);
1686
+ let etag;
1687
+ const lean = conserveData(), cached = this.cachedDirectory(mode,entry,page);
1688
+ const conditional = lean && cached?.data.preloaded ? undefined : cached;
1689
+ const pending = this.requestTree(mode === 'changes'?'changes':'tree',
1690
+ {entry,page,prefetch:!lean && !entry && page === 0?1:undefined,refresh:force?1:undefined},undefined,conditional,value => { etag = value; })
1691
+ .then(data => {
1692
+ if (this.directoryReads.get(key) === pending && this.isConnected && data.page === page && Array.isArray(data.entries)) {
1693
+ app.directoryCache.set(key,data,Date.now(),etag); app.scheduleCacheSave();
1694
+ }
1695
+ return data;
1696
+ }).finally(() => { if (this.directoryReads.get(key) === pending) this.directoryReads.delete(key); });
1697
+ this.directoryReads.set(key,pending);
1698
+ return pending;
1699
+ }
556
1700
  showChangesCountError(error) {
557
1701
  const button = this.querySelector('[data-list=changes]');
558
1702
  const count = button.querySelector('.count-badge'); count.textContent = '!'; count.hidden = false;
559
- button.title = '读取未提交改动失败:'+error.message; button.setAttribute('aria-label',button.title);
1703
+ button.dataset.tooltip = '读取未提交改动失败:'+error.message; button.setAttribute('aria-label',button.dataset.tooltip);
560
1704
  }
561
1705
  applyChangesMetadata(data) {
562
1706
  const button = this.querySelector('[data-list=changes]'), count = button.querySelector('.count-badge');
563
1707
  count.textContent = String(data.totalChanges); count.hidden = data.totalChanges === 0;
564
- button.title = '未提交改动,'+data.totalChanges+' 个'+(data.notice?' · '+data.notice:''); button.setAttribute('aria-label',button.title);
1708
+ button.dataset.tooltip = '未提交改动,'+data.totalChanges+' 个'+(data.notice?' · '+data.notice:''); button.setAttribute('aria-label',button.dataset.tooltip);
565
1709
  this.dispatchEvent(new CustomEvent('workspace-status',{bubbles:true,detail:{label:data.branch || data.notice || '只读工作台',repository:data.repository === true}}));
566
1710
  }
567
1711
  cacheMetadata(view, data) {
568
- if (!Array.isArray(data.preloaded)) return;
1712
+ if (!Array.isArray(data.preloaded)) { view.preloaded = view.directoryCache = undefined; return; }
569
1713
  view.preloaded = data.preloaded; view.directoryCache = new Map([['',[]]]);
570
1714
  for (const item of data.preloaded) {
571
1715
  const parent = item.path.includes('/')?item.path.slice(0,item.path.lastIndexOf('/')):'';
@@ -579,22 +1723,26 @@
579
1723
  button.dataset.filePath = item.path;
580
1724
  button.append(fileIcon(item.path),element('span',item.name,changed?'change-name':undefined));
581
1725
  const title = item.originalPath ? item.originalPath+' → '+item.path : item.path;
582
- button.title = item.error || title; button.disabled = item.blocked;
1726
+ button.dataset.tooltip = item.error || title; button.disabled = item.blocked;
1727
+ if (!item.error && !item.originalPath) button.dataset.tooltipOverflow = ':scope > span:first-of-type';
583
1728
  if (item.ignored) { button.classList.add('is-git-ignored'); button.setAttribute('aria-label',title+' · Git 已忽略'); }
584
1729
  const status = gitStatus(item);
585
1730
  if (status) {
586
1731
  const stats = lineStats(item), metadata = element('span',undefined,'tree-git-meta');
587
- metadata.append(stats,status); button.setAttribute('aria-label',title+' · '+status.title+' · '+stats.title); button.append(metadata);
1732
+ metadata.append(stats,status); button.setAttribute('aria-label',title+' · '+status.dataset.tooltip+' · '+stats.dataset.tooltip); button.append(metadata);
588
1733
  }
589
1734
  button.onclick = event => {
590
1735
  const selection = window.getSelection();
591
1736
  if (event.detail > 0 && selection && !selection.isCollapsed && selection.containsNode(button,true)) return;
592
- this.openFile(item.path,changed?'diff':'file',item.originalPath);
1737
+ this.openFile(item.path,changed?'diff':'file',item.originalPath,undefined,undefined,this.explorerDirectory || undefined);
593
1738
  }; return button;
594
1739
  }
595
1740
  updateCurrentFile() {
596
- const tab = this.tabs.get(this.activeKey), path = tab && ['file','diff'].includes(tab.kind) ? tab.path : undefined, currentPath = this.pathKey(path);
597
- this.locateButton.disabled = !path || this.revealing;
1741
+ const tab = this.tabs.get(this.activeKey);
1742
+ const hasFile = tab && ['file','diff'].includes(tab.kind);
1743
+ const path = hasFile && tab.source === (this.explorerDirectory || undefined) ? tab.path : undefined;
1744
+ const currentPath = this.pathKey(path);
1745
+ this.locateButton.disabled = !hasFile || this.revealing || (!path && !this.previewRoot(tab.source));
598
1746
  for (const view of this.navigationViews.values()) for (const node of [view.node,view.filterNode]) if (node) {
599
1747
  for (const button of node.querySelectorAll('[data-file-path]')) {
600
1748
  const active = this.pathKey(button.dataset.filePath) === currentPath; button.classList.toggle('is-current-file',active);
@@ -606,11 +1754,19 @@
606
1754
  }
607
1755
  }
608
1756
  }
609
- async revealCurrentFile(keepView = false) {
610
- const tab = this.tabs.get(this.activeKey); if (this.revealing || !tab || !['file','diff'].includes(tab.kind)) return;
1757
+ async revealCurrentFile(keepView = false, replacePending = false, switchDirectory = !keepView) {
1758
+ const tab = this.tabs.get(this.activeKey);
1759
+ if ((this.revealing && !replacePending) || !tab || !['file','diff'].includes(tab.kind)) return;
1760
+ if (tab.source !== (this.explorerDirectory || undefined)) {
1761
+ if (!switchDirectory || !this.directoryPanel || !this.previewRoot(tab.source)) return;
1762
+ const open = tab.source && !this.directoryPanel.tabs.some(directory => directory.id === tab.source);
1763
+ const selected = await this.directoryAction(open?'open-recorded':'activate',{directory:tab.source || null});
1764
+ if (!selected || this.hidden || this.tabs.get(this.activeKey) !== tab) return;
1765
+ if (keepView) this.navigate(() => this.prepareAddressFile(),true);
1766
+ }
611
1767
  const mode = keepView?this.listMode:tab.kind === 'diff' ? 'changes' : 'files';
612
1768
  if (keepView && this.navigationView(mode).query) { this.pendingFilterTarget = {key:tab.key,mode,path:tab.path,query:this.navigationView(mode).query}; this.revealFilteredFile(); return; }
613
- this.revealing = true; this.revealMessage.hidden = true; this.locateButton.setAttribute('aria-busy','true'); this.updateCurrentFile();
1769
+ const reveal = this.revealing = {}; this.revealMessage.hidden = true; this.locateButton.setAttribute('aria-busy','true'); this.updateCurrentFile();
614
1770
  if (!keepView) this.navigate(() => {
615
1771
  this.saveScroll(); this.selectList(mode);
616
1772
  if (this.navigationView(mode).query) { this.search.value = ''; this.setFilter(''); }
@@ -618,7 +1774,7 @@
618
1774
  const app = this.closest('agentbot-workspace'); app.selectPane('files'); if (app.layout.explorerCollapsed) { app.layout.explorerCollapsed = false; app.applyLayout(); }
619
1775
  });
620
1776
  const view = this.navigationView(mode), generation = view.generation;
621
- const current = () => this.isConnected && this.activeKey === tab.key && this.listMode === mode && (keepView || this.dataset.view === 'list' && this.closest('agentbot-workspace').dataset.pane === 'files') && this.navigation === view.node && generation === view.generation && !view.query;
1777
+ const current = () => this.isConnected && this.revealing === reveal && this.tabs.get(this.activeKey) === tab && this.listMode === mode && (keepView || this.dataset.view === 'list' && this.closest('agentbot-workspace').dataset.pane === 'files') && this.navigation === view.node && generation === view.generation && !view.query;
622
1778
  const find = async (container, path) => {
623
1779
  let loaded;
624
1780
  while (current()) {
@@ -636,22 +1792,24 @@
636
1792
  let container = view.node.firstElementChild; const parts = this.pathKey(tab.path).split('/');
637
1793
  for (let index = 1; index < parts.length; index++) {
638
1794
  const path = parts.slice(0,index).join('/'), directory = await find(container,path); if (!directory || !current()) return;
639
- if (!directory.dataset.directory) throw new Error('父目录不是可访问目录:'+directory.title);
1795
+ if (!directory.dataset.directory) throw new Error('父目录不是可访问目录:'+directory.dataset.tooltip);
640
1796
  if (directory.firstElementChild.getAttribute('aria-disabled') === 'true') throw new Error(directory.textContent);
641
1797
  view.expanded.add(directory.dataset.directory); directory.open = true; await directory.loadChildren(); if (!current() || !directory.open) return; container = directory.lastElementChild;
642
1798
  }
643
1799
  const target = await find(container,tab.path); if (!target || !current()) return;
644
1800
  for (let parent = target.closest('details'); parent; parent = parent.parentElement.closest('details')) if (!parent.open) return;
645
1801
  if (!target.dataset.filePath) throw new Error('当前路径已变成目录,无法定位原文件。');
646
- if (target.disabled) throw new Error(target.title);
1802
+ if (target.disabled) throw new Error(target.dataset.tooltip);
647
1803
  this.updateCurrentFile();
648
1804
  this.pendingTreeTarget = {key:tab.key,mode,node:target}; this.centerTreeTarget();
649
1805
  if (!keepView) target.focus({preventScroll:true}); this.saveScroll(); this.queuePersist();
650
1806
  } catch (error) {
651
1807
  if (current()) { this.revealMessage.hidden = false; this.notice(this.revealMessage,'定位失败:'+error.message,() => { this.loadNavigation(mode,true).then(() => this.revealCurrentFile(keepView)); }); }
652
1808
  } finally {
653
- this.revealing = false;
654
- if (this.isConnected) { this.locateButton.removeAttribute('aria-busy'); this.updateCurrentFile(); }
1809
+ if (this.revealing === reveal) {
1810
+ this.revealing = undefined;
1811
+ if (this.isConnected) { this.locateButton.removeAttribute('aria-busy'); this.updateCurrentFile(); }
1812
+ }
655
1813
  }
656
1814
  }
657
1815
  centerTreeTarget() {
@@ -676,8 +1834,10 @@
676
1834
  const view = this.navigationView(this.listMode); if (!view.query) this.saveScroll();
677
1835
  if (view.query !== query.trim()) { view.filterScrollTop = 0; view.filterCollapsed = new Set(); }
678
1836
  view.query = query.trim(); this.searchController?.abort(); this.searchSequence = (this.searchSequence || 0)+1; clearTimeout(this.searchTimer);
679
- if (!view.query) { this.navigation.replaceWith(view.node); this.navigation = view.node; this.navigation.scrollTop = view.scrollTop; this.listScrollTop = view.scrollTop; }
680
- else {
1837
+ if (!view.query) {
1838
+ this.navigation.replaceWith(view.node); this.navigation = view.node; this.navigation.scrollTop = view.scrollTop; this.listScrollTop = view.scrollTop;
1839
+ if (this.liveReady) this.resumeDirtyDirectories();
1840
+ } else {
681
1841
  if (!view.filterNode) view.filterNode = view.node.cloneNode(false);
682
1842
  if (this.navigation !== view.filterNode) { this.navigation.replaceWith(view.filterNode); this.navigation = view.filterNode; }
683
1843
  this.notice(view.filterNode,'正在过滤…'); view.filterNode.scrollTop = this.listScrollTop = 0;
@@ -685,18 +1845,24 @@
685
1845
  }
686
1846
  this.queuePersist();
687
1847
  }
688
- async filterNavigation(mode) {
1848
+ async filterNavigation(mode,background = false) {
689
1849
  const view = this.navigationView(mode), query = view.query; if (!query) return;
690
1850
  if (!view.filterNode) view.filterNode = view.node.cloneNode(false);
691
1851
  if (mode !== this.listMode) return;
692
1852
  const sequence = this.searchSequence = (this.searchSequence || 0)+1;
693
1853
  if (mode === this.listMode && this.navigation !== view.filterNode) { this.navigation.replaceWith(view.filterNode); this.navigation = view.filterNode; }
694
- const node = view.filterNode; this.notice(node,'正在过滤…');
1854
+ const node = view.filterNode;
1855
+ if (!background || view.filterQuery !== query) this.notice(node,'正在过滤…');
695
1856
  this.searchController?.abort(); const controller = this.searchController = new AbortController();
696
1857
  try {
697
1858
  const normalized = query.replaceAll('\\','/').toLowerCase();
698
- const data = view.preloaded ? {entries:view.preloaded.filter(item => item.path.toLowerCase().includes(normalized)),truncated:false,gitError:view.gitError} : await this.request(mode === 'changes'?'changes':'tree',{query},controller);
1859
+ const cached = view.filterResponse?.query === query ? view.filterResponse : undefined;
1860
+ let etag;
1861
+ const data = view.preloaded ? {entries:view.preloaded.filter(item => item.path.toLowerCase().includes(normalized)),truncated:false,gitError:view.gitError}
1862
+ : await this.requestTree(mode === 'changes'?'changes':'tree',{query},controller,cached,value => { etag = value; });
699
1863
  if (!this.isConnected || sequence !== this.searchSequence || query !== view.query) return;
1864
+ view.filterResponse = etag ? {query,data,etag} : undefined;
1865
+ if (background && view.filterQuery === query && data === cached?.data) { node.querySelector('.filter-failure')?.remove(); return; }
700
1866
  view.filterQuery = query;
701
1867
  const flat = new Map(), ignored = new Set((data.ignoredPaths || view.preloaded?.filter(item => item.directory && item.ignored).map(item => item.path) || []).map(value => this.pathKey(value)));
702
1868
  const directoryChanges = new Map((data.directoryChanges || view.preloaded?.filter(item => item.directory) || []).map(item => [this.pathKey(item.path),item]));
@@ -711,7 +1877,8 @@
711
1877
  for (const item of entries) {
712
1878
  const parent = folders.get(item.path.includes('/')?item.path.slice(0,item.path.lastIndexOf('/')):'');
713
1879
  if (item.directory) {
714
- const details = element('details'), summary = element('summary'), children = element('div'); summary.append(element('span',item.name)); summary.title = item.path;
1880
+ const details = element('details'), summary = element('summary'), children = element('div'); summary.append(element('span',item.name));
1881
+ summary.dataset.tooltip = item.path; summary.dataset.tooltipOverflow = ':scope > span:first-of-type';
715
1882
  directoryGitStatus(summary,item);
716
1883
  details.dataset.filterDirectory = item.path;
717
1884
  details.open = !view.filterCollapsed?.has(item.path); details.append(summary,children); parent.append(details); folders.set(item.path,children);
@@ -728,11 +1895,19 @@
728
1895
  this.updateCurrentFile();
729
1896
  this.revealFilteredFile();
730
1897
  } catch (error) {
731
- if (this.isConnected && sequence === this.searchSequence && query === view.query) this.notice(node,'过滤失败:'+error.message,() => this.filterNavigation(mode));
1898
+ if (this.isConnected && sequence === this.searchSequence && query === view.query) {
1899
+ if (background && view.filterQuery === query) {
1900
+ node.querySelector('.filter-failure')?.remove();
1901
+ const failure = element('div',undefined,'filter-failure'); node.append(failure);
1902
+ this.notice(failure,'过滤结果未更新:'+error.message,() => this.filterNavigation(mode,true));
1903
+ } else this.notice(node,'过滤失败:'+error.message,() => this.filterNavigation(mode));
1904
+ }
732
1905
  }
733
1906
  }
734
1907
  async loadNavigation(mode = this.listMode, refresh = false) {
735
- const generation = ++this.navigationSequence, view = this.navigationView(mode);
1908
+ const view = this.navigationView(mode);
1909
+ if (refresh && view.ready) { await this.refreshTree(mode,{reset:true},true); return; }
1910
+ const generation = ++this.navigationSequence;
736
1911
  if (mode === this.listMode) this.navigationGeneration = generation;
737
1912
  for (const details of view.node.querySelectorAll('details[data-directory]')) {
738
1913
  if (details.open) view.expanded.add(details.dataset.directory); else view.expanded.delete(details.dataset.directory);
@@ -740,14 +1915,15 @@
740
1915
  for (const observer of view.observers) observer.disconnect(); view.observers.clear();
741
1916
  if (!view.restorePages.size) view.restorePages = new Map(view.pages); view.pages.clear();
742
1917
  view.generation = generation; view.ready = false;
743
- if (refresh) view.preloaded = view.directoryCache = view.rootData = undefined;
1918
+ view.preloaded = view.directoryCache = undefined; view.directories.clear(); view.failures = new Set();
744
1919
  view.node.setAttribute('aria-label',mode === 'changes'?'未提交改动目录树':'项目文件');
745
1920
  const list = element('div',undefined,'navigation-tree'); view.node.replaceChildren(list);
746
- view.loading = this.loadDirectory(list,'',0,generation,mode); await view.loading;
747
- if (generation === view.generation) {
1921
+ view.loading = this.loadDirectory(list,'',0,generation,mode,false,refresh); await view.loading;
1922
+ if (this.isConnected && generation === view.generation) {
748
1923
  view.ready = true;
749
1924
  if (view.query) this.filterNavigation(mode);
750
1925
  if (this.navigation === view.node) { this.listScrollTop = view.scrollTop; this.restoreScroll(); }
1926
+ this.warmDirectories();
751
1927
  }
752
1928
  }
753
1929
  expandSingleDirectory(container) {
@@ -755,98 +1931,346 @@
755
1931
  while (parent) { if (!parent.open) return; parent = parent.parentElement.closest('details'); }
756
1932
  return container.expandSingle?.();
757
1933
  }
758
- loadDirectory(container, entry, page, generation, mode, expandChain = false) {
759
- const pending = this.readDirectory(container,entry,page,generation,mode,expandChain); container.loading = pending; return pending;
760
- }
761
- async readDirectory(container, entry, page, generation, mode, expandChain = false) {
762
- const view = this.navigationViews.get(mode), rootPage = !entry && page === 0; view.pending++;
763
- const loading = element('div','正在读取…','navigation-message'); loading.setAttribute('role','status'); container.append(loading);
1934
+ loadDirectory(container,entry,page,generation,mode,expandChain = false,force = false) {
1935
+ const pending = this.readDirectory(container,entry,page,generation,mode,expandChain,force);
1936
+ container.loading = pending; return pending;
1937
+ }
1938
+ async readDirectory(container,entry,page,generation,mode,expandChain,force) {
1939
+ const view = this.navigationView(mode), rootPage = !entry && page === 0;
1940
+ const directory = container.directoryState ??= {container,entry,records:[],rows:new Map(),pending:0};
1941
+ view.directories.set(entry,directory); view.pending++; directory.pending++;
1942
+ const current = () => this.isConnected && generation === view.generation && view.directories.get(entry) === directory;
1943
+ let loading;
1944
+ const timer = setTimeout(() => {
1945
+ if (!current() || directory.rows.size) return;
1946
+ loading = element('div','正在读取…','navigation-message'); loading.setAttribute('role','status'); container.append(loading);
1947
+ },250);
764
1948
  try {
765
- let data = view.directoryCache?.get(entry) || (rootPage ? view.rootData : undefined);
766
- if (!data) data = await this.request(mode === 'changes'?'changes':'tree',{entry,page,prefetch:rootPage?1:undefined});
767
- if (!this.isConnected || generation !== view.generation) return;
768
- if (data.preloaded) { this.cacheMetadata(view,data); data = view.directoryCache.get(entry); }
1949
+ const preloaded = !force && page === 0 && view.directoryCache?.get(entry);
1950
+ const cached = !force && !preloaded && this.cachedDirectory(mode,entry,page);
1951
+ const data = preloaded || cached?.data || await this.fetchDirectory(mode,entry,page,force);
1952
+ if (!current()) return;
769
1953
  if (data.page !== page) throw new Error('目录内容发生变化,请刷新后重试。');
770
- loading.remove();
771
- view.gitError = data.gitError; if (data.gitError && page === 0) container.append(element('div','读取 Git 信息失败:'+data.gitError,'navigation-message error'));
772
- if (mode === 'changes') this.applyChangesMetadata(data);
773
- if (!data.total) container.append(element('div',data.notice || (mode === 'changes'?'没有尚未提交的改动。':'空目录'),'navigation-message'));
774
- const expandedLoads = [];
775
- for (const item of data.entries) {
776
- if (item.directory) {
777
- const details = element('details'), summary = element('summary'); summary.append(element('span',item.name)); summary.title = item.path;
778
- details.dataset.directory = item.path;
779
- directoryGitStatus(summary,item);
780
- const children = element('div'); details.append(summary,children); let loaded = false;
781
- const expandChildren = chain => {
782
- if (generation !== view.generation) return;
783
- if (!loaded && !item.blocked) { loaded = true; return this.loadDirectory(children,item.path,0,generation,mode,chain); }
784
- if (chain) return this.expandSingleDirectory(children);
785
- };
786
- details.loadChildren = () => expandChildren(false) || children.loading;
787
- if (page === 0 && data.total === 1 && data.entries.length === 1 && !item.blocked) {
788
- container.expandSingle = () => {
789
- if (generation !== view.generation) return;
790
- details.open = true; view.expanded.add(item.path); return expandChildren(true);
791
- };
792
- }
793
- if (item.blocked) { summary.setAttribute('aria-disabled','true'); this.notice(children,item.error); }
794
- details.addEventListener('toggle',() => {
795
- if (generation !== view.generation) return;
796
- const changed = view.expanded.has(item.path) !== details.open;
797
- if (details.open) view.expanded.add(item.path); else view.expanded.delete(item.path);
798
- if (details.open) expandChildren(changed);
799
- const app = this.closest('agentbot-workspace');
800
- if (changed && app?.filesPanel === this && !app.restoring) app.persistHistory(); else this.queuePersist();
801
- });
802
- container.append(details);
803
- if (view.expanded.has(item.path)) {
804
- details.open = true;
805
- if (!item.blocked) expandedLoads.push(expandChildren(expandChain));
806
- }
807
- } else container.append(this.createFileButton(item,mode));
808
- }
809
- view.pages.set(entry,data.page+1);
810
- if (data.page+1<data.totalPages && data.page+1<(view.restorePages.get(entry) || 1)) {
811
- expandedLoads.push(this.loadDirectory(container,entry,data.page+1,generation,mode));
812
- } else if (data.page+1<data.totalPages) {
1954
+ if (cached) this.recheckCachedDirectory(cached,entry);
1955
+ if (rootPage) this.cacheMetadata(view,data);
1956
+ directory.records[page] = rootPage && view.directoryCache ? view.directoryCache.get('') : data;
1957
+ view.failures.delete(entry);
1958
+ const next = page+1, restore = next < data.totalPages && next < (view.restorePages.get(entry) || 1)
1959
+ && (!conserveData() || Boolean(this.cachedDirectory(mode,entry,next)));
1960
+ if (!restore) {
1961
+ if (next < (view.restorePages.get(entry) || 1)) view.clampRestoredScroll = true;
813
1962
  view.restorePages.delete(entry);
814
- const continuation = element('div',Math.min((data.page+1)*100,data.total)+'/'+data.total+' · 向下滚动加载','navigation-message navigation-continuation');
815
- continuation.setAttribute('role','status'); container.append(continuation);
816
- const observer = new IntersectionObserver(entries => {
817
- if (!entries.some(item => item.isIntersecting) || !this.isConnected || !continuation.isConnected || generation !== view.generation || this.navigation !== view.node || view.node.clientHeight <= 0) return;
818
- let parent = continuation.parentElement.closest('details');
819
- while (parent) { if (!parent.open) return; parent = parent.parentElement.closest('details'); }
820
- continuation.loadNext();
821
- },{root:view.node,rootMargin:'120px 0px'});
822
- continuation.loadNext = () => {
823
- if (continuation.loading) return continuation.loading;
824
- if (!continuation.isConnected || generation !== view.generation) return;
825
- observer.disconnect(); view.observers.delete(observer); continuation.remove();
826
- return continuation.loading = this.loadDirectory(container,entry,data.page+1,generation,mode);
827
- };
828
- view.observers.add(observer); observer.observe(continuation);
829
- } else view.restorePages.delete(entry);
830
- if (expandChain) expandedLoads.push(this.expandSingleDirectory(container));
831
- await Promise.all(expandedLoads);
832
- this.updateCurrentFile();
833
- this.queuePersist();
1963
+ }
1964
+ const loads = this.renderDirectory(view,directory,mode,expandChain);
1965
+ if (restore) loads.push(this.loadDirectory(container,entry,next,generation,mode));
1966
+ if (expandChain) loads.push(this.expandSingleDirectory(container));
1967
+ await Promise.all(loads);
1968
+ this.updateCurrentFile(); this.queuePersist();
834
1969
  } catch (error) {
835
- if (this.isConnected && generation === view.generation) {
836
- if (mode === 'changes' && rootPage) this.showChangesCountError(error);
837
- loading.remove(); const failure = element('div'); container.append(failure);
838
- this.notice(failure,(mode === 'changes'?'读取未提交改动失败:':'')+error.message,() => { failure.remove(); this.loadDirectory(container,entry,page,generation,mode,expandChain); });
1970
+ if (current()) {
1971
+ if (mode === 'changes' && rootPage && !directory.records.length) this.showChangesCountError(error);
1972
+ this.directoryFailure(view,directory,error,() => this.loadDirectory(container,entry,page,generation,mode,expandChain,true));
1973
+ }
1974
+ } finally { clearTimeout(timer); loading?.remove(); view.pending--; directory.pending--; }
1975
+ }
1976
+ directoryFailure(view,directory,error,retry) {
1977
+ directory.failure?.remove(); view.failures.add(directory.entry);
1978
+ directory.failure = element('div',undefined,'directory-failure'); directory.container.append(directory.failure);
1979
+ this.notice(directory.failure,'读取目录失败:'+error.message,() => { directory.failure.remove(); retry(); });
1980
+ }
1981
+ forgetDirectory(view,container) {
1982
+ const directory = container.directoryState; if (!directory) return;
1983
+ if (directory.observer) { directory.observer.disconnect(); view.observers.delete(directory.observer); }
1984
+ view.directories.delete(directory.entry); view.pages.delete(directory.entry); view.failures.delete(directory.entry);
1985
+ for (const row of directory.rows.values()) if (row.dataset.directory) this.forgetDirectory(view,row.lastElementChild);
1986
+ }
1987
+ renderDirectory(view,directory,mode,expandChain = false) {
1988
+ const {container,entry,records} = directory, data = records.at(-1), first = records[0];
1989
+ const generation = view.generation, loads = [], rows = new Map();
1990
+ const active = document.activeElement, top = view.node.scrollTop;
1991
+ let focus;
1992
+ if (!entry && mode === 'changes') this.applyChangesMetadata(first);
1993
+ if (!entry) view.gitError = first.gitError;
1994
+ const messages = [];
1995
+ if (!entry && first.gitError) messages.push(element('div','读取 Git 信息失败:'+first.gitError,'navigation-message error'));
1996
+ if (!first.total) messages.push(element('div',first.notice || (mode === 'changes'?'没有尚未提交的改动。':'空目录'),'navigation-message'));
1997
+ container.expandSingle = undefined;
1998
+ for (const item of records.flatMap(page => page.entries)) {
1999
+ if (rows.has(item.path)) continue;
2000
+ const old = directory.rows.get(item.path), signature = JSON.stringify(item);
2001
+ let row;
2002
+ if (item.directory) {
2003
+ row = old?.dataset.directory ? old : this.createDirectoryRow(view,item.path,mode,generation);
2004
+ if (row.signature !== signature) {
2005
+ const summary = row.firstElementChild;
2006
+ summary.replaceChildren(element('span',item.name)); summary.classList.remove('is-git-ignored'); summary.removeAttribute('aria-label'); directoryGitStatus(summary,item);
2007
+ summary.toggleAttribute('aria-disabled',Boolean(item.blocked));
2008
+ if (item.blocked) { this.forgetDirectory(view,row.lastElementChild); row.lastElementChild.directoryState = undefined; this.notice(row.lastElementChild,item.error); }
2009
+ else if (row.blocked) row.lastElementChild.replaceChildren();
2010
+ row.blocked = item.blocked; row.signature = signature;
2011
+ }
2012
+ if (!old && view.expanded.has(item.path)) row.open = true;
2013
+ if (!item.blocked && first.total === 1) container.expandSingle = () => {
2014
+ row.open = true; view.expanded.add(item.path); return row.loadChildren(true);
2015
+ };
2016
+ if (row.open && !item.blocked && !row.lastElementChild.directoryState) {
2017
+ if (!conserveData() || expandChain || view.directoryCache?.has(item.path) || this.cachedDirectory(mode,item.path,0)) loads.push(() => row.loadChildren(expandChain));
2018
+ else if (!row.openObserver) {
2019
+ const observer = row.openObserver = new IntersectionObserver(entries => {
2020
+ if (!entries.some(value => value.isIntersecting) || !row.open || this.navigation !== view.node) return;
2021
+ observer.disconnect(); view.observers.delete(observer); row.openObserver = undefined; row.loadChildren();
2022
+ },{root:view.node});
2023
+ view.observers.add(observer); observer.observe(row.firstElementChild);
2024
+ }
2025
+ }
2026
+ } else {
2027
+ row = old?.signature === signature ? old : this.createFileButton(item,mode);
2028
+ row.signature = signature;
2029
+ if (old && old !== row && old === active) focus = row;
2030
+ }
2031
+ rows.set(item.path,row);
2032
+ }
2033
+ for (const [key,row] of directory.rows) if (rows.get(key) !== row && row.dataset.directory) {
2034
+ if (row.openObserver) { row.openObserver.disconnect(); view.observers.delete(row.openObserver); }
2035
+ this.forgetDirectory(view,row.lastElementChild);
2036
+ }
2037
+ directory.rows = rows;
2038
+ view.pages.set(entry,records.length);
2039
+ if (directory.observer) { directory.observer.disconnect(); view.observers.delete(directory.observer); directory.observer = undefined; }
2040
+ if (records.length < data.totalPages && records.length >= (view.restorePages.get(entry) || 1)) {
2041
+ const continuation = element('div',Math.min(records.length*100,data.total)+'/'+data.total+' · 向下滚动加载','navigation-message navigation-continuation');
2042
+ continuation.setAttribute('role','status');
2043
+ const observer = directory.observer = new IntersectionObserver(entries => {
2044
+ if (!entries.some(item => item.isIntersecting) || this.navigation !== view.node || view.node.clientHeight <= 0) return;
2045
+ for (let parent = continuation.parentElement?.closest('details'); parent; parent = parent.parentElement.closest('details')) if (!parent.open) return;
2046
+ continuation.loadNext();
2047
+ },{root:view.node,rootMargin:conserveData()?'0px':'120px 0px'});
2048
+ continuation.loadNext = () => {
2049
+ if (continuation.loading) return continuation.loading;
2050
+ if (!continuation.isConnected || generation !== view.generation) return;
2051
+ observer.disconnect(); view.observers.delete(observer); continuation.remove();
2052
+ return continuation.loading = this.loadDirectory(container,entry,records.length,generation,mode);
2053
+ };
2054
+ view.observers.add(observer); observer.observe(continuation); messages.push(continuation);
2055
+ }
2056
+ directory.failure = undefined;
2057
+ const nodes = [...rows.values(),...messages], keep = new Set(nodes);
2058
+ for (const child of [...container.children]) if (!keep.has(child)) child.remove();
2059
+ let next = container.firstElementChild;
2060
+ for (const node of nodes) { if (node !== next) container.insertBefore(node,next); next = node.nextElementSibling; }
2061
+ if (view.node === this.navigation && view.node.clientHeight > 0) { this.reserveTreeScroll(top); view.node.scrollTop = top; }
2062
+ (focus || (active && container.contains(active) && document.activeElement !== active ? active : undefined))?.focus({preventScroll:true});
2063
+ return loads.map(load => load());
2064
+ }
2065
+ createDirectoryRow(view,entry,mode,generation) {
2066
+ const details = element('details'), summary = element('summary'), children = element('div');
2067
+ details.dataset.directory = entry; summary.dataset.tooltip = entry; summary.dataset.tooltipOverflow = ':scope > span:first-of-type'; details.append(summary,children);
2068
+ details.loadChildren = (chain = false) => {
2069
+ if (generation !== view.generation || details.blocked) return;
2070
+ if (details.openObserver) { details.openObserver.disconnect(); view.observers.delete(details.openObserver); details.openObserver = undefined; }
2071
+ if (!children.directoryState) return this.loadDirectory(children,entry,0,generation,mode,chain);
2072
+ if (children.directoryState.dirty) this.queueFileSync({paths:[entry]});
2073
+ if (chain && !children.directoryState.pending) return this.expandSingleDirectory(children);
2074
+ return children.loading;
2075
+ };
2076
+ details.addEventListener('toggle',() => {
2077
+ if (generation !== view.generation || !view.node.contains(details)) return;
2078
+ const changed = view.expanded.has(entry) !== details.open;
2079
+ if (details.open) {
2080
+ view.expanded.add(entry);
2081
+ if (changed || !details.openObserver) details.loadChildren(changed);
2082
+ } else view.expanded.delete(entry);
2083
+ const app = this.closest('agentbot-workspace');
2084
+ if (changed && app?.filesPanel === this && !app.restoring) app.persistHistory(); else this.queuePersist();
2085
+ });
2086
+ const warm = () => this.warmDirectory(mode,entry);
2087
+ summary.addEventListener('pointerenter',warm); summary.addEventListener('focus',warm);
2088
+ return details;
2089
+ }
2090
+ warmDirectory(mode,entry) {
2091
+ const view = this.navigationView(mode);
2092
+ if (conserveData() || !this.liveReady || this.hidden || !this.isConnected || view.directoryCache || this.cachedDirectory(mode,entry,0)) return;
2093
+ if (this.directoryReads?.has(this.directoryKey(mode,entry,0)) || (this.warming || 0) >= 3) return;
2094
+ this.warming = (this.warming || 0)+1;
2095
+ void this.fetchDirectory(mode,entry,0).catch(() => {}).finally(() => { this.warming--; });
2096
+ }
2097
+ warmDirectories() {
2098
+ if (conserveData() || !this.liveReady || this.hidden || this.warmTimer) return;
2099
+ this.warmTimer = setTimeout(() => {
2100
+ this.warmTimer = undefined;
2101
+ if (this.hidden || !this.isConnected || !this.liveReady || document.hidden || this.navigation.clientHeight <= 0) return;
2102
+ this.warmChildren(this.navigationView(this.listMode),this.listMode);
2103
+ },220);
2104
+ }
2105
+ warmChildren(view,mode) {
2106
+ if (view.directoryCache || this.warmedMode === mode) return;
2107
+ const root = view.directories.get(''); if (!root?.records.length) return;
2108
+ this.warmedMode = mode;
2109
+ for (const row of [...root.rows.values()].filter(row => row.dataset.directory && !row.blocked && !row.open).slice(0,3)) this.warmDirectory(mode,row.dataset.directory);
2110
+ }
2111
+ directoryVisible(view,directory) {
2112
+ if (!directory.entry) return true;
2113
+ if (this.navigation !== view.node || view.node.clientHeight <= 0) return false;
2114
+ for (let parent = directory.container.closest('details'); parent; parent = parent.parentElement.closest('details')) if (!parent.open) return false;
2115
+ const region = directory.container.parentElement.getBoundingClientRect(), viewport = view.node.getBoundingClientRect();
2116
+ return region.bottom >= viewport.top && region.top <= viewport.bottom;
2117
+ }
2118
+ pageVisible(view,directory,page) {
2119
+ const entries = directory.records[page].entries, first = directory.rows.get(entries[0]?.path), last = directory.rows.get(entries.at(-1)?.path);
2120
+ if (!first || !last) return false;
2121
+ const viewport = view.node.getBoundingClientRect();
2122
+ return first.getBoundingClientRect().top <= viewport.bottom && last.getBoundingClientRect().bottom >= viewport.top;
2123
+ }
2124
+ resumeDirtyDirectories() {
2125
+ const view = this.navigationView(this.listMode);
2126
+ const paths = [...view.directories.values()].filter(directory => this.directoryVisible(view,directory)
2127
+ && (directory.dirty || [...directory.dirtyPages || []].some(page => this.pageVisible(view,directory,page)))).map(directory=>directory.entry);
2128
+ if (paths.length || view.needsSync) this.queueFileSync(view.needsSync?{reset:true}:{paths});
2129
+ }
2130
+ queueFileSync(change) {
2131
+ const queued = this.fileChanges ??= {paths:new Set(),git:false,reset:false};
2132
+ queued.git ||= Boolean(change.git); queued.reset ||= Boolean(change.reset);
2133
+ for (const entry of change.paths || []) { if (queued.paths.size >= 64) { queued.reset = true; queued.paths.clear(); break; } queued.paths.add(entry); }
2134
+ if (this.syncTimer || this.syncingFiles || this.hidden || !this.isConnected || document.hidden) return;
2135
+ const delay = conserveData() ? Math.max(350,2000-(Date.now()-(this.lastFileSync || 0))) : 350;
2136
+ this.syncTimer = setTimeout(async () => {
2137
+ this.syncTimer = undefined;
2138
+ if (this.hidden || !this.isConnected || document.hidden) return;
2139
+ const update = this.fileChanges, nav = this.navigationViews;
2140
+ this.fileChanges = undefined; this.syncingFiles = true; this.lastFileSync = Date.now();
2141
+ try {
2142
+ const mode = this.listMode;
2143
+ this.navigationView(mode === 'files'?'changes':'files').needsSync = true;
2144
+ if (this.navigation.clientHeight > 0) {
2145
+ await this.refreshTree(mode,update);
2146
+ if (nav === this.navigationViews && !this.hidden && this.isConnected && this.listMode === 'files') await this.updateChangesSummary();
2147
+ } else this.navigationView(mode).needsSync = true;
2148
+ if (nav !== this.navigationViews || this.hidden || !this.isConnected) return;
2149
+ this.updateChangedPreviews(update);
2150
+ this.warmDirectories();
2151
+ } finally {
2152
+ this.syncingFiles = false;
2153
+ if (this.fileChanges) this.queueFileSync({});
839
2154
  }
840
- } finally { view.pending--; }
2155
+ },350);
2156
+ }
2157
+ async refreshTree(mode,change,manual = false) {
2158
+ const view = this.navigationView(mode);
2159
+ if (view.refreshing) { if (!manual) await view.refreshing; else { await view.refreshing; if (this.isConnected && this.navigationViews.get(mode) === view) return this.refreshTree(mode,change,true); } return; }
2160
+ const work = async () => {
2161
+ if (!view.ready && view.loading) await view.loading;
2162
+ if (!this.isConnected || this.navigationViews.get(mode) !== view) return;
2163
+ const generation = view.generation;
2164
+ const current = () => this.isConnected && view.generation === generation;
2165
+ const root = view.directories.get(''), lean = !manual && conserveData();
2166
+ let rootData;
2167
+ try {
2168
+ rootData = await this.fetchDirectory(mode,'',0,manual);
2169
+ if (!current()) return;
2170
+ if (!root) { if (mode === 'changes') this.applyChangesMetadata(rootData); view.needsSync = false; return; }
2171
+ this.cacheMetadata(view,rootData);
2172
+ } catch (error) {
2173
+ if (current() && root) this.directoryFailure(view,root,error,() => this.refreshTree(mode,change,true));
2174
+ else if (current() && mode === 'changes' && !this.querySelector('[data-list=changes] .count-badge').textContent) this.showChangesCountError(error);
2175
+ return;
2176
+ }
2177
+ const matches = entry => change.reset || change.git || mode === 'changes' || !entry || [...change.paths].some(value => {
2178
+ const key = this.pathKey(value), folder = this.pathKey(entry);
2179
+ return key === folder || key.startsWith(folder+'/') || folder.startsWith(key+'/');
2180
+ });
2181
+ const directories = [...view.directories.values()].filter(directory => {
2182
+ if (!directory.dirty && !matches(directory.entry)) return false;
2183
+ if (!manual && !this.directoryVisible(view,directory)) { directory.dirty = true; return false; }
2184
+ return true;
2185
+ });
2186
+ const refresh = async directory => {
2187
+ const {entry,container} = directory;
2188
+ if (directory.pending) await container.loading;
2189
+ if (!current() || view.directories.get(entry) !== directory) return;
2190
+ try {
2191
+ const full = view.directoryCache?.get(entry);
2192
+ if (view.directoryCache && !full) return;
2193
+ const first = full || (!entry ? rootData : await this.fetchDirectory(mode,entry,0));
2194
+ const records = [first], count = Math.min(first.totalPages,Math.max(directory.records.length,view.restorePages.get(entry) || 1));
2195
+ directory.dirtyPages = new Set();
2196
+ for (let page = 1; page < count; page++) {
2197
+ if (!current() || view.directories.get(entry) !== directory) return;
2198
+ const previous = directory.records[page];
2199
+ if (!manual && previous && !this.pageVisible(view,directory,page)) {
2200
+ records.push(previous); directory.dirtyPages.add(page); continue;
2201
+ }
2202
+ const data = await this.fetchDirectory(mode,entry,page);
2203
+ if (data.page !== page) break;
2204
+ records.push(data);
2205
+ }
2206
+ if (!current() || view.directories.get(entry) !== directory) return;
2207
+ directory.dirty = false;
2208
+ const unchanged = !directory.failure && directory.records.length === records.length && records.every((data,index) => data === directory.records[index]);
2209
+ if (!unchanged) {
2210
+ directory.records = records; view.failures.delete(entry); view.restorePages.delete(entry);
2211
+ await Promise.all(this.renderDirectory(view,directory,mode));
2212
+ }
2213
+ } catch (error) {
2214
+ if (current() && view.directories.get(entry) === directory && error.status !== 404) this.directoryFailure(view,directory,error,() => this.refreshTree(mode,change,true));
2215
+ }
2216
+ };
2217
+ if (root) await refresh(root);
2218
+ let next = 1;
2219
+ await Promise.all(Array.from({length:Math.min(lean?1:3,directories.length-1)},async () => {
2220
+ while (current() && next < directories.length) await refresh(directories[next++]);
2221
+ }));
2222
+ if (!current()) return;
2223
+ view.needsSync = false;
2224
+ if (view.query) void this.filterNavigation(mode,true);
2225
+ this.updateCurrentFile(); this.queuePersist();
2226
+ };
2227
+ view.refreshing = work();
2228
+ try { await view.refreshing; } finally { view.refreshing = undefined; }
2229
+ }
2230
+ updateChangedPreviews(change) {
2231
+ const matches = tab => change.reset || change.git || [...change.paths].some(value => {
2232
+ const key = this.pathKey(value), entry = this.pathKey(tab.path);
2233
+ return entry === key || entry.startsWith(key+'/');
2234
+ });
2235
+ const revision = {};
2236
+ for (const views of this.views.values()) for (const tab of views.values()) if (['file','diff'].includes(tab.kind) && tab.source === (this.explorerDirectory || undefined) && matches(tab)) tab.stale = revision;
2237
+ const tab = this.tabs.get(this.activeKey);
2238
+ if (tab?.stale) void this.refreshLivePreview(tab);
2239
+ }
2240
+ async refreshLivePreview(tab) {
2241
+ const visible = () => this.isConnected && !this.hidden && !document.hidden && this.content.clientHeight > 0;
2242
+ if (!visible() || !tab.preview || this.loadingTab || this.livePreview || this.toolbar.contains(document.activeElement)) return;
2243
+ const generation = this.generation, revision = tab.stale, preview = tab.preview;
2244
+ this.livePreview = true;
2245
+ const current = () => visible() && generation === this.generation && tab.stale === revision && this.tabs.get(this.activeKey) === tab;
2246
+ const hint = this.toolbar.querySelector('.launch-hint');
2247
+ try {
2248
+ let etag;
2249
+ const data = await this.request(tab.kind,{entry:tab.path,mode:tab.mode,original:tab.original},undefined,
2250
+ {etag:preview.etag,data:preview}, value => { etag = value; },this.previewApi(tab.source));
2251
+ if (!current() || this.toolbar.contains(document.activeElement)) return;
2252
+ if (data.html === preview.html && JSON.stringify(data.change) === JSON.stringify(preview.change)
2253
+ && data.gitError === preview.gitError && data.canViewFile === preview.canViewFile) {
2254
+ preview.etag = etag; tab.stale = undefined;
2255
+ if (hint) { hint.textContent = data.gitError ? '读取 Git 状态失败:'+data.gitError : ''; hint.hidden = !data.gitError; }
2256
+ } else { this.saveScroll(); await this.loadTab(tab,true,{...data,etag}); }
2257
+ } catch (error) {
2258
+ if (current() && hint) { hint.textContent = error.status === 404 ? '该文件已移动或删除,下方保留上一次预览。' : '预览暂未更新:'+error.message; hint.hidden = false; }
2259
+ } finally {
2260
+ this.livePreview = false;
2261
+ const active = this.tabs.get(this.activeKey);
2262
+ if (active?.stale && active.stale !== revision) void this.refreshLivePreview(active);
2263
+ }
841
2264
  }
842
2265
  activateTab(key) {
2266
+ if (key !== this.activeKey) this.clearPreviewCaret();
843
2267
  this.activeKey = key; this.recentTabs = this.recentTabs.filter(current => current !== key && this.tabs.has(current));
844
2268
  if (key) this.recentTabs.push(key);
845
2269
  }
846
- tabView(key, path, kind, original) {
2270
+ tabView(key, path, kind, original, source) {
847
2271
  let views = this.views.get(key); if (!views) { views = new Map(); this.views.set(key,views); }
848
- const viewKey = kind+':'+path; let tab = views.get(viewKey);
849
- if (!tab) { tab = {key,path,kind,original,mode:'all',scrollTop:0,scrollLeft:0}; views.set(viewKey,tab); }
2272
+ const viewKey = previewKey(kind,path,source); let tab = views.get(viewKey);
2273
+ if (!tab) { tab = {key,path,kind,original,source,mode:'all',scrollTop:0,scrollLeft:0}; views.set(viewKey,tab); }
850
2274
  return tab;
851
2275
  }
852
2276
  showTab(tab) {
@@ -855,14 +2279,15 @@
855
2279
  this.renderTabs(); this.restoreScroll(); this.loadTab(tab);
856
2280
  }
857
2281
  closeViews(key) { for (const tab of this.views.get(key)?.values() || []) { tab.titleController?.abort(); tab.frame?.remove(); tab.frame = tab.preview = undefined; } this.views.delete(key); }
858
- openFile(path, kind, original, hash, replaceKey) {
2282
+ openFile(path, kind, original, hash, replaceKey, source) {
859
2283
  this.navigate(() => {
860
2284
  this.saveScroll(); this.dataset.view = 'content';
861
- let tab = [...this.tabs.values()].find(tab => this.pathKey(tab.path) === this.pathKey(path) && tab.kind === kind);
862
- if (tab && ['file','diff'].includes(kind)) { if (original !== undefined) tab.original = original; if (hash) tab.hash = tab.requestedHash = hash; this.showTab(tab); this.revealActiveTab(); return; }
2285
+ const root = this.previewRoot(source);
2286
+ let tab = [...this.tabs.values()].find(tab => tab.kind === kind && tab.source === source && projectPath(tab.path,root) === projectPath(path,root));
2287
+ if (tab && ['file','diff','directory'].includes(kind)) { if (original !== undefined) tab.original = original; if (hash) tab.hash = tab.requestedHash = hash; this.showTab(tab); this.revealActiveTab(); return; }
863
2288
  const replace = replaceKey === this.activeKey && this.tabs.get(replaceKey)?.kind === 'new';
864
2289
  if (!tab || replace) {
865
- tab ??= this.tabView(replace?replaceKey:kind==='new'?path:instanceId(),path,kind,original);
2290
+ tab ??= this.tabView(replace?replaceKey:kind==='new'?path:instanceId(),path,kind,original,source);
866
2291
  const key = tab.key;
867
2292
  const tabs = new Map();
868
2293
  for (const [currentKey,current] of this.tabs) {
@@ -881,46 +2306,111 @@
881
2306
  });
882
2307
  }
883
2308
  openNew() { this.openFile(instanceId(),'new'); }
884
- navigateAddress(path, kind, tabKey, hash) {
2309
+ prepareAddressFile() {
2310
+ if (this.choosingDirectory && this.treeApi) this.showDirectoryChooser(false);
2311
+ this.selectList('files');
2312
+ if (this.navigationView('files').query) { this.search.value = ''; this.setFilter(''); }
2313
+ }
2314
+ openAndRevealFile(path) {
2315
+ this.navigate(() => { this.prepareAddressFile(); this.openFile(path,'file'); });
2316
+ void this.revealCurrentFile(true,true);
2317
+ }
2318
+ addressSource(tab) { return tab?.kind === 'new' ? this.explorerDirectory || undefined : tab?.source; }
2319
+ navigateAddress(path, kind, tabKey, hash, source) {
885
2320
  this.navigate(() => {
886
2321
  const current = this.tabs.get(tabKey);
887
2322
  if (kind === 'file') {
888
- const existing = [...this.tabs.values()].find(tab => tab.kind === 'file' && this.pathKey(tab.path) === this.pathKey(path));
889
- if (existing) { current.draft = existing.draft = undefined; this.openFile(path,kind,undefined,hash); return; }
2323
+ if (source === (this.explorerDirectory || undefined)) this.prepareAddressFile();
2324
+ const root = this.previewRoot(source);
2325
+ const existing = [...this.tabs.values()].find(tab => tab.kind === kind && tab.source === source && projectPath(tab.path,root) === projectPath(path,root));
2326
+ if (existing) { current.draft = existing.draft = undefined; this.openFile(path,kind,undefined,hash,undefined,source); return; }
890
2327
  }
891
- this.saveScroll(); const tab = this.tabView(tabKey,path,kind); current.draft = tab.draft = undefined;
2328
+ this.saveScroll(); const tab = this.tabView(tabKey,path,kind,undefined,source); current.draft = tab.draft = undefined;
892
2329
  if (kind === 'file') tab.hash = tab.requestedHash = hash;
893
2330
  this.showTab(tab);
894
2331
  });
2332
+ if (kind === 'file') void this.revealCurrentFile(true,true,true);
2333
+ }
2334
+ navigateDirectoryAddress(path, tabKey, entry) {
2335
+ this.navigate(() => {
2336
+ this.saveScroll();
2337
+ const current = this.tabs.get(tabKey);
2338
+ const tab = [...this.tabs.values()].find(tab => tab.kind === 'directory' && tab.path === path) || this.tabView(tabKey,path,'directory');
2339
+ current.draft = tab.draft = undefined;
2340
+ tab.directoryEntry = entry;
2341
+ tab.pendingDirectoryEntry = true;
2342
+ this.showTab(tab); this.revealActiveTab();
2343
+ });
895
2344
  }
896
2345
  async openAddress(value, source, tabKey, selectedPath) {
897
2346
  const current = this.tabs.get(tabKey), picker = this.addressPicker; if (!current || tabKey !== this.activeKey || !picker) return;
2347
+ current.draft = value;
898
2348
  picker.lookupController?.abort(); const submission = picker.submission = (picker.submission || 0)+1;
899
2349
  const pane = this.closest('agentbot-workspace').dataset.pane, view = this.dataset.view;
900
2350
  const active = () => this.addressPicker === picker && picker.submission === submission && picker.input.isConnected && picker.input.value === value && this.activeKey === tabKey && this.tabs.get(tabKey) === current && this.dataset.view === view && this.closest('agentbot-workspace').dataset.pane === pane;
901
2351
  this.hideAddressSuggestions(picker);
902
2352
  try {
903
- const input = value.trim(); if (!input) throw new Error('请输入项目文件路径或 HTTP / HTTPS 网址。');
2353
+ const input = value.trim().replace(/^"(.+)"$/u,'$1'); if (!input) throw new Error('请输入本地文件、目录路径或 HTTP / HTTPS 网址。');
904
2354
 
905
- if (input.startsWith('#')) {
906
- if (['file','diff'].includes(current.kind)) { this.navigate(() => { current.draft = undefined; current.hash = current.requestedHash = input; this.restoreHash(current); }); return; }
907
- if (current.kind === 'web') { this.navigateAddress(webAddress(new URL(input,current.path).toString()),'web',tabKey); return; }
2355
+ const scope = this.addressSource(current), api = this.previewApi(scope);
2356
+ const base = current.kind === 'directory' ? this.directory(current.path)?.path : this.previewRoot(scope);
2357
+ if (['file','diff'].includes(current.kind)) {
2358
+ const line = parseAddressLine(input);
2359
+ const sameFile = line && (!line.path || projectPath(line.path.replaceAll('\\','/'),base) === projectPath(current.path,base));
2360
+ const hash = input.startsWith('#') ? input : sameFile ? line.hash : undefined;
2361
+ if (hash) { this.navigate(() => { current.draft = undefined; current.hash = current.requestedHash = hash; this.restoreHash(current); }); return; }
908
2362
  }
909
- const target = fileAddress(input,this.projectRoot);
910
- if (selectedPath !== undefined) { this.navigateAddress(selectedPath,'file',tabKey,this.pathKey(target?.path) === this.pathKey(selectedPath)?target?.hash:undefined); return; }
2363
+ if (input.startsWith('#') && current.kind === 'web') { this.navigateAddress(webAddress(new URL(input,current.path).toString()),'web',tabKey); return; }
2364
+ const hostPath = localAddress(input) ? input : base && /^\.{1,2}(?:[\\/]|$)/u.test(input)
2365
+ ? base.replace(/[\\/]+$/u,'')+'/'+input.replaceAll('\\','/') : undefined;
2366
+ const canOpenLocal = Boolean(hostPath && (appBase || embedded && window.parent !== window));
2367
+ let target;
2368
+ try { if (api && base && current.kind !== 'directory') target = fileAddress(input,base); }
2369
+ catch (error) { if (!canOpenLocal) throw error; }
2370
+ if (selectedPath !== undefined) { this.navigateAddress(selectedPath,'file',tabKey,projectPath(target?.path,base) === projectPath(selectedPath,base)?target?.hash:undefined,scope); return; }
911
2371
  if (target) {
912
2372
  picker.lookupController = new AbortController(); picker.input.setAttribute('aria-busy','true');
913
2373
  let entry = target.path; if (target.literal) try { entry = relativePath(target.literal); } catch {}
914
- let data = await this.request('address',{entry},picker.lookupController), hash = entry === target.path?target.hash:undefined;
2374
+ let data = await this.request('address',{entry},picker.lookupController,undefined,undefined,api), hash = entry === target.path?target.hash:undefined;
915
2375
  if (!active()) return;
916
2376
  if (data.exact === undefined && entry !== target.path) {
917
- data = await this.request('address',{entry:target.path},picker.lookupController); hash = target.hash;
2377
+ data = await this.request('address',{entry:target.path},picker.lookupController,undefined,undefined,api); hash = target.hash;
918
2378
  if (!active()) return;
919
2379
  }
920
- if (data.exact !== undefined) { this.navigateAddress(data.exact,'file',tabKey,hash); return; }
2380
+ if (data.exact !== undefined) { this.navigateAddress(data.exact,'file',tabKey,hash,scope); return; }
921
2381
  }
2382
+ if (canOpenLocal) {
2383
+ if (!active()) return;
2384
+ if (embedded) {
2385
+ window.parent.postMessage({type:'agentbot-workspace-open-local-directory',address:hostPath},window.location.origin);
2386
+ return;
2387
+ }
2388
+ const sessions = this.closest('agentbot-workspace').sessions;
2389
+ picker.lookupController = new AbortController(); picker.input.setAttribute('aria-busy','true');
2390
+ await sessions?.sessionCheck;
2391
+ if (!active()) return;
2392
+ if (!sessions?.csrf) throw Object.assign(new Error('登录工作台后即可打开外部路径。'),{login:true});
2393
+ const {entry,...directory} = await sessions.fetch('/directory',{body:{address:hostPath},signal:picker.lookupController.signal});
2394
+ if (!active()) return;
2395
+ const id = localDirectoryPrefix+directory.id; this.localDirectories.set(id,directory);
2396
+ this.navigateDirectoryAddress(id,tabKey,entry);
2397
+ return;
2398
+ }
2399
+ if (embedded) throw new Error('未找到对应的目录内文件。');
922
2400
  if (active()) this.navigateAddress(addressTarget(input),'web',tabKey);
923
- } catch (error) { if (active()) { source.textContent = error.message; source.hidden = false; source.classList.add('workspace-address-error'); } }
2401
+ } catch (error) {
2402
+ if (active()) {
2403
+ source.textContent = error.message; source.hidden = false; source.classList.add('workspace-address-error');
2404
+ if (error.login) {
2405
+ const login = element('button','登录'); login.type = 'button';
2406
+ login.onclick = () => {
2407
+ const app = this.closest('agentbot-workspace');
2408
+ app.sessions.showLogin(() => app.navigate(() => app.selectPane('files')));
2409
+ };
2410
+ source.append(' ',login);
2411
+ }
2412
+ }
2413
+ }
924
2414
  finally { if (this.addressPicker === picker && picker.submission === submission) picker.input.removeAttribute('aria-busy'); }
925
2415
  }
926
2416
  hideAddressSuggestions(picker = this.addressPicker) {
@@ -946,8 +2436,10 @@
946
2436
  }
947
2437
  async suggestAddress(picker, direction) {
948
2438
  this.hideAddressSuggestions(picker); const value = picker.input.value, input = value.trim();
949
- let target; try { target = input && !input.startsWith('#') ? fileAddress(input,this.projectRoot) : undefined; } catch { return; }
950
- const query = (target?.literal || target?.path)?.replaceAll('\\','/'); if (!query) return; try { relativePath(query); } catch { return; }
2439
+ const tab = this.tabs.get(picker.key), source = this.addressSource(tab), root = this.previewRoot(source), api = this.previewApi(source);
2440
+ if (tab?.kind === 'directory') return;
2441
+ let target; try { target = api && root && input && !input.startsWith('#') ? fileAddress(input,root) : undefined; } catch { return; }
2442
+ const query = target?.query; if (!query) return; try { relativePath(query); } catch { return; }
951
2443
  const sequence = picker.sequence, active = () => this.addressPicker === picker && sequence === picker.sequence && picker.input.isConnected && picker.input.value === value;
952
2444
  picker.value = value;
953
2445
  const show = (items, message, error = false) => {
@@ -955,7 +2447,8 @@
955
2447
  picker.items = items; picker.list.replaceChildren(); picker.list.hidden = false; picker.input.setAttribute('aria-expanded','true'); picker.input.removeAttribute('aria-busy');
956
2448
  for (const [index,item] of items.entries()) {
957
2449
  const option = element('button',undefined,'address-option'); option.type = 'button'; option.tabIndex = -1; option.id = picker.list.id+'-'+index;
958
- option.setAttribute('role','option'); option.setAttribute('aria-selected','false'); option.title = item.path; option.append(fileIcon(item.path),element('span',item.path));
2450
+ option.setAttribute('role','option'); option.setAttribute('aria-selected','false'); option.dataset.tooltip = item.path;
2451
+ option.dataset.tooltipOverflow = ':scope > span'; option.append(fileIcon(item.path),element('span',item.path));
959
2452
  option.onpointerdown = event => { if (event.button === 0) event.preventDefault(); };
960
2453
  option.onclick = () => { if (active() && option.isConnected && !picker.list.hidden) this.openAddress(value,picker.hint,picker.key,item.path); };
961
2454
  picker.list.append(option);
@@ -964,7 +2457,7 @@
964
2457
  if (direction && items.length) this.selectAddressOption(picker,direction > 0?0:items.length-1);
965
2458
  };
966
2459
  if (query.length > 160) { show([],'路径较长,请输入完整路径后按回车。'); return; }
967
- const preloaded = this.navigationViews.get('files')?.preloaded;
2460
+ const preloaded = api === this.treeApi ? this.navigationViews.get('files')?.preloaded : undefined;
968
2461
  if (preloaded) {
969
2462
  const matches = preloaded.filter(item => !item.directory && !item.blocked && item.path.toLowerCase().includes(query.toLowerCase())).sort((a,b) => a.path.localeCompare(b.path,undefined,{numeric:true}));
970
2463
  show(matches.slice(0,20),matches.length > 20?'还有更多匹配,请继续输入路径。':matches.length?'':'没有匹配的文件;按回车打开输入地址。'); return;
@@ -974,13 +2467,14 @@
974
2467
  if (!active()) return;
975
2468
  picker.controller = new AbortController();
976
2469
  try {
977
- const data = await this.request('address',{entry:query,query},picker.controller);
2470
+ const data = await this.request('address',{entry:query,query},picker.controller,undefined,undefined,api);
978
2471
  if (!active()) return;
979
2472
  show(data.entries,data.truncated?'匹配结果未完整显示,请继续输入路径。':data.entries.length?'':'没有匹配的文件;按回车打开输入地址。');
980
2473
  } catch (error) { if (active()) show([],'读取匹配文件失败:'+error.message,true); }
981
2474
  },180);
982
2475
  }
983
- tabTitle(tab) { return tab.kind === 'new'?'新标签':tab.kind === 'terminal'?'Terminal':tab.kind === 'web'?tab.pageTitle || tab.path:tab.path.split('/').pop(); }
2476
+ directory(id) { return isLocalDirectory(id) ? this.localDirectories.get(id) : this.taskDirectories?.find(item => item.id === id); }
2477
+ tabTitle(tab) { return tab.kind === 'directory'?this.directory(tab.path)?.name || '任务目录':tab.kind === 'new'?'新标签':tab.kind === 'terminal'?'Terminal':tab.kind === 'web'?tab.pageTitle || tab.path:tab.path.split('/').pop(); }
984
2478
  async loadWebTitle(tab, refresh = false) {
985
2479
  if (tab.titleRead && !refresh) return;
986
2480
  tab.titleRead = true; tab.titleController?.abort(); const controller = tab.titleController = new AbortController();
@@ -997,13 +2491,13 @@
997
2491
  const current = this.tabs.get(this.activeKey), framed = Boolean(current?.frame);
998
2492
  this.dataset.fileTab = String(Boolean(current && ['file','diff'].includes(current.kind)));
999
2493
  if (this.dataset.fileTab === 'false') this.explorerToggle.remove();
1000
- this.dataset.specialTab = String(Boolean(current && ['new','web','terminal'].includes(current.kind)));
2494
+ this.dataset.specialTab = String(Boolean(current && ['new','web','terminal','directory'].includes(current.kind)));
1001
2495
  this.frameLayer.hidden = !framed; this.content.hidden = framed;
1002
2496
  for (const views of this.views.values()) for (const tab of views.values()) if (tab.frame) {
1003
2497
  tab.frame.hidden = tab.frame !== current?.frame;
1004
- if (tab.kind === 'terminal') {
1005
- const visible = !tab.frame.hidden && tab.frame.clientHeight > 0;
1006
- const start = visible && tab.frameReady && tab.startTerminal === true;
2498
+ if (tab.kind === 'terminal' || tab.kind === 'directory') {
2499
+ const visible = !this.hidden && !tab.frame.hidden && tab.frame.clientHeight > 0;
2500
+ const start = visible && tab.kind === 'terminal' && tab.frameReady && tab.startTerminal === true;
1007
2501
  tab.frame.contentWindow?.postMessage({type:'agentbot-workspace-visibility',visible,start},window.location.origin);
1008
2502
  if (start) tab.startTerminal = false;
1009
2503
  }
@@ -1013,7 +2507,7 @@
1013
2507
  this.disposeAddressPicker();
1014
2508
  const address = element('div',undefined,'workspace-address'), field = element('div',undefined,'workspace-address-field'), input = element('input'), list = element('div',undefined,'address-options');
1015
2509
  list.id = 'workspace-address-options-'+instanceId(); list.setAttribute('role','listbox'); list.setAttribute('aria-label','匹配的项目文件'); list.hidden = true;
1016
- input.placeholder = '文件路径或 https://…'; input.setAttribute('aria-label','文件路径或网页地址'); input.maxLength = 4096; input.autocomplete = 'off'; input.spellcheck = false;
2510
+ input.placeholder = embedded ? '文件或目录路径' : '文件、目录或 https://…'; input.setAttribute('aria-label',embedded ? '文件路径' : '文件路径或网页地址'); input.maxLength = 4096; input.autocomplete = 'off'; input.spellcheck = false;
1017
2511
  input.setAttribute('role','combobox'); input.setAttribute('aria-autocomplete','list'); input.setAttribute('aria-controls',list.id); input.setAttribute('aria-expanded','false');
1018
2512
  this.addressInput = input; this.updateAddress();
1019
2513
  const picker = this.addressPicker = {input,list,field,hint,key:tab.key,sequence:0,items:[],index:-1};
@@ -1036,10 +2530,96 @@
1036
2530
  };
1037
2531
  field.append(input,list); address.append(this.navigationBack,this.navigationForward,field); this.toolbar.append(address); return input;
1038
2532
  }
1039
- updateAddress() { const tab = this.tabs.get(this.activeKey); if (this.addressInput && tab) this.addressInput.value = tab.draft ?? (['file','diff'].includes(tab.kind)?tab.path+(tab.hash || ''):tab.kind==='web'?tab.path:''); }
2533
+ updateAddress() {
2534
+ const tab = this.tabs.get(this.activeKey); if (!this.addressInput || !tab) return;
2535
+ const suffix = (tab.hash || '').replace(/^#L(\d+)$/u,':$1');
2536
+ this.addressInput.value = tab.draft ?? (['file','diff'].includes(tab.kind)?tab.path+suffix:tab.kind==='web'?tab.path:tab.kind==='directory'?this.directory(tab.path)?.path || '':'');
2537
+ }
2538
+ setTaskDirectories(directories = []) {
2539
+ if (JSON.stringify(this.taskDirectories) === JSON.stringify(directories)) return;
2540
+ this.taskDirectories = directories;
2541
+ if (this.choosingDirectory) this.renderDirectoryPanel();
2542
+ for (const views of this.views.values()) for (const tab of views.values()) {
2543
+ if (tab.kind === 'directory' && !isLocalDirectory(tab.path) && !this.directory(tab.path) && tab.frame) {
2544
+ tab.frame.remove(); tab.frame = undefined;
2545
+ }
2546
+ }
2547
+ this.renderTabs();
2548
+ const current = this.tabs.get(this.activeKey);
2549
+ if (current?.kind === 'new' && current.launch) this.renderTaskDirectories(current);
2550
+ else if (current?.kind === 'directory' && !isLocalDirectory(current.path)) this.loadDirectoryTab(current);
2551
+ }
2552
+ renderTaskDirectories(tab) {
2553
+ tab.launch.querySelector('.launch-directories')?.remove();
2554
+ if (!this.taskDirectories?.length) return;
2555
+ const section = element('section',undefined,'launch-directories'), list = element('ul');
2556
+ section.append(element('h3','任务目录'),list);
2557
+ for (const directory of this.taskDirectories) {
2558
+ const row = element('li'), button = element('button',undefined,'launch-directory');
2559
+ const label = element('span',undefined,'launch-directory-label');
2560
+ label.append(element('strong',directory.name),element('span',directory.path,'launch-directory-path'));
2561
+ button.append(icon('folder'),label);
2562
+ button.dataset.tooltip = directory.path; button.dataset.tooltipOverflow = '.launch-directory-path';
2563
+ button.onclick = () => this.openFile(directory.id,'directory',undefined,undefined,tab.key);
2564
+ row.append(button); list.append(row);
2565
+ }
2566
+ tab.launch.append(section);
2567
+ }
2568
+ syncDirectoryEntry(tab) {
2569
+ if (!tab.frameReady || !tab.frame || !tab.pendingDirectoryEntry && tab.frameEntry === tab.directoryEntry) return;
2570
+ tab.frame.contentWindow?.postMessage({type:'agentbot-workspace-directory-entry',entry:tab.directoryEntry},window.location.origin);
2571
+ tab.frameEntry = tab.directoryEntry; tab.pendingDirectoryEntry = false;
2572
+ }
2573
+ async loadDirectoryTab(tab, controller) {
2574
+ this.toolbar.hidden = false; this.toolbar.replaceChildren();
2575
+ const hint = element('p',undefined,'launch-hint'); hint.hidden = true; hint.setAttribute('role','status');
2576
+ const input = this.renderAddress(tab,hint);
2577
+ const list = iconControl('button','tree','返回主文件列表','mobile-list'); list.onclick = () => this.showList();
2578
+ this.toolbar.append(list,hint);
2579
+ this.content.replaceChildren();
2580
+ const local = isLocalDirectory(tab.path);
2581
+ let directory = this.directory(tab.path);
2582
+ const current = () => input.isConnected && this.tabs.get(this.activeKey) === tab && !controller?.signal.aborted;
2583
+ if (local && !directory && appBase) {
2584
+ this.notice(this.content,'正在打开目录…');
2585
+ const sessions = this.closest('agentbot-workspace').sessions;
2586
+ try {
2587
+ await sessions?.sessionCheck;
2588
+ if (!current()) return;
2589
+ if (!sessions?.csrf) throw new Error('登录工作台后可在地址栏重新打开此目录。');
2590
+ directory = await sessions.fetch('/directory',{params:{local:tab.path.slice(localDirectoryPrefix.length),info:1},signal:controller?.signal});
2591
+ if (!current()) return;
2592
+ this.localDirectories.set(tab.path,directory); this.renderTabs();
2593
+ this.updateAddress(); this.content.replaceChildren();
2594
+ } catch (error) {
2595
+ if (current()) this.notice(this.content,error.message);
2596
+ return;
2597
+ }
2598
+ }
2599
+ if (!directory || !appBase || !local && !this.taskId) {
2600
+ this.content.append(element('div',this.taskDirectories === undefined ? '登录并打开任务后可浏览此目录。' : '此目录已从当前任务移除。','content-empty'));
2601
+ } else if (!tab.frame) {
2602
+ const url = new URL(appBase+'/directory',window.location.href);
2603
+ if (local) url.searchParams.set('local',directory.id);
2604
+ else { url.searchParams.set('task',this.taskId); url.searchParams.set('directory',directory.id); }
2605
+ if (tab.directoryEntry) {
2606
+ url.searchParams.set('entry',tab.directoryEntry); url.searchParams.set('reveal','1');
2607
+ }
2608
+ const frame = element('iframe',undefined,'workspace-frame'); frame.title = '浏览目录 '+directory.name;
2609
+ frame.referrerPolicy = 'no-referrer'; frame.src = url.href;
2610
+ tab.frame = frame; tab.frameReady = false; tab.frameEntry = tab.directoryEntry; tab.pendingDirectoryEntry = false;
2611
+ frame.addEventListener('load',() => {
2612
+ tab.frameReady = true; this.syncFrames(); this.syncDirectoryEntry(tab);
2613
+ this.closest('agentbot-workspace')?.annotations?.syncFrame(tab);
2614
+ });
2615
+ this.frameLayer.append(frame);
2616
+ }
2617
+ this.renderedKey = tab.key; this.syncFrames();
2618
+ this.syncDirectoryEntry(tab);
2619
+ }
1040
2620
  async loadSpecialTab(tab, forceRefresh, generation, controller) {
1041
2621
  this.toolbar.hidden = false; this.toolbar.replaceChildren();
1042
- const hint = element('p',tab.kind === 'web'?'网页仍可能受网站嵌入策略、第三方 Cookie 或混合内容限制,可在新窗口打开。':'输入项目内文件路径或 HTTP / HTTPS 网址。','launch-hint'), input = this.renderAddress(tab,hint);
2622
+ const hint = element('p',tab.kind === 'web'?'网页仍可能受网站嵌入策略、第三方 Cookie 或混合内容限制,可在新窗口打开。':appBase?'输入文件、目录路径或 HTTP / HTTPS 网址。':'输入项目内文件路径或 HTTP / HTTPS 网址。','launch-hint'), input = this.renderAddress(tab,hint);
1043
2623
  const actions = element('div',undefined,'workspace-view-actions'); this.toolbar.append(actions);
1044
2624
  const list = iconControl('button','tree','返回文件列表','mobile-list'); list.onclick = () => this.showList(); actions.append(list);
1045
2625
  if (tab.kind === 'new') {
@@ -1047,12 +2627,14 @@
1047
2627
  const launch = element('div',undefined,'workspace-launchpad'), actions = element('div',undefined,'launch-actions');
1048
2628
  for (const [kind,label] of [['file','打开文件'],['web','打开网页'],['terminal','打开 Terminal']]) {
1049
2629
  const button = element('button'); button.append(icon(kind),element('span',label)); button.dataset.launch = kind;
2630
+ if (!this.fileApi && (kind === 'terminal' || kind === 'file' && !appBase)) button.disabled = true;
1050
2631
  actions.append(button);
1051
2632
  }
1052
2633
  launch.append(element('h2','新标签'),actions); tab.launch = launch;
1053
2634
  }
1054
- for (const button of tab.launch.querySelectorAll('[data-launch]')) button.onclick = () => { if (button.dataset.launch === 'terminal') this.openFile(tab.path,'terminal',undefined,undefined,tab.key); else { input.placeholder = button.dataset.launch === 'file'?'项目内完整文件路径':'网址(自动补齐协议)'; input.focus(); this.suggestAddress(this.addressPicker); } };
1055
- tab.launch.querySelector('.launch-hint')?.remove(); tab.launch.append(hint); this.content.replaceChildren(tab.launch); this.renderedKey = tab.key; this.syncFrames(); return;
2635
+ for (const button of tab.launch.querySelectorAll('[data-launch]')) button.onclick = () => { if (button.dataset.launch === 'terminal') this.openFile(tab.path,'terminal',undefined,undefined,tab.key); else { input.placeholder = button.dataset.launch === 'file'?(appBase?'文件或目录路径':'项目内完整文件路径'):'网址(自动补齐协议)'; input.focus(); this.suggestAddress(this.addressPicker); } };
2636
+ tab.launch.querySelector('.launch-hint')?.remove(); tab.launch.append(hint); this.renderTaskDirectories(tab);
2637
+ this.content.replaceChildren(tab.launch); this.renderedKey = tab.key; this.syncFrames(); return;
1056
2638
  }
1057
2639
  const refresh = iconControl('button','refresh','刷新视图'); refresh.onclick = () => this.loadTab(tab,true); actions.append(refresh);
1058
2640
  try {
@@ -1076,7 +2658,7 @@
1076
2658
  } else if (forceRefresh) tab.frame.src = tab.frame.src;
1077
2659
  if (tab.kind === 'web') this.loadWebTitle(tab,forceRefresh);
1078
2660
  const external = iconControl('a','external','新窗口打开'); external.href = tab.path; if (tab.kind === 'terminal') external.href = tab.frame.src; external.target = '_blank'; external.rel = 'noopener noreferrer'; actions.append(external);
1079
- if (tab.kind === 'web') { const label = element('span','无法内嵌时在新窗口打开','frame-hint'); label.title = hint.textContent; actions.append(label); }
2661
+ if (tab.kind === 'web') { const label = element('span','无法内嵌时在新窗口打开','frame-hint'); label.dataset.tooltip = hint.textContent; actions.append(label); }
1080
2662
  this.renderedKey = tab.key; this.syncFrames(); this.queuePersist();
1081
2663
  } catch (error) {
1082
2664
  if (!this.isConnected || generation !== this.generation) return;
@@ -1105,8 +2687,20 @@
1105
2687
  restoreScroll() {
1106
2688
  const current = this.tabs.get(this.activeKey);
1107
2689
  if (current && this.content.clientHeight > 0) { this.content.scrollTop = current.scrollTop; this.content.scrollLeft = current.scrollLeft; }
1108
- if (this.navigation.clientHeight > 0) { this.reserveTreeScroll(this.listScrollTop); this.navigation.scrollTop = this.listScrollTop; }
1109
- if (current && this.renderedKey === this.activeKey) this.restoreHash(current);
2690
+ if (this.navigation.clientHeight > 0) {
2691
+ const view = this.navigationView(this.listMode);
2692
+ if (view.clampRestoredScroll && this.navigation === view.node) {
2693
+ view.clampRestoredScroll = false;
2694
+ this.reserveTreeScroll(0);
2695
+ this.listScrollTop = Math.min(this.listScrollTop,Math.max(0,this.navigation.scrollHeight-this.navigation.clientHeight));
2696
+ }
2697
+ this.reserveTreeScroll(this.listScrollTop); this.navigation.scrollTop = this.listScrollTop;
2698
+ if (this.liveReady) this.resumeDirtyDirectories();
2699
+ }
2700
+ if (current && this.renderedKey === this.activeKey) {
2701
+ this.restoreHash(current);
2702
+ if (current.stale) void this.refreshLivePreview(current);
2703
+ }
1110
2704
  this.centerTreeTarget();
1111
2705
  this.updateDiffNavigation();
1112
2706
  }
@@ -1129,10 +2723,9 @@
1129
2723
  showList() {
1130
2724
  this.navigate(() => { this.saveScroll(); this.dataset.view = 'list'; this.restoreScroll(); this.syncFrames(); });
1131
2725
  }
1132
- diffBlockScrollTop(block) {
1133
- let end = block;
1134
- while (end.nextElementSibling?.matches('.diff-addition,.diff-deletion')) end = end.nextElementSibling;
1135
- const center = (block.getBoundingClientRect().top+end.getBoundingClientRect().bottom)/2;
2726
+ diffBlockScrollTop(firstLine) {
2727
+ const line = firstLine.getBoundingClientRect();
2728
+ const center = (line.top+line.bottom)/2;
1136
2729
  const top = this.content.scrollTop+center-this.content.getBoundingClientRect().top-this.content.clientHeight/2;
1137
2730
  return Math.min(Math.max(0,top),Math.max(0,this.content.scrollHeight-this.content.clientHeight));
1138
2731
  }
@@ -1172,7 +2765,7 @@
1172
2765
  this.restoreScroll(); if (!retained) this.loadTab(tab);
1173
2766
  } else {
1174
2767
  this.tabController?.abort(); this.generation++; this.activeKey = this.renderedKey = undefined;
1175
- this.toolbar.hidden = true; this.syncFrames(); this.content.replaceChildren(element('div',this.fileApi?'选择一个文件或改动。':'此任务没有可浏览的项目目录。','content-empty')); this.renderTabs(); this.restoreScroll();
2768
+ this.toolbar.hidden = true; this.syncFrames(); this.showExplorerEmpty(); this.renderTabs(); this.restoreScroll();
1176
2769
  }
1177
2770
  }
1178
2771
  renderTabs() {
@@ -1190,14 +2783,19 @@
1190
2783
  if (tab.key === this.activeKey) addedActive = true;
1191
2784
  }
1192
2785
  const select = row.querySelector('[role=tab]'), close = row.querySelector('.close-tab');
1193
- if (select.title !== tab.path || row.dataset.kind !== tab.kind) {
1194
- select.replaceChildren(['file','diff'].includes(tab.kind)?fileIcon(tab.path):icon(tab.kind),element('span',this.tabTitle(tab),'tab-name'));
2786
+ if (select.dataset.tabPath !== tab.path || row.dataset.kind !== tab.kind) {
2787
+ select.replaceChildren(['file','diff'].includes(tab.kind)?fileIcon(tab.path):icon(tab.kind === 'directory'?'folder':tab.kind),element('span',this.tabTitle(tab),'tab-name'));
1195
2788
  if (tab.kind === 'diff') { const badge = element('span','±','tab-diff-badge'); badge.setAttribute('aria-hidden','true'); select.append(badge); }
1196
- select.title = tab.path; row.dataset.kind = tab.kind;
2789
+ select.dataset.tabPath = tab.path; row.dataset.kind = tab.kind;
1197
2790
  }
1198
2791
  const name = select.querySelector('.tab-name'), title = this.tabTitle(tab); if (name.textContent !== title) name.textContent = title;
1199
- select.setAttribute('aria-label',(tab.kind === 'diff'?'查看改动 ':tab.kind === 'web'?'查看网页 ':tab.kind === 'terminal'?'查看终端 ':tab.kind === 'new'?'':'查看文件 ')+(tab.kind === 'new'?'新标签':tab.kind === 'web' && tab.pageTitle?tab.pageTitle+' · '+tab.path:tab.path));
1200
- const label = '关闭 '+this.tabTitle(tab)+(tab.kind === 'diff'?' 改动':''); close.title = label; close.setAttribute('aria-label',label);
2792
+ const source = tab.source ? this.previewRoot(tab.source) : undefined;
2793
+ const fullPath = source ? source+' · '+tab.path : tab.kind === 'directory' ? this.directory(tab.path)?.path : ['file','diff','web'].includes(tab.kind) ? tab.path : undefined;
2794
+ if (fullPath && fullPath !== title) { select.dataset.tooltip = fullPath; delete select.dataset.tooltipOverflow; }
2795
+ else { delete select.dataset.tooltip; select.dataset.tooltipOverflow = '.tab-name'; }
2796
+ select.setAttribute('aria-label',tab.kind === 'directory'?'浏览目录 '+title:(tab.kind === 'diff'?'查看改动 ':tab.kind === 'web'?'查看网页 ':tab.kind === 'terminal'?'查看终端 ':tab.kind === 'new'?'':'查看文件 ')+(tab.kind === 'new'?'新标签':tab.kind === 'web' && tab.pageTitle?tab.pageTitle+' · '+tab.path:tab.path));
2797
+ const label = '关闭 '+title+(tab.kind === 'diff'?' 改动':'');
2798
+ if (close.getAttribute('aria-label') !== label) { close.dataset.tooltip = label; close.setAttribute('aria-label',label); }
1201
2799
  select.onclick = () => this.navigate(() => { this.saveScroll(); this.showTab(this.tabs.get(tab.key)); });
1202
2800
  close.onclick = () => this.navigate(() => {
1203
2801
  const keys = [...this.tabs.keys()], index = keys.indexOf(tab.key);
@@ -1246,15 +2844,16 @@
1246
2844
  this.tabWidth = width; this.tabBar.scrollLeft = this.tabScrollLeft;
1247
2845
  }
1248
2846
  resizeTabs() { this.scrollTabs(this.rememberTabsScroll()); }
1249
- async loadTab(tab, forceRefresh = false) {
1250
- if (!forceRefresh && this.loadingTab?.key === tab.key && this.loadingTab.path === tab.path && this.loadingTab.kind === tab.kind && this.loadingTab.mode === tab.mode && this.loadingTab.original === tab.original && !this.tabController.signal.aborted) return;
1251
- const generation = ++this.generation;
2847
+ async loadTab(tab, forceRefresh = false, liveData) {
2848
+ if (!forceRefresh && this.loadingTab?.key === tab.key && this.loadingTab.path === tab.path && this.loadingTab.kind === tab.kind && this.loadingTab.mode === tab.mode && this.loadingTab.original === tab.original && this.loadingTab.source === tab.source && !this.tabController.signal.aborted) return;
2849
+ const generation = ++this.generation, revision = tab.stale;
1252
2850
  this.tabController?.abort(); const controller = new AbortController(); this.tabController = controller;
1253
2851
  this.syncFrames();
2852
+ if (tab.kind === 'directory') { this.loadingTab = undefined; this.diffBlocks = []; this.diffControls = undefined; await this.loadDirectoryTab(tab,controller); return; }
1254
2853
  if (['new','web','terminal'].includes(tab.kind)) { this.loadingTab = undefined; this.diffBlocks = []; this.diffControls = undefined; await this.loadSpecialTab(tab,forceRefresh,generation,controller); return; }
1255
2854
  const cached = !forceRefresh && tab.preview?.mode === tab.mode && tab.preview.original === tab.original ? tab.preview : undefined;
1256
2855
  const focusFirstDiff = tab.kind === 'diff' && !tab.preview && !tab.hash && tab.scrollTop === 0;
1257
- this.loadingTab = cached ? undefined : {key:tab.key,path:tab.path,kind:tab.kind,mode:tab.mode,original:tab.original};
2856
+ this.loadingTab = cached ? undefined : {key:tab.key,path:tab.path,kind:tab.kind,mode:tab.mode,original:tab.original,source:tab.source};
1258
2857
  this.diffBlocks = []; this.diffControls = undefined;
1259
2858
  if (!cached) tab.preview = undefined;
1260
2859
  this.toolbar.hidden = false; this.toolbar.replaceChildren();
@@ -1270,7 +2869,6 @@
1270
2869
  previous.disabled = next.disabled = true; previous.onclick = () => this.jumpDiff('previous'); next.onclick = () => this.jumpDiff('next');
1271
2870
  this.diffControls = {previous,next}; actions.append(previous,next);
1272
2871
  const select = element('select'); select.setAttribute('aria-label','Diff 范围');
1273
- select.title = 'Diff 范围:全部、已暂存、未暂存';
1274
2872
  for (const [value,label] of [['all','全部'],['staged','已暂存'],['unstaged','未暂存']]) {
1275
2873
  const option = element('option',label); option.value = value; option.selected = value === tab.mode; select.append(option);
1276
2874
  }
@@ -1281,16 +2879,21 @@
1281
2879
  const retained = this.renderedKey === tab.key;
1282
2880
  if (!retained && !cached) { this.renderedKey = undefined; this.content.replaceChildren(element('div','正在读取…','content-empty')); }
1283
2881
  try {
1284
- const data = cached || await this.request(tab.kind,{entry:tab.path,mode:tab.mode,original:tab.original},controller);
2882
+ let etag = liveData?.etag;
2883
+ const data = liveData || cached || await this.request(tab.kind,{entry:tab.path,mode:tab.mode,original:tab.original},controller,undefined,value => { etag = value; },this.previewApi(tab.source));
1285
2884
  if (!this.isConnected || generation !== this.generation || !this.tabs.has(tab.key)) return;
1286
2885
  const visible = retained && this.content.clientHeight > 0;
1287
2886
  const top = visible ? this.content.scrollTop : tab.scrollTop, left = visible ? this.content.scrollLeft : tab.scrollLeft;
1288
- if (cached) { if (!retained) this.content.replaceChildren(...cached.nodes); }
1289
- else {
2887
+ if (cached) {
2888
+ if (!retained) { this.clearPreviewCaret(); this.content.replaceChildren(...cached.nodes); }
2889
+ } else {
2890
+ this.clearPreviewCaret();
1290
2891
  this.content.innerHTML = data.html;
1291
- tab.preview = {mode:tab.mode,original:tab.original,nodes:[...this.content.childNodes],canViewFile:data.canViewFile,rawUrl:data.rawUrl,change:data.change,gitError:data.gitError};
2892
+ tab.preview = {mode:tab.mode,original:tab.original,etag,html:data.html,nodes:[...this.content.childNodes],canViewFile:data.canViewFile,rawUrl:data.rawUrl,change:data.change,gitError:data.gitError};
2893
+ if (tab.stale === revision) tab.stale = undefined;
1292
2894
  }
1293
2895
  this.renderedKey = tab.key;
2896
+ if (!forceRefresh) this.rememberRecentFile(tab);
1294
2897
  if (tab.kind === 'diff') this.diffBlocks = [...this.content.querySelectorAll('.git-diff .diff-addition,.git-diff .diff-deletion')].filter(block => !block.previousElementSibling?.matches('.diff-addition,.diff-deletion'));
1295
2898
  this.content.scrollTop = top; this.content.scrollLeft = left;
1296
2899
  if (focusFirstDiff && this.diffBlocks.length) tab.hash = tab.requestedHash = '#'+this.diffBlocks[0].id;
@@ -1298,12 +2901,12 @@
1298
2901
  this.restoreHash(tab); this.updateDiffNavigation(); this.queuePersist();
1299
2902
  if (tab.kind === 'diff') {
1300
2903
  const file = iconControl('button','openFile','查看文件内容','file-content'); file.disabled = !data.canViewFile;
1301
- file.onclick = () => this.openFile(tab.path,'file'); refresh.before(file);
2904
+ file.onclick = () => this.openFile(tab.path,'file',undefined,undefined,undefined,tab.source); refresh.before(file);
1302
2905
  } else if (data.rawUrl) {
1303
2906
  const download = iconControl('a','download','下载'), url = new URL(data.rawUrl); url.searchParams.set('download','1');
1304
2907
  download.href = url; download.target = '_blank'; download.rel = 'noopener noreferrer'; refresh.before(download);
1305
2908
  }
1306
- if (tab.kind === 'file' && data.change) { const changes = iconControl('button','diff','查看文件变更','file-changes'); changes.onclick = () => this.openFile(data.change.path,'diff',data.change.originalPath); refresh.before(changes); }
2909
+ if (tab.kind === 'file' && data.change) { const changes = iconControl('button','diff','查看文件变更','file-changes'); changes.onclick = () => this.openFile(data.change.path,'diff',data.change.originalPath,undefined,undefined,tab.source); refresh.before(changes); }
1307
2910
  if (data.gitError) { hint.textContent = '读取 Git 状态失败:'+data.gitError; hint.hidden = false; }
1308
2911
  } catch (error) {
1309
2912
  if (this.isConnected && generation === this.generation) {
@@ -1311,16 +2914,28 @@
1311
2914
  this.updateDiffNavigation();
1312
2915
  this.notice(this.content,'读取'+(tab.kind === 'diff'?' Diff':'文件')+'失败:'+error.message,() => this.loadTab(tab,true));
1313
2916
  }
1314
- } finally { if (generation === this.generation) this.loadingTab = undefined; }
2917
+ } finally {
2918
+ if (generation === this.generation) {
2919
+ this.loadingTab = undefined;
2920
+ if (!liveData && tab.stale && tab.preview) void this.refreshLivePreview(tab);
2921
+ }
2922
+ }
1315
2923
  }
1316
2924
  }
1317
2925
  class AgentBotWorkspace extends HTMLElement {
2926
+ toolIcon(kind) {
2927
+ const glyph = icon(Object.hasOwn(toolIcons,kind) ? toolIcons[kind] : 'tool');
2928
+ glyph.classList.add('session-tool-icon');
2929
+ return glyph;
2930
+ }
1318
2931
  connectedCallback() {
1319
2932
  this.positions = new Map(); this.historyRoutes = new Map(); this.paneScrollPositions = new Map(); this.navigating = this.restoring = false;
1320
2933
  this.taskPanels = new Map(); this.guestPanel = undefined;
2934
+ if (embedded) this.embeddedHistory = new Map();
2935
+ this.directoryCache = new DirectoryCache(); this.fileRevision = 0;
1321
2936
  const initialHref = window.location.href, initialTask = appBase ? this.taskFromUrl(initialHref) : undefined;
1322
2937
  this.guestUrl = root ? apiBase : historyScope;
1323
- const state = window.history.state; this.historyIndex = state?.workspace === historyScope ? state.index : 0;
2938
+ const state = embedded ? undefined : window.history.state; this.historyIndex = state?.workspace === historyScope ? state.index : 0;
1324
2939
  this.historyMaximum = state?.workspace === historyScope ? state.maximum ?? state.index : 0;
1325
2940
  this.historyMaximumKnown = state?.workspace !== historyScope || state.maximum !== undefined;
1326
2941
  this.historyGuard = Boolean(state?.workspace === historyScope && state.guarded);
@@ -1334,22 +2949,94 @@
1334
2949
  this.showFilesPanel(files);
1335
2950
  const collapse = iconControl('button','sidebar','折叠任务侧栏','toggle-sidebar'); collapse.onclick = () => this.togglePanel('sidebar'); this.querySelector('.workspace-header').prepend(collapse);
1336
2951
  const collapseFiles = iconControl('button','explorer','折叠文件工作区','toggle-files'); collapseFiles.onclick = () => this.togglePanel('files'); this.querySelector('.workspace-header').append(collapseFiles);
2952
+ this.themeToggle = iconControl('button','moon','切换到深色模式','toggle-theme');
2953
+ this.themeToggle.type = 'button';
2954
+ collapseFiles.before(this.themeToggle);
2955
+ this.systemTheme = window.matchMedia?.('(prefers-color-scheme: dark)');
2956
+ this.themePreference = stored(themeKey);
2957
+ this.themeToggle.onclick = () => {
2958
+ this.themePreference = document.documentElement.dataset.workspaceTheme === 'dark' ? 'light' : 'dark';
2959
+ put(themeKey,this.themePreference);
2960
+ this.applyTheme();
2961
+ };
2962
+ this.systemTheme?.addEventListener?.('change',this.applyTheme);
2963
+ window.addEventListener('storage',this.syncTheme);
2964
+ this.applyTheme();
1337
2965
  this.layoutResize = () => this.applyLayout(); window.addEventListener('resize',this.layoutResize);
1338
2966
  this.scrollbars = new WorkspaceScrollbars(this);
1339
- this.querySelector('.workspace-title').textContent = project+' · Workspace'; this.querySelector('.workspace-title').title = root;
1340
- const status = this.querySelector('.workspace-status'); status.replaceChildren(icon('lock'),element('span','只读')); status.title = '只读工作台';
2967
+ this.tooltips = new WorkspaceTooltips(this);
2968
+ this.commandPalette = new WorkspaceCommandPalette(this);
2969
+ if (!embedded) {
2970
+ const search = iconControl('button','search','打开命令面板','open-command-palette');
2971
+ search.type = 'button'; search.setAttribute('aria-haspopup','dialog'); search.setAttribute('aria-controls',this.commandPalette.dialog.id);
2972
+ search.setAttribute('aria-keyshortcuts','Control+P Meta+P');
2973
+ search.onclick = () => this.commandPalette.open('overview');
2974
+ collapse.after(search);
2975
+ }
2976
+ this.updateProjectHeading(project,root);
2977
+ const status = this.querySelector('.workspace-status'); status.replaceChildren(icon('lock'),element('span','只读'));
1341
2978
  for (const button of this.querySelectorAll('[data-pane]')) {
1342
2979
  const pane = button.dataset.pane, label = {tasks:'任务',chat:'聊天',files:'文件与改动列表'}[pane];
1343
- button.replaceChildren(icon(pane === 'files'?'folder':pane)); button.classList.add('icon-control'); button.title = label; button.setAttribute('aria-label',label);
2980
+ button.replaceChildren(icon(pane === 'files'?'folder':pane)); button.classList.add('icon-control'); button.dataset.tooltip = label; button.setAttribute('aria-label',label);
1344
2981
  button.onclick = () => this.navigate(() => {
1345
2982
  if (pane === 'files' && this.dataset.pane === pane) this.filesPanel.showList();
1346
2983
  else this.selectPane(pane);
1347
2984
  });
1348
2985
  }
1349
2986
  this.addEventListener('workspace-status',this.statusChanged);
2987
+ this.saveDirectoryCache = () => { this.directoryCache.persist(); this.stopFileEvents(); };
2988
+ this.resumeFileSync = () => { if (!document.hidden && this.filesPanel?.fileChanges) this.filesPanel.queueFileSync({}); };
2989
+ this.resumeFileEvents = () => { if (this.filesPanel) this.watchFiles(this.filesPanel); };
2990
+ this.embeddedVisibility = event => {
2991
+ if (event.source !== window.parent || event.origin !== window.location.origin) return;
2992
+ if (event.data?.type === 'agentbot-workspace-visibility') {
2993
+ this.embeddedVisible = event.data.visible === true;
2994
+ if (this.embeddedVisible) this.resumeFileEvents(); else this.stopFileEvents();
2995
+ } else if (event.data?.type === 'agentbot-workspace-directory-entry') {
2996
+ const files = this.filesPanel, entry = event.data.entry;
2997
+ if (entry === undefined) { files.selectList('files'); files.showList(); }
2998
+ else {
2999
+ let path;
3000
+ try { path = relativePath(entry); } catch { return; }
3001
+ files.openAndRevealFile(path);
3002
+ }
3003
+ }
3004
+ };
3005
+ this.handleEmbeddedAction = event => {
3006
+ const address = event.data?.address, files = this.filesPanel, tab = files?.tabs.get(files.activeKey);
3007
+ if (event.origin !== window.location.origin) return;
3008
+ if (event.data?.type === 'agentbot-workspace-annotate') {
3009
+ const {annotation,request,task} = event.data;
3010
+ const source = [...(files?.tabs.values() || [])].find(tab => tab.kind === 'directory' && tab.frame?.contentWindow === event.source);
3011
+ if (!source || typeof request !== 'string' || request.length > 64 || !this.sessions || typeof annotation?.path !== 'string') return;
3012
+ const error = this.sessions.addAnnotation(annotation,task);
3013
+ event.source.postMessage({type:'agentbot-workspace-annotation-result',request,error},window.location.origin);
3014
+ return;
3015
+ }
3016
+ if (!tab?.frame || event.source !== tab.frame.contentWindow || files.dataset.view !== 'content') return;
3017
+ if (event.data?.type === 'agentbot-workspace-open-file-search' && tab.kind === 'terminal') {
3018
+ this.commandPalette.open(event.data.commands === true ? 'commands' : 'files'); return;
3019
+ }
3020
+ if (event.data?.type !== 'agentbot-workspace-open-local-directory' || tab.kind !== 'directory'
3021
+ || typeof address !== 'string' || address.length > 4096 || !localAddress(address)) return;
3022
+ const picker = files.addressPicker;
3023
+ if (!picker) return;
3024
+ picker.input.value = address; tab.draft = address;
3025
+ void files.openAddress(address,picker.hint,tab.key);
3026
+ };
3027
+ if (embedded) window.addEventListener('message',this.embeddedVisibility);
3028
+ if (appBase) window.addEventListener('message',this.handleEmbeddedAction);
3029
+ document.addEventListener('visibilitychange',this.resumeFileSync);
3030
+ if (!embedded) {
3031
+ document.addEventListener('visibilitychange',this.checkWorkspaceVersion);
3032
+ window.addEventListener('online',this.checkWorkspaceVersion);
3033
+ this.scheduleWorkspaceVersionCheck();
3034
+ }
3035
+ window.addEventListener('pagehide',this.saveDirectoryCache); window.addEventListener('pageshow',this.resumeFileEvents);
1350
3036
  window.addEventListener('popstate',this.historyChanged); window.addEventListener('pagehide',this.persistHistory);
1351
3037
  window.addEventListener('beforeunload',this.persistHistory);
1352
3038
  if (appBase) this.sessions = new window.AgentBotSessionWorkspace(this,appBase);
3039
+ if (appBase || embedded) this.annotations = new WorkspaceAnnotations(this);
1353
3040
  // Reload may snapshot its URL before beforeunload saves the final reading position.
1354
3041
  const reload = state?.workspace === historyScope && window.performance?.getEntriesByType('navigation')[0]?.type === 'reload';
1355
3042
  if (root || !initialTask) this.restoreFilesPanel(reload?state.position:undefined,reload?state.url:undefined);
@@ -1361,7 +3048,7 @@
1361
3048
  this.applyLayout();
1362
3049
  }
1363
3050
  this.addEventListener('scroll',this.queuePersist,true);
1364
- if (appBase && !root && !initialTask) this.selectPane('tasks');
3051
+ if (appBase && !root && !initialTask && !new URL(initialHref).searchParams.has('entry')) this.selectPane('tasks');
1365
3052
  window.addEventListener('hashchange',this.urlChanged);
1366
3053
  if (state?.workspace === historyScope && state.boundary) { this.syncedUrl = window.location.href; this.stepHistory(1,false,true); return; }
1367
3054
  if (state?.workspace !== historyScope && files.tabs.get(files.activeKey)?.kind === 'web') {
@@ -1369,17 +3056,45 @@
1369
3056
  window.history.replaceState({...initial,index:-1,boundary:true},'',initial.url); window.history.pushState(initial,'',initial.url);
1370
3057
  }
1371
3058
  this.persistHistory();
1372
- if (!this.savedTreeModes.has(files.listMode)) files.revealCurrentFile(true);
3059
+ if ((embedded && new URL(initialHref).searchParams.get('reveal') === '1') || !this.savedTreeModes.has(files.listMode)) {
3060
+ files.revealCurrentFile(true);
3061
+ }
1373
3062
  }
1374
3063
  disconnectedCallback() {
1375
3064
  this.removeEventListener('workspace-status',this.statusChanged);
1376
- this.sessions?.dispose();
1377
- this.scrollbars.disconnect();
3065
+ this.sessions?.dispose(); this.stopFileEvents();
3066
+ this.annotations?.disconnect();
3067
+ this.commandPalette.disconnect();
3068
+ this.systemTheme?.removeEventListener?.('change',this.applyTheme);
3069
+ window.removeEventListener('storage',this.syncTheme);
3070
+ clearTimeout(this.cacheSaveTimer); this.directoryCache.persist();
3071
+ document.removeEventListener('visibilitychange',this.resumeFileSync);
3072
+ document.removeEventListener('visibilitychange',this.checkWorkspaceVersion);
3073
+ window.removeEventListener('online',this.checkWorkspaceVersion);
3074
+ clearTimeout(this.workspaceVersionTimer); this.workspaceVersionRequest?.abort();
3075
+ window.removeEventListener('pagehide',this.saveDirectoryCache); window.removeEventListener('pageshow',this.resumeFileEvents); window.removeEventListener('message',this.embeddedVisibility);
3076
+ if (appBase) window.removeEventListener('message',this.handleEmbeddedAction);
3077
+ this.scrollbars.disconnect(); this.tooltips.disconnect();
1378
3078
  this.finishHistoryTraversal();
1379
3079
  window.removeEventListener('resize',this.layoutResize); this.endDrag?.();
1380
3080
  this.removeEventListener('scroll',this.queuePersist,true); window.removeEventListener('hashchange',this.urlChanged); clearTimeout(this.persistTimer);
1381
3081
  window.removeEventListener('popstate',this.historyChanged); window.removeEventListener('pagehide',this.persistHistory); window.removeEventListener('beforeunload',this.persistHistory);
1382
3082
  }
3083
+ applyTheme = () => {
3084
+ const dark = this.themePreference === 'dark' || (this.themePreference !== 'light' && this.systemTheme?.matches);
3085
+ const theme = dark ? 'dark' : 'light', previousTheme = document.documentElement.dataset.workspaceTheme;
3086
+ document.documentElement.dataset.workspaceTheme = theme;
3087
+ const label = dark ? '切换到浅色模式' : '切换到深色模式';
3088
+ this.themeToggle.replaceChildren(icon(dark ? 'sun' : 'moon'));
3089
+ this.themeToggle.dataset.tooltip = label;
3090
+ this.themeToggle.setAttribute('aria-label',label);
3091
+ if (theme !== previousTheme) window.agentBotDiagrams?.scan();
3092
+ };
3093
+ syncTheme = event => {
3094
+ if (event.key !== themeKey && event.key !== null) return;
3095
+ this.themePreference = stored(themeKey);
3096
+ this.applyTheme();
3097
+ };
1383
3098
  selectPane(pane) {
1384
3099
  if (pane === this.dataset.pane) return;
1385
3100
  const files = this.filesPanel, scrollers = this.paneScrollers();
@@ -1393,14 +3108,14 @@
1393
3108
  const position = this.paneScrollPositions.get(node);
1394
3109
  if (position && node.clientHeight > 0) { node.scrollTop = position.top; if (node === files.tabBar) files.scrollTabs(position.left); else node.scrollLeft = position.left; }
1395
3110
  }
1396
- files.resizeTabs(); this.sessions?.restorePosition();
3111
+ files.resizeTabs(); this.sessions?.restorePosition(); this.annotations?.refresh();
1397
3112
  }
1398
3113
  globalLayout() { const saved = stored('agentbot-workspace-layout') || {}; return {
1399
3114
  ...(typeof saved.sidebar === 'number' ? {sidebar:saved.sidebar} : {}),
1400
3115
  ...(typeof saved.sidebarCollapsed === 'boolean' ? {sidebarCollapsed:saved.sidebarCollapsed} : {}),
1401
3116
  }; }
1402
3117
  initTreeStorage(projectRoot, taskId) {
1403
- this.treeStorageKey = taskId ? 'agentbot-workspace-task-tree:'+taskId+':'+projectPath(projectRoot,projectRoot) : 'agentbot-workspace-tree:'+projectPath(projectRoot);
3118
+ this.treeStorageKey = embedded ? 'agentbot-workspace-directory-tree:'+apiBase : taskId ? 'agentbot-workspace-task-tree:'+taskId+':'+projectPath(projectRoot,projectRoot) : 'agentbot-workspace-tree:'+projectPath(projectRoot);
1404
3119
  this.treeStates = {};
1405
3120
  try { const saved = stored(this.treeStorageKey); if (saved?.v === 1) this.treeStates = readTreeState(saved.trees); } catch {}
1406
3121
  this.savedTreeModes = new Set(Object.keys(this.treeStates));
@@ -1427,20 +3142,75 @@
1427
3142
  showFilesPanel(files) {
1428
3143
  const previous = this.filesPanel;
1429
3144
  if (previous === files) return;
3145
+ this.commandPalette?.close();
1430
3146
  if (previous?.isConnected) {
1431
3147
  previous.saveScroll(); previous.panelLayout = this.rightLayout();
3148
+ this.persistTrees();
3149
+ previous.liveReady = false;
1432
3150
  previous.hidden = true; previous.setAddressPickerVisible(false); previous.syncFrames();
1433
3151
  }
1434
3152
  this.filesPanel = files;
1435
- this.initTreeStorage(files.projectRoot,files.taskId);
3153
+ this.initTreeStorage(files.treeRoot,files.taskId);
1436
3154
  if (files.panelLayout) this.layout = {...this.globalLayout(),...files.panelLayout};
1437
3155
  files.hidden = false; files.setAddressPickerVisible(true);
1438
3156
  this.statusChanged({target:files,detail:files.lastStatus || {label:'只读',repository:false}});
3157
+ this.watchFiles(files);
3158
+ }
3159
+ scheduleCacheSave() {
3160
+ if (this.cacheSaveTimer) return;
3161
+ this.cacheSaveTimer = setTimeout(() => { this.cacheSaveTimer = undefined; this.directoryCache.persist(); },350);
3162
+ }
3163
+ stopFileEvents() {
3164
+ this.fileStream?.close(); this.fileStream = undefined;
3165
+ clearTimeout(this.filePoll); this.filePoll = undefined;
3166
+ this.watchedFiles = undefined; this.fileStreamReady = false;
3167
+ }
3168
+ watchFiles(files) {
3169
+ if (this.watchedFiles === files.treeApi) { if (this.fileStreamReady) this.filesConnected(files); return; }
3170
+ this.stopFileEvents();
3171
+ if (!files.treeApi || embedded && window.parent !== window && !this.embeddedVisible) return;
3172
+ const api = this.watchedFiles = files.treeApi, url = new URL(api); url.searchParams.set('api','events');
3173
+ const stream = this.fileStream = new EventSource(url);
3174
+ const fallback = () => {
3175
+ if (this.fileStream !== stream) return;
3176
+ if (!document.hidden) this.filesPanel?.queueFileSync({reset:true});
3177
+ if (stream.readyState === 2) { this.stopFileEvents(); this.watchFiles(this.filesPanel); }
3178
+ else this.filePoll = setTimeout(fallback,15_000);
3179
+ };
3180
+ this.filePoll = setTimeout(fallback,15_000);
3181
+ stream.addEventListener('ready',() => {
3182
+ if (this.fileStream !== stream) return;
3183
+ clearTimeout(this.filePoll); this.filePoll = undefined;
3184
+ this.fileStreamReady = true; this.filesConnected(this.filesPanel);
3185
+ });
3186
+ stream.addEventListener('change',event => {
3187
+ if (this.fileStream !== stream) return;
3188
+ try {
3189
+ const change = JSON.parse(event.data); this.filesPanel.liveRevision = ++this.fileRevision;
3190
+ this.filesPanel.lastFileChange = Date.now(); this.filesPanel.queueFileSync(change);
3191
+ } catch {}
3192
+ });
3193
+ stream.onerror = () => {
3194
+ if (this.fileStream !== stream) return;
3195
+ this.fileStreamReady = false;
3196
+ this.scheduleWorkspaceVersionCheck(2000);
3197
+ if (!this.filePoll) this.filePoll = setTimeout(fallback,5000);
3198
+ };
3199
+ }
3200
+ filesConnected(files) {
3201
+ if (!files?.isConnected) return;
3202
+ const resumed = files.liveRevision !== undefined && (!files.liveReady || files.liveRevision !== this.fileRevision);
3203
+ const reconnected = files.liveReady;
3204
+ files.liveReady = true; files.liveRevision = this.fileRevision;
3205
+ if (resumed || reconnected || files.usedDirectoryCache || files.fileChanges) {
3206
+ files.usedDirectoryCache = false; files.lastFileChange = Date.now(); files.queueFileSync({reset:true});
3207
+ }
3208
+ files.warmDirectories();
1439
3209
  }
1440
3210
  restoreFilesPanel(position, href, pane) {
1441
3211
  const files = this.filesPanel;
1442
3212
  this.restoreUrl(false,position,href,false,pane);
1443
- if (files.fileApi && files.listMode !== 'changes') void files.updateChangesCount();
3213
+ if (files.treeApi && files.listMode !== 'changes') void files.updateChangesCount();
1444
3214
  }
1445
3215
  activateTaskPanel(task, nav, render) {
1446
3216
  const apply = () => {
@@ -1452,10 +3222,12 @@
1452
3222
  }
1453
3223
  this.taskId = task.id;
1454
3224
  this.dataset.hasTask = 'true';
3225
+ files.setTaskDirectories(task.directories);
1455
3226
  this.paneScrollPositions.delete(this.querySelector('.chat-body'));
1456
3227
  this.paneScrollPositions.delete(this.querySelector('workspace-chat textarea'));
1457
3228
  const pane = nav.history ? nav.pane || this.dataset.pane : nav.initial ? this.dataset.pane : 'chat';
1458
3229
  this.showFilesPanel(files);
3230
+ files.setDirectoryPanel(task.directoryPanel);
1459
3231
  if (previous !== files && !files.panelLayout) {
1460
3232
  const saved = stored('agentbot-workspace-task:'+task.id), currentHref = window.location.href;
1461
3233
  let href = nav.initial && this.taskFromUrl(currentHref) === task.id ? currentHref : nav.href;
@@ -1470,8 +3242,7 @@
1470
3242
  this.restoreFilesPanel(nav.position,href || this.taskRouteUrl(task.id,list),pane);
1471
3243
  if (!this.savedTreeModes.has(files.listMode)) void files.revealCurrentFile(true);
1472
3244
  } else if (!nav.initial && (!nav.history || !this.restoreUrl(true,nav.position,nav.href,false,pane))) this.selectPane(pane);
1473
- this.querySelector('.workspace-title').textContent = task.project.name+' · Workspace';
1474
- this.querySelector('.workspace-title').title = task.project.root || '无项目';
3245
+ this.updateProjectHeading(task.project.name,task.project.root);
1475
3246
  if (previous !== files) this.applyLayout();
1476
3247
  render();
1477
3248
  };
@@ -1490,38 +3261,102 @@
1490
3261
  if (!href) {
1491
3262
  if (this.taskId) this.persistHistory();
1492
3263
  for (const panel of this.taskPanels.values()) this.removeFilesPanel(panel);
1493
- this.taskPanels.clear();
3264
+ this.taskPanels.clear(); this.directoryCache.clear();
1494
3265
  if (this.guestPanel) this.removeFilesPanel(this.guestPanel);
1495
3266
  this.guestPanel = undefined;
1496
3267
  }
1497
3268
  this.taskId = undefined; this.dataset.hasTask = 'false'; this.taskHistoryPending = false;
3269
+ this.updateTaskTitle();
1498
3270
  const guest = this.getGuestPanel(), returning = this.filesPanel !== guest;
1499
3271
  this.showFilesPanel(guest);
1500
3272
  if (href) this.restoreFilesPanel(undefined,href,root ? 'files' : 'tasks');
1501
3273
  else if (returning && !guest.panelLayout) this.restoreFilesPanel(undefined,this.guestUrl,this.dataset.pane);
1502
3274
  this.applyLayout();
1503
- this.querySelector('.workspace-title').textContent = project+' · Workspace'; this.querySelector('.workspace-title').title = root;
3275
+ this.updateProjectHeading(project,root);
3276
+ }
3277
+ updateProjectHeading(name, directory) {
3278
+ const heading = this.querySelector('.workspace-title');
3279
+ heading.textContent = name+' · Workspace';
3280
+ if (directory) heading.dataset.tooltip = directory;
3281
+ else delete heading.dataset.tooltip;
3282
+ }
3283
+ updateTaskTitle(task) {
3284
+ const title = task ? [task.title,task.promptPreview,task.project.root && task.project.name,'AgentBot Workspace'].filter(Boolean).join(' · ') : workspacePageTitle;
3285
+ if (document.title !== title) document.title = title;
1504
3286
  }
1505
3287
  updateSessionStatus(connected,label) {
1506
3288
  this.sessionConnection = label; this.dataset.liveConnection = String(connected);
1507
3289
  this.statusChanged({target:this.filesPanel,detail:this.filesPanel.lastStatus || {label:'只读',repository:false}});
1508
3290
  }
1509
- openChatFile(entry,kind,hash) {
1510
- if (!this.taskId || !this.filesPanel.fileApi) return;
3291
+ scheduleWorkspaceVersionCheck(delay = 30_000) {
3292
+ if (embedded || !workspaceRevision || !workspaceScript || this.reloadingWorkspace || !this.isConnected) return;
3293
+ const due = Date.now()+delay;
3294
+ if (this.workspaceVersionTimer !== undefined && this.workspaceVersionDue <= due) return;
3295
+ clearTimeout(this.workspaceVersionTimer);
3296
+ this.workspaceVersionDue = due;
3297
+ this.workspaceVersionTimer = setTimeout(() => {
3298
+ this.workspaceVersionTimer = undefined;
3299
+ void this.checkWorkspaceVersion();
3300
+ },delay);
3301
+ }
3302
+ checkWorkspaceVersion = async () => {
3303
+ if (document.hidden || this.workspaceVersionRequest || this.reloadingWorkspace || !this.isConnected || !workspaceRevision || !workspaceScript) return;
3304
+ const controller = this.workspaceVersionRequest = new AbortController();
3305
+ const timeout = setTimeout(() => controller.abort(),5000);
3306
+ let delay = 30_000;
3307
+ try {
3308
+ const response = await fetch(new URL(workspaceScript,window.location.href),{method:'HEAD',cache:'no-store',signal:controller.signal});
3309
+ if (response.ok && !controller.signal.aborted) this.reloadWorkspaceIfUpdated(response.headers?.get('X-AgentBot-Workspace-Revision'),
3310
+ response.headers?.get('X-AgentBot-Workspace-Instance'));
3311
+ else delay = 5000;
3312
+ } catch { delay = 5000; }
3313
+ finally {
3314
+ clearTimeout(timeout); this.workspaceVersionRequest = undefined;
3315
+ this.scheduleWorkspaceVersionCheck(this.workspaceUpdatePending ? 3000 : delay);
3316
+ }
3317
+ };
3318
+ reloadWorkspaceIfUpdated(revision,instance) {
3319
+ if (this.reloadingWorkspace) return true;
3320
+ if (!this.isConnected || !workspaceRevision) return false;
3321
+ const updated = /^[a-f0-9]{64}$/u.test(revision || '') && revision !== workspaceRevision;
3322
+ const restarted = workspaceInstance && /^[a-f0-9]{32}$/u.test(instance || '') && instance !== workspaceInstance;
3323
+ this.workspaceUpdatePending ||= Boolean(updated || restarted);
3324
+ if (!this.workspaceUpdatePending) return false;
3325
+ if (this.sessions?.hasUnstoredDraft()) {
3326
+ this.scheduleWorkspaceVersionCheck(3000);
3327
+ return false;
3328
+ }
3329
+ this.reloadingWorkspace = true;
3330
+ this.persistHistory();
3331
+ window.location.reload();
3332
+ return true;
3333
+ }
3334
+ chatDiffUrl({entry,source,original}) {
3335
+ const url = new URL(this.taskRouteUrl(this.taskId));
3336
+ url.searchParams.set('entry',entry);
3337
+ url.searchParams.set('kind','diff');
3338
+ if (source) url.searchParams.set('sourceDir',source);
3339
+ if (original) url.searchParams.set('original',original);
3340
+ return url.href;
3341
+ }
3342
+ openChatFile(entry,kind,hash,source,original) {
3343
+ const files = this.filesPanel;
3344
+ if (!this.taskId || !files.previewApi(source) || source && !files.previewRoot(source)) return;
1511
3345
  this.navigate(() => {
1512
3346
  this.selectPane('files');
1513
3347
  if (this.layout.filesCollapsed) { this.layout.filesCollapsed = false; this.applyLayout(); }
1514
- this.filesPanel.openFile(entry,kind,undefined,hash);
3348
+ files.openFile(entry,kind,original,hash,undefined,source);
1515
3349
  });
1516
3350
  }
1517
3351
  paneScrollers() { return [...this.querySelectorAll('workspace-task-list,.chat-body,workspace-chat textarea'),this.filesPanel.tabBar]; }
1518
3352
  route() {
1519
3353
  const files = this.filesPanel, tab = files.tabs.get(files.activeKey);
1520
- return {task:files.taskId,pane:this.dataset.pane,listMode:files.listMode,view:files.dataset.view,tab:tab?{id:tab.key,path:tab.path,kind:tab.kind,original:tab.original,mode:tab.mode,hash:tab.hash}:null};
3354
+ return {task:files.taskId,pane:this.dataset.pane,listMode:files.listMode,view:files.dataset.view,tab:tab?{id:tab.key,path:tab.path,kind:tab.kind,original:tab.original,mode:tab.mode,hash:tab.hash,directoryEntry:tab.directoryEntry,source:tab.source}:null};
1521
3355
  }
1522
3356
  separator(panel, label) {
1523
3357
  const node = element('div',undefined,'workspace-separator'); node.dataset.panel = panel; node.tabIndex = 0;
1524
3358
  node.setAttribute('role','separator'); node.setAttribute('aria-orientation','vertical'); node.setAttribute('aria-label',label);
3359
+ node.dataset.tooltipShortcut = '← / →'; node.setAttribute('aria-keyshortcuts','ArrowLeft ArrowRight');
1525
3360
  const change = delta => {
1526
3361
  const current = panel === 'explorer' ? this.filesPanel.querySelector('.file-explorer').getBoundingClientRect().width : this.querySelector(panel === 'sidebar'?'workspace-task-list':'workspace-chat').getBoundingClientRect().width;
1527
3362
  this.layout[panel] = current + (panel === 'explorer'?-delta:delta); this.applyLayout(); this.queuePersist();
@@ -1565,14 +3400,14 @@
1565
3400
  }
1566
3401
  for (const panel of ['sidebar','files','explorer']) {
1567
3402
  const button = panel === 'explorer' ? files.explorerToggle : this.querySelector(panel === 'files'?'.toggle-files':'.toggle-sidebar'), collapsed = Boolean(this.layout[panel+'Collapsed']);
1568
- button.title = (collapsed?'展开':'折叠')+{sidebar:'任务侧栏',files:'文件工作区',explorer:'文件列表'}[panel]; button.setAttribute('aria-label',button.title); button.setAttribute('aria-pressed',String(!collapsed));
3403
+ button.dataset.tooltip = (collapsed?'展开':'折叠')+{sidebar:'任务侧栏',files:'文件工作区',explorer:'文件列表'}[panel]; button.setAttribute('aria-label',button.dataset.tooltip); button.setAttribute('aria-pressed',String(!collapsed));
1569
3404
  }
1570
3405
  files.syncFrames();
1571
3406
  files.resizeTabs();
1572
3407
  }
1573
3408
  rememberPosition() {
1574
3409
  const files = this.filesPanel; files.saveScroll(); const tab = files.tabs.get(files.activeKey);
1575
- const position = {listScrollTop:files.listScrollTop,scrollTop:tab?.scrollTop || 0,scrollLeft:tab?.scrollLeft || 0,chat:this.taskId ? this.sessions?.position() : undefined};
3410
+ const position = {listScrollTop:files.listScrollTop,treeDirectory:files.explorerDirectory || undefined,scrollTop:tab?.scrollTop || 0,scrollLeft:tab?.scrollLeft || 0,chat:this.taskId ? this.sessions?.position() : undefined};
1576
3411
  this.positions.set(this.historyIndex,position); return position;
1577
3412
  }
1578
3413
  historyState() { return {workspace:historyScope,index:this.historyIndex,maximum:this.historyMaximumKnown?this.historyMaximum:undefined,guarded:this.historyGuard,route:this.route(),position:this.rememberPosition(),url:this.stateUrl()}; }
@@ -1604,6 +3439,8 @@
1604
3439
  if (route.tab.kind !== 'file') url.searchParams.set('kind',route.tab.kind);
1605
3440
  if (route.tab.mode !== 'all') url.searchParams.set('mode',route.tab.mode);
1606
3441
  if (route.tab.original) url.searchParams.set('original',route.tab.original);
3442
+ if (route.tab.directoryEntry) url.searchParams.set('directoryFile',route.tab.directoryEntry);
3443
+ if (route.tab.source) url.searchParams.set('sourceDir',route.tab.source);
1607
3444
  if (route.view !== 'content') url.searchParams.set('view',route.view);
1608
3445
  } else if (route.view !== 'list') url.searchParams.set('view',route.view);
1609
3446
  const tabs = [...files.tabs.values()].map(tab => {
@@ -1611,6 +3448,8 @@
1611
3448
  if (tab.kind !== 'file') value.kind = tab.kind;
1612
3449
  if (tab.mode !== 'all') value.mode = tab.mode;
1613
3450
  if (tab.original) value.original = tab.original;
3451
+ if (tab.directoryEntry) value.directoryEntry = tab.directoryEntry;
3452
+ if (tab.source) value.source = tab.source;
1614
3453
  if (tab.scrollTop > 0) value.scrollTop = tab.scrollTop;
1615
3454
  if (tab.scrollLeft > 0) value.scrollLeft = tab.scrollLeft;
1616
3455
  if (tab.hash) value.hash = tab.hash;
@@ -1620,6 +3459,7 @@
1620
3459
  if (tabs.length !== (route.tab?1:0) || tabs.some(tab => tab.scrollTop || tab.scrollLeft || tab.hash || tab.requestedHash)) extra.tabs = tabs;
1621
3460
  if (files.recentTabs.length > 1) extra.recentTabs = files.recentTabs;
1622
3461
  const trees = {};
3462
+ if (files.explorerDirectory) extra.treeDirectory = files.explorerDirectory;
1623
3463
  for (const [mode,view] of files.navigationViews) {
1624
3464
  if (view.query) trees[mode] = {query:view.query};
1625
3465
  }
@@ -1647,6 +3487,7 @@
1647
3487
  if (event && window.history.state?.workspace !== historyScope) return;
1648
3488
  clearTimeout(this.persistTimer); const state = this.historyState(), url = state.url;
1649
3489
  this.persistTrees();
3490
+ if (embedded) this.embeddedHistory.set(this.historyIndex,state);
1650
3491
  if (this.taskId) put('agentbot-workspace-task:'+this.taskId,{root:this.filesPanel.projectRoot,href:url,chat:state.position.chat});
1651
3492
  if (window.history.state?.workspace !== historyScope || window.history.state.url !== url || window.history.state.index !== this.historyIndex) window.history.replaceState(state,'',url);
1652
3493
  this.syncedUrl = url; this.historyRoutes.set(this.historyIndex,state.route); this.updateNavigation();
@@ -1660,6 +3501,10 @@
1660
3501
  if (changed && !replace) {
1661
3502
  this.historyIndex++; this.historyMaximum = this.historyIndex; this.historyMaximumKnown = true;
1662
3503
  for (const index of this.historyRoutes.keys()) if (index >= this.historyIndex) this.historyRoutes.delete(index);
3504
+ if (embedded) {
3505
+ for (const index of this.embeddedHistory.keys()) if (index >= this.historyIndex) this.embeddedHistory.delete(index);
3506
+ this.persistHistory(); return;
3507
+ }
1663
3508
  const state = this.historyState(), url = state.url; window.history.pushState(state,'',url); this.syncedUrl = url;
1664
3509
  this.historyRoutes.set(this.historyIndex,state.route); this.updateNavigation();
1665
3510
  }
@@ -1687,6 +3532,15 @@
1687
3532
  const files = this.filesPanel, current = files.tabs.get(files.activeKey);
1688
3533
  this.updateNavigation(); if (!current || (direction < 0 ? files.navigationBack : files.navigationForward).disabled) return;
1689
3534
  files.revealActiveTab(); this.persistHistory();
3535
+ if (embedded) {
3536
+ for (let index = this.historyIndex+direction; index >= 0 && index <= this.historyMaximum; index += direction) {
3537
+ const state = this.embeddedHistory.get(index);
3538
+ if (state && this.restoreUrl(true,state.position,state.url,true)) {
3539
+ this.historyIndex = index; this.persistHistory(); break;
3540
+ }
3541
+ }
3542
+ return;
3543
+ }
1690
3544
  if (direction < 0 && this.historyIndex === 0 && (!this.historyGuard || current?.kind !== 'web')) return;
1691
3545
  this.stepHistory(direction,true,false);
1692
3546
  }
@@ -1706,8 +3560,8 @@
1706
3560
  this.restoring = true;
1707
3561
  try {
1708
3562
  const files = this.filesPanel;
1709
- const resolveId = (kind,path) => {
1710
- const view = kind+':'+path;
3563
+ const resolveId = (kind,path,source) => {
3564
+ const view = previewKey(kind,path,source);
1711
3565
  if (files.views.get(files.activeKey)?.has(view)) return files.activeKey;
1712
3566
  for (const [key,views] of files.views) if (files.tabs.has(key) && views.has(view)) return key;
1713
3567
  };
@@ -1720,23 +3574,34 @@
1720
3574
  if (pane) saved.route.pane = pane;
1721
3575
  if (local && files.taskId) saved.route.pane = 'files';
1722
3576
  saved.route.task = files.taskId;
1723
- if (!files.fileApi) saved = {...saved,route:{...saved.route,listMode:'files',view:'list',tab:null},tabs:[],recentTabs:[],trees:{}};
3577
+ if (!files.fileApi) {
3578
+ const allowed = tab => appBase && (['new','web'].includes(tab.kind)
3579
+ || tab.kind === 'directory' && (isLocalDirectory(tab.path) || files.taskDirectories?.length)
3580
+ || tab.source && files.previewRoot(tab.source));
3581
+ const tab = saved.route.tab;
3582
+ saved = {...saved,route:{...saved.route,listMode:files.treeApi?saved.route.listMode:'files',...(tab && allowed(tab)?{}:{view:'list',tab:null})},tabs:saved.tabs.filter(allowed)};
3583
+ } else if (!files.taskId && saved.tabs.some(tab => tab.source)) {
3584
+ saved.tabs = saved.tabs.filter(tab => !tab.source);
3585
+ if (saved.route.tab?.source) { saved.route.tab = null; saved.route.view = 'list'; }
3586
+ }
1724
3587
  const activeKey = saved.route.tab?.id;
1725
- if (merge) this.historyRoutes.set(window.history.state.index,{...saved.route});
3588
+ if (merge && !embedded) this.historyRoutes.set(window.history.state.index,{...saved.route});
1726
3589
  if (merge && (saved.route.tab && !files.tabs.has(activeKey) || local && (!saved.route.tab || saved.route.pane !== 'files' || saved.route.view !== 'content'))) return false;
1727
3590
  if (merge) {
1728
3591
  const tab = saved.tabs.find(tab => tab.id === activeKey), previous = files.tabs.get(activeKey);
1729
3592
  if (tab) {
1730
- if (files.activeKey === activeKey && (previous.path !== tab.path || previous.kind !== tab.kind || previous.mode !== tab.mode || previous.original !== tab.original)) files.renderedKey = undefined;
1731
- files.tabs.set(activeKey,Object.assign(files.tabView(activeKey,tab.path,tab.kind,tab.original),tab));
3593
+ if (files.activeKey === activeKey && (previous.path !== tab.path || previous.kind !== tab.kind || previous.mode !== tab.mode
3594
+ || previous.original !== tab.original || previous.directoryEntry !== tab.directoryEntry || previous.source !== tab.source)) files.renderedKey = undefined;
3595
+ files.tabs.set(activeKey,Object.assign(files.tabView(activeKey,tab.path,tab.kind,tab.original,tab.source),tab));
1732
3596
  }
1733
3597
  if (local) saved.route.listMode = files.listMode;
1734
3598
  } else {
1735
3599
  this.layout = {...(appBase ? this.globalLayout() : {}),...saved.layout}; this.applyLayout();
1736
- files.tabs = new Map(saved.tabs.map(tab => [tab.id,Object.assign(files.tabView(tab.id,tab.path,tab.kind,tab.original),tab)])); files.recentTabs = saved.recentTabs || [];
3600
+ files.tabs = new Map(saved.tabs.map(tab => [tab.id,Object.assign(files.tabView(tab.id,tab.path,tab.kind,tab.original,tab.source),tab)])); files.recentTabs = (saved.recentTabs || []).filter(key => files.tabs.has(key));
1737
3601
  const trees = {};
1738
3602
  for (const mode of ['files','changes']) {
1739
- const value = this.treeStates[mode] || {}, query = saved.trees[mode]?.query || '';
3603
+ const value = this.treeStates[mode] || {};
3604
+ const query = saved.treeDirectory === (files.explorerDirectory || undefined) && saved.trees[mode] ? saved.trees[mode].query : value.query || '';
1740
3605
  trees[mode] = {...value,query,...(query !== (value.query || '')?{filterCollapsed:[],filterScrollTop:0}:{})};
1741
3606
  }
1742
3607
  files.restoreTrees(trees); const view = files.navigationView(files.listMode); files.listScrollTop = (view.query?view.filterScrollTop:view.scrollTop) || 0;
@@ -1745,7 +3610,7 @@
1745
3610
  this.selectPane(saved.route.pane);
1746
3611
  const tree = files.navigationView(saved.route.listMode);
1747
3612
  const active = files.tabs.get(activeKey), target = {...(position || {listScrollTop:(tree?.query?tree.filterScrollTop:tree?.scrollTop) || 0,scrollTop:active?.scrollTop || 0,scrollLeft:active?.scrollLeft || 0})};
1748
- if (merge) { const view = files.navigationView(saved.route.listMode); target.listScrollTop = (view.query?view.filterScrollTop:view.scrollTop) || 0; }
3613
+ if (merge || position?.treeDirectory !== (files.explorerDirectory || undefined)) target.listScrollTop = (tree.query?tree.filterScrollTop:tree.scrollTop) || 0;
1749
3614
  files.restoreView(saved.route,target);
1750
3615
  if (!merge) for (const [name,selector] of [['tasks','workspace-task-list'],['chat','.chat-body'],['composer','workspace-chat textarea'],['tabs','.file-tabs']]) {
1751
3616
  const node = name === 'tabs' ? files.tabBar : this.querySelector(selector), values = saved.scroll[name];
@@ -1785,7 +3650,8 @@
1785
3650
  if (event.target !== this.filesPanel) return;
1786
3651
  const status = this.querySelector('.workspace-status'), label = this.sessionConnection || event.detail.label;
1787
3652
  status.replaceChildren(icon(event.detail.repository?'branch':'lock'),element('span',label));
1788
- status.title = this.sessionConnection && event.detail.repository ? label+' · '+event.detail.label : label;
3653
+ if (this.sessionConnection && event.detail.repository && label !== event.detail.label) status.dataset.tooltip = event.detail.label;
3654
+ else delete status.dataset.tooltip;
1789
3655
  };
1790
3656
  }
1791
3657
  customElements.define('workspace-task-list',WorkspaceTaskList);