@whybebabo/dsh-file-review-tab 0.7.0 → 0.7.2

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.
package/lib/index.js CHANGED
@@ -2,6 +2,152 @@ import { lstat, readFile, realpath } from "node:fs/promises";
2
2
  import { isAbsolute, relative, resolve } from "node:path";
3
3
  import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
4
4
  import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
5
+ import { structuredPatch } from "diff";
6
+ //#region src/mutation-order.ts
7
+ /**
8
+ * Order settlements by their recorded event sequence, so undo/redo walk the
9
+ * file's history in the order it actually happened.
10
+ *
11
+ * This is what keeps a `run_code` mutation and a model-direct edit to the same
12
+ * file from being applied out of order: the two arrive through different
13
+ * channels (the conversation snapshot vs. the Host recorder) and are merged
14
+ * asynchronously, so the array order is a merge artifact rather than history.
15
+ *
16
+ * Only when EVERY entry carries a sequence is the order provable. A partially
17
+ * stamped list keeps its incoming order, which is the conservative choice —
18
+ * guessing at the position of an unstamped settlement could silently corrupt a
19
+ * file. The sort is stable, so entries sharing one sequence (a single
20
+ * `run_code` root's nested dispatch chain) keep their dispatch order.
21
+ *
22
+ * @param entries - Settlements or events carrying an optional `seq`.
23
+ * @returns A new array in ascending event order, or the same order when unprovable.
24
+ */
25
+ function orderBySequence(entries) {
26
+ if (entries.some((entry) => entry.seq === void 0)) return [...entries];
27
+ return [...entries].sort((left, right) => left.seq - right.seq);
28
+ }
29
+ /**
30
+ * Split one path's hunks into contiguous same-coordinate groups, in settlement
31
+ * order. Hunks that carry no `mutation` form a single group.
32
+ * @param diffs - One path's accumulated hunks, in settlement order.
33
+ * @returns The groups, in settlement order.
34
+ */
35
+ function mutationGroups(diffs) {
36
+ const groups = [];
37
+ let current = null;
38
+ let currentStamp;
39
+ for (const diff of diffs) {
40
+ if (current === null || diff.mutation !== currentStamp) {
41
+ current = [];
42
+ currentStamp = diff.mutation;
43
+ groups.push(current);
44
+ }
45
+ current.push(diff);
46
+ }
47
+ return groups;
48
+ }
49
+ /**
50
+ * The order one settlement's hunks must be applied in: back-to-front by the
51
+ * anchor of the direction being applied, because a hunk that changes the line
52
+ * count would otherwise shift the anchors of the hunks behind it. This is what
53
+ * makes a multi-hunk redo land on the coordinates the hunks recorded instead of
54
+ * the ones left over after the first hunk moved them.
55
+ *
56
+ * Hunks without a line anchor are content-matched and so coordinate-free; they
57
+ * sort after the anchored ones, where they cannot invalidate a pending anchor.
58
+ * @param group - One settlement's hunks.
59
+ * @param action - Direction being applied.
60
+ * @returns The hunks in application order (descending anchor).
61
+ */
62
+ function hunksForApply(group, action) {
63
+ const anchorOf = (diff) => {
64
+ return (action === "undo" ? diff.newStart : diff.oldStart) ?? Number.NEGATIVE_INFINITY;
65
+ };
66
+ return [...group].sort((left, right) => anchorOf(right) - anchorOf(left));
67
+ }
68
+ //#endregion
69
+ //#region src/anchor-locate.ts
70
+ /** Split file text into lines the way the diff basis does (a trailing LF is not a line). */
71
+ function contentLines(text) {
72
+ if (text === "") return [];
73
+ return (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
74
+ }
75
+ /**
76
+ * The only line index where `block` matches `lines`, or null when the block is
77
+ * absent or ambiguous.
78
+ * @param lines - the file's lines.
79
+ * @param block - the fragment's new side, as lines.
80
+ * @returns the 0-based index of the single match.
81
+ */
82
+ function uniqueBlockAt(lines, block) {
83
+ if (block.length === 0) return null;
84
+ const last = lines.length - block.length;
85
+ let found = null;
86
+ for (let at = 0; at <= last; at += 1) {
87
+ let matches = true;
88
+ for (let offset = 0; offset < block.length; offset += 1) if (lines[at + offset] !== block[offset]) {
89
+ matches = false;
90
+ break;
91
+ }
92
+ if (!matches) continue;
93
+ if (found !== null) return null;
94
+ found = at;
95
+ }
96
+ return found;
97
+ }
98
+ /**
99
+ * Coordinates for one call's fragments, or null when any of them is unplaceable.
100
+ *
101
+ * All fragments of a call must resolve: they came from one patch, so a partial
102
+ * answer would number part of a file and leave the rest to a per-hunk count.
103
+ * @param fileText - the file's current text (LF basis).
104
+ * @param hunks - the call's fragments, in engine order.
105
+ * @returns one anchor per fragment, in the same order.
106
+ */
107
+ function locateAnchors(fileText, hunks) {
108
+ const lines = contentLines(fileText);
109
+ const anchors = [];
110
+ let addedByEarlierHunks = 0;
111
+ for (const hunk of hunks) {
112
+ const block = hunk.newText === "" ? [] : hunk.newText.replace(/\r\n?/g, "\n").split("\n");
113
+ const at = uniqueBlockAt(lines, block);
114
+ if (at === null) return null;
115
+ const newStart = at + 1;
116
+ anchors.push({
117
+ oldStart: Math.max(0, newStart - addedByEarlierHunks),
118
+ newStart
119
+ });
120
+ const oldSide = hunk.oldText === null ? [] : hunk.oldText.replace(/\r\n?/g, "\n").split("\n");
121
+ addedByEarlierHunks += block.length - oldSide.length;
122
+ }
123
+ return anchors;
124
+ }
125
+ //#endregion
126
+ //#region src/reversible.ts
127
+ /**
128
+ * Whether one hunk carries both sides completely enough to replay exactly.
129
+ * @param diff - the hunk under test.
130
+ * @param path - the file the hunk claims to belong to.
131
+ * @returns true when the hunk can be undone/redone by exact replacement.
132
+ */
133
+ function hunkReversible(diff, path) {
134
+ if (diff.path !== path) return false;
135
+ if (diff.oldText === null || diff.oldText === diff.newText) return false;
136
+ if (diff.oldText === "" && diff.oldStart === void 0) return false;
137
+ if (diff.newText === "" && diff.newStart === void 0) return false;
138
+ return true;
139
+ }
140
+ /**
141
+ * Whether a file's whole change set is reversible: non-empty and every hunk
142
+ * passes {@link hunkReversible}.
143
+ * @param path - the path every hunk must name.
144
+ * @param diffs - the file's hunks, in settlement order.
145
+ * @returns true when the Host can replay the complete change.
146
+ */
147
+ function changeReversible(path, diffs) {
148
+ return diffs.length > 0 && diffs.every((diff) => hunkReversible(diff, path));
149
+ }
150
+ //#endregion
5
151
  //#region src/file-review-service.ts
6
152
  /** Host-side, workspace-contained undo / redo service for produced text diffs. */
7
153
  /**
@@ -66,18 +212,16 @@ function replaceHunk(text, source, replacement, line) {
66
212
  }
67
213
  return text.slice(0, offset) + replacement + text.slice(offset + source.length);
68
214
  }
69
- function hunkSupported(diff, path) {
70
- if (diff.path !== path || diff.oldText === null || diff.oldText === diff.newText) return false;
71
- if (diff.oldText === "" && diff.oldStart === void 0) return false;
72
- if (diff.newText === "" && diff.newStart === void 0) return false;
73
- return true;
74
- }
75
215
  /** Apply a complete file's hunk sequence in memory, or report a strict mismatch. */
76
216
  function transformFile(text, file, action) {
77
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return null;
78
- const diffs = action === "undo" ? [...file.diffs].reverse() : file.diffs;
217
+ if (!changeReversible(file.path, file.diffs)) return null;
218
+ const groups = orderBySequence(mutationGroups(file.diffs).map((group) => ({
219
+ seq: group[0]?.seq,
220
+ diffs: group
221
+ }))).map((settlement) => settlement.diffs);
222
+ const ordered = action === "undo" ? [...groups].reverse() : groups;
79
223
  let next = text;
80
- for (const diff of diffs) {
224
+ for (const group of ordered) for (const diff of hunksForApply(group, action)) {
81
225
  const source = action === "undo" ? diff.newText : diff.oldText;
82
226
  const replacement = action === "undo" ? diff.oldText : diff.newText;
83
227
  if (source === null || replacement === null) return null;
@@ -100,7 +244,7 @@ function hunkSidePresent(text, file, side) {
100
244
  return true;
101
245
  }
102
246
  function inspectText(text, file) {
103
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return {
247
+ if (!changeReversible(file.path, file.diffs)) return {
104
248
  state: "unsupported",
105
249
  reason: "change has no complete reversible diff"
106
250
  };
@@ -131,7 +275,7 @@ function inspectText(text, file) {
131
275
  };
132
276
  }
133
277
  async function inspectOne(cwd, file) {
134
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return {
278
+ if (!changeReversible(file.path, file.diffs)) return {
135
279
  path: file.path,
136
280
  state: "unsupported",
137
281
  changed: false,
@@ -155,7 +299,7 @@ async function inspectOne(cwd, file) {
155
299
  }
156
300
  }
157
301
  async function applyOne(cwd, file, action) {
158
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return {
302
+ if (!changeReversible(file.path, file.diffs)) return {
159
303
  path: file.path,
160
304
  state: "unsupported",
161
305
  changed: false,
@@ -206,6 +350,14 @@ function sessionCwd(agent) {
206
350
  }
207
351
  /** Per-agent cap on recorded Code Mode mutations (oldest evicted first). */
208
352
  const RECORDED_PER_AGENT_CAP = 4e3;
353
+ /**
354
+ * Per-agent cap on recorded hunk-coordinate sets (oldest evicted first).
355
+ *
356
+ * Kept separate from the Code Mode record log — and larger — because an anchor
357
+ * set is tiny (two integers per hunk, never file content) and every mutation has
358
+ * one, not just the programmatic ones.
359
+ */
360
+ const ANCHORS_PER_AGENT_CAP = 8e3;
209
361
  function agentKey(agent) {
210
362
  return String(agent.id);
211
363
  }
@@ -213,6 +365,15 @@ function agentKey(agent) {
213
365
  var FileReviewService = class extends TypertRemoteService {
214
366
  /** Per-agent record of Code Mode (`run_code`) file mutations, dispatch order. */
215
367
  recordLog = /* @__PURE__ */ new Map();
368
+ /**
369
+ * Per-agent map of call id to the hunk coordinates that call applied.
370
+ *
371
+ * Keyed by call id alone: a mutation call writes one path, so the id already
372
+ * names the settlement the anchors belong to. Re-recording an id replaces its
373
+ * entry (a replay never duplicates), and insertion order is what the cap
374
+ * evicts by.
375
+ */
376
+ anchorLog = /* @__PURE__ */ new Map();
216
377
  constructor(ctx) {
217
378
  super(ctx, "fileReview");
218
379
  }
@@ -227,6 +388,66 @@ var FileReviewService = class extends TypertRemoteService {
227
388
  list.push(mutation);
228
389
  if (list.length > RECORDED_PER_AGENT_CAP) list.splice(0, list.length - RECORDED_PER_AGENT_CAP);
229
390
  }
391
+ /**
392
+ * Record one mutation's hunk coordinates, model-direct calls included.
393
+ *
394
+ * Called from `tools/post-execute` for every settled file mutation — that hook
395
+ * is the last place the full before/after text exists, and therefore the only
396
+ * place a hunk's absolute line numbers can still be recovered once the engine
397
+ * has trimmed it down to context fragments.
398
+ * @param agent - the agent that ran the mutation.
399
+ * @param entry - the call id, path and per-hunk coordinates.
400
+ */
401
+ recordAnchors(agent, entry) {
402
+ const key = agentKey(agent);
403
+ let log = this.anchorLog.get(key);
404
+ if (log === void 0) {
405
+ log = /* @__PURE__ */ new Map();
406
+ this.anchorLog.set(key, log);
407
+ }
408
+ log.delete(entry.callId);
409
+ log.set(entry.callId, entry);
410
+ if (log.size > ANCHORS_PER_AGENT_CAP) {
411
+ const oldest = log.keys().next();
412
+ if (!oldest.done) log.delete(oldest.value);
413
+ }
414
+ }
415
+ /**
416
+ * Coordinates for the requested mutation calls.
417
+ *
418
+ * Two sources, in order. A call the recorder saw answers with the coordinates
419
+ * captured at settlement — exact, and immune to later edits. A call it did not
420
+ * (the plugin was installed or restarted after the change) is placed in the
421
+ * file as it stands now, which is where the reviewer wants to look anyway, and
422
+ * only when every one of its fragments matches exactly one place in the file.
423
+ * A call that resolves neither way is simply absent: the client keeps that
424
+ * hunk's fragment-relative count, so a missing entry can only cost the
425
+ * improvement, never the diff itself.
426
+ */
427
+ async anchors(agent, request) {
428
+ if (request.calls.length === 0) return { anchors: [] };
429
+ const log = this.anchorLog.get(agentKey(agent));
430
+ const anchors = [];
431
+ let cwd = null;
432
+ for (const call of request.calls) {
433
+ const recorded = log?.get(call.callId);
434
+ if (recorded !== void 0) {
435
+ anchors.push(recorded);
436
+ continue;
437
+ }
438
+ if (call.path === "" || call.hunks.length === 0) continue;
439
+ try {
440
+ cwd ??= sessionCwd(agent);
441
+ const located = locateAnchors((await resolveFile(cwd, call.path)).lfText, call.hunks);
442
+ if (located !== null) anchors.push({
443
+ callId: call.callId,
444
+ path: call.path,
445
+ anchors: located
446
+ });
447
+ } catch {}
448
+ }
449
+ return { anchors };
450
+ }
230
451
  /** Return the recorded mutations for the requested `run_code` roots. */
231
452
  async recorded(agent, request) {
232
453
  const list = this.recordLog.get(agentKey(agent));
@@ -249,16 +470,24 @@ var FileReviewService = class extends TypertRemoteService {
249
470
  });
250
471
  }
251
472
  };
473
+ /**
474
+ * Hunk coordinates for one mutation, in the engine's hunk order.
475
+ * @param before - file text before the mutation, or null when it did not exist.
476
+ * @param after - file text after the mutation.
477
+ * @returns one anchor per applied hunk; empty when the texts do not differ.
478
+ */
479
+ function hunkAnchors(before, after) {
480
+ return structuredPatch("", "", before ?? "", after, void 0, void 0, { context: 3 }).hunks.map((hunk) => ({
481
+ oldStart: hunk.oldStart,
482
+ newStart: hunk.newStart
483
+ }));
484
+ }
252
485
  //#endregion
253
486
  //#region src/index.ts
254
- /** Services required for the model guidance paired with the browser renderer. */
255
- const inject = ["systemPrompt"];
256
- /** Stable final-response guidance owned by the matching renderer. */
257
- const FILE_REFERENCE_PROMPT = "When you successfully create or modify files, mention the primary outputs in your final response. To make those and any other changed-file references clickable in Web, format them as Markdown inline code using the exact file-tool path, or a basename when unique among the files changed in that turn.";
487
+ /** No host services are required: the recorder only listens to the tool waterfall. */
488
+ const inject = [];
258
489
  /**
259
- * Register model guidance for the file-reference renderer shipped by this package,
260
- * and the Code Mode (`run_code`) mutation recorder that backs the browser-side
261
- * review tab.
490
+ * Record every settled file mutation for the browser-side review surfaces.
262
491
  *
263
492
  * Nested dispatch results carry no wire views — the diff cards only ride
264
493
  * model-direct tool/call frames — so reviewing programmatic file edits needs a
@@ -266,15 +495,10 @@ const FILE_REFERENCE_PROMPT = "When you successfully create or modify files, men
266
495
  * every nested file mutation (`edit`/`write` — recognized by result shape, not
267
496
  * tool name) into the `fileReview` service, which the browser half later turns
268
497
  * into line-level hunks and merges into the owning `run_code` turn.
269
- * @param ctx - host context carrying the system-prompt registry and tool waterfall.
498
+ * @param ctx - host context carrying the tool waterfall.
270
499
  */
271
500
  function apply(ctx) {
272
501
  const service = new FileReviewService(ctx);
273
- ctx.systemPrompt.section({
274
- name: "ui:file-review-references",
275
- order: 190,
276
- text: FILE_REFERENCE_PROMPT
277
- });
278
502
  const emitter = ctx;
279
503
  ctx.effect(() => {
280
504
  const off = emitter.on("tools/post-execute", async (execRaw, resultRaw, nextRaw) => {
@@ -282,17 +506,24 @@ function apply(ctx) {
282
506
  const result = resultRaw;
283
507
  const decision = await nextRaw();
284
508
  if (decision.kind !== "accept") return decision;
285
- if (exec.parent === void 0 || exec.agent === void 0) return decision;
509
+ if (exec.agent === void 0) return decision;
286
510
  const value = result.value;
287
511
  if (typeof value !== "object" || value === null || Array.isArray(value)) return decision;
288
512
  const candidate = value;
289
513
  if (typeof candidate.path !== "string" || typeof candidate.after !== "string") return decision;
290
514
  if (candidate.before !== null && typeof candidate.before !== "string") return decision;
515
+ const before = candidate.before ?? null;
516
+ service.recordAnchors(exec.agent, {
517
+ callId: String(exec.callId),
518
+ path: candidate.path,
519
+ anchors: hunkAnchors(before, candidate.after)
520
+ });
521
+ if (exec.parent === void 0) return decision;
291
522
  service.recordMutation(exec.agent, {
292
523
  rootCallId: String(exec.rootCallId ?? exec.callId),
293
524
  name: exec.name,
294
525
  path: candidate.path,
295
- before: candidate.before ?? null,
526
+ before,
296
527
  after: candidate.after
297
528
  });
298
529
  return decision;
@@ -36,7 +36,16 @@ const diffSchema = z.object({
36
36
  oldText: z.string().nullable(),
37
37
  newText: z.string(),
38
38
  oldStart: z.number().int().min(1).optional(),
39
- newStart: z.number().int().min(1).optional()
39
+ newStart: z.number().int().min(1).optional(),
40
+ /** Coordinate space, so hunks from several settlements stay separable. */
41
+ mutation: z.number().int().min(0).optional(),
42
+ /** Event sequence, so settlements merge in the order they happened. */
43
+ seq: z.number().int().min(0).optional(),
44
+ /**
45
+ * The emitting call, carried so the renderer can pair this fragment with the
46
+ * coordinates the Host recorded for it. Ignored by the apply side.
47
+ */
48
+ callId: z.string().optional()
40
49
  });
41
50
  const requestSchema = z.object({
42
51
  action: z.enum(["undo", "redo"]),
@@ -71,6 +80,28 @@ const recordedRequestSchema = z.object({ rootCallIds: z.array(z.string()) });
71
80
  const recordedResultSchema = z.object({ mutations: z.array(recordedMutationSchema) });
72
81
  const recordedRequestCodec = strictCodec(`${PACKAGE_NAME}#RecordedRequest`, () => recordedRequestSchema);
73
82
  const recordedResultCodec = strictCodec(`${PACKAGE_NAME}#RecordedResult`, () => recordedResultSchema);
83
+ const hunkAnchorSchema = z.object({
84
+ oldStart: z.number().int().min(0),
85
+ newStart: z.number().int().min(1)
86
+ });
87
+ const recordedAnchorSchema = z.object({
88
+ callId: z.string(),
89
+ path: z.string(),
90
+ anchors: z.array(hunkAnchorSchema)
91
+ });
92
+ const anchorHunkSchema = z.object({
93
+ oldText: z.string().nullable(),
94
+ newText: z.string()
95
+ });
96
+ const anchorCallSchema = z.object({
97
+ callId: z.string(),
98
+ path: z.string(),
99
+ hunks: z.array(anchorHunkSchema)
100
+ });
101
+ const anchorRequestSchema = z.object({ calls: z.array(anchorCallSchema) });
102
+ const anchorResultSchema = z.object({ anchors: z.array(recordedAnchorSchema) });
103
+ const anchorRequestCodec = strictCodec(`${PACKAGE_NAME}#AnchorRequest`, () => anchorRequestSchema);
104
+ const anchorResultCodec = strictCodec(`${PACKAGE_NAME}#AnchorResult`, () => anchorResultSchema);
74
105
  function descriptor(method) {
75
106
  return {
76
107
  id: `${PACKAGE_NAME}#fileReview/${method}`,
@@ -123,10 +154,37 @@ function recordedDescriptor() {
123
154
  result: recordedResultCodec
124
155
  };
125
156
  }
157
+ function anchorsDescriptor() {
158
+ return {
159
+ id: `${PACKAGE_NAME}#fileReview/anchors`,
160
+ service: "fileReview",
161
+ namespace: "fileReview",
162
+ method: "anchors",
163
+ invocation: { kind: "direct" },
164
+ scope: {
165
+ context: "agent",
166
+ wire: "agentId"
167
+ },
168
+ parameters: [{
169
+ name: "agent",
170
+ wire: "agentId",
171
+ source: "lookup",
172
+ lookup: "agent",
173
+ codec: agentCodec
174
+ }, {
175
+ name: "request",
176
+ wire: "request",
177
+ source: "json",
178
+ codec: anchorRequestCodec
179
+ }],
180
+ result: anchorResultCodec
181
+ };
182
+ }
126
183
  const FILE_REVIEW_INVOCATIONS = [
127
184
  descriptor("status"),
128
185
  descriptor("apply"),
129
- recordedDescriptor()
186
+ recordedDescriptor(),
187
+ anchorsDescriptor()
130
188
  ];
131
189
  //#endregion
132
190
  export { PACKAGE_NAME as n, FILE_REVIEW_INVOCATIONS as t };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Place a mutation's fragments in the file as it stands, for hunks whose
3
+ * coordinates were never recorded.
4
+ *
5
+ * The recorder captures coordinates at settlement (see `hunk-anchors.ts`), which
6
+ * covers every edit made while the plugin was loaded. A session reviewed after
7
+ * the plugin was installed — or after a Host restart — carries hunks recorded
8
+ * earlier, and those must not stay stuck at a per-hunk count of 1.
9
+ *
10
+ * The fragments themselves are enough: each carries up to three context lines on
11
+ * both sides, so its new side is a run of literal lines that either appears in
12
+ * the file exactly once or is ambiguous. Only a UNIQUE match is accepted. A
13
+ * repeated block (a blank run, a copy-pasted table row) places nothing at all,
14
+ * because a wrong line number is worse than the hunk-local count it replaces.
15
+ *
16
+ * Coordinates therefore describe the file as it is NOW. When the file was edited
17
+ * again above the hunk, that is exactly what a reviewer wants to jump to — and it
18
+ * is why these coordinates are a fallback: the recorded ones describe the
19
+ * settlement itself and cannot drift with later edits.
20
+ */
21
+ import type { HunkAnchor } from './change-types.ts';
22
+ /**
23
+ * Coordinates for one call's fragments, or null when any of them is unplaceable.
24
+ *
25
+ * All fragments of a call must resolve: they came from one patch, so a partial
26
+ * answer would number part of a file and leave the rest to a per-hunk count.
27
+ * @param fileText - the file's current text (LF basis).
28
+ * @param hunks - the call's fragments, in engine order.
29
+ * @returns one anchor per fragment, in the same order.
30
+ */
31
+ export declare function locateAnchors(fileText: string, hunks: readonly {
32
+ readonly oldText: string | null;
33
+ readonly newText: string;
34
+ }[]): HunkAnchor[] | null;
35
+ //# sourceMappingURL=anchor-locate.d.ts.map
@@ -20,6 +20,104 @@ export interface ProducedFileDiff {
20
20
  * Host recorder's `before === null`.
21
21
  */
22
22
  readonly created?: true;
23
+ /**
24
+ * Coordinate space this hunk's `oldStart`/`newStart` are expressed in.
25
+ *
26
+ * One path mutated several times in one turn accumulates hunks from several
27
+ * settlements, and each settlement's line numbers refer to the text the
28
+ * PREVIOUS settlement left behind — they are not interchangeable. Hunks
29
+ * sharing this stamp are anchored in the same text and must be applied
30
+ * back-to-front within it; groups apply in settlement order forward and in
31
+ * reverse order backward (see `mutation-order.ts`).
32
+ *
33
+ * Optional: absent means "all of this path's hunks share one coordinate
34
+ * space", the correct reading for the single-settlement payloads that
35
+ * predate the field.
36
+ */
37
+ readonly mutation?: number | undefined;
38
+ /**
39
+ * Event sequence this settlement happened at, used to order settlements.
40
+ *
41
+ * A file's history can be split across two channels — the conversation
42
+ * snapshot (model-direct `edit`/`write`) and the Host recorder (nested
43
+ * `run_code` dispatches) — which the tab merges asynchronously. Array order is
44
+ * therefore a merge artifact, not history; this sequence is what restores the
45
+ * real order. For a snapshot settlement it is the tool-result node's `seq`,
46
+ * and for a recorded one the owning `run_code` root's `seq`.
47
+ *
48
+ * Optional: when absent the order is not provable and the array order stands.
49
+ */
50
+ readonly seq?: number | undefined;
51
+ /**
52
+ * The tool call this hunk came from (client-side bookkeeping).
53
+ *
54
+ * A hunk delivered on the wire carries only `oldText`/`newText` — the engine's
55
+ * `meta.diffs` are context-trimmed fragment pairs with no absolute line
56
+ * numbers, so numbering them from 1 is the only thing the payload alone
57
+ * allows. The Host recorder knows each mutation's real coordinates and
58
+ * publishes them under the call's id (see {@link RecordedAnchor}); this stamp
59
+ * is what pairs a fragment with them again. It never affects undo: the Host
60
+ * ignores it, and the coordinates that would make replacement stricter are
61
+ * deliberately NOT written into the hunk.
62
+ *
63
+ * Optional: recorded (Code Mode) hunks already carry their own coordinates,
64
+ * and a snapshot that lost the call id keeps the fragment numbering.
65
+ */
66
+ readonly callId?: string | undefined;
67
+ }
68
+ /** Absolute line coordinates of one hunk, as the engine's patch reports them. */
69
+ export interface HunkAnchor {
70
+ /** First line of the hunk on the old side (0 for a pure insertion at the top). */
71
+ readonly oldStart: number;
72
+ /** First line of the hunk on the new side. */
73
+ readonly newStart: number;
74
+ }
75
+ /**
76
+ * One settled mutation's hunk coordinates, in the order the engine reported its
77
+ * hunks.
78
+ *
79
+ * The Host records these for EVERY file mutation, model-direct calls included:
80
+ * it sees the mutation's full before/after text at settlement, which is the one
81
+ * place the absolute line numbers still exist. The count is expected to match
82
+ * the number of `meta.diffs` fragments the conversation snapshot carries for the
83
+ * same call — both are the same first-lines-of-hunk patch over the same texts —
84
+ * so the client may pair them positionally, and must refuse to when they differ.
85
+ */
86
+ export interface RecordedAnchor {
87
+ /** The mutation's tool call id, matching the hunk's {@link ProducedFileDiff.callId}. */
88
+ readonly callId: string;
89
+ /** Path the mutation wrote, echoed back so a client can sanity-check the pairing. */
90
+ readonly path: string;
91
+ readonly anchors: readonly HunkAnchor[];
92
+ }
93
+ /** Host request: the mutation calls whose hunk coordinates are wanted. */
94
+ export interface AnchorRequest {
95
+ readonly calls: readonly AnchorCall[];
96
+ }
97
+ /**
98
+ * One call's fragments, as the client holds them, sent so the Host can place
99
+ * them when it never recorded the mutation.
100
+ *
101
+ * The recorder only sees mutations that settle while the plugin is loaded, so a
102
+ * session reviewed after upgrading has hunks whose coordinates were never
103
+ * captured. Those fragments are still enough to place the hunk in the file as it
104
+ * stands, which is what a reviewer wants to see anyway — the Host is the only
105
+ * side that can read the file, so the client ships the text.
106
+ */
107
+ export interface AnchorCall {
108
+ readonly callId: string;
109
+ readonly path: string;
110
+ /** The call's fragments, in the engine's hunk order. */
111
+ readonly hunks: readonly AnchorHunk[];
112
+ }
113
+ /** One fragment's two sides, exactly as the wire hunk carries them. */
114
+ export interface AnchorHunk {
115
+ readonly oldText: string | null;
116
+ readonly newText: string;
117
+ }
118
+ /** Host response: coordinates for the requested calls it could resolve. */
119
+ export interface AnchorResult {
120
+ readonly anchors: readonly RecordedAnchor[];
23
121
  }
24
122
  /** One produced file and the applied hunks available for review. */
25
123
  export interface ProducedFileReview {
@@ -1,6 +1,6 @@
1
1
  import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';
2
2
  import type { TurnTailOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client';
3
- import type { FileReviewRequest, FileReviewResult } from '../change-types.ts';
3
+ import type { AnchorCall, FileReviewRequest, FileReviewResult, RecordedAnchor } from '../change-types.ts';
4
4
  import type { NS } from './chat-locales.ts';
5
5
  /**
6
6
  * Turn-tail owner currency plus the opener and locale supplied by the slot.
@@ -17,6 +17,15 @@ export type ProducedFilesProps = TurnTailOwnerProps & {
17
17
  reviewSessionId?: string | undefined;
18
18
  inspectChanges?: (request: FileReviewRequest) => Promise<FileReviewResult>;
19
19
  applyChanges?: (request: FileReviewRequest) => Promise<FileReviewResult>;
20
+ /**
21
+ * Fetch the Host-recorded line coordinates for the calls a preview draws.
22
+ *
23
+ * The card's own hunks come from the conversation snapshot, which carries
24
+ * context fragments without line numbers; these coordinates are what let the
25
+ * hover preview number them by the file's real lines. Absent (an older Host, or
26
+ * a session with no remote) the preview falls back to hunk-local numbering.
27
+ */
28
+ loadHunkAnchors?: ((calls: readonly AnchorCall[]) => Promise<readonly RecordedAnchor[]>) | undefined;
20
29
  /**
21
30
  * Open the plugin's sidebar tab with the given paths pre-expanded
22
31
  * (the 审查 button passes every produced path; a file row passes its own).
@@ -22,6 +22,51 @@ export interface FileReviewSeed {
22
22
  /** Monotonic publish id; a new value means a new link to replay. */
23
23
  readonly nonce: number;
24
24
  }
25
+ /** A row a deep link resolved to, keyed the way the tab keys its state. */
26
+ export interface DeepLinkRow {
27
+ readonly turn: number;
28
+ readonly path: string;
29
+ }
30
+ /** Everything one replay must do, computed without touching component state. */
31
+ export interface DeepLinkPlan {
32
+ /** Rows to expand, as `turn|path` state keys. */
33
+ readonly expanded: readonly string[];
34
+ /** The row to scroll to (the first match), or null when nothing matched. */
35
+ readonly first: DeepLinkRow | null;
36
+ /**
37
+ * Archive section to reveal: a link into an auto-archived turn must render
38
+ * that turn before its row can be scrolled to. Null when the target is
39
+ * already in the main list.
40
+ */
41
+ readonly archive: {
42
+ readonly pages: number;
43
+ } | null;
44
+ }
45
+ /**
46
+ * Resolve a deep link against EVERY change the tab can render, including turns
47
+ * still hidden behind a closed archive section.
48
+ *
49
+ * The target is deliberately resolved against the full change set rather than
50
+ * the currently mounted rows. A link into an archived turn is replayed in the
51
+ * same commit that opens the archive, so at that moment its rows are not
52
+ * mounted yet; resolving against the mounted set made the match fail, the
53
+ * pending scroll get cleared, and the link land nowhere with no retry.
54
+ *
55
+ * @param turns - Every turn, ascending (the source of truth for all rows).
56
+ * @param archivedTurns - The auto-archived subset, newest first.
57
+ * @param paths - Paths the link targets.
58
+ * @param targetTurn - Turn anchor, or undefined for a path-only (legacy) link.
59
+ * @returns The expand set, the scroll target, and the archive reveal to apply.
60
+ */
61
+ export declare function planDeepLink(turns: readonly {
62
+ readonly turn: number;
63
+ readonly live: boolean;
64
+ readonly files: readonly {
65
+ readonly path: string;
66
+ }[];
67
+ }[], archivedTurns: readonly {
68
+ readonly turn: number;
69
+ }[], paths: readonly string[], targetTurn: number | undefined): DeepLinkPlan;
25
70
  type SeedListener = (sessionId: string, seed: FileReviewSeed) => void;
26
71
  type InvalidationListener = (sessionId: string) => void;
27
72
  /** Publish a deep link for one session and return the stored seed. */