@tea-agent/loop-agent 0.52.0-next.5 → 0.52.0-next.7

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 (82) hide show
  1. package/CHANGELOG.md +3 -1
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/shared/pi-context-pressure/checkpoint.js +94 -24
  4. package/dist/shared/pi-context-pressure/compaction-policy.js +104 -11
  5. package/dist/shared/pi-context-pressure/extension.js +25 -8
  6. package/dist/shared/pi-context-pressure/telemetry.js +5 -0
  7. package/dist/worker/console/chat/chat-event-projection.js +4 -0
  8. package/dist/worker/console/chat/context-insights.js +37 -0
  9. package/dist/worker/console/chat/pi-runtime.js +109 -14
  10. package/dist/worker/console/chat/routes.js +22 -38
  11. package/dist/worker/console/chat/terminal-sessions.js +10 -4
  12. package/dist/worker/console/chat/tool-presentation.js +17 -10
  13. package/dist/worker/console/chat/turn-process.js +7 -12
  14. package/dist/worker/console/chat/workspace-changes.js +3 -133
  15. package/dist/worker/console/pi-compaction-settings.js +182 -0
  16. package/dist/worker/console/server.js +59 -1
  17. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-q8Zn-JlS.js → abnfDiagram-N423BO3Z-dqs14ztl.js} +1 -1
  18. package/dist/worker/console/static/assets/{arc-CqXYi6Cq.js → arc-ycCsBOKq.js} +1 -1
  19. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-BfrVQFaO.js → architectureDiagram-T3A2C74G-zH6OsJ3F.js} +1 -1
  20. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFl6xIeQ.js → blockDiagram-VBNYF7ZC-BTHa7mum.js} +1 -1
  21. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BkeCachn.js → c4Diagram-5PPSVZJV-C-rMuO2s.js} +1 -1
  22. package/dist/worker/console/static/assets/channel-CGeKfL9B.js +1 -0
  23. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DKbA7wvS.js → chunk-2GRJ4B5K-BcCeUNR1.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-COeFrK0l.js → chunk-2Q5K7J3B-CNTQ1sD2.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DN50xlDZ.js → chunk-5RXB4S5H-Wi4w1cx2.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-Cds3bTQr.js → chunk-5VM5RSS4-p_Hs9_Wk.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-GnSZ3Q_F.js → chunk-6Q2QTUOP-v1DdjVn6.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-C6UwY9nR.js → chunk-GF5L2VYU-BoI0eRG-.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BuYYcpOE.js → chunk-JWPE2WC7-BMFMpcqo.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BksBBron.js → chunk-KBJHAD2P-DEwXnLp8.js} +1 -1
  31. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-lATCww1u.js → chunk-RYQCIY6F-CBPsPN5L.js} +1 -1
  32. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-w1pNKtr7.js → chunk-XXDRQBXY-nSCNGsQV.js} +1 -1
  33. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CtCV0pXe.js +1 -0
  34. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CtCV0pXe.js +1 -0
  35. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-C-M-DjUn.js → cose-bilkent-JH36ORCC-DYgOAECJ.js} +1 -1
  36. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-zh47XBGY.js → cynefinDiagram-MW4NZA55-CEMHeSID.js} +1 -1
  37. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DmBrLR56.js → dagre-VZM6K2ZE-Ch2LSfkh.js} +1 -1
  38. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-_aQq1Uwl.js → diagram-7IWD3JNH-Z2rwBl2B.js} +1 -1
  39. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-rD-1FbDW.js → diagram-B4RE2ZJO-hKdk3uIF.js} +1 -1
  40. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-BIOtuSUO.js → diagram-LBJQPF4R-DV9iVK1o.js} +1 -1
  41. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-COYOUs-A.js → diagram-Q27KOJAE-_B9vXFks.js} +1 -1
  42. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DHBljm5_.js → diagram-UB23O5K3-BiFODYVn.js} +1 -1
  43. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-B2aPoFUL.js → ebnfDiagram-BXEA7PRR-BtppKXOk.js} +1 -1
  44. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-S3jGp2gH.js → erDiagram-JOGREHBK-NGdG4Zd0.js} +1 -1
  45. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-4PZPJme4.js → flowDiagram-UKHOOZJN-CaWIGxHl.js} +1 -1
  46. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-hY9AqGVo.js → ganttDiagram-PKOTCBZU-BLPJG36P.js} +1 -1
  47. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DBNB0wWX.js → gitGraphDiagram-DS77QQ5N-DuO1QAht.js} +1 -1
  48. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-Cej8plCh.js → infoDiagram-6WML65LV-BPpFnqhB.js} +1 -1
  49. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BmeNegTv.js → ishikawaDiagram-WSZJBQD7-BfAMPJEM.js} +1 -1
  50. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BlL2uW1B.js → journeyDiagram-NVQOT4AX-BpSswWxo.js} +1 -1
  51. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BUQ6cZg2.js → kanban-definition-27J2QSJJ-BpN7JQBv.js} +1 -1
  52. package/dist/worker/console/static/assets/{linear-XcBbsyGj.js → linear-BzzDVsu_.js} +1 -1
  53. package/dist/worker/console/static/assets/main-BthRH_xj.css +1 -0
  54. package/dist/worker/console/static/assets/{main-BtQuxoWS.js → main-Co5N9UKN.js} +132 -132
  55. package/dist/worker/console/static/assets/{mermaid.core-CIj0Ef-_.js → mermaid.core-Bt5WNmlD.js} +4 -4
  56. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-J2HWWWHK.js → mindmap-definition-FAOFIHXS-C9MjPB5l.js} +1 -1
  57. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-Bi4Txdnd.js → pegDiagram-VL7TDLO6-B36xJmjp.js} +1 -1
  58. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-C_Ir9kQa.js → pieDiagram-7S7Q4E2Y-BV7T5gTj.js} +1 -1
  59. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-Wmzc16HI.js → quadrantDiagram-CIZ2JOQS-D2gDIP9w.js} +1 -1
  60. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BBlE2mdV.js → railroadDiagram-AXF67PYL-CIZlGt7n.js} +1 -1
  61. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-10tJvPpg.js → requirementDiagram-LRYGKXZP-DvRiX28G.js} +1 -1
  62. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-CMyZUusG.js → sankeyDiagram-W5VNT64P-B7yaoTpY.js} +1 -1
  63. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BAMpiKB0.js → sequenceDiagram-SI44F4Z6-BCiJSVEd.js} +1 -1
  64. package/dist/worker/console/static/assets/{sheet-workbook-C-2fz9qI.js → sheet-workbook-C1Erf8Y1.js} +1 -1
  65. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-f5t9RbJB.js → sizeCapture-X5ZJPWSS-65jTNocn.js} +1 -1
  66. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-EMnmXMw9.js → stateDiagram-OKZ733FA-BpK4s7Tw.js} +1 -1
  67. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DcaxcyWN.js +1 -0
  68. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BosIuNEF.js → swimlanes-SLNWSIFB--zalGoVa.js} +2 -2
  69. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CH4koTkS.js +8 -0
  70. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-dhqGUSL1.js → timeline-definition-Z64GVDOM-6kZdrjCx.js} +1 -1
  71. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-Buj6-SnQ.js → vennDiagram-T6HMQDX7-D_7c8PzZ.js} +1 -1
  72. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BdmO-2xt.js → wardleyDiagram-T6FBY63Y-DJ1p4Tas.js} +1 -1
  73. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-dbO2MqJN.js → xychartDiagram-ELKLHX3M-DjeW3yhW.js} +1 -1
  74. package/dist/worker/console/static/index.html +2 -2
  75. package/dist/worker/console/static-src/operator-chat/compaction-message.js +4 -0
  76. package/package.json +3 -3
  77. package/dist/worker/console/static/assets/channel-bnnK2hoC.js +0 -1
  78. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CRSYuU2u.js +0 -1
  79. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CRSYuU2u.js +0 -1
  80. package/dist/worker/console/static/assets/main-C9HyHMYb.css +0 -1
  81. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-pqCJTCQK.js +0 -1
  82. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-6P0fI_e1.js +0 -8
