@spzxg/cli-ui 0.6.19 → 0.6.20

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.
@@ -1,5 +1,5 @@
1
- import { g as ms, a as vs } from "./cli-ui-embed-CqlqLmqo.js";
2
- import { r as ys } from "./cli-ui-jszip.min-sxxjuGID.js";
1
+ import { g as ms, a as vs } from "./cli-ui-embed-BIeQkXIU.js";
2
+ import { r as ys } from "./cli-ui-jszip.min-cpxytNM4.js";
3
3
  function gs(e, t) {
4
4
  for (var n = 0; n < t.length; n++) {
5
5
  const r = t[n];
@@ -1,5 +1,5 @@
1
- import { a } from "./cli-ui-embed-CqlqLmqo.js";
2
- import { r as p } from "./cli-ui-jszip.min-sxxjuGID.js";
1
+ import { a } from "./cli-ui-embed-BIeQkXIU.js";
2
+ import { r as p } from "./cli-ui-jszip.min-cpxytNM4.js";
3
3
  function f(t, n) {
4
4
  for (var o = 0; o < n.length; o++) {
5
5
  const e = n[o];
@@ -1,4 +1,4 @@
1
- import { c as bt } from "./cli-ui-embed-CqlqLmqo.js";
1
+ import { c as bt } from "./cli-ui-embed-BIeQkXIU.js";
2
2
  function vt(yt) {
3
3
  throw new Error('Could not dynamically require "' + yt + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
4
4
  }
@@ -28,7 +28,7 @@ function v(e) {
28
28
  }
29
29
  async function R(e) {
30
30
  var E;
31
- const t = await import("./cli-ui-jszip.min-CRpifsVf.js").then((s) => s.j), o = await (t.default ?? t).loadAsync(e), m = async (s) => {
31
+ const t = await import("./cli-ui-jszip.min-DeMMXc2T.js").then((s) => s.j), o = await (t.default ?? t).loadAsync(e), m = async (s) => {
32
32
  const a = o.file(s);
33
33
  return a ? a.async("string") : null;
34
34
  }, S = await m("xl/workbook.xml");
package/dist/cli-ui.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as a, b as i, d as r, e as t, f as o, h as C, i as l, j as n, k as m, m as d, l as u, n as w, o as B, p as f } from "./cli-ui-embed-CqlqLmqo.js";
1
+ import { C as a, b as i, d as r, e as t, f as o, h as C, i as l, j as n, k as m, m as d, l as u, n as w, o as B, p as f } from "./cli-ui-embed-BIeQkXIU.js";
2
2
  export {
3
3
  a as CliBoard,
4
4
  i as CliBrowserView,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spzxg/cli-ui",
3
- "version": "0.6.19",
3
+ "version": "0.6.20",
4
4
  "type": "module",
5
5
  "description": "相互联动的 CliMsgList、CliChat、CliBoard,支持任务中枢和完整 Operator 工作区。",
6
6
  "main": "src/index.ts",
@@ -330,6 +330,11 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
330
330
 
331
331
  const activeRef = useRef(activeTab);
332
332
  activeRef.current = activeTab;
333
+ const closedVersions = useRef(new Map<string, number>());
334
+ useEffect(() => { closedVersions.current.clear(); }, [jobId]);
335
+ const rememberClosedVersion = (closed: OpenFile) => {
336
+ closedVersions.current.set(closed.path, Math.max(closedVersions.current.get(closed.path) ?? -1, closed.version));
337
+ };
333
338
  /** 打开文件:已经开着就切过去(并重读),否则新开一个页签;超过 MAX_FILE_TABS 关掉最早的(不关正在看的)。 */
334
339
  const openPath = useCallback((path: string, entry?: Partial<FileEntry>) => {
335
340
  const requested = path.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -339,10 +344,12 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
339
344
  setFiles((list) => {
340
345
  const have = list.find((f) => f.path === clean);
341
346
  if (have) return list.map((f) => (f.path === clean ? { ...f, name: entry?.name ?? f.name, size: entry?.size ?? f.size, mtime: entry?.mtime ?? f.mtime, version: f.version + 1 } : f));
342
- const next = [...list, { path: clean, name: entry?.name, size: entry?.size, mtime: entry?.mtime, version: 0, ...(resolvedFrom ? { resolvedFrom } : {}) }];
347
+ const priorClosed = closedVersions.current.get(clean);
348
+ const next = [...list, { path: clean, name: entry?.name, size: entry?.size, mtime: entry?.mtime, version: priorClosed !== undefined ? priorClosed + 1 : 0, ...(resolvedFrom ? { resolvedFrom } : {}) }];
343
349
  while (next.length > MAX_FILE_TABS) {
344
350
  const i = next.findIndex((f) => fileTabId(f.path) !== activeRef.current && f.path !== clean);
345
- next.splice(i >= 0 ? i : 0, 1);
351
+ const [evicted] = next.splice(i >= 0 ? i : 0, 1);
352
+ if (evicted) rememberClosedVersion(evicted);
346
353
  }
347
354
  return next;
348
355
  });
@@ -381,6 +388,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
381
388
  setFiles((list) => {
382
389
  const i = list.findIndex((f) => f.path === path);
383
390
  if (i < 0) return list;
391
+ rememberClosedVersion(list[i]);
384
392
  const next = list.filter((f) => f.path !== path);
385
393
  if (activeRef.current === fileTabId(path)) setTab(next.length ? fileTabId(next[Math.min(i, next.length - 1)].path) : "files");
386
394
  return next;
@@ -458,6 +466,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
458
466
  displayName={file.name}
459
467
  size={file.size}
460
468
  mtime={file.mtime}
469
+ workspaceRoot={info?.workspaceRoot}
461
470
  version={file.version + manual} reloadKey={file.reloadKey}
462
471
  actions={allFileActions}
463
472
  onOpenPath={(p) => openPath(p)}
@@ -134,6 +134,8 @@ export interface FileViewerProps {
134
134
  /** 文件信息(列表里已有的话省一次请求)。 */
135
135
  size?: number;
136
136
  mtime?: number;
137
+ /** 工作区根目录(用于 HTML 根相对资源解析与越界边界保护)。 */
138
+ workspaceRoot?: string;
137
139
  /** 变了就重新读(看板在文件更新时递增)。 */
138
140
  version?: number;
139
141
  /** 明确的文件变更事件使内容重新读取,不能只按末尾重叠判断为追加。 */
@@ -170,7 +172,13 @@ export function FileViewer(props:FileViewerProps) {
170
172
  let id=viewerBackendIds.get(props.backend);if(id===undefined){id=nextViewerBackendId++;viewerBackendIds.set(props.backend,id);}
171
173
  return <FileViewerInner key={JSON.stringify([id,props.jobId,props.path])} {...props}/>;
172
174
  }
173
- function FileViewerInner({ backend, jobId, path, displayName, size, mtime, version = 0, reloadKey, onOpenPath, onClose, lead, onBack, actions = [], bare, toolbarHost, onQuoteText, resolveMissing, onResolved, resolvedFrom }: FileViewerProps) {
175
+ function cacheMetaMatches(cached: { mtime?: number; size?: number }, mtime?: number, size?: number): boolean {
176
+ if (mtime !== undefined && cached.mtime !== undefined && cached.mtime !== mtime) return false;
177
+ if (size !== undefined && cached.size !== undefined && cached.size !== size) return false;
178
+ return true;
179
+ }
180
+
181
+ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, workspaceRoot, version = 0, reloadKey, onOpenPath, onClose, lead, onBack, actions = [], bare, toolbarHost, onQuoteText, resolveMissing, onResolved, resolvedFrom }: FileViewerProps) {
174
182
  const name = displayName || path.split("/").pop() || path;
175
183
  const kind: PreviewKind = previewKind(path);
176
184
  const initialCached = useMemo(() => getCachedPreview(backend, jobId, path), [backend, jobId, path]);
@@ -240,10 +248,12 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
240
248
  linksRef.current = links;
241
249
  const htmlTooBig = size !== undefined && size > HTML_QUOTE_MAX;
242
250
  const htmlBridge = (!!backend.fileSync || !!onQuoteText || links.blob) && kind === "html" && mode === "preview" && !htmlReading && !links.pending && !htmlTooBig;
243
- const [htmlDoc, setHtmlDoc] = useState<{ srcDoc: string; token: string; revision?: string } | "fallback" | "toobig" | null>(() => {
251
+ const [htmlDoc, setHtmlDoc] = useState<{ srcDoc: string; token: string; revision?: string; preparedHtml?: string } | "fallback" | "toobig" | null>(() => {
244
252
  if (initialCached?.kind !== "html" || htmlTooBig || kind !== "html") return null;
245
253
  const bridgeToken = frameToken();
246
- return { srcDoc: bridgeDoc(initialCached.preparedHtml, { token: bridgeToken, allowScripts: true }), token: bridgeToken, revision: initialCached.revision };
254
+ const url = links.url?.(path);
255
+ const base = url ? new URL(url, window.location.href).href : undefined;
256
+ return { srcDoc: bridgeDoc(initialCached.preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: initialCached.revision, preparedHtml: initialCached.preparedHtml };
247
257
  });
248
258
  useEffect(() => { if (htmlReading || mode === "source") setHtmlDoc(null); }, [htmlReading, mode]);
249
259
  const [frameState, setFrameState] = useState<"rendering" | "slow" | "ready">("rendering");
@@ -253,14 +263,14 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
253
263
  useEffect(() => {
254
264
  if (!htmlBridge) return;
255
265
  const cached = getCachedPreview(backend, jobId, path);
256
- if (attempt === 0 && cached?.kind === "html" && cached.version === version && cached.reloadKey === reloadKey) {
266
+ if (attempt === 0 && cached?.kind === "html" && cached.version === version && cached.reloadKey === reloadKey && cacheMetaMatches(cached, mtime, size)) {
257
267
  revisionRef.current = cached.revision;
258
268
  const url = linksRef.current.url?.(path);
259
269
  const base = url ? new URL(url, window.location.href).href : undefined;
260
270
  setHtmlDoc(previous => {
261
- if (previous && typeof previous === "object" && previous.revision === cached.revision) return previous;
271
+ if (previous && typeof previous === "object" && previous.revision === cached.revision && previous.preparedHtml === cached.preparedHtml) return previous;
262
272
  const bridgeToken = frameToken();
263
- return { srcDoc: bridgeDoc(cached.preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: cached.revision };
273
+ return { srcDoc: bridgeDoc(cached.preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: cached.revision, preparedHtml: cached.preparedHtml };
264
274
  });
265
275
  return;
266
276
  }
@@ -279,7 +289,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
279
289
  const latestCached = getCachedPreview(backend, jobId, path);
280
290
  let preparedHtml: string;
281
291
  let blobUrls: string[];
282
- if (result.revision && latestCached?.kind === "html" && latestCached.revision === result.revision) {
292
+ if (attempt === 0 && result.revision && latestCached?.kind === "html" && latestCached.revision === result.revision) {
283
293
  preparedHtml = latestCached.preparedHtml;
284
294
  blobUrls = latestCached.blobUrls;
285
295
  } else {
@@ -288,6 +298,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
288
298
  htmlPath: path,
289
299
  backend,
290
300
  jobId,
301
+ workspaceRoot,
291
302
  signal: ctl.signal,
292
303
  fresh: attempt > 0,
293
304
  });
@@ -305,6 +316,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
305
316
  blobUrls,
306
317
  revision: result.revision,
307
318
  size: result.size,
319
+ mtime,
308
320
  version,
309
321
  reloadKey,
310
322
  chars: result.text.length + (preparedHtml === result.text ? 0 : preparedHtml.length),
@@ -313,9 +325,9 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
313
325
  const base = url ? new URL(url, window.location.href).href : undefined;
314
326
  revisionRef.current = result.revision;
315
327
  setHtmlDoc(previous => {
316
- if (result.revision && previous && typeof previous === "object" && previous.revision === result.revision) return previous;
328
+ if (result.revision && previous && typeof previous === "object" && previous.revision === result.revision && previous.preparedHtml === preparedHtml) return previous;
317
329
  const bridgeToken = frameToken();
318
- return { srcDoc: bridgeDoc(preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: result.revision };
330
+ return { srcDoc: bridgeDoc(preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: result.revision, preparedHtml };
319
331
  });
320
332
  }).catch((error: unknown) => {
321
333
  if (ctl.signal.aborted) return;
@@ -330,7 +342,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
330
342
  else setHtmlDoc("fallback");
331
343
  }).finally(() => { if (!ctl.signal.aborted) setSyncing(false); });
332
344
  return () => ctl.abort();
333
- }, [htmlBridge, backend, jobId, path, version, reloadKey, attempt, htmlPresentation]);
345
+ }, [htmlBridge, backend, jobId, path, workspaceRoot, mtime, size, version, reloadKey, attempt, htmlPresentation]);
334
346
  const activeToken = htmlDoc && typeof htmlDoc === "object" ? htmlDoc.token : token;
335
347
  useEffect(() => {
336
348
  if (!bridged || !htmlDoc || typeof htmlDoc !== "object") return;
@@ -367,7 +379,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
367
379
  const sourceWin = frame.contentWindow;
368
380
  const reqId = data.assetReq;
369
381
  const relUrl = data.relUrl;
370
- const target = resolveWorkspaceAssetPath(path, relUrl);
382
+ const target = resolveWorkspaceAssetPath(path, relUrl, workspaceRoot);
371
383
  if (!target) {
372
384
  sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: false, error: "路径无效" }, "*");
373
385
  return;
@@ -387,7 +399,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
387
399
  return;
388
400
  }
389
401
  if (typeof data.openPath === "string") {
390
- const target = resolveWorkspaceAssetPath(path, data.openPath);
402
+ const target = resolveWorkspaceAssetPath(path, data.openPath, workspaceRoot);
391
403
  if (target && openPathRef.current) openPathRef.current(target);
392
404
  return;
393
405
  }
@@ -402,7 +414,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
402
414
  };
403
415
  window.addEventListener("message", onMessage);
404
416
  return () => { disposed = true; window.removeEventListener("message", onMessage); };
405
- }, [backend, jobId, path, onQuoteText, activeToken]);
417
+ }, [backend, jobId, path, workspaceRoot, onQuoteText, activeToken]);
406
418
  useEffect(() => {
407
419
  if (!onQuoteText) return;
408
420
  const read = () => {
@@ -494,7 +506,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
494
506
  } else {
495
507
  const max = htmlReading || progressiveText || backend.fileSync && kind === "markdown" ? textLimit : TEXT_MAX;
496
508
  const cached = getCachedPreview(backend, jobId, path);
497
- if (attempt === 0 && cached?.kind === "text" && cached.version === version && cached.reloadKey === reloadKey && cached.tail === tail && (cached.textLimit >= max || !cached.loaded.truncated)) {
509
+ if (attempt === 0 && cached?.kind === "text" && cached.version === version && cached.reloadKey === reloadKey && cached.tail === tail && (cached.textLimit >= max || !cached.loaded.truncated) && cacheMetaMatches(cached, mtime, size)) {
498
510
  revisionRef.current = cached.loaded.revision;
499
511
  setLoaded(previous => previous?.kind === "text" && previous.revision === cached.loaded.revision && previous.text === cached.loaded.text ? previous : { kind: "text", ...cached.loaded });
500
512
  return () => { alive = false; ctl.abort(); };
@@ -512,7 +524,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
512
524
  const box = bodyRef.current;
513
525
  stick.current = tail || (!!box && box.scrollHeight > box.clientHeight && box.scrollHeight - box.scrollTop - box.clientHeight < 40);
514
526
  revisionRef.current = r.revision;
515
- setCachedPreview(backend, jobId, path, { kind: "text", loaded: r, tail, textLimit: max, version, reloadKey, chars: r.text.length });
527
+ setCachedPreview(backend, jobId, path, { kind: "text", loaded: r, tail, textLimit: max, size: r.size, mtime, version, reloadKey, chars: r.text.length });
516
528
  setLoaded({ kind: "text", ...r });
517
529
  },
518
530
  (e: unknown) => { if (alive && !ctl.signal.aborted) {
@@ -526,7 +538,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
526
538
  ).finally(() => { if (alive) setSyncing(false); });
527
539
  }
528
540
  return () => { alive = false; ctl.abort(); };
529
- }, [backend, jobId, path, kind, needsSrc, version, reloadKey, tail, attempt, textLimit, htmlReading]); // eslint-disable-line react-hooks/exhaustive-deps
541
+ }, [backend, jobId, path, kind, needsSrc, mtime, size, version, reloadKey, tail, attempt, textLimit, htmlReading]); // eslint-disable-line react-hooks/exhaustive-deps
530
542
  useLayoutEffect(() => {
531
543
  const box = bodyRef.current;
532
544
  if (box && stick.current && loaded?.kind === "text") box.scrollTop = box.scrollHeight;
@@ -25,7 +25,9 @@ const randomId = () => Math.random().toString(36).slice(2, 12) + Math.random().t
25
25
  export const frameToken = randomId;
26
26
 
27
27
  function runtimeAssetBridge() {
28
- return `var pending=new Map(),blobs=new Map(),seq=0,ext=/^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i;
28
+ return `if(typeof History!=="undefined"&&History.prototype){["replaceState","pushState"].forEach(function(fn){var orig=History.prototype[fn];if(typeof orig==="function")History.prototype[fn]=function(){try{return orig.apply(this,arguments)}catch(e){}}})}
29
+ (function(){function memStore(){var d=Object.create(null);return{get length(){return Object.keys(d).length},key:function(i){return Object.keys(d)[i]||null},getItem:function(k){return Object.prototype.hasOwnProperty.call(d,String(k))?d[String(k)]:null},setItem:function(k,v){d[String(k)]=String(v)},removeItem:function(k){delete d[String(k)]},clear:function(){d=Object.create(null)}}}["localStorage","sessionStorage"].forEach(function(k){try{var st=window[k];if(!st)throw 1;st.getItem("__cli_ui_probe__")}catch(e){try{Object.defineProperty(window,k,{configurable:true,value:memStore()})}catch(e2){}}})})();
30
+ var pending=new Map(),blobs=new Map(),seq=0,ext=/^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i;
29
31
  function isRel(u){return typeof u==="string"&&!!u.trim()&&!ext.test(u.trim())}
30
32
  function askAsset(u){var k=u.trim();if(blobs.has(k))return blobs.get(k);var p=new Promise(function(res,rej){var id="r"+(++seq);var tm=setTimeout(function(){pending.delete(id);rej(new Error("资源加载超时"))},30000);pending.set(id,{res:res,rej:rej,tm:tm});post({assetReq:id,relUrl:k})});blobs.set(k,p);return p}
31
33
  addEventListener("message",function(e){if(e.source!==parent||!e.data||e.data.cliUiAsset!==t)return;var w=pending.get(e.data.assetReq);if(!w)return;pending.delete(e.data.assetReq);clearTimeout(w.tm);if(e.data.ok&&e.data.bytes){var b=new Blob([e.data.bytes],{type:e.data.mime||"application/octet-stream"});w.res({url:URL.createObjectURL(b),bytes:e.data.bytes,mime:e.data.mime||"application/octet-stream"})}else{blobs.delete(e.data.relUrl);w.rej(new Error(e.data.error||"资源不存在"))}});
@@ -39,6 +41,7 @@ Node.prototype.appendChild=function(c){if(patchNode(c))return c;return origAppen
39
41
  Node.prototype.insertBefore=function(c,r){if(patchNode(c))return c;return origInsertBefore.call(this,c,r)};
40
42
  if(typeof MutationObserver!=="undefined"){new MutationObserver(function(ms){for(var i=0;i<ms.length;i++){var m=ms[i];if(m.type==="attributes"&&m.target)patchNode(m.target);else if(m.addedNodes)for(var j=0;j<m.addedNodes.length;j++){var nd=m.addedNodes[j];if(nd.nodeType===1){patchNode(nd);if(nd.querySelectorAll){var imgs=nd.querySelectorAll("img[src],link[href]");for(var k=0;k<imgs.length;k++)patchNode(imgs[k])}}}}}).observe(document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:["src"]})}
41
43
  if(typeof window.fetch==="function"){var origFetch=window.fetch.bind(window);window.fetch=function(input,init){var u=typeof input==="string"?input:input&&typeof input.url==="string"?input.url:"";if(isRel(u))return askAsset(u).then(function(r){return new Response(r.bytes,{status:200,headers:{"Content-Type":r.mime}})},function(){return new Response("Not Found",{status:404})});return origFetch(input,init)}}
44
+ if(typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest.prototype){var xo=XMLHttpRequest.prototype.open,xs=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(m,u,a){this._cliRel=a!==false&&isRel(u)?u:null;return xo.apply(this,arguments)};XMLHttpRequest.prototype.send=function(){if(!this._cliRel)return xs.apply(this,arguments);var x=this,u=this._cliRel;this._cliRel=null;askAsset(u).then(function(r){var txt=new TextDecoder().decode(r.bytes),resp=txt;if(x.responseType==="arraybuffer")resp=r.bytes.buffer;else if(x.responseType==="blob")resp=new Blob([r.bytes],{type:r.mime});else if(x.responseType==="json"){try{resp=JSON.parse(txt)}catch(e){resp=null}}Object.defineProperty(x,"readyState",{configurable:true,value:4});Object.defineProperty(x,"status",{configurable:true,value:200});if(!x.responseType||x.responseType==="text")Object.defineProperty(x,"responseText",{configurable:true,value:txt});Object.defineProperty(x,"response",{configurable:true,value:resp});x.dispatchEvent(new Event("readystatechange"));x.dispatchEvent(new Event("load"));x.dispatchEvent(new Event("loadend"))},function(){Object.defineProperty(x,"readyState",{configurable:true,value:4});Object.defineProperty(x,"status",{configurable:true,value:404});x.dispatchEvent(new Event("readystatechange"));x.dispatchEvent(new Event("error"));x.dispatchEvent(new Event("loadend"))})}}
42
45
  document.addEventListener("click",function(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;var a=e.target&&e.target.closest&&e.target.closest("a[href]");if(!a)return;var hr=a.getAttribute("href")||"";if(!isRel(hr))return;var clean=hr.split(/[?#]/)[0]||"";if(/\\.(?:html|htm)$/i.test(clean)){e.preventDefault();post({openPath:clean})}});`;
43
46
  }
44
47
 
@@ -66,18 +66,28 @@ export function resolveWorkspaceAssetPath(fromFile: string, rawRef: string | nul
66
66
 
67
67
  const normalizedRoot = workspaceRoot ? workspaceRoot.replace(/\\/g, "/").replace(/\/+$/, "") : undefined;
68
68
  if (cleanRef.startsWith("/")) {
69
- if (!normalizedRoot) return null;
70
69
  const rel = cleanRef.replace(/^\/+/, "");
71
70
  const resolved = normalizeSegments(rel.split("/"));
72
- return resolved ? `${normalizedRoot}/${resolved.join("/")}` : null;
71
+ if (!resolved) return null;
72
+ if (isAbsFrom) {
73
+ if (!normalizedRoot || !normalizedRoot.startsWith("/")) return null;
74
+ return `${normalizedRoot}/${resolved.join("/")}`;
75
+ }
76
+ if (isHomeFrom) return null;
77
+ if (normalizedRoot && !normalizedRoot.startsWith("/")) {
78
+ return `${normalizedRoot}/${resolved.join("/")}`;
79
+ }
80
+ return resolved.join("/");
73
81
  }
74
82
 
75
83
  const prefix = isAbsFrom ? "/" : isHomeFrom ? "~/" : "";
76
84
  const bodyFrom = isAbsFrom ? normalizedFrom.slice(1) : isHomeFrom ? normalizedFrom.slice(2) : normalizedFrom;
77
85
  const baseSegments = bodyFrom.split("/").filter(Boolean).slice(0, -1);
78
- const minDepth = normalizedRoot && isAbsFrom && normalizedFrom.startsWith(`${normalizedRoot}/`)
86
+ const minDepth = normalizedRoot && isAbsFrom && normalizedRoot.startsWith("/") && normalizedFrom.startsWith(`${normalizedRoot}/`)
79
87
  ? normalizedRoot.slice(1).split("/").filter(Boolean).length
80
- : 0;
88
+ : normalizedRoot && !isAbsFrom && !isHomeFrom && !normalizedRoot.startsWith("/") && normalizedFrom.startsWith(`${normalizedRoot}/`)
89
+ ? normalizedRoot.split("/").filter(Boolean).length
90
+ : 0;
81
91
 
82
92
  const stack = [...baseSegments];
83
93
  for (const rawSeg of cleanRef.split("/")) {
@@ -8,6 +8,7 @@ export interface CachedHtmlPreview {
8
8
  blobUrls: string[];
9
9
  revision?: string;
10
10
  size?: number;
11
+ mtime?: number;
11
12
  version: number;
12
13
  reloadKey?: number | string;
13
14
  chars: number;
@@ -18,6 +19,8 @@ export interface CachedTextPreview {
18
19
  loaded: LoadedText;
19
20
  tail: boolean;
20
21
  textLimit: number;
22
+ size?: number;
23
+ mtime?: number;
21
24
  version: number;
22
25
  reloadKey?: number | string;
23
26
  chars: number;
@@ -888,7 +888,7 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
888
888
  <div className="scrim" onClick={(e) => { if (e.target === e.currentTarget) setPopup(null); }}>
889
889
  <div className={`modal cli-popup ${popup.kind}`} role="dialog" aria-modal="true" aria-label={popup.kind === "file" ? popup.path : "任务浏览器"}>
890
890
  {popup.kind === "file" ? (
891
- <FileViewer backend={board} jobId={key} path={popup.path} onClose={() => setPopup(null)} onOpenPath={(p) => setPopup({ key: popup.key, kind: "file", path: p })}
891
+ <FileViewer backend={board} jobId={key} path={popup.path} workspaceRoot={attachmentScope?.workspaceRoot} onClose={() => setPopup(null)} onOpenPath={(p) => setPopup({ key: popup.key, kind: "file", path: p })}
892
892
  resolveMissing={resolvePopupPath} onResolved={(to) => setPopup({ key: popup.key, kind: "file", path: to, resolvedFrom: popup.resolvedFrom ?? popup.path })} resolvedFrom={popup.resolvedFrom} />
893
893
  ) : (
894
894
  <>
@@ -239,7 +239,10 @@ export function SessionRail({ project, task, sessions, running, onResolveWithAI,
239
239
  // A relative path the agent wrote against a subfolder → the existing file it was
240
240
  // completed to (board/pathResolve). Clicking the same link again opens that one.
241
241
  const aliases=useRef(new Map<string,string>());
242
- const openFile=(taskId:string,path:string)=>{
242
+ const closedVersions=useRef(new Map<string,number>());
243
+ useEffect(()=>{closedVersions.current.clear();},[task.id]);
244
+ const rememberClosed=(closed:OpenFile)=>{const k=fileKey(closed);closedVersions.current.set(k,Math.max(closedVersions.current.get(k)??-1,closed.version));};
245
+ const openFile=(taskId:string,path:string,entry?:{name?:string;size?:number;mtime?:number})=>{
243
246
  if(!available.includes('files'))return;
244
247
  const requested=path.replace(/^\.\//,'').replace(/\/+$/,'');if(!requested)return;
245
248
  const clean=aliases.current.get(fileKey({taskId,path:requested}))??requested;
@@ -248,9 +251,10 @@ export function SessionRail({ project, task, sessions, running, onResolveWithAI,
248
251
  visitBoardFile(task.id,{sourceId:taskId,path:clean});
249
252
  setFiles(previous=>{
250
253
  const found=previous.find(f=>fileKey(f)===id);
251
- if(found)return previous.map(f=>fileKey(f)===id?{...f,version:f.version+1}:f);
252
- const next=[...previous,{taskId,path:clean,version:0}];
253
- if(next.length>8){const index=next.findIndex(f=>fileKey(f)!==current.current&&fileKey(f)!==id);next.splice(index<0?0:index,1);}
254
+ if(found)return previous.map(f=>fileKey(f)===id?{...f,name:entry?.name??f.name,size:entry?.size??f.size,mtime:entry?.mtime??f.mtime,version:f.version+1}:f);
255
+ const priorClosed=closedVersions.current.get(id);
256
+ const next=[...previous,{taskId,path:clean,name:entry?.name,size:entry?.size,mtime:entry?.mtime,version:priorClosed!==undefined?priorClosed+1:0}];
257
+ if(next.length>8){const index=next.findIndex(f=>fileKey(f)!==current.current&&fileKey(f)!==id);const [evicted]=next.splice(index<0?0:index,1);if(evicted)rememberClosed(evicted);}
254
258
  return next;
255
259
  });setTab(id);inlineRef.current?.onActivate();
256
260
  };
@@ -294,7 +298,7 @@ export function SessionRail({ project, task, sessions, running, onResolveWithAI,
294
298
  useEffect(()=>()=>releaseBoardState(task.id,owner),[task.id,owner]);
295
299
  const label=(id:string)=>LABEL[id]??files.find(f=>fileKey(f)===id)?.name??files.find(f=>fileKey(f)===id)?.path.split('/').pop()??id;
296
300
  const close=(id:string)=>{
297
- if(id.startsWith('file:'))setFiles(previous=>previous.filter(f=>fileKey(f)!==id));else panels.close(id);
301
+ if(id.startsWith('file:'))setFiles(previous=>{const closed=previous.find(f=>fileKey(f)===id);if(closed)rememberClosed(closed);return previous.filter(f=>fileKey(f)!==id);});else panels.close(id);
298
302
  if(active===id){const next=shown.find(item=>item!==id)??'';setTab(next);if(!next)inlineLayout?.onChat();}
299
303
  };
300
304
  const railTabs=<div className="rail-tabs">
@@ -316,11 +320,11 @@ export function SessionRail({ project, task, sessions, running, onResolveWithAI,
316
320
  </>}
317
321
  {contentVisible&&active==='files'&&<>
318
322
  {folderTask!==task.id&&<div className="fork-merge-note cli-source-workspace"><span>正在浏览来源任务的工作区。</span><button className="btn btn-ghost btn-sm" onClick={()=>{setFolderTask(task.id);setDir('');}}>返回当前工作区</button></div>}
319
- <FilesPane toolbarHost={toolbarHost} backend={backend} jobId={folderTask} dir={dir} onDir={setDir} onOpen={entry=>openFile(folderTask,entry.path)} refreshKey={tick}/>
323
+ <FilesPane toolbarHost={toolbarHost} backend={backend} jobId={folderTask} dir={dir} onDir={setDir} onOpen={entry=>openFile(folderTask,entry.path,entry)} refreshKey={tick}/>
320
324
  </>}
321
325
  {contentVisible&&file&&<>
322
326
  {file.taskId!==task.id&&<div className="fork-merge-note">正在查看来源任务的文件,不会切换当前执行分支。</div>}
323
- <FileViewer toolbarHost={toolbarHost} key={fileKey(file)} backend={backend} jobId={file.taskId} path={file.path} displayName={file.name} size={file.size} mtime={file.mtime} version={file.version} reloadKey={file.reloadKey}
327
+ <FileViewer toolbarHost={toolbarHost} key={fileKey(file)} backend={backend} jobId={file.taskId} path={file.path} displayName={file.name} size={file.size} mtime={file.mtime} workspaceRoot={workspaceRoots[file.taskId]} version={file.version} reloadKey={file.reloadKey}
324
328
  onOpenPath={path=>openFile(file.taskId,path)}
325
329
  actions={quote?[{label:'引用到对话',onClick:()=>quote({id:`file:${file.taskId}:${file.path}`,sourceTaskId:file.taskId,author:`文件 ${file.path}`,text:`${file.taskId===task.id?'当前工作区':`来源任务 ${file.taskId} 的工作区`}文件 ${file.path}`})}]:[]}
326
330
  onQuoteText={quote?(text, context)=>quote({id:`selection:${file.taskId}:${file.path}`,sourceTaskId:file.taskId,author:`${file.taskId===task.id?"当前工作区":`来源任务 ${file.taskId} 的工作区`}文件 ${file.path}`,text:context?`文件修订:${context.revision}\n${text}`:text}):undefined}