@whybebabo/dsh-file-review-tab 0.7.1 → 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,7 @@ 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";
5
6
  //#region src/mutation-order.ts
6
7
  /**
7
8
  * Order settlements by their recorded event sequence, so undo/redo walk the
@@ -65,6 +66,88 @@ function hunksForApply(group, action) {
65
66
  return [...group].sort((left, right) => anchorOf(right) - anchorOf(left));
66
67
  }
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
68
151
  //#region src/file-review-service.ts
69
152
  /** Host-side, workspace-contained undo / redo service for produced text diffs. */
70
153
  /**
@@ -129,15 +212,9 @@ function replaceHunk(text, source, replacement, line) {
129
212
  }
130
213
  return text.slice(0, offset) + replacement + text.slice(offset + source.length);
131
214
  }
132
- function hunkSupported(diff, path) {
133
- if (diff.path !== path || diff.oldText === null || diff.oldText === diff.newText) return false;
134
- if (diff.oldText === "" && diff.oldStart === void 0) return false;
135
- if (diff.newText === "" && diff.newStart === void 0) return false;
136
- return true;
137
- }
138
215
  /** Apply a complete file's hunk sequence in memory, or report a strict mismatch. */
139
216
  function transformFile(text, file, action) {
140
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return null;
217
+ if (!changeReversible(file.path, file.diffs)) return null;
141
218
  const groups = orderBySequence(mutationGroups(file.diffs).map((group) => ({
142
219
  seq: group[0]?.seq,
143
220
  diffs: group
@@ -167,7 +244,7 @@ function hunkSidePresent(text, file, side) {
167
244
  return true;
168
245
  }
169
246
  function inspectText(text, file) {
170
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return {
247
+ if (!changeReversible(file.path, file.diffs)) return {
171
248
  state: "unsupported",
172
249
  reason: "change has no complete reversible diff"
173
250
  };
@@ -198,7 +275,7 @@ function inspectText(text, file) {
198
275
  };
199
276
  }
200
277
  async function inspectOne(cwd, file) {
201
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return {
278
+ if (!changeReversible(file.path, file.diffs)) return {
202
279
  path: file.path,
203
280
  state: "unsupported",
204
281
  changed: false,
@@ -222,7 +299,7 @@ async function inspectOne(cwd, file) {
222
299
  }
223
300
  }
224
301
  async function applyOne(cwd, file, action) {
225
- if (file.diffs.length === 0 || !file.diffs.every((diff) => hunkSupported(diff, file.path))) return {
302
+ if (!changeReversible(file.path, file.diffs)) return {
226
303
  path: file.path,
227
304
  state: "unsupported",
228
305
  changed: false,
@@ -273,6 +350,14 @@ function sessionCwd(agent) {
273
350
  }
274
351
  /** Per-agent cap on recorded Code Mode mutations (oldest evicted first). */
275
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;
276
361
  function agentKey(agent) {
277
362
  return String(agent.id);
278
363
  }
@@ -280,6 +365,15 @@ function agentKey(agent) {
280
365
  var FileReviewService = class extends TypertRemoteService {
281
366
  /** Per-agent record of Code Mode (`run_code`) file mutations, dispatch order. */
282
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();
283
377
  constructor(ctx) {
284
378
  super(ctx, "fileReview");
285
379
  }
@@ -294,6 +388,66 @@ var FileReviewService = class extends TypertRemoteService {
294
388
  list.push(mutation);
295
389
  if (list.length > RECORDED_PER_AGENT_CAP) list.splice(0, list.length - RECORDED_PER_AGENT_CAP);
296
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
+ }
297
451
  /** Return the recorded mutations for the requested `run_code` roots. */
298
452
  async recorded(agent, request) {
299
453
  const list = this.recordLog.get(agentKey(agent));
@@ -316,16 +470,24 @@ var FileReviewService = class extends TypertRemoteService {
316
470
  });
317
471
  }
318
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
+ }
319
485
  //#endregion
320
486
  //#region src/index.ts
321
- /** Services required for the model guidance paired with the browser renderer. */
322
- const inject = ["systemPrompt"];
323
- /** Stable final-response guidance owned by the matching renderer. */
324
- 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 = [];
325
489
  /**
326
- * Register model guidance for the file-reference renderer shipped by this package,
327
- * and the Code Mode (`run_code`) mutation recorder that backs the browser-side
328
- * review tab.
490
+ * Record every settled file mutation for the browser-side review surfaces.
329
491
  *
330
492
  * Nested dispatch results carry no wire views — the diff cards only ride
331
493
  * model-direct tool/call frames — so reviewing programmatic file edits needs a
@@ -333,15 +495,10 @@ const FILE_REFERENCE_PROMPT = "When you successfully create or modify files, men
333
495
  * every nested file mutation (`edit`/`write` — recognized by result shape, not
334
496
  * tool name) into the `fileReview` service, which the browser half later turns
335
497
  * into line-level hunks and merges into the owning `run_code` turn.
336
- * @param ctx - host context carrying the system-prompt registry and tool waterfall.
498
+ * @param ctx - host context carrying the tool waterfall.
337
499
  */
338
500
  function apply(ctx) {
339
501
  const service = new FileReviewService(ctx);
340
- ctx.systemPrompt.section({
341
- name: "ui:file-review-references",
342
- order: 190,
343
- text: FILE_REFERENCE_PROMPT
344
- });
345
502
  const emitter = ctx;
346
503
  ctx.effect(() => {
347
504
  const off = emitter.on("tools/post-execute", async (execRaw, resultRaw, nextRaw) => {
@@ -349,17 +506,24 @@ function apply(ctx) {
349
506
  const result = resultRaw;
350
507
  const decision = await nextRaw();
351
508
  if (decision.kind !== "accept") return decision;
352
- if (exec.parent === void 0 || exec.agent === void 0) return decision;
509
+ if (exec.agent === void 0) return decision;
353
510
  const value = result.value;
354
511
  if (typeof value !== "object" || value === null || Array.isArray(value)) return decision;
355
512
  const candidate = value;
356
513
  if (typeof candidate.path !== "string" || typeof candidate.after !== "string") return decision;
357
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;
358
522
  service.recordMutation(exec.agent, {
359
523
  rootCallId: String(exec.rootCallId ?? exec.callId),
360
524
  name: exec.name,
361
525
  path: candidate.path,
362
- before: candidate.before ?? null,
526
+ before,
363
527
  after: candidate.after
364
528
  });
365
529
  return decision;
@@ -40,7 +40,12 @@ const diffSchema = z.object({
40
40
  /** Coordinate space, so hunks from several settlements stay separable. */
41
41
  mutation: z.number().int().min(0).optional(),
42
42
  /** Event sequence, so settlements merge in the order they happened. */
43
- seq: z.number().int().min(0).optional()
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()
44
49
  });
45
50
  const requestSchema = z.object({
46
51
  action: z.enum(["undo", "redo"]),
@@ -75,6 +80,28 @@ const recordedRequestSchema = z.object({ rootCallIds: z.array(z.string()) });
75
80
  const recordedResultSchema = z.object({ mutations: z.array(recordedMutationSchema) });
76
81
  const recordedRequestCodec = strictCodec(`${PACKAGE_NAME}#RecordedRequest`, () => recordedRequestSchema);
77
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);
78
105
  function descriptor(method) {
79
106
  return {
80
107
  id: `${PACKAGE_NAME}#fileReview/${method}`,
@@ -127,10 +154,37 @@ function recordedDescriptor() {
127
154
  result: recordedResultCodec
128
155
  };
129
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
+ }
130
183
  const FILE_REVIEW_INVOCATIONS = [
131
184
  descriptor("status"),
132
185
  descriptor("apply"),
133
- recordedDescriptor()
186
+ recordedDescriptor(),
187
+ anchorsDescriptor()
134
188
  ];
135
189
  //#endregion
136
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
@@ -48,6 +48,76 @@ export interface ProducedFileDiff {
48
48
  * Optional: when absent the order is not provable and the array order stands.
49
49
  */
50
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[];
51
121
  }
52
122
  /** One produced file and the applied hunks available for review. */
53
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).
@@ -11,7 +11,7 @@
11
11
  * trimming context the same way, so a one-line edit in a long file renders as one
12
12
  * small hunk instead of the whole file.
13
13
  */
14
- import type { ProducedFileDiff } from '../change-types.ts';
14
+ import type { HunkAnchor, ProducedFileDiff } from '../change-types.ts';
15
15
  /** How one drawn line relates to the two sides of the comparison. */
16
16
  export type DiffLineKind = 'context' | 'del' | 'add';
17
17
  /** One line of a comparison, already numbered against both sides. */
@@ -41,8 +41,16 @@ export interface NativeDiffHunk {
41
41
  }
42
42
  /** Whether a comparison touches only one side, which forces the unified view. */
43
43
  export declare function isOneSided(hunks: readonly NativeDiffHunk[]): boolean;
44
- /** Pair one recorded before/after snapshot into numbered lines. */
45
- export declare function pairLines(diff: ProducedFileDiff): DiffLine[];
44
+ /**
45
+ * Pair one recorded before/after snapshot into numbered lines.
46
+ *
47
+ * `anchor` overrides where the pairing starts. The wire hunks the conversation
48
+ * snapshot carries are context fragments with no line numbers at all, so without
49
+ * an anchor their numbering can only start at 1 — a per-hunk counter, not the
50
+ * file's lines. The Host knows each mutation's real coordinates (see
51
+ * {@link HunkAnchor}) and this is where they enter the drawing.
52
+ */
53
+ export declare function pairLines(diff: ProducedFileDiff, anchor?: HunkAnchor | undefined): DiffLine[];
46
54
  /** Count added and removed lines using the viewer's exact line-diff algorithm. */
47
55
  export declare function summarizeDiffs(diffs: readonly ProducedFileDiff[]): DiffStats;
48
56
  /**
@@ -74,13 +82,16 @@ export declare function diffNote(diffs: readonly ProducedFileDiff[], hunks: read
74
82
  * @returns the copy to show.
75
83
  */
76
84
  export declare function missingMessage(deleted: boolean, deletedHint: string, missing: string): string;
85
+ /** Recorded coordinates by the call that applied them. */
86
+ export type HunkAnchorLookup = ReadonlyMap<string, readonly HunkAnchor[]>;
77
87
  /**
78
88
  * Convert recorded comparisons into dsh's served hunk shape.
79
89
  * @param diffs - the recorded before/after snapshots for one file.
80
90
  * @param contextLines - unchanged lines kept on each side of a change.
91
+ * @param anchors - recorded absolute coordinates by call id, when known.
81
92
  * @returns the hunks to render, in order.
82
93
  */
83
- export declare function toNativeHunks(diffs: readonly ProducedFileDiff[], contextLines?: number): NativeDiffHunk[];
94
+ export declare function toNativeHunks(diffs: readonly ProducedFileDiff[], contextLines?: number, anchors?: HunkAnchorLookup | undefined): NativeDiffHunk[];
84
95
  /** Serialize recorded hunks as one plain-text unified diff. */
85
96
  export declare function nativeDiffText(hunks: readonly NativeDiffHunk[]): string;
86
97
  //# sourceMappingURL=diff-hunks.d.ts.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Client cache and hook for the Host's per-mutation hunk coordinates.
3
+ *
4
+ * The comparison surfaces read the conversation snapshot, and its hunks are the
5
+ * engine's context fragments — text only, no line numbers. Numbering those from
6
+ * 1 puts a change at the end of a long file on "line 1". The Host recorded each
7
+ * mutation's real coordinates at settlement (see the node half's hunk-anchors
8
+ * module); this module fetches them once per session and hands them to the
9
+ * renderer.
10
+ *
11
+ * Deliberately a cache rather than view state: a call's coordinates never change
12
+ * once recorded, so the sidebar tab, a chat hover preview and every remount reuse
13
+ * the same answer. Only the FIRST lookup of a call id costs a round trip, and a
14
+ * call the recorder never saw stays marked as asked — a session whose mutations
15
+ * happened outside the tool pipeline must not turn every render into a request.
16
+ */
17
+ import type { AnchorCall, RecordedAnchor } from '../change-types.ts';
18
+ import type { ProducedFileDiff } from '../change-types.ts';
19
+ import type { HunkAnchorLookup } from './diff-hunks.ts';
20
+ /**
21
+ * Group one file's hunks into the calls that produced them.
22
+ *
23
+ * Fragments of a call are consecutive and keep the engine's hunk order, so this
24
+ * both names the calls to ask about and supplies the text the Host needs to place
25
+ * a hunk whose coordinates were never recorded. Hunks without a call id (the
26
+ * recorded Code Mode path, which already carries coordinates) are skipped.
27
+ * @param diffs - the file's hunks, in settlement order.
28
+ * @returns one entry per call, in first-seen order.
29
+ */
30
+ export declare function anchorCalls(diffs: readonly ProducedFileDiff[]): AnchorCall[];
31
+ /**
32
+ * Coordinates remembered for one session, as the lookup the renderer takes.
33
+ * @param sessionId - the session whose anchors are wanted.
34
+ * @returns the cached map (empty before any lookup completes).
35
+ */
36
+ export declare function cachedHunkAnchors(sessionId: string): HunkAnchorLookup;
37
+ /** Merge a Host answer into the cache and return the new lookup. */
38
+ export declare function rememberHunkAnchors(sessionId: string, entries: readonly RecordedAnchor[]): HunkAnchorLookup;
39
+ /**
40
+ * Drop a session's cache. Called when a session is disposed: a later session can
41
+ * reuse neither the id nor the call ids.
42
+ * @param sessionId - the session leaving.
43
+ */
44
+ export declare function forgetHunkAnchors(sessionId: string): void;
45
+ /**
46
+ * Claim the ids that still need a lookup, marking them as asked.
47
+ *
48
+ * Claiming before the request is what stops two surfaces painting the same hunk
49
+ * in one commit from fetching it twice. An id marked this way is never asked
50
+ * again unless {@link releaseCallIds} returns it: a call the recorder never saw
51
+ * answers successfully with no coordinates, and that must not become a request
52
+ * per render.
53
+ * @param sessionId - session key for the shared cache.
54
+ * @param callIds - the calls the painted hunks came from.
55
+ * @returns the ids to ask about now; empty when nothing new is wanted.
56
+ */
57
+ export declare function claimCallIds(sessionId: string, callIds: readonly string[]): string[];
58
+ /**
59
+ * Un-claim ids whose lookup failed.
60
+ *
61
+ * A thrown lookup is NOT the Host saying "this call has no coordinates" — it is
62
+ * the Host not answering (an unmounted Remote, a transport error). Releasing the
63
+ * ids is what lets a later attempt (new hunks, a now-visible tab, a remount) ask
64
+ * again instead of leaving those hunks permanently unanchored.
65
+ * @param sessionId - session key for the shared cache.
66
+ * @param callIds - the ids whose request failed.
67
+ */
68
+ export declare function releaseCallIds(sessionId: string, callIds: readonly string[]): void;
69
+ /**
70
+ * Coordinates for the calls a set of painted hunks came from, fetched on demand.
71
+ *
72
+ * Call it unconditionally from the component that draws the hunks; the request
73
+ * lives in an effect, so a surface that never paints a diff never asks the Host.
74
+ * @param sessionId - session key for the shared cache.
75
+ * @param callIds - the calls the painted hunks came from, in any order.
76
+ * @param load - Host lookup; undefined while the Remote is unavailable.
77
+ * @param enabled - false pauses the lookup (a hidden tab, a closed preview).
78
+ * @returns the lookup `toNativeHunks` takes.
79
+ */
80
+ export declare function useHunkAnchors(sessionId: string, callIds: readonly string[], load: ((ids: readonly string[]) => Promise<readonly RecordedAnchor[]>) | undefined, enabled?: boolean): HunkAnchorLookup;
81
+ //# sourceMappingURL=hunk-anchors.d.ts.map