@@ -45,6 +45,7 @@ import { createWorkflowRecorder } from "./workflow/record.js";
45
45
  import { buildWorkflowJobTools } from "./workflow/job-tools.js";
46
46
  import { assertConsoleResourcePolicy, withConsoleResourcePolicy } from "./subagents/resource-policy.js";
47
47
  import { bindSessionExtensions, createConsoleToolPolicyExtension, disposeSessionExtensions, setSessionToolPolicy } from "./pi-runtime/extension-bindings.js";
48
+ import { createPiCompactionSettings, resolveCompactionSettings, } from "../pi-compaction-settings.js";
48
49
  import { createOperatorChatResourceLoader, } from "./resource-loader.js";
49
50
  import { applySkillAutoInvocationPreferences, loadResourcePreferences, } from "./resource-preferences-store.js";
50
51
  import { buildPiModeLoopIsolationOptions } from "./pi-mode-loop-isolation.js";
@@ -478,6 +479,27 @@ export class PiSessionInitFailedError extends Error {
478
479
  this.name = "PiSessionInitFailedError";
479
480
  }
480
481
  }
482
+ /**
483
+ * Merge saved user preferences into a parsed policy.
484
+ *
485
+ * Only the two deployment-shaped knobs are overridable here; everything else
486
+ * stays with the environment parser so there is a single source for each
487
+ * decision. The environment still wins inside `resolveCompactionSettings`.
488
+ */
489
+ function withUserCompactionSettings(policy, settings) {
490
+ if (!settings)
491
+ return policy;
492
+ const resolved = resolveCompactionSettings({ saved: settings });
493
+ return {
494
+ ...policy,
495
+ ...(resolved.gatewayInputLimitTokens === undefined
496
+ ? {}
497
+ : { gatewayInputLimitTokens: resolved.gatewayInputLimitTokens }),
498
+ ...(resolved.keepRecentTokens === undefined
499
+ ? {}
500
+ : { keepRecentTokens: resolved.keepRecentTokens }),
501
+ };
502
+ }
481
503
  async function readModelConfigFileVersion(filePath) {
482
504
  try {
483
505
  const value = await stat(filePath, { bigint: true });
@@ -867,20 +889,68 @@ export class ConsolePiRuntime {
867
889
  ...(pruneSettings.enabled && policy.mode !== "off" ? { prune: pruneSettings.config } : {}),
868
890
  });
869
891
  }
870
- applySessionRecoveryOverrides(sessionId, services, session) {
892
+ /**
893
+ * The conversation window Pi itself reports, and the window Pi will compute
894
+ * its threshold against.
895
+ *
896
+ * Pi derives its own compaction threshold from the model definition, so the
897
+ * reserve handed to it must be expressed against that same number. A gateway
898
+ * limit only narrows the Console's trigger basis; feeding it to Pi as the
899
+ * window would make Pi subtract the limit twice and never fire.
900
+ */
901
+ piDeclaredWindow(session, reportedWindow) {
902
+ const configured = session?.model?.contextWindow;
903
+ if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
904
+ return configured;
905
+ }
906
+ if (typeof reportedWindow === "number" && reportedWindow > 0) {
907
+ return reportedWindow;
908
+ }
909
+ return undefined;
910
+ }
911
+ applySessionRecoveryOverrides(sessionId, services, session, userSettings) {
871
912
  applyProcessRetryOverride(services?.settingsManager);
872
913
  const manager = services?.settingsManager;
873
- const window = session?.getSessionStats?.()?.contextUsage?.contextWindow;
914
+ const reportedWindow = session?.getSessionStats?.()?.contextUsage?.contextWindow;
915
+ const declaredWindow = this.piDeclaredWindow(session, reportedWindow);
874
916
  applyProcessCompactionOverride(manager, {
875
- policy: parseCompactionPolicy(),
876
- ...(typeof window === "number" ? { contextWindow: window } : {}),
877
- // Console should allow an explicit compact as soon as there is a
878
- // previous turn. Pi's 20k default is a useful retention policy for
879
- // the TUI, but becomes a hard "session too small" gate here.
880
- keepRecentTokens: 0,
917
+ // User-scoped gateway limit / retained tail, when the operator saved
918
+ // one in 模型与认证. Environment variables still win inside
919
+ // resolveCompactionSettings.
920
+ policy: withUserCompactionSettings(parseCompactionPolicy(), userSettings),
921
+ ...(typeof declaredWindow === "number"
922
+ ? {
923
+ contextWindow: declaredWindow,
924
+ declaredContextWindow: declaredWindow,
925
+ }
926
+ : {}),
927
+ // NOTE: no explicit keepRecentTokens here on purpose. Forcing 0 made
928
+ // `messagesToSummarize` span the whole branch, so the summary request
929
+ // re-sent the history the gateway had just rejected and failed too.
930
+ // The policy derives a bounded tail from the trigger line (see
931
+ // resolveKeepRecentTokens); saved settings or
932
+ // HARNESS_COMPACTION_KEEP_RECENT_TOKENS override that split.
881
933
  });
882
934
  void sessionId;
883
935
  }
936
+ /**
937
+ * Read the saved compaction preferences once per session start.
938
+ *
939
+ * A missing or unreadable file must not break session creation; the policy
940
+ * falls back to environment variables and then to the declared window.
941
+ */
942
+ async loadUserCompactionSettings() {
943
+ const appDataRoot = this.options.appDataRoot;
944
+ if (!appDataRoot)
945
+ return undefined;
946
+ try {
947
+ const store = await createPiCompactionSettings(appDataRoot);
948
+ return await store.current();
949
+ }
950
+ catch {
951
+ return undefined;
952
+ }
953
+ }
884
954
  /**
885
955
  * Pick the context window to gate proactive compaction on.
886
956
  *
@@ -907,18 +977,25 @@ export class ConsolePiRuntime {
907
977
  return DEFAULT_CONTEXT_WINDOW;
908
978
  }
909
979
  async runPrePromptCompaction(sessionId, session, promptText, imageCount, onEvent, signal) {
910
- const policy = parseCompactionPolicy();
911
980
  if (signal?.aborted)
912
981
  return;
913
- if (policy.mode === "off")
982
+ const parsed = parseCompactionPolicy();
983
+ if (parsed.mode === "off")
914
984
  return;
985
+ // The saved preferences must reach this check too: the operator sets the
986
+ // gateway limit here, and evaluating it only when writing Pi's settings
987
+ // left the pre-prompt gate on the declared window.
988
+ const policy = withUserCompactionSettings(parsed, await this.loadUserCompactionSettings());
915
989
  const controller = this.getCompactionController(sessionId);
916
990
  const stats = session.getSessionStats?.();
917
991
  const reportedWindow = stats?.contextUsage?.contextWindow;
918
992
  const tokens = stats?.contextUsage?.tokens;
919
993
  const window = this.resolveContextWindow(session, reportedWindow);
994
+ // Keep Pi's own threshold on the same line as this gate. The settings
995
+ // write is idempotent, so repeating it here costs nothing and guarantees
996
+ // the two thresholds agree even when the window changed mid-session.
920
997
  if (typeof window === "number" && window > 0) {
921
- this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session);
998
+ this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session, await this.loadUserCompactionSettings());
922
999
  }
923
1000
  const projection = projectPromptPressure({
924
1001
  currentContextTokens: tokens,
@@ -1347,7 +1424,7 @@ export class ConsolePiRuntime {
1347
1424
  return undefined;
1348
1425
  }
1349
1426
  this.pinSessionTools(init.sessionId, session);
1350
- this.applySessionRecoveryOverrides(init.sessionId, services, session);
1427
+ this.applySessionRecoveryOverrides(init.sessionId, services, session, await this.loadUserCompactionSettings());
1351
1428
  }
1352
1429
  catch (error) {
1353
1430
  abandon();
@@ -2348,8 +2425,9 @@ export class ConsolePiRuntime {
2348
2425
  if (this.disposedSessions.has(sessionId))
2349
2426
  return disposedResult();
2350
2427
  const services = this.serviceScopes.get(sessionId);
2351
- if (services)
2352
- this.applySessionRecoveryOverrides(sessionId, services, session);
2428
+ if (services) {
2429
+ this.applySessionRecoveryOverrides(sessionId, services, session, await this.loadUserCompactionSettings());
2430
+ }
2353
2431
  await this.refreshModelConfiguration(sessionId, "force");
2354
2432
  if (this.disposedSessions.has(sessionId))
2355
2433
  return disposedResult();
@@ -3235,6 +3313,23 @@ export class ConsolePiRuntime {
3235
3313
  ? activeCompaction?.compactionId ?? newCompactionId(sessionId)
3236
3314
  : undefined;
3237
3315
  const mapped = mapSdkEvent(sessionId, event.type === "tool_execution_start" ? { ...event, args: projectSkillReadArgs(event.toolName, event.args, currentSkills(), this.serviceScopes.get(sessionId)?.cwd ?? this.options.cwd) } : event, compactionId, Math.max(1, step));
3316
+ /*
3317
+ * Say WHY a compaction produced a local summary.
3318
+ *
3319
+ * The extension only takes over after the provider summary request
3320
+ * failed, so a completed compaction with the fallback armed means the
3321
+ * gateway refused twice: once for the original request and again for
3322
+ * the summary. Without this the message stream shows a compaction that
3323
+ * looks identical to a normal one, while the content is visibly worse.
3324
+ */
3325
+ if (mapped?.type === "compaction_end") {
3326
+ const controller = this.compactionControllers.get(sessionId);
3327
+ if (controller?.summaryRetryPending) {
3328
+ mapped.localFallback = true;
3329
+ mapped.localFallbackReason = "网关拒绝了摘要请求,已改用本地摘要";
3330
+ controller.summaryRetryPending = undefined;
3331
+ }
3332
+ }
3238
3333
  if (event.type === "compaction_end")
3239
3334
  activeCompaction = undefined;
3240
3335
  if (mapped?.type === "error") {
@@ -11,7 +11,8 @@ import { cleanChatTitle, isBlankChatSession } from "./session-store.js";
11
11
  import { projectUserTurnOutline } from "./user-turn-outline.js";
12
12
  import { hashChatTurnPayload, projectCompactSnapshot, } from "./chat-event-store.js";
13
13
  import { fileToolPreview, toolRecord } from "./tool-presentation.js";
14
- import { captureWorkspaceBaseline, captureWorkspaceChanges, fallbackWorkspaceChanges } from "./workspace-changes.js";
14
+ import { projectFileResult } from "./tool-presentation-projection.js";
15
+ import { summarizeTurnFileEdits } from "./workspace-changes.js";
15
16
  import { projectDeferredTurnSummary, projectDeferredTurnSummaries, } from "./deferred-turn.js";
16
17
  import { THINKING_LEVELS, RuntimeSnapshotUnavailableError, } from "./pi-runtime.js";
17
18
  import { ResourcePreferencesError, setSkillAutoInvocationPreference, } from "./resource-preferences-store.js";
@@ -355,25 +356,25 @@ function ensureAgentEndEvent(deps, sessionId, turnId) {
355
356
  });
356
357
  }
357
358
  }
358
- function recordTurnFileMutation(event, fallbackToolPaths, fallbackFiles) {
359
+ function recordTurnFileMutation(event, editToolPaths, editedFiles) {
359
360
  if (event.type === "tool_call" && (event.toolName === "edit" || event.toolName === "write")) {
360
361
  const args = toolRecord(event.args);
361
362
  const path = typeof args?.path === "string" ? args.path : typeof args?.file_path === "string" ? args.file_path : "";
362
363
  if (path && typeof event.toolCallId === "string") {
363
- fallbackToolPaths.set(event.toolCallId, path);
364
+ editToolPaths.set(event.toolCallId, path);
364
365
  }
365
366
  return;
366
367
  }
367
- if (event.type === "tool_result" && !event.isError && (event.toolName === "edit" || event.toolName === "write")) {
368
+ if (event.type === "tool_result" && !event.isError && !event.interrupted && (event.toolName === "edit" || event.toolName === "write")) {
368
369
  const toolCallId = typeof event.toolCallId === "string" ? event.toolCallId : "";
369
- const rawPath = fallbackToolPaths.get(toolCallId) ?? "";
370
+ const rawPath = editToolPaths.get(toolCallId) ?? "";
370
371
  if (!rawPath)
371
372
  return;
372
373
  const display = rawPath.replace(/\\/g, "/");
373
- const preview = fileToolPreview(event.result);
374
+ const preview = fileToolPreview(event.result) ?? fileToolPreview(projectFileResult(event.toolName, event.result));
374
375
  const added = preview?.added ?? 0;
375
376
  const deleted = preview?.removed ?? 0;
376
- const existing = fallbackFiles.get(display);
377
+ const existing = editedFiles.get(display);
377
378
  if (existing) {
378
379
  existing.added += added;
379
380
  existing.deleted += deleted;
@@ -382,7 +383,7 @@ function recordTurnFileMutation(event, fallbackToolPaths, fallbackFiles) {
382
383
  }
383
384
  }
384
385
  else {
385
- fallbackFiles.set(display, {
386
+ editedFiles.set(display, {
386
387
  path: rawPath,
387
388
  display,
388
389
  added,
@@ -393,24 +394,12 @@ function recordTurnFileMutation(event, fallbackToolPaths, fallbackFiles) {
393
394
  }
394
395
  }
395
396
  }
396
- async function resolveTurnWorkspaceChanges(input) {
397
- const toolFiles = [...input.fallbackFiles.values()];
398
- if (input.workspaceBaseline) {
399
- const snapshot = await captureWorkspaceChanges({
400
- baseline: input.workspaceBaseline,
401
- sessionId: input.sessionId,
402
- turnId: input.turnId,
403
- turnNumber: input.turnNumber,
404
- failedTurn: input.failedTurn,
405
- toolFiles,
406
- }).catch(() => undefined);
407
- if (snapshot)
408
- return snapshot;
409
- }
410
- return fallbackWorkspaceChanges({
397
+ function resolveTurnWorkspaceChanges(input) {
398
+ return summarizeTurnFileEdits({
411
399
  sessionId: input.sessionId,
412
400
  turnId: input.turnId,
413
- files: toolFiles,
401
+ turnNumber: input.turnNumber,
402
+ files: [...input.editedFiles.values()],
414
403
  failedTurn: input.failedTurn,
415
404
  });
416
405
  }
@@ -2542,7 +2531,6 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
2542
2531
  return;
2543
2532
  }
2544
2533
  const turnId = createdTurn.turn.turnId;
2545
- const workspaceBaseline = await captureWorkspaceBaseline(deps.appData.repoRoot).catch(() => undefined);
2546
2534
  deps.events.setTurnState(sessionId, turnId, "running");
2547
2535
  // Stream events via SSE. Each event is FIRST persisted to the chat event
2548
2536
  // ring (so a reconnect via GET /events can resume by Last-Event-ID), THEN
@@ -2563,8 +2551,8 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
2563
2551
  // Lazily import to avoid circular module load.
2564
2552
  const { runChatTurn } = await import("./session-store.js");
2565
2553
  let firstUserText;
2566
- const fallbackFiles = new Map();
2567
- const fallbackToolPaths = new Map();
2554
+ const editedFiles = new Map();
2555
+ const editToolPaths = new Map();
2568
2556
  try {
2569
2557
  const outcome = await runChatTurn({
2570
2558
  runtime: deps.runtime,
@@ -2624,7 +2612,7 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
2624
2612
  return;
2625
2613
  }
2626
2614
  recordRequestEventFact(deps, sessionId, turnId, event);
2627
- recordTurnFileMutation(event, fallbackToolPaths, fallbackFiles);
2615
+ recordTurnFileMutation(event, editToolPaths, editedFiles);
2628
2616
  const partial = turnEventToStorePartial(event);
2629
2617
  if (!partial)
2630
2618
  return;
@@ -2635,11 +2623,10 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
2635
2623
  });
2636
2624
  const appendWorkspaceChanges = async (failedTurn) => {
2637
2625
  const summary = await resolveTurnWorkspaceChanges({
2638
- workspaceBaseline,
2639
2626
  sessionId,
2640
2627
  turnId,
2641
2628
  turnNumber: createdTurn.turn.ordinal,
2642
- fallbackFiles,
2629
+ editedFiles,
2643
2630
  failedTurn,
2644
2631
  });
2645
2632
  if (!summary)
@@ -2673,11 +2660,10 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
2673
2660
  const message = error instanceof Error ? error.message : String(error);
2674
2661
  {
2675
2662
  const summary = await resolveTurnWorkspaceChanges({
2676
- workspaceBaseline,
2677
2663
  sessionId,
2678
2664
  turnId,
2679
2665
  turnNumber: createdTurn.turn.ordinal,
2680
- fallbackFiles,
2666
+ editedFiles,
2681
2667
  failedTurn: true,
2682
2668
  });
2683
2669
  if (summary) {
@@ -2934,16 +2920,14 @@ export async function handleCreateChatTurn(req, res, deps, sessionId, trustedPay
2934
2920
  // Abort ownership lives in the execution registry (real Stop path).
2935
2921
  void (async () => {
2936
2922
  const { runChatTurn } = await import("./session-store.js");
2937
- const workspaceBaseline = await captureWorkspaceBaseline(deps.appData.repoRoot).catch(() => undefined);
2938
- const fallbackFiles = new Map();
2939
- const fallbackToolPaths = new Map();
2923
+ const editedFiles = new Map();
2924
+ const editToolPaths = new Map();
2940
2925
  const appendWorkspaceChanges = async (failedTurn) => {
2941
2926
  const summary = await resolveTurnWorkspaceChanges({
2942
- workspaceBaseline,
2943
2927
  sessionId,
2944
2928
  turnId: turn.turnId,
2945
2929
  turnNumber: turn.ordinal,
2946
- fallbackFiles,
2930
+ editedFiles,
2947
2931
  failedTurn,
2948
2932
  });
2949
2933
  if (summary)
@@ -2992,7 +2976,7 @@ export async function handleCreateChatTurn(req, res, deps, sessionId, trustedPay
2992
2976
  if (event.type === "heartbeat")
2993
2977
  return;
2994
2978
  recordRequestEventFact(deps, sessionId, turn.turnId, event);
2995
- recordTurnFileMutation(event, fallbackToolPaths, fallbackFiles);
2979
+ recordTurnFileMutation(event, editToolPaths, editedFiles);
2996
2980
  const partial = turnEventToStorePartial(event);
2997
2981
  if (partial)
2998
2982
  deps.events.append(sessionId, turn.turnId, partial);
@@ -328,13 +328,19 @@ export class TerminalSessionRegistry {
328
328
  /** Full buffered output (post-trim prefix may be incomplete). */
329
329
  readAll(sessionId) {
330
330
  const entry = this.mustGet(sessionId);
331
- let text = entry.buffer.join("");
332
- // If the caller reads before any real PTY output has arrived, the
333
- // banner injection in onData hasn't fired yet — fold it in here.
331
+ /*
332
+ * If the caller reads before any real PTY output has arrived, the banner
333
+ * injection in onData hasn't fired yet. Fold it into the BUFFER, not just
334
+ * this response: consuming it here used to drop the banner for every
335
+ * later read, so a reader who opened the panel once and refreshed saw a
336
+ * terminal that had silently lost its startup banner.
337
+ */
334
338
  if (entry.pendingBanner !== undefined) {
335
- text = entry.pendingBanner + text;
339
+ entry.buffer.unshift(entry.pendingBanner);
340
+ entry.bufferChars += entry.pendingBanner.length;
336
341
  entry.pendingBanner = undefined;
337
342
  }
343
+ const text = entry.buffer.join("");
338
344
  return {
339
345
  text,
340
346
  truncated: entry.info.totalOutputChars > entry.bufferChars,
@@ -12,22 +12,29 @@ export function toolRecord(value) {
12
12
  export function patchRows(patch) {
13
13
  const lines = patch.replace(/\r\n/g, "\n").split("\n");
14
14
  let inHunk = false;
15
+ let oldLine, newLine;
15
16
  const rows = [];
16
17
  for (const line of lines) {
17
18
  if (line.startsWith("@@")) {
19
+ const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
18
20
  if (inHunk)
19
21
  rows.push({ kind: "gap", text: "⋯" });
22
+ oldLine = header ? Number(header[1]) : undefined;
23
+ newLine = header ? Number(header[2]) : undefined;
20
24
  inHunk = true;
21
25
  continue;
22
26
  }
23
27
  if (!inHunk)
24
28
  continue;
25
- if (line.startsWith("+"))
26
- rows.push({ kind: "add", text: line.slice(1) });
27
- else if (line.startsWith("-"))
28
- rows.push({ kind: "del", text: line.slice(1) });
29
- else if (line.startsWith(" "))
30
- rows.push({ kind: "context", text: line.slice(1) });
29
+ if (line.startsWith("+")) {
30
+ rows.push({ kind: "add", text: line.slice(1), ...(newLine !== undefined ? { newLine: newLine++ } : {}) });
31
+ }
32
+ else if (line.startsWith("-")) {
33
+ rows.push({ kind: "del", text: line.slice(1), ...(oldLine !== undefined ? { oldLine: oldLine++ } : {}) });
34
+ }
35
+ else if (line.startsWith(" ")) {
36
+ rows.push({ kind: "context", text: line.slice(1), ...(oldLine !== undefined ? { oldLine: oldLine++ } : {}), ...(newLine !== undefined ? { newLine: newLine++ } : {}) });
37
+ }
31
38
  }
32
39
  return rows;
33
40
  }
@@ -43,10 +50,10 @@ export function replacementRows(before, after) {
43
50
  if (head === oldLines.length && head === newLines.length)
44
51
  return before === after ? [] : [{ kind: "gap", text: "仅换行格式或末尾换行发生变化" }];
45
52
  return [
46
- ...oldLines.slice(Math.max(0, head - 3), head).map(text => ({ kind: "context", text })),
47
- ...oldLines.slice(head, oldLines.length - tail).map(text => ({ kind: "del", text })),
48
- ...newLines.slice(head, newLines.length - tail).map(text => ({ kind: "add", text })),
49
- ...newLines.slice(newLines.length - tail, newLines.length - tail + 3).map(text => ({ kind: "context", text })),
53
+ ...oldLines.slice(Math.max(0, head - 3), head).map((text, i) => ({ kind: "context", text, oldLine: Math.max(0, head - 3) + i + 1, newLine: Math.max(0, head - 3) + i + 1 })),
54
+ ...oldLines.slice(head, oldLines.length - tail).map((text, i) => ({ kind: "del", text, oldLine: head + i + 1 })),
55
+ ...newLines.slice(head, newLines.length - tail).map((text, i) => ({ kind: "add", text, newLine: head + i + 1 })),
56
+ ...newLines.slice(newLines.length - tail, newLines.length - tail + 3).map((text, i) => ({ kind: "context", text, oldLine: oldLines.length - tail + i + 1, newLine: newLines.length - tail + i + 1 })),
50
57
  ];
51
58
  }
52
59
  export function fileToolPreview(value) {
@@ -6,6 +6,7 @@ import { dagProgressActivityForTool, semanticActivityForTool, } from "./semantic
6
6
  import { compareChatOrder } from "./turn-order.js";
7
7
  import { ensureLinkedSubmissionOrder } from "./timeline-message-order.js";
8
8
  import { fileToolPreview, toolRecord } from "./tool-presentation.js";
9
+ import { summarizeTurnFileEdits } from "./workspace-changes.js";
9
10
  /** Cumulative argument updates may refresh preparing calls, never regress dispatched/settled ones. */
10
11
  export function upsertPreparingTools(existing, content, meta) {
11
12
  let next = existing;
@@ -544,19 +545,12 @@ function deriveToolWorkspaceChanges(group) {
544
545
  });
545
546
  }
546
547
  }
547
- if (byDisplay.size === 0)
548
- return undefined;
549
- const files = [...byDisplay.values()].sort((a, b) => a.display.localeCompare(b.display));
550
- return {
548
+ return summarizeTurnFileEdits({
551
549
  sessionId: "",
552
550
  turnId: group.turnId ?? group.key,
553
- files,
554
- total: files.length,
555
- added: files.reduce((sum, file) => sum + file.added, 0),
556
- deleted: files.reduce((sum, file) => sum + file.deleted, 0),
557
- source: "tool-fallback",
558
- ...(group.turnState === "failed" || group.turnState === "aborted" ? { failedTurn: true } : {}),
559
- };
551
+ files: [...byDisplay.values()],
552
+ failedTurn: group.turnState === "failed" || group.turnState === "aborted",
553
+ });
560
554
  }
561
555
  export function buildTurnProcessGroups(input) {
562
556
  const visible = ensureLinkedSubmissionOrder(input.messages
@@ -696,8 +690,9 @@ export function buildTurnProcessGroups(input) {
696
690
  group.conversationItems = (input.conversationNodes ?? [])
697
691
  .filter((node) => node.location.kind !== "session" && node.location.turnId === group.turnId)
698
692
  .map((node) => ({ kind: node.kind, node }));
693
+ // Old Git snapshots and fallback counts do not prove this turn edited these files.
699
694
  group.workspaceChanges =
700
- (group.turnId ? input.workspaceChanges?.find(item => item.turnId === group.turnId) : undefined) ??
695
+ (group.turnId ? input.workspaceChanges?.find(item => item.turnId === group.turnId && item.source === "tool-events") : undefined) ??
701
696
  deriveToolWorkspaceChanges(group);
702
697
  if (group.conversationItems.some((item) => item.kind === "turn-error")) {
703
698
  group.processItems = group.processItems.filter((item) => item.kind !== "provider-error");
@@ -1,138 +1,8 @@
1
- import { execFile } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { readFile } from "node:fs/promises";
4
- import { resolve } from "node:path";
5
- import { promisify } from "node:util";
6
- const execFileAsync = promisify(execFile);
7
- const MAX_OUTPUT = 8 * 1024 * 1024;
8
- function parseStatus(output) {
9
- const result = new Map();
10
- for (const record of output.split("\0")) {
11
- if (!record || record.length < 4)
12
- continue;
13
- const code = record.slice(0, 2);
14
- const rawPath = record.slice(3).trim();
15
- if (!rawPath)
16
- continue;
17
- const path = rawPath.includes(" -> ") ? rawPath.split(" -> ").at(-1) : rawPath;
18
- const status = code.includes("??") ? "added" : code.includes("D") ? "deleted" : code.includes("R") ? "renamed" : "modified";
19
- result.set(path.replace(/\\/g, "/"), status);
20
- }
21
- return result;
22
- }
23
- function parseNumstat(output) {
24
- const result = new Map();
25
- for (const line of output.split(/\r?\n/)) {
26
- if (!line.trim())
27
- continue;
28
- const parts = line.split("\t");
29
- if (parts.length < 3)
30
- continue;
31
- const path = parts.slice(2).at(-1).replace(/\\/g, "/");
32
- const binary = parts[0] === "-" || parts[1] === "-";
33
- result.set(path, binary ? { added: 0, deleted: 0, binary: true } : { added: Number(parts[0]) || 0, deleted: Number(parts[1]) || 0 });
34
- }
35
- return result;
36
- }
37
- async function git(cwd, args) {
38
- const result = await execFileAsync("git", ["-C", cwd, ...args], { encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
39
- return result.stdout;
40
- }
41
- async function digestFiles(cwd, paths) {
42
- const entries = await Promise.all([...paths].map(async (path) => {
43
- try {
44
- const content = await readFile(resolve(cwd, path));
45
- return [path, createHash("sha256").update(content).digest("hex")];
46
- }
47
- catch {
48
- return undefined;
49
- }
50
- }));
51
- return new Map(entries.filter((entry) => Boolean(entry)));
52
- }
53
- export async function captureWorkspaceBaseline(cwd) {
54
- const [status, unstaged, staged] = await Promise.all([
55
- git(cwd, ["status", "--porcelain=v1", "--untracked-files=all", "-z"]),
56
- git(cwd, ["diff", "--numstat"]),
57
- git(cwd, ["diff", "--cached", "--numstat"]),
58
- ]);
59
- const paths = new Set(parseStatus(status).keys());
60
- return { cwd, paths, stats: parseNumstat(`${unstaged}\n${staged}`), digests: await digestFiles(cwd, paths) };
61
- }
62
- export function fallbackWorkspaceChanges(input) {
1
+ // Only confirmed edit/write results belong to a turn. Never infer ownership from Git.
2
+ export function summarizeTurnFileEdits(input) {
63
3
  const files = input.files.filter(file => file.path).sort((a, b) => a.display.localeCompare(b.display));
64
4
  if (files.length === 0)
65
5
  return undefined;
66
- return { sessionId: input.sessionId, turnId: input.turnId, files, total: files.length, added: files.reduce((sum, file) => sum + file.added, 0), deleted: files.reduce((sum, file) => sum + file.deleted, 0), source: "tool-fallback", ...(input.failedTurn ? { failedTurn: true } : {}) };
67
- }
68
- export async function captureWorkspaceChanges(input) {
69
- const [statusText, unstaged, staged] = await Promise.all([
70
- git(input.baseline.cwd, ["status", "--porcelain=v1", "--untracked-files=all", "-z"]),
71
- git(input.baseline.cwd, ["diff", "--numstat"]),
72
- git(input.baseline.cwd, ["diff", "--cached", "--numstat"]),
73
- ]);
74
- const statuses = parseStatus(statusText);
75
- const finalDigests = await digestFiles(input.baseline.cwd, statuses.keys());
76
- const stats = parseNumstat(`${unstaged}\n${staged}`);
77
- const byTool = new Map();
78
- for (const tf of input.toolFiles ?? []) {
79
- const norm = tf.display.replace(/\\/g, "/");
80
- byTool.set(norm, { ...tf, display: norm });
81
- }
82
- for (const [path, status] of statuses) {
83
- if (!stats.has(path) && status === "added") {
84
- try {
85
- const absolute = resolve(input.baseline.cwd, path);
86
- const content = await readFile(absolute);
87
- if (content.includes(0))
88
- stats.set(path, { added: 0, deleted: 0, binary: true });
89
- else
90
- stats.set(path, { added: content.toString("utf8").split(/\r?\n/).filter(Boolean).length, deleted: 0 });
91
- }
92
- catch { /* status remains visible without line counts */ }
93
- }
94
- }
95
- const files = [];
96
- const seen = new Set();
97
- /*
98
- * Sessions can share one working directory, so the two `git status` calls
99
- * bracket every write in the repo — including another Session's. When this
100
- * turn recorded file-tool edits, those records decide WHICH files belong to
101
- * it; the snapshot is then only a source of counts for those same paths.
102
- * Without tool records (shell-driven edits) the snapshot stays authoritative.
103
- */
104
- const toolScoped = byTool.size > 0;
105
- for (const [path, status] of statuses) {
106
- if (toolScoped && !byTool.has(path))
107
- continue;
108
- const stat = stats.get(path) ?? { added: 0, deleted: 0 };
109
- const before = input.baseline.stats.get(path);
110
- const changedSinceBaseline = !input.baseline.paths.has(path) || input.baseline.digests.get(path) !== finalDigests.get(path) || !before || before.added !== stat.added || before.deleted !== stat.deleted || before.binary !== stat.binary;
111
- if (!changedSinceBaseline)
112
- continue;
113
- const toolEntry = byTool.get(path);
114
- const useToolCounts = Boolean(before && toolEntry && (toolEntry.added > 0 || toolEntry.deleted > 0));
115
- const added = useToolCounts ? toolEntry.added : before ? Math.max(0, stat.added - before.added) : stat.added;
116
- const deleted = useToolCounts ? toolEntry.deleted : before ? Math.max(0, stat.deleted - before.deleted) : stat.deleted;
117
- seen.add(path);
118
- files.push({
119
- path,
120
- display: path,
121
- added,
122
- deleted,
123
- ...(toolEntry?.firstChangedLine !== undefined ? { firstChangedLine: toolEntry.firstChangedLine } : {}),
124
- status,
125
- ...(stat.binary ? { binary: true } : {}),
126
- });
127
- }
128
- for (const [normPath, tf] of byTool) {
129
- if (!seen.has(normPath)) {
130
- files.push(tf);
131
- }
132
- }
133
- if (files.length === 0)
134
- return undefined;
135
- files.sort((a, b) => a.display.localeCompare(b.display));
136
6
  return {
137
7
  sessionId: input.sessionId,
138
8
  turnId: input.turnId,
@@ -141,7 +11,7 @@ export async function captureWorkspaceChanges(input) {
141
11
  total: files.length,
142
12
  added: files.reduce((sum, file) => sum + file.added, 0),
143
13
  deleted: files.reduce((sum, file) => sum + file.deleted, 0),
144
- source: "workspace-snapshot",
14
+ source: "tool-events",
145
15
  ...(input.failedTurn ? { failedTurn: true } : {}),
146
16
  };
147
17
  }