@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/client.js CHANGED
@@ -4038,7 +4038,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4038
4038
  oldText: string().nullable(),
4039
4039
  newText: string(),
4040
4040
  oldStart: number().int().min(1).optional(),
4041
- newStart: number().int().min(1).optional()
4041
+ newStart: number().int().min(1).optional(),
4042
+ /** Coordinate space, so hunks from several settlements stay separable. */
4043
+ mutation: number().int().min(0).optional(),
4044
+ /** Event sequence, so settlements merge in the order they happened. */
4045
+ seq: number().int().min(0).optional(),
4046
+ /**
4047
+ * The emitting call, carried so the renderer can pair this fragment with the
4048
+ * coordinates the Host recorded for it. Ignored by the apply side.
4049
+ */
4050
+ callId: string().optional()
4042
4051
  });
4043
4052
  const requestSchema = object({
4044
4053
  action: _enum(["undo", "redo"]),
@@ -4073,6 +4082,27 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4073
4082
  const recordedResultSchema = object({ mutations: array(recordedMutationSchema) });
4074
4083
  const recordedRequestCodec = strictCodec(`${PACKAGE_NAME}#RecordedRequest`, () => recordedRequestSchema);
4075
4084
  const recordedResultCodec = strictCodec(`${PACKAGE_NAME}#RecordedResult`, () => recordedResultSchema);
4085
+ const hunkAnchorSchema = object({
4086
+ oldStart: number().int().min(0),
4087
+ newStart: number().int().min(1)
4088
+ });
4089
+ const recordedAnchorSchema = object({
4090
+ callId: string(),
4091
+ path: string(),
4092
+ anchors: array(hunkAnchorSchema)
4093
+ });
4094
+ const anchorHunkSchema = object({
4095
+ oldText: string().nullable(),
4096
+ newText: string()
4097
+ });
4098
+ const anchorRequestSchema = object({ calls: array(object({
4099
+ callId: string(),
4100
+ path: string(),
4101
+ hunks: array(anchorHunkSchema)
4102
+ })) });
4103
+ const anchorResultSchema = object({ anchors: array(recordedAnchorSchema) });
4104
+ const anchorRequestCodec = strictCodec(`${PACKAGE_NAME}#AnchorRequest`, () => anchorRequestSchema);
4105
+ const anchorResultCodec = strictCodec(`${PACKAGE_NAME}#AnchorResult`, () => anchorResultSchema);
4076
4106
  function descriptor(method) {
4077
4107
  return {
4078
4108
  id: `${PACKAGE_NAME}#fileReview/${method}`,
@@ -4125,6 +4155,32 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4125
4155
  result: recordedResultCodec
4126
4156
  };
4127
4157
  }
4158
+ function anchorsDescriptor() {
4159
+ return {
4160
+ id: `${PACKAGE_NAME}#fileReview/anchors`,
4161
+ service: "fileReview",
4162
+ namespace: "fileReview",
4163
+ method: "anchors",
4164
+ invocation: { kind: "direct" },
4165
+ scope: {
4166
+ context: "agent",
4167
+ wire: "agentId"
4168
+ },
4169
+ parameters: [{
4170
+ name: "agent",
4171
+ wire: "agentId",
4172
+ source: "lookup",
4173
+ lookup: "agent",
4174
+ codec: agentCodec
4175
+ }, {
4176
+ name: "request",
4177
+ wire: "request",
4178
+ source: "json",
4179
+ codec: anchorRequestCodec
4180
+ }],
4181
+ result: anchorResultCodec
4182
+ };
4183
+ }
4128
4184
  //#endregion
4129
4185
  //#region src/remote.ts
4130
4186
  const TYPERT_REMOTE = {
@@ -4132,7 +4188,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4132
4188
  descriptors: [
4133
4189
  descriptor("status"),
4134
4190
  descriptor("apply"),
4135
- recordedDescriptor()
4191
+ recordedDescriptor(),
4192
+ anchorsDescriptor()
4136
4193
  ]
4137
4194
  };
4138
4195
  //#endregion
@@ -4173,6 +4230,72 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4173
4230
  ]);
4174
4231
  /** PowerShell parameters whose NEXT argument is the path, not an option value. */
4175
4232
  const PATH_PARAMETERS = /^-(path|literalpath)$/i;
4233
+ /**
4234
+ * Options whose NEXT token is a VALUE, not a path (`shred -n 3 file` — `3` is an
4235
+ * iteration count). Keyed by command, because `-n` means different things to
4236
+ * different tools; an option absent here is assumed valueless.
4237
+ *
4238
+ * Options that carry their value inline (`--iterations=3`) need no entry: they
4239
+ * are consumed as a single token.
4240
+ */
4241
+ const VALUE_OPTIONS = /* @__PURE__ */ new Map([["shred", /* @__PURE__ */ new Set([
4242
+ "n",
4243
+ "iterations",
4244
+ "s",
4245
+ "size"
4246
+ ])], ["trash", /* @__PURE__ */ new Set(["trash-dir"])]]);
4247
+ /**
4248
+ * cmd.exe `/x` switches, per command. `del /q file` deletes `file`, so `/q` is a
4249
+ * switch and not a path.
4250
+ *
4251
+ * The lists are EXACTLY what each cmd builtin defines, because these command
4252
+ * names also exist in PowerShell, where `/tmp/x` is an absolute path and not a
4253
+ * switch at all. Accepting any `/letters` token would silently swallow such a
4254
+ * path (`rd /tmp` is a real deletion in PowerShell); accepting only the real
4255
+ * switches keeps both shells correct.
4256
+ */
4257
+ const SLASH_SWITCHES = /* @__PURE__ */ new Map([
4258
+ ["del", /* @__PURE__ */ new Set([
4259
+ "p",
4260
+ "f",
4261
+ "s",
4262
+ "q",
4263
+ "a"
4264
+ ])],
4265
+ ["erase", /* @__PURE__ */ new Set([
4266
+ "p",
4267
+ "f",
4268
+ "s",
4269
+ "q",
4270
+ "a"
4271
+ ])],
4272
+ ["rd", /* @__PURE__ */ new Set(["s", "q"])],
4273
+ ["rmdir", /* @__PURE__ */ new Set(["s", "q"])]
4274
+ ]);
4275
+ /**
4276
+ * The option name one `/…` token declares, or null when it is a path.
4277
+ *
4278
+ * `/a` may carry an attached value (`/a:h`, `/a:-r`), so a `:value` suffix is
4279
+ * allowed; the name is what precedes the colon.
4280
+ */
4281
+ function slashSwitchName(command, token) {
4282
+ const match = /^\/([A-Za-z]+)(?::[^\s]*)?$/.exec(token);
4283
+ if (match === null) return null;
4284
+ const name = match[1].toLowerCase();
4285
+ return SLASH_SWITCHES.get(command)?.has(name) === true ? name : null;
4286
+ }
4287
+ /**
4288
+ * The option name a token declares, lowercased, with the switch prefix and any
4289
+ * inline value removed, or null when the token is not an option at all.
4290
+ * @param token - One argument.
4291
+ * @param command - The command it was passed to.
4292
+ * @returns The bare option name, or null for a path.
4293
+ */
4294
+ function optionName(token, command) {
4295
+ if (token.startsWith("-")) return token.replace(/^-+/, "").split("=")[0].toLowerCase();
4296
+ if (token.startsWith("/")) return slashSwitchName(command, token);
4297
+ return null;
4298
+ }
4176
4299
  /** Arguments never treated as paths: glob/expansion-bearing or self/parent refs. */
4177
4300
  function isPathlike(token) {
4178
4301
  if (token === "" || token === "." || token === "..") return false;
@@ -4226,21 +4349,34 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4226
4349
  return segments;
4227
4350
  }
4228
4351
  /**
4229
- * Shell-like tokenization of one segment, quotes joined into the token.
4352
+ * Shell-like tokenization of one segment. Quotes are joined into the token and
4353
+ * recorded, because quote boundaries decide whether a comma separates paths.
4354
+ *
4230
4355
  * Backslash semantics follow the Windows-relevant reading: inside SINGLE
4231
4356
  * quotes (bash/PowerShell alike) everything is literal, and unquoted
4232
4357
  * backslashes stay literal too (PowerShell paths); only inside DOUBLE quotes
4233
4358
  * does a backslash escape the closing quote or itself (bash). A trailing open
4234
4359
  * quote still yields the tokens gathered so far.
4360
+ *
4361
+ * Each token is returned as its comma-separated PARTS: PowerShell passes a list
4362
+ * as `'a.txt','b.txt'`, which is one whitespace token but two paths. Only an
4363
+ * UNQUOTED comma splits, so a comma that is part of a filename survives —
4364
+ * `rm 'a,b.txt'` is one path, not two.
4235
4365
  */
4236
4366
  function tokenize$1(segment) {
4237
4367
  const tokens = [];
4368
+ let parts = [];
4238
4369
  let current = "";
4239
4370
  let quote = null;
4240
- const flush = () => {
4241
- if (current !== "") tokens.push(current);
4371
+ const flushPart = () => {
4372
+ if (current !== "") parts.push(current);
4242
4373
  current = "";
4243
4374
  };
4375
+ const flushToken = () => {
4376
+ flushPart();
4377
+ if (parts.length > 0) tokens.push(parts);
4378
+ parts = [];
4379
+ };
4244
4380
  for (let at = 0; at < segment.length; at += 1) {
4245
4381
  const char = segment[at];
4246
4382
  if (char === void 0) break;
@@ -4267,12 +4403,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4267
4403
  continue;
4268
4404
  }
4269
4405
  if (/\s/.test(char)) {
4270
- flush();
4406
+ flushToken();
4407
+ continue;
4408
+ }
4409
+ if (char === ",") {
4410
+ flushPart();
4271
4411
  continue;
4272
4412
  }
4273
4413
  current += char;
4274
4414
  }
4275
- flush();
4415
+ flushToken();
4276
4416
  return tokens;
4277
4417
  }
4278
4418
  /**
@@ -4284,37 +4424,65 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4284
4424
  const paths = [];
4285
4425
  const seen = /* @__PURE__ */ new Set();
4286
4426
  const accept = (raw) => {
4287
- for (const part of raw.split(",")) {
4288
- if (!isPathlike(part) || seen.has(part)) continue;
4289
- seen.add(part);
4290
- paths.push(part);
4291
- }
4427
+ if (!isPathlike(raw) || seen.has(raw)) return;
4428
+ seen.add(raw);
4429
+ paths.push(raw);
4430
+ };
4431
+ /** Accept every path a token names (a PowerShell list carries several). */
4432
+ const acceptAll = (token) => {
4433
+ for (const part of token) accept(part);
4292
4434
  };
4435
+ /**
4436
+ * The token's text when it is a single argument, or undefined when it is a
4437
+ * comma-separated LIST. Only single-part tokens can be options: an unquoted
4438
+ * comma always separated paths, and no option in these commands takes one.
4439
+ */
4440
+ const optionToken = (token) => token.length === 1 ? token[0] : void 0;
4293
4441
  for (const segment of splitSegments(command)) {
4294
4442
  if (segment.includes("$(") || segment.includes("`") || segment.includes("<(")) continue;
4295
4443
  const tokens = tokenize$1(segment);
4296
4444
  let at = 0;
4297
4445
  while (at < tokens.length) {
4298
- const head = tokens[at];
4446
+ const head = tokens[at] === void 0 ? void 0 : optionToken(tokens[at]);
4299
4447
  if (head === void 0 || !/^[A-Za-z_][A-Za-z0-9_]*=/.test(head)) break;
4300
4448
  at += 1;
4301
4449
  }
4302
- const commandWord = tokens[at];
4450
+ const commandWord = tokens[at] === void 0 ? void 0 : optionToken(tokens[at]);
4303
4451
  if (commandWord === void 0) continue;
4304
- const basename = commandWord.slice(Math.max(commandWord.lastIndexOf("/"), commandWord.lastIndexOf("\\")) + 1);
4305
- if (!DELETERS.has(basename.toLowerCase())) continue;
4452
+ const command = commandWord.slice(Math.max(commandWord.lastIndexOf("/"), commandWord.lastIndexOf("\\")) + 1).toLowerCase();
4453
+ if (!DELETERS.has(command)) continue;
4454
+ const valueOptions = VALUE_OPTIONS.get(command);
4455
+ let optionsEnded = false;
4306
4456
  for (let index = at + 1; index < tokens.length; index += 1) {
4307
- const token = tokens[index];
4308
- if (token === void 0) continue;
4309
- if (token.startsWith("-")) {
4310
- if (PATH_PARAMETERS.test(token) && index + 1 < tokens.length) {
4311
- index += 1;
4312
- const named = tokens[index];
4313
- if (named !== void 0) accept(named);
4314
- }
4457
+ const parts = tokens[index];
4458
+ if (parts === void 0) continue;
4459
+ const token = optionToken(parts);
4460
+ if (optionsEnded || token === void 0) {
4461
+ acceptAll(parts);
4462
+ continue;
4463
+ }
4464
+ if (token === "--") {
4465
+ optionsEnded = true;
4466
+ continue;
4467
+ }
4468
+ if (PATH_PARAMETERS.test(token) && index + 1 < tokens.length) {
4469
+ index += 1;
4470
+ const named = tokens[index];
4471
+ if (named !== void 0) acceptAll(named);
4472
+ continue;
4473
+ }
4474
+ const inlinePath = /^-(?:path|literalpath):(.*)$/i.exec(token);
4475
+ if (inlinePath !== null) {
4476
+ const named = inlinePath[1];
4477
+ if (named !== void 0 && named !== "") accept(named);
4478
+ continue;
4479
+ }
4480
+ const option = optionName(token, command);
4481
+ if (option !== null) {
4482
+ if (!token.includes("=") && token !== "-" && valueOptions?.has(option) === true) index += 1;
4315
4483
  continue;
4316
4484
  }
4317
- accept(token);
4485
+ acceptAll(parts);
4318
4486
  }
4319
4487
  }
4320
4488
  return paths;
@@ -4449,6 +4617,106 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4449
4617
  return out;
4450
4618
  }
4451
4619
  //#endregion
4620
+ //#region src/mutation-order.ts
4621
+ /**
4622
+ * Append one settlement's hunks, stamping them with the coordinate space they
4623
+ * were recorded in and the event sequence that orders them.
4624
+ *
4625
+ * The stamp is the accumulator's current length, which is strictly increasing
4626
+ * per path, so two settlements can never share one — that uniqueness is what
4627
+ * lets {@link mutationGroups} split a path's hunks back into settlements.
4628
+ *
4629
+ * `seq` is the ordering key: the conversation node's sequence for a
4630
+ * snapshot-derived settlement, or the owning `run_code` root's sequence for a
4631
+ * Host-recorded one. It is recorded separately from `mutation` because the two
4632
+ * answer different questions — a chain of nested dispatches produces several
4633
+ * distinct settlements that all share one node sequence.
4634
+ *
4635
+ * @param target - The path's accumulated hunks, mutated in place.
4636
+ * @param diffs - One settlement's hunks, all anchored in the same text.
4637
+ * @param seq - Event sequence that orders this settlement, when known.
4638
+ */
4639
+ function appendMutation(target, diffs, seq) {
4640
+ const mutation = target.length;
4641
+ for (const diff of diffs) target.push(seq === void 0 ? {
4642
+ ...diff,
4643
+ mutation
4644
+ } : {
4645
+ ...diff,
4646
+ mutation,
4647
+ seq
4648
+ });
4649
+ }
4650
+ /**
4651
+ * Order settlements by their recorded event sequence, so undo/redo walk the
4652
+ * file's history in the order it actually happened.
4653
+ *
4654
+ * This is what keeps a `run_code` mutation and a model-direct edit to the same
4655
+ * file from being applied out of order: the two arrive through different
4656
+ * channels (the conversation snapshot vs. the Host recorder) and are merged
4657
+ * asynchronously, so the array order is a merge artifact rather than history.
4658
+ *
4659
+ * Only when EVERY entry carries a sequence is the order provable. A partially
4660
+ * stamped list keeps its incoming order, which is the conservative choice —
4661
+ * guessing at the position of an unstamped settlement could silently corrupt a
4662
+ * file. The sort is stable, so entries sharing one sequence (a single
4663
+ * `run_code` root's nested dispatch chain) keep their dispatch order.
4664
+ *
4665
+ * @param entries - Settlements or events carrying an optional `seq`.
4666
+ * @returns A new array in ascending event order, or the same order when unprovable.
4667
+ */
4668
+ function orderBySequence(entries) {
4669
+ if (entries.some((entry) => entry.seq === void 0)) return [...entries];
4670
+ return [...entries].sort((left, right) => left.seq - right.seq);
4671
+ }
4672
+ /**
4673
+ * Recover the settlements one path's flat hunk list was built from.
4674
+ * @param diffs - One path's accumulated hunks.
4675
+ * @returns One entry per coordinate space, in the order they were appended.
4676
+ */
4677
+ function settlementsOf(diffs) {
4678
+ return mutationGroups(diffs).map((group) => ({
4679
+ seq: group[0]?.seq,
4680
+ diffs: group
4681
+ }));
4682
+ }
4683
+ /**
4684
+ * Re-stamp a settlement list back into one flat hunk list, in event order.
4685
+ *
4686
+ * Stamps are reassigned rather than preserved because they encode POSITION
4687
+ * (`mutation` is the append offset), and reordering invalidates the old values;
4688
+ * leaving them stale would make {@link mutationGroups} split the same
4689
+ * coordinate space into several groups.
4690
+ *
4691
+ * @param settlements - Settlements, in any order.
4692
+ * @returns The flat hunk list, ordered by `seq` with fresh stamps.
4693
+ */
4694
+ function flattenSettlements(settlements) {
4695
+ const out = [];
4696
+ for (const settlement of orderBySequence(settlements)) appendMutation(out, settlement.diffs, settlement.seq);
4697
+ return out;
4698
+ }
4699
+ /**
4700
+ * Split one path's hunks into contiguous same-coordinate groups, in settlement
4701
+ * order. Hunks that carry no `mutation` form a single group.
4702
+ * @param diffs - One path's accumulated hunks, in settlement order.
4703
+ * @returns The groups, in settlement order.
4704
+ */
4705
+ function mutationGroups(diffs) {
4706
+ const groups = [];
4707
+ let current = null;
4708
+ let currentStamp;
4709
+ for (const diff of diffs) {
4710
+ if (current === null || diff.mutation !== currentStamp) {
4711
+ current = [];
4712
+ currentStamp = diff.mutation;
4713
+ groups.push(current);
4714
+ }
4715
+ current.push(diff);
4716
+ }
4717
+ return groups;
4718
+ }
4719
+ //#endregion
4452
4720
  //#region src/client/snapshot-compat.ts
4453
4721
  /** Structural view-source guard: a store with a callable `get`. */
4454
4722
  function viewStore(value) {
@@ -5063,15 +5331,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5063
5331
  if (!change.removed && !change.added) {
5064
5332
  const run = change.value;
5065
5333
  if (hunk !== null) {
5066
- const beforeLen = hunk.old.length;
5334
+ const oldKept = hunk.old.length + CONTEXT_LINES;
5335
+ const newKept = hunk.new.length + CONTEXT_LINES;
5067
5336
  hunk.old.push(...run);
5068
5337
  hunk.new.push(...run);
5069
5338
  oldCursor += run.length;
5070
5339
  newCursor += run.length;
5071
5340
  if (run.length > 6) {
5072
- const target = beforeLen + CONTEXT_LINES;
5073
- hunk.old.length = target;
5074
- hunk.new.length = target;
5341
+ hunk.old.length = oldKept;
5342
+ hunk.new.length = newKept;
5075
5343
  contextBuffer = run.slice(-3);
5076
5344
  hunk = null;
5077
5345
  }
@@ -5151,6 +5419,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5151
5419
  if (own.length > 0) diffs = own;
5152
5420
  }
5153
5421
  }
5422
+ const callId = block.callId;
5423
+ if (typeof callId === "string") diffs = diffs.map((diff) => ({
5424
+ ...diff,
5425
+ callId
5426
+ }));
5154
5427
  if (diffs.length > 0) changes.push({
5155
5428
  path: intent.path,
5156
5429
  diffs
@@ -5163,7 +5436,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5163
5436
  });
5164
5437
  return changes;
5165
5438
  }
5166
- /** Settled changes for a tool block tree (the block itself plus `subCalls`). */
5439
+ /**
5440
+ * Settled changes for a tool block tree (the block itself plus `subCalls`).
5441
+ *
5442
+ * The tree contributes one settlement per top-level node, NOT one per nested
5443
+ * dispatch: the Host recorder attributes a `run_code` root's mutations to the
5444
+ * ROOT's seq (a nested dispatch it observes carries no separate conversation
5445
+ * sequence of its own). Ordering the two channels against different clocks
5446
+ * would be comparing incomparable numbers, and a child's seq could also fall
5447
+ * past the turn boundary that owns its root.
5448
+ */
5167
5449
  function collectChanges(block, out) {
5168
5450
  if (block.kind === "tool-result") for (const change of blockChanges(block)) out.push(change);
5169
5451
  const subCalls = block.subCalls;
@@ -5204,41 +5486,58 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5204
5486
  const changes = [];
5205
5487
  collectChanges(node, changes);
5206
5488
  if (changes.length === 0) continue;
5489
+ const seq = typeof node.seq === "number" ? node.seq : void 0;
5207
5490
  const { turn, live } = attribute(node.seq);
5208
5491
  let group = byTurn.get(turn);
5209
5492
  if (group === void 0) {
5210
5493
  group = {
5211
5494
  live,
5212
- files: /* @__PURE__ */ new Map()
5495
+ changes: []
5213
5496
  };
5214
5497
  byTurn.set(turn, group);
5215
5498
  }
5216
- for (const change of changes) {
5217
- const existing = group.files.get(change.path);
5499
+ for (const change of changes) group.changes.push({
5500
+ seq,
5501
+ change
5502
+ });
5503
+ }
5504
+ return [...byTurn.entries()].sort((a, b) => a[0] - b[0]).map(([turn, group]) => {
5505
+ const files = /* @__PURE__ */ new Map();
5506
+ for (const { seq, change } of orderBySequence(group.changes)) {
5507
+ const existing = files.get(change.path);
5218
5508
  if (change.deleted === true) {
5219
- if (existing === void 0) group.files.set(change.path, {
5509
+ if (existing === void 0) files.set(change.path, {
5220
5510
  diffs: [],
5221
- deleted: true
5511
+ deleted: true,
5512
+ deletedSeq: seq
5222
5513
  });
5223
- else existing.deleted = true;
5514
+ else {
5515
+ existing.deleted = true;
5516
+ existing.deletedSeq = seq;
5517
+ }
5224
5518
  continue;
5225
5519
  }
5226
- if (existing === void 0) group.files.set(change.path, { diffs: [...change.diffs] });
5227
- else {
5228
- existing.diffs.push(...change.diffs);
5520
+ if (existing === void 0) {
5521
+ const diffs = [];
5522
+ appendMutation(diffs, change.diffs, seq);
5523
+ files.set(change.path, { diffs });
5524
+ } else {
5525
+ appendMutation(existing.diffs, change.diffs, seq);
5229
5526
  delete existing.deleted;
5527
+ delete existing.deletedSeq;
5230
5528
  }
5231
5529
  }
5232
- }
5233
- return [...byTurn.entries()].sort((a, b) => a[0] - b[0]).map(([turn, group]) => ({
5234
- turn,
5235
- live: group.live,
5236
- files: [...group.files.entries()].map(([path, own]) => ({
5237
- path,
5238
- diffs: own.diffs,
5239
- ...own.deleted === true ? { deleted: true } : {}
5240
- }))
5241
- }));
5530
+ return {
5531
+ turn,
5532
+ live: group.live,
5533
+ files: [...files.entries()].map(([path, own]) => ({
5534
+ path,
5535
+ diffs: own.diffs,
5536
+ ...own.deleted === true ? { deleted: true } : {},
5537
+ ...own.deletedSeq !== void 0 ? { deletedSeq: own.deletedSeq } : {}
5538
+ }))
5539
+ };
5540
+ });
5242
5541
  }
5243
5542
  /**
5244
5543
  * Snapshot-identity cache: the sidebar badge runs this derivation on every
@@ -5264,32 +5563,49 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5264
5563
  if (node.kind !== "tool-result" || node.isError) continue;
5265
5564
  if (node.subCalls.length === 0) continue;
5266
5565
  const nested = [];
5267
- for (const child of node.subCalls) if (child.kind === "tool-result") collectChanges(child, nested);
5566
+ let settled = 0;
5567
+ for (const child of node.subCalls) {
5568
+ if (child.kind !== "tool-result") continue;
5569
+ settled += 1;
5570
+ collectChanges(child, nested);
5571
+ }
5268
5572
  if (nested.some((change) => change.diffs.length > 0)) continue;
5269
5573
  const { turn, live } = attribute(node.seq);
5574
+ const seq = typeof node.seq === "number" ? node.seq : void 0;
5270
5575
  roots.push({
5271
5576
  turn,
5272
5577
  live,
5273
- rootCallId: node.callId
5578
+ rootCallId: node.callId,
5579
+ seq,
5580
+ progress: settled
5274
5581
  });
5275
5582
  }
5276
5583
  return roots;
5277
5584
  }
5278
5585
  /**
5279
5586
  * Merge Host-recorded Code Mode mutations into the snapshot-derived turns:
5280
- * hunks rebuilt from the full before/after are appended to the owning turn's
5281
- * file groups (same-path entries stay one row, hunks appended in dispatch
5282
- * order), so the tab's diff rendering, status inspection and undo all work on
5283
- * programmatic edits exactly like model-direct ones. All inputs are immutable;
5284
- * the result is a fresh array only when a recorded mutation matched a visible
5285
- * root.
5587
+ * hunks rebuilt from the full before/after are inserted into the owning turn's
5588
+ * file groups at the position their EVENT SEQUENCE puts them (same-path entries
5589
+ * stay one row), so the tab's diff rendering, status inspection and undo all
5590
+ * work on programmatic edits exactly like model-direct ones.
5591
+ *
5592
+ * Ordering is by sequence rather than "snapshot first, recorded after": the two
5593
+ * sources are separate channels merged asynchronously, so appending recorded
5594
+ * mutations could invert them. A `run_code` insert at the top of a file followed
5595
+ * by a model-direct edit near its end must replay in that order — reversed, the
5596
+ * rear edit's line anchors describe text the front insert already shifted, and
5597
+ * BOTH undo and redo fail on a file that was perfectly reviewable.
5598
+ *
5599
+ * All inputs are immutable; the result is a fresh array only when a recorded
5600
+ * mutation matched a visible root.
5286
5601
  */
5287
5602
  function mergeRecordedTurns(turns, roots, recorded) {
5288
5603
  if (recorded.length === 0 || roots.length === 0) return turns;
5289
5604
  const rootTurns = /* @__PURE__ */ new Map();
5290
5605
  for (const root of roots) rootTurns.set(root.rootCallId, {
5291
5606
  turn: root.turn,
5292
- live: root.live
5607
+ live: root.live,
5608
+ seq: root.seq
5293
5609
  });
5294
5610
  const byRoot = /* @__PURE__ */ new Map();
5295
5611
  for (const mutation of recorded) {
@@ -5303,46 +5619,76 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5303
5619
  break;
5304
5620
  }
5305
5621
  if (!matched) return turns;
5306
- const groups = /* @__PURE__ */ new Map();
5307
- for (const turn of turns) {
5308
- const files = /* @__PURE__ */ new Map();
5309
- for (const file of turn.files) files.set(file.path, {
5310
- diffs: [...file.diffs],
5311
- ...file.deleted === true ? { deleted: true } : {}
5312
- });
5313
- groups.set(turn.turn, {
5314
- live: turn.live,
5315
- files
5316
- });
5317
- }
5622
+ const pending = /* @__PURE__ */ new Map();
5318
5623
  for (const [rootCallId, mutations] of byRoot) {
5319
5624
  const owner = rootTurns.get(rootCallId);
5320
5625
  if (owner === void 0) continue;
5321
- let group = groups.get(owner.turn);
5322
- if (group === void 0) {
5323
- group = {
5324
- live: owner.live,
5325
- files: /* @__PURE__ */ new Map()
5326
- };
5327
- groups.set(owner.turn, group);
5626
+ let paths = pending.get(owner.turn);
5627
+ if (paths === void 0) {
5628
+ paths = /* @__PURE__ */ new Map();
5629
+ pending.set(owner.turn, paths);
5328
5630
  }
5329
5631
  for (const mutation of mutations) {
5330
5632
  const diffs = diffsFromBeforeAfter(mutation.path, mutation.before, mutation.after);
5331
5633
  if (diffs.length === 0) continue;
5332
- const existing = group.files.get(mutation.path);
5333
- if (existing === void 0) group.files.set(mutation.path, { diffs: [...diffs] });
5334
- else existing.diffs.push(...diffs);
5634
+ const list = paths.get(mutation.path);
5635
+ if (list === void 0) paths.set(mutation.path, [{
5636
+ seq: owner.seq,
5637
+ diffs
5638
+ }]);
5639
+ else list.push({
5640
+ seq: owner.seq,
5641
+ diffs
5642
+ });
5335
5643
  }
5336
5644
  }
5337
- return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([turn, group]) => ({
5338
- turn,
5339
- live: group.live,
5340
- files: [...group.files.entries()].map(([path, own]) => ({
5341
- path,
5342
- diffs: own.diffs,
5343
- ...own.deleted === true ? { deleted: true } : {}
5344
- }))
5345
- }));
5645
+ const merge = (existing, extra) => {
5646
+ const diffs = flattenSettlements([...settlementsOf(existing?.diffs ?? []), ...extra.map((entry) => ({
5647
+ seq: entry.seq,
5648
+ diffs: entry.diffs
5649
+ }))]);
5650
+ const lastRecordedSeq = extra.reduce((highest, entry) => entry.seq === void 0 ? highest : Math.max(highest ?? entry.seq, entry.seq), void 0);
5651
+ if (diffs.length > 0 && lastRecordedSeq !== void 0 && (existing?.deletedSeq === void 0 || lastRecordedSeq > existing.deletedSeq) || existing?.deleted !== true) return { diffs };
5652
+ return {
5653
+ diffs,
5654
+ deleted: true,
5655
+ ...existing.deletedSeq !== void 0 ? { deletedSeq: existing.deletedSeq } : {}
5656
+ };
5657
+ };
5658
+ const out = [];
5659
+ for (const turn of turns) {
5660
+ const paths = pending.get(turn.turn);
5661
+ const files = /* @__PURE__ */ new Map();
5662
+ for (const file of turn.files) files.set(file.path, {
5663
+ diffs: [...file.diffs],
5664
+ ...file.deleted === true ? { deleted: true } : {},
5665
+ ...file.deletedSeq !== void 0 ? { deletedSeq: file.deletedSeq } : {}
5666
+ });
5667
+ if (paths !== void 0) for (const [path, extra] of paths) files.set(path, merge(files.get(path), extra));
5668
+ out.push({
5669
+ turn: turn.turn,
5670
+ live: turn.live,
5671
+ files: [...files.entries()].map(([path, own]) => ({
5672
+ path,
5673
+ diffs: own.diffs,
5674
+ ...own.deleted === true ? { deleted: true } : {},
5675
+ ...own.deletedSeq !== void 0 ? { deletedSeq: own.deletedSeq } : {}
5676
+ }))
5677
+ });
5678
+ }
5679
+ for (const [turn, paths] of pending) {
5680
+ if (turns.some((entry) => entry.turn === turn)) continue;
5681
+ const owner = roots.find((root) => root.turn === turn);
5682
+ out.push({
5683
+ turn,
5684
+ live: owner?.live ?? true,
5685
+ files: [...paths.entries()].map(([path, extra]) => ({
5686
+ path,
5687
+ ...merge(void 0, extra)
5688
+ }))
5689
+ });
5690
+ }
5691
+ return out.sort((a, b) => a.turn - b.turn);
5346
5692
  }
5347
5693
  /** Count distinct changed paths across every turn (the sidebar badge count). */
5348
5694
  function countChangedFiles(turns) {
@@ -5414,12 +5760,20 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5414
5760
  function isOneSided(hunks) {
5415
5761
  return hunks.some((hunk) => hunk.lines.some((line) => line.startsWith("+"))) !== hunks.some((hunk) => hunk.lines.some((line) => line.startsWith("-")));
5416
5762
  }
5417
- /** Pair one recorded before/after snapshot into numbered lines. */
5418
- function pairLines(diff) {
5763
+ /**
5764
+ * Pair one recorded before/after snapshot into numbered lines.
5765
+ *
5766
+ * `anchor` overrides where the pairing starts. The wire hunks the conversation
5767
+ * snapshot carries are context fragments with no line numbers at all, so without
5768
+ * an anchor their numbering can only start at 1 — a per-hunk counter, not the
5769
+ * file's lines. The Host knows each mutation's real coordinates (see
5770
+ * {@link HunkAnchor}) and this is where they enter the drawing.
5771
+ */
5772
+ function pairLines(diff, anchor) {
5419
5773
  const changes = diffArrays(diff.oldText === null ? [] : diffContentLines(diff.oldText), diffContentLines(diff.newText));
5420
5774
  const lines = [];
5421
- let oldNumber = diff.oldStart ?? 1;
5422
- let newNumber = diff.newStart ?? 1;
5775
+ let oldNumber = anchor?.oldStart ?? diff.oldStart ?? 1;
5776
+ let newNumber = anchor?.newStart ?? diff.newStart ?? 1;
5423
5777
  for (const change of changes) if (change.removed) for (const text of change.value) {
5424
5778
  lines.push({
5425
5779
  kind: "del",
@@ -5539,14 +5893,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5539
5893
  return fallback;
5540
5894
  }
5541
5895
  /** Convert one paired comparison into the hunks dsh's FileDiff renders. */
5542
- function comparisonToHunks(diff, contextLines) {
5543
- const lines = pairLines(diff);
5896
+ function comparisonToHunks(diff, contextLines, anchor) {
5897
+ const lines = pairLines(diff, anchor);
5544
5898
  return contextRanges(lines, contextLines).map((range) => {
5545
5899
  const kept = lines.slice(range.start, range.end);
5546
5900
  return {
5547
- oldStart: startOf(lines, range, "oldNumber", diff.oldStart ?? 1),
5901
+ oldStart: startOf(lines, range, "oldNumber", anchor?.oldStart ?? diff.oldStart ?? 1),
5548
5902
  oldLines: kept.filter((line) => line.oldNumber !== null).length,
5549
- newStart: startOf(lines, range, "newNumber", diff.newStart ?? 1),
5903
+ newStart: startOf(lines, range, "newNumber", anchor?.newStart ?? diff.newStart ?? 1),
5550
5904
  newLines: kept.filter((line) => line.newNumber !== null).length,
5551
5905
  lines: kept.map((line) => {
5552
5906
  return `${line.kind === "del" ? "-" : line.kind === "add" ? "+" : " "}${line.text}`;
@@ -5555,17 +5909,215 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5555
5909
  });
5556
5910
  }
5557
5911
  /**
5912
+ * Pair every hunk with the coordinates recorded for its call.
5913
+ *
5914
+ * A call's fragments are consecutive in `diffs` and were produced by the same
5915
+ * patch the anchors come from, so they map positionally. That mapping is only
5916
+ * trustworthy when the two counts agree: a mismatch means the anchor list
5917
+ * describes a different patch, and using it anyway would shift every number in
5918
+ * the file instead of merely leaving them hunk-local. Such a call is refused
5919
+ * outright rather than partially applied.
5920
+ * @param diffs - the file's hunks, in settlement order.
5921
+ * @param lookup - recorded coordinates by call id, or undefined when none loaded.
5922
+ * @returns one optional anchor per hunk, aligned with `diffs`.
5923
+ */
5924
+ function anchorPlan(diffs, lookup) {
5925
+ if (lookup === void 0 || lookup.size === 0) return diffs.map(() => void 0);
5926
+ const totals = /* @__PURE__ */ new Map();
5927
+ for (const diff of diffs) {
5928
+ if (diff.callId === void 0) continue;
5929
+ totals.set(diff.callId, (totals.get(diff.callId) ?? 0) + 1);
5930
+ }
5931
+ const seen = /* @__PURE__ */ new Map();
5932
+ return diffs.map((diff) => {
5933
+ const callId = diff.callId;
5934
+ if (callId === void 0) return void 0;
5935
+ const list = lookup.get(callId);
5936
+ if (list === void 0 || list.length !== totals.get(callId)) return void 0;
5937
+ const at = seen.get(callId) ?? 0;
5938
+ seen.set(callId, at + 1);
5939
+ return list[at];
5940
+ });
5941
+ }
5942
+ /**
5558
5943
  * Convert recorded comparisons into dsh's served hunk shape.
5559
5944
  * @param diffs - the recorded before/after snapshots for one file.
5560
5945
  * @param contextLines - unchanged lines kept on each side of a change.
5946
+ * @param anchors - recorded absolute coordinates by call id, when known.
5561
5947
  * @returns the hunks to render, in order.
5562
5948
  */
5563
- function toNativeHunks(diffs, contextLines = 3) {
5564
- return diffs.flatMap((diff) => comparisonToHunks(diff, contextLines));
5949
+ function toNativeHunks(diffs, contextLines = 3, anchors) {
5950
+ const plan = anchorPlan(diffs, anchors);
5951
+ return diffs.flatMap((diff, at) => comparisonToHunks(diff, contextLines, plan[at]));
5952
+ }
5953
+ //#endregion
5954
+ //#region src/client/hunk-anchors.ts
5955
+ /**
5956
+ * Client cache and hook for the Host's per-mutation hunk coordinates.
5957
+ *
5958
+ * The comparison surfaces read the conversation snapshot, and its hunks are the
5959
+ * engine's context fragments — text only, no line numbers. Numbering those from
5960
+ * 1 puts a change at the end of a long file on "line 1". The Host recorded each
5961
+ * mutation's real coordinates at settlement (see the node half's hunk-anchors
5962
+ * module); this module fetches them once per session and hands them to the
5963
+ * renderer.
5964
+ *
5965
+ * Deliberately a cache rather than view state: a call's coordinates never change
5966
+ * once recorded, so the sidebar tab, a chat hover preview and every remount reuse
5967
+ * the same answer. Only the FIRST lookup of a call id costs a round trip, and a
5968
+ * call the recorder never saw stays marked as asked — a session whose mutations
5969
+ * happened outside the tool pipeline must not turn every render into a request.
5970
+ */
5971
+ /** Immutable per-session lookup: a new map identity whenever it gains entries. */
5972
+ const anchorsBySession = /* @__PURE__ */ new Map();
5973
+ /** Call ids already asked about, including the ones the Host had nothing for. */
5974
+ const askedBySession = /* @__PURE__ */ new Map();
5975
+ const EMPTY = /* @__PURE__ */ new Map();
5976
+ /**
5977
+ * Group one file's hunks into the calls that produced them.
5978
+ *
5979
+ * Fragments of a call are consecutive and keep the engine's hunk order, so this
5980
+ * both names the calls to ask about and supplies the text the Host needs to place
5981
+ * a hunk whose coordinates were never recorded. Hunks without a call id (the
5982
+ * recorded Code Mode path, which already carries coordinates) are skipped.
5983
+ * @param diffs - the file's hunks, in settlement order.
5984
+ * @returns one entry per call, in first-seen order.
5985
+ */
5986
+ function anchorCalls(diffs) {
5987
+ const byCall = /* @__PURE__ */ new Map();
5988
+ for (const diff of diffs) {
5989
+ if (diff.callId === void 0) continue;
5990
+ let call = byCall.get(diff.callId);
5991
+ if (call === void 0) {
5992
+ call = {
5993
+ path: diff.path,
5994
+ hunks: []
5995
+ };
5996
+ byCall.set(diff.callId, call);
5997
+ }
5998
+ call.hunks.push({
5999
+ oldText: diff.oldText,
6000
+ newText: diff.newText
6001
+ });
6002
+ }
6003
+ return [...byCall.entries()].map(([callId, call]) => ({
6004
+ callId,
6005
+ path: call.path,
6006
+ hunks: call.hunks
6007
+ }));
6008
+ }
6009
+ /**
6010
+ * Coordinates remembered for one session, as the lookup the renderer takes.
6011
+ * @param sessionId - the session whose anchors are wanted.
6012
+ * @returns the cached map (empty before any lookup completes).
6013
+ */
6014
+ function cachedHunkAnchors(sessionId) {
6015
+ return anchorsBySession.get(sessionId) ?? EMPTY;
6016
+ }
6017
+ /** Merge a Host answer into the cache and return the new lookup. */
6018
+ function rememberHunkAnchors(sessionId, entries) {
6019
+ const next = new Map(anchorsBySession.get(sessionId) ?? []);
6020
+ for (const entry of entries) next.set(entry.callId, entry.anchors);
6021
+ anchorsBySession.set(sessionId, next);
6022
+ return next;
6023
+ }
6024
+ /**
6025
+ * Claim the ids that still need a lookup, marking them as asked.
6026
+ *
6027
+ * Claiming before the request is what stops two surfaces painting the same hunk
6028
+ * in one commit from fetching it twice. An id marked this way is never asked
6029
+ * again unless {@link releaseCallIds} returns it: a call the recorder never saw
6030
+ * answers successfully with no coordinates, and that must not become a request
6031
+ * per render.
6032
+ * @param sessionId - session key for the shared cache.
6033
+ * @param callIds - the calls the painted hunks came from.
6034
+ * @returns the ids to ask about now; empty when nothing new is wanted.
6035
+ */
6036
+ function claimCallIds(sessionId, callIds) {
6037
+ const asked = askedFor(sessionId);
6038
+ const wanted = [];
6039
+ for (const id of callIds) {
6040
+ if (asked.has(id) || wanted.includes(id)) continue;
6041
+ asked.add(id);
6042
+ wanted.push(id);
6043
+ }
6044
+ return wanted;
6045
+ }
6046
+ /**
6047
+ * Un-claim ids whose lookup failed.
6048
+ *
6049
+ * A thrown lookup is NOT the Host saying "this call has no coordinates" — it is
6050
+ * the Host not answering (an unmounted Remote, a transport error). Releasing the
6051
+ * ids is what lets a later attempt (new hunks, a now-visible tab, a remount) ask
6052
+ * again instead of leaving those hunks permanently unanchored.
6053
+ * @param sessionId - session key for the shared cache.
6054
+ * @param callIds - the ids whose request failed.
6055
+ */
6056
+ function releaseCallIds(sessionId, callIds) {
6057
+ const asked = askedFor(sessionId);
6058
+ for (const id of callIds) asked.delete(id);
6059
+ }
6060
+ /** The ids of one session already looked up (recorded or not). */
6061
+ function askedFor(sessionId) {
6062
+ const existing = askedBySession.get(sessionId);
6063
+ if (existing !== void 0) return existing;
6064
+ const created = /* @__PURE__ */ new Set();
6065
+ askedBySession.set(sessionId, created);
6066
+ return created;
6067
+ }
6068
+ /**
6069
+ * Coordinates for the calls a set of painted hunks came from, fetched on demand.
6070
+ *
6071
+ * Call it unconditionally from the component that draws the hunks; the request
6072
+ * lives in an effect, so a surface that never paints a diff never asks the Host.
6073
+ * @param sessionId - session key for the shared cache.
6074
+ * @param callIds - the calls the painted hunks came from, in any order.
6075
+ * @param load - Host lookup; undefined while the Remote is unavailable.
6076
+ * @param enabled - false pauses the lookup (a hidden tab, a closed preview).
6077
+ * @returns the lookup `toNativeHunks` takes.
6078
+ */
6079
+ function useHunkAnchors(sessionId, callIds, load, enabled = true) {
6080
+ const key = (0, react.useMemo)(() => [...new Set(callIds)].sort().join("\0"), [callIds]);
6081
+ const [lookup, setLookup] = (0, react.useState)(() => cachedHunkAnchors(sessionId));
6082
+ (0, react.useEffect)(() => {
6083
+ setLookup(cachedHunkAnchors(sessionId));
6084
+ }, [sessionId]);
6085
+ (0, react.useEffect)(() => {
6086
+ if (!enabled || load === void 0) return;
6087
+ const wanted = claimCallIds(sessionId, key === "" ? [] : key.split("\0"));
6088
+ if (wanted.length === 0) return;
6089
+ let active = true;
6090
+ load(wanted).then((entries) => {
6091
+ const next = rememberHunkAnchors(sessionId, entries);
6092
+ if (active) setLookup(next);
6093
+ }).catch(() => {
6094
+ releaseCallIds(sessionId, wanted);
6095
+ });
6096
+ return () => {
6097
+ active = false;
6098
+ };
6099
+ }, [
6100
+ sessionId,
6101
+ key,
6102
+ enabled,
6103
+ load
6104
+ ]);
6105
+ return lookup;
6106
+ }
6107
+ /**
6108
+ * Delay before the next `recorded` fetch.
6109
+ * @param anchor - Timestamp of the last completed fetch, or of the moment the
6110
+ * fetch was first armed when none has completed yet. Must never be a value that
6111
+ * an incoming update can reset, or the fetch starves.
6112
+ * @param now - Current timestamp.
6113
+ * @returns Milliseconds to wait; 0 once the interval has already elapsed.
6114
+ */
6115
+ function recordedFetchDelay(anchor, now) {
6116
+ return Math.max(0, 200 - (now - anchor));
5565
6117
  }
5566
6118
  //#endregion
5567
6119
  //#region \0@whybebabo/dsh-file-review-tab-css:C:\Users\wuzhiwei\Documents\dsh_file_review_tab\dsh-file-review-tab\src\client\NativeDiff.module.css.mjs
5568
- const css$3 = "._3_Jlsa_body{--diff-empty-fill:color-mix(in srgb, var(--dsw-alias-interactive-bg-hover) 50%, transparent);min-height:0;font:var(--dsw-font-markdown-code-block);flex-direction:column;flex:auto;padding:8px 0 16px;display:flex;overflow:auto}._3_Jlsa_status{color:var(--dsw-alias-label-secondary);align-items:center;gap:12px;margin:0;padding:16px;font-size:13px;display:flex}._3_Jlsa_columns{flex:auto;grid-template-columns:minmax(0,1fr) minmax(0,1fr);min-height:0;display:grid}._3_Jlsa_column,._3_Jlsa_body[data-review-view=unified]:not([data-review-wrap]){grid-template-columns:minmax(max-content,100%);align-content:start;display:grid}._3_Jlsa_column{overscroll-behavior:none;min-width:0;overflow-x:scroll}._3_Jlsa_column+._3_Jlsa_column{border-left:.5px solid var(--dsw-alias-border-l3)}._3_Jlsa_sideLine{box-sizing:border-box;white-space:pre;grid-template-columns:3.5em max-content;width:max-content;min-width:100%;min-height:22px;line-height:22px;display:grid}._3_Jlsa_note{color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xs-13);margin:0;padding:4px 16px 8px}._3_Jlsa_hunk{margin-bottom:8px}._3_Jlsa_hunkHeader{color:var(--dsw-alias-label-tertiary);white-space:pre;padding:4px 16px}._3_Jlsa_line{box-sizing:border-box;white-space:pre;grid-template-columns:3.5em 3.5em 1.2em minmax(0,1fr);min-height:22px;line-height:22px;display:grid}._3_Jlsa_splitLine{white-space:pre;grid-template-columns:minmax(0,1fr) minmax(0,1fr);min-height:22px;line-height:22px;display:grid}._3_Jlsa_cell{box-sizing:border-box;grid-template-columns:3.5em minmax(0,1fr);min-width:0;display:grid}._3_Jlsa_cell+._3_Jlsa_cell{border-left:.5px solid var(--dsw-alias-border-l3)}._3_Jlsa_number{color:var(--dsw-alias-label-tertiary);text-align:right;user-select:none;padding-right:8px}._3_Jlsa_sign{text-align:center;user-select:none}._3_Jlsa_text{padding-right:16px}._3_Jlsa_body[data-review-wrap] ._3_Jlsa_line,._3_Jlsa_body[data-review-wrap] ._3_Jlsa_splitLine{white-space:pre-wrap}._3_Jlsa_body[data-review-wrap] ._3_Jlsa_text{overflow-wrap:anywhere}._3_Jlsa_add{--diff-gutter-fill:var(--dsw-alias-file-diff-added-gutter);--diff-marker:var(--dsw-alias-file-diff-added-marker);background:var(--dsw-alias-file-diff-added-bg)}._3_Jlsa_del{--diff-gutter-fill:var(--dsw-alias-file-diff-deleted-gutter);--diff-marker:var(--dsw-alias-file-diff-deleted-marker);background:var(--dsw-alias-file-diff-deleted-bg)}._3_Jlsa_add ._3_Jlsa_number,._3_Jlsa_del ._3_Jlsa_number{background:var(--diff-gutter-fill);color:var(--diff-marker)}._3_Jlsa_add ._3_Jlsa_number:first-child,._3_Jlsa_del ._3_Jlsa_number:first-child{box-shadow:inset 3px 0 0 var(--diff-marker)}._3_Jlsa_add ._3_Jlsa_sign,._3_Jlsa_del ._3_Jlsa_sign{color:var(--diff-marker)}._3_Jlsa_context ._3_Jlsa_text{color:var(--dsw-alias-label-secondary)}._3_Jlsa_empty{background:var(--diff-empty-fill)}";
6120
+ const css$3 = "._3_Jlsa_body{--diff-empty-fill:color-mix(in srgb, var(--dsw-alias-interactive-bg-hover) 50%, transparent);min-height:0;font:var(--dsw-font-markdown-code-block);flex-direction:column;flex:auto;padding:8px 0 16px;display:flex;overflow:auto}._3_Jlsa_status{color:var(--dsw-alias-label-secondary);align-items:center;gap:12px;margin:0;padding:16px;font-size:13px;display:flex}._3_Jlsa_columns{flex:auto;grid-template-columns:minmax(0,1fr) minmax(0,1fr);min-height:0;display:grid}._3_Jlsa_column,._3_Jlsa_body[data-review-view=unified]:not([data-review-wrap]){grid-template-columns:minmax(max-content,100%);align-content:start;display:grid}._3_Jlsa_column{overscroll-behavior-x:none;min-width:0;overflow-x:scroll}._3_Jlsa_column+._3_Jlsa_column{border-left:.5px solid var(--dsw-alias-border-l3)}._3_Jlsa_sideLine{box-sizing:border-box;white-space:pre;grid-template-columns:3.5em max-content;width:max-content;min-width:100%;min-height:22px;line-height:22px;display:grid}._3_Jlsa_note{color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-xs-13);margin:0;padding:4px 16px 8px}._3_Jlsa_hunk{margin-bottom:8px}._3_Jlsa_hunkHeader{color:var(--dsw-alias-label-tertiary);white-space:pre;padding:4px 16px}._3_Jlsa_line{box-sizing:border-box;white-space:pre;grid-template-columns:3.5em 3.5em 1.2em minmax(0,1fr);min-height:22px;line-height:22px;display:grid}._3_Jlsa_splitLine{white-space:pre;grid-template-columns:minmax(0,1fr) minmax(0,1fr);min-height:22px;line-height:22px;display:grid}._3_Jlsa_cell{box-sizing:border-box;grid-template-columns:3.5em minmax(0,1fr);min-width:0;display:grid}._3_Jlsa_cell+._3_Jlsa_cell{border-left:.5px solid var(--dsw-alias-border-l3)}._3_Jlsa_number{color:var(--dsw-alias-label-tertiary);text-align:right;user-select:none;padding-right:8px}._3_Jlsa_sign{text-align:center;user-select:none}._3_Jlsa_text{padding-right:16px}._3_Jlsa_body[data-review-wrap] ._3_Jlsa_line,._3_Jlsa_body[data-review-wrap] ._3_Jlsa_splitLine{white-space:pre-wrap}._3_Jlsa_body[data-review-wrap] ._3_Jlsa_text{overflow-wrap:anywhere}._3_Jlsa_add{--diff-gutter-fill:var(--dsw-alias-file-diff-added-gutter);--diff-marker:var(--dsw-alias-file-diff-added-marker);background:var(--dsw-alias-file-diff-added-bg)}._3_Jlsa_del{--diff-gutter-fill:var(--dsw-alias-file-diff-deleted-gutter);--diff-marker:var(--dsw-alias-file-diff-deleted-marker);background:var(--dsw-alias-file-diff-deleted-bg)}._3_Jlsa_add ._3_Jlsa_number,._3_Jlsa_del ._3_Jlsa_number{background:var(--diff-gutter-fill);color:var(--diff-marker)}._3_Jlsa_add ._3_Jlsa_number:first-child,._3_Jlsa_del ._3_Jlsa_number:first-child{box-shadow:inset 3px 0 0 var(--diff-marker)}._3_Jlsa_add ._3_Jlsa_sign,._3_Jlsa_del ._3_Jlsa_sign{color:var(--diff-marker)}._3_Jlsa_context ._3_Jlsa_text{color:var(--dsw-alias-label-secondary)}._3_Jlsa_empty{background:var(--diff-empty-fill)}";
5569
6121
  const styleId$3 = "@whybebabo/dsh-file-review-tab/NativeDiff.module.css";
5570
6122
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(styleId$3) + "]") === null) {
5571
6123
  const style = document.createElement("style");
@@ -6093,7 +6645,98 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6093
6645
  return text;
6094
6646
  }
6095
6647
  //#endregion
6648
+ //#region src/reversible.ts
6649
+ /**
6650
+ * Whether one hunk carries both sides completely enough to replay exactly.
6651
+ * @param diff - the hunk under test.
6652
+ * @param path - the file the hunk claims to belong to.
6653
+ * @returns true when the hunk can be undone/redone by exact replacement.
6654
+ */
6655
+ function hunkReversible(diff, path) {
6656
+ if (diff.path !== path) return false;
6657
+ if (diff.oldText === null || diff.oldText === diff.newText) return false;
6658
+ if (diff.oldText === "" && diff.oldStart === void 0) return false;
6659
+ if (diff.newText === "" && diff.newStart === void 0) return false;
6660
+ return true;
6661
+ }
6662
+ /**
6663
+ * Whether a file's whole change set is reversible: non-empty and every hunk
6664
+ * passes {@link hunkReversible}.
6665
+ * @param path - the path every hunk must name.
6666
+ * @param diffs - the file's hunks, in settlement order.
6667
+ * @returns true when the Host can replay the complete change.
6668
+ */
6669
+ function changeReversible(path, diffs) {
6670
+ return diffs.length > 0 && diffs.every((diff) => hunkReversible(diff, path));
6671
+ }
6672
+ //#endregion
6096
6673
  //#region src/client/deep-link.ts
6674
+ /**
6675
+ * Chat → sidebar deep-link channel.
6676
+ *
6677
+ * The chat turn-tail row knows which paths (and which turn) the user wants to
6678
+ * inspect, but better-sidebar's native right Sidebar mints its own tab ids and
6679
+ * does not refresh an already-open tab's `meta` (dsh-better-sidebar #632 /
6680
+ * 0.19.1 adapter behaviour). Passing a `path` seed is also unsafe there: the
6681
+ * native surface routes path-bearing opens to the file editor, so the review
6682
+ * tab would never mount.
6683
+ *
6684
+ * The channel therefore carries the seed inside this plugin: the chat row
6685
+ * publishes it and then opens the tab by type; the tab body subscribes and
6686
+ * replays whatever arrived, whether it mounted just now or was already open.
6687
+ * Sessions are keyed separately, and each publish gets a monotonic nonce so a
6688
+ * replay can never be mistaken for a fresh link.
6689
+ */
6690
+ /** State-map key for one (turn, file) change group. */
6691
+ function rowKey(turn, path) {
6692
+ return `${turn}|${path}`;
6693
+ }
6694
+ /**
6695
+ * Resolve a deep link against EVERY change the tab can render, including turns
6696
+ * still hidden behind a closed archive section.
6697
+ *
6698
+ * The target is deliberately resolved against the full change set rather than
6699
+ * the currently mounted rows. A link into an archived turn is replayed in the
6700
+ * same commit that opens the archive, so at that moment its rows are not
6701
+ * mounted yet; resolving against the mounted set made the match fail, the
6702
+ * pending scroll get cleared, and the link land nowhere with no retry.
6703
+ *
6704
+ * @param turns - Every turn, ascending (the source of truth for all rows).
6705
+ * @param archivedTurns - The auto-archived subset, newest first.
6706
+ * @param paths - Paths the link targets.
6707
+ * @param targetTurn - Turn anchor, or undefined for a path-only (legacy) link.
6708
+ * @returns The expand set, the scroll target, and the archive reveal to apply.
6709
+ */
6710
+ function planDeepLink(turns, archivedTurns, paths, targetTurn) {
6711
+ const expanded = [];
6712
+ let first = null;
6713
+ for (let index = turns.length - 1; index >= 0; index -= 1) {
6714
+ const turn = turns[index];
6715
+ if (turn === void 0) continue;
6716
+ for (const file of turn.files) {
6717
+ if (!paths.includes(file.path)) continue;
6718
+ if (targetTurn !== void 0 && turn.turn !== targetTurn) continue;
6719
+ expanded.push(rowKey(turn.turn, file.path));
6720
+ first ??= {
6721
+ turn: turn.turn,
6722
+ path: file.path
6723
+ };
6724
+ }
6725
+ }
6726
+ let archive = null;
6727
+ if (first !== null) {
6728
+ const owner = turns.find((turn) => turn.turn === first.turn);
6729
+ if (owner !== void 0 && owner.live !== true) {
6730
+ const archivedIndex = archivedTurns.findIndex((turn) => turn.turn === first.turn);
6731
+ if (archivedIndex !== -1) archive = { pages: Math.ceil((archivedIndex + 1) / 10) };
6732
+ }
6733
+ }
6734
+ return {
6735
+ expanded,
6736
+ first,
6737
+ archive
6738
+ };
6739
+ }
6097
6740
  const latest = /* @__PURE__ */ new Map();
6098
6741
  const listeners = /* @__PURE__ */ new Set();
6099
6742
  const invalidationListeners = /* @__PURE__ */ new Set();
@@ -6134,7 +6777,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6134
6777
  }
6135
6778
  //#endregion
6136
6779
  //#region \0@whybebabo/dsh-file-review-tab-css:C:\Users\wuzhiwei\Documents\dsh_file_review_tab\dsh-file-review-tab\src\client\FileReviewTab.module.css.mjs
6137
- const css$2 = ".r1eXuW_root{height:100%;min-height:0;color:var(--dsw-alias-label-primary);flex-direction:column;display:flex;container-type:inline-size}.r1eXuW_header{box-sizing:border-box;border-bottom:.5px solid var(--dsw-alias-border-l3);flex:none;align-items:center;gap:6px;height:38px;padding:0 6px 0 8px;display:flex}.r1eXuW_selectorLabel{text-overflow:ellipsis;white-space:nowrap;flex:auto;min-width:0;font-size:12px;overflow:hidden}.r1eXuW_selector{flex:0 auto;min-width:0}.r1eXuW_selectorButton{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;height:28px;color:var(--dsw-alias-label-primary);cursor:pointer;font:inherit;background:0 0;border:0;align-items:center;gap:4px;padding:0 6px 0 8px;font-size:12px;line-height:20px;display:inline-flex}.r1eXuW_selectorButton:hover,.r1eXuW_selectorButton[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover)}.r1eXuW_selectorButton svg{flex:none;display:block}.r1eXuW_item{justify-content:space-between;align-items:center;gap:12px;min-width:0;display:flex}.r1eXuW_itemPath{text-overflow:ellipsis;white-space:nowrap;min-width:0;line-height:20px;overflow:hidden}.r1eXuW_itemCounts{color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code);flex:none;align-items:center;gap:6px;font-size:12px;line-height:20px;display:inline-flex}.r1eXuW_counts{min-width:0;color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code);align-items:center;gap:6px;margin-right:auto;font-size:12px;line-height:20px;display:inline-flex}.r1eXuW_added{color:var(--dsw-alias-state-success-primary)}.r1eXuW_deleted{color:var(--dsw-alias-state-error-primary)}.r1eXuW_label{color:var(--dsw-alias-label-tertiary)}.r1eXuW_tools{flex:none;align-items:center;gap:2px;margin-left:auto;display:inline-flex}.r1eXuW_tool{border-radius:var(--dsw-radius-sm);width:28px;height:28px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:0;flex:none;justify-content:center;align-items:center;padding:6px;display:inline-flex}.r1eXuW_tool svg{width:15px;height:15px}.r1eXuW_tool:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.r1eXuW_tool[aria-pressed=true] .r1eXuW_compareIcon{transform:rotate(90deg)}.r1eXuW_tool:disabled{cursor:progress}.r1eXuW_tool[data-pending] svg{animation:.9s linear infinite r1eXuW_reviewToolSpin}@keyframes r1eXuW_reviewToolSpin{to{transform:rotate(360deg)}}@media (prefers-reduced-motion:reduce){.r1eXuW_tool[data-pending] svg{animation:none}}.r1eXuW_tool[data-error]{color:var(--dsw-alias-state-error-primary)}.r1eXuW_notice{border-radius:var(--dsw-radius-sm);flex:none;margin:8px 10px 0;padding:6px 10px;font-size:12px}.r1eXuW_noticeSuccess{color:var(--dsw-alias-state-success-primary);background:var(--dsw-alias-bg-layer-1);border:.5px solid var(--dsw-alias-border-l2)}.r1eXuW_noticeError{color:var(--dsw-alias-state-error-primary);background:var(--dsw-alias-bg-layer-1);border:.5px solid var(--dsw-alias-border-l2)}.r1eXuW_body{flex:1;min-height:0;padding:8px 0 16px;overflow-y:auto}.r1eXuW_empty{color:var(--dsw-alias-label-tertiary);text-align:center;padding:24px 12px}.r1eXuW_turnGroup{--changes-fill:var(--dsw-static-neutral-50);border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-1);margin:0 8px 8px;overflow:hidden}body[data-ds-dark-theme] .r1eXuW_turnGroup{--changes-fill:var(--dsw-static-neutral-850)}.r1eXuW_turnHeader{background:var(--changes-fill);flex-wrap:wrap;align-items:center;gap:4px 8px;min-height:34px;padding:0 8px 0 10px;display:flex}.r1eXuW_turnTitle{white-space:nowrap;font-weight:500}.r1eXuW_liveBadge{color:var(--dsw-alias-state-warning-primary,#d9a13b);white-space:nowrap;border-radius:999px;padding:0 6px;font-size:11px;line-height:18px}.r1eXuW_turnCount{color:var(--dsw-alias-label-tertiary);white-space:nowrap}.r1eXuW_stats{font-family:var(--ds-font-family-code);gap:6px;font-size:12px;display:inline-flex}.r1eXuW_removed{color:var(--dsw-alias-state-error-primary)}.r1eXuW_actionButton{border-radius:var(--dsw-radius-sm);height:24px;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;white-space:nowrap;background:0 0;border:0;flex:none;align-items:center;gap:4px;padding:0 8px;font-size:12px;display:inline-flex}.r1eXuW_actionButton:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.r1eXuW_actionButton:disabled{cursor:progress;opacity:.55}.r1eXuW_buttonIcon{fill:none;stroke:currentColor;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round;width:14px;height:14px}.r1eXuW_fileList{border-top:.5px solid var(--dsw-alias-border-l2);margin:0;padding:0;list-style:none}.r1eXuW_fileItem{border-top:.5px solid var(--dsw-alias-border-l1)}.r1eXuW_fileItem:first-child{border-top:0}.r1eXuW_fileRow{cursor:pointer;align-items:center;gap:8px;min-height:30px;padding:0 8px 0 10px;display:flex}.r1eXuW_fileRow:hover{background:var(--dsw-alias-interactive-bg-hover)}.r1eXuW_fileRow:focus-visible{box-shadow:inset 0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline:none}.r1eXuW_chevron{fill:none;width:12px;height:12px;stroke:var(--dsw-alias-label-tertiary);stroke-width:2px;stroke-linecap:round;stroke-linejoin:round;flex:none;transition:transform .12s}.r1eXuW_chevronOpen{transform:rotate(90deg)}.r1eXuW_fileName{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}.r1eXuW_stateBadge{white-space:nowrap;border-radius:999px;flex:none;padding:0 6px;font-size:11px;line-height:18px}.r1eXuW_badgeUndone,.r1eXuW_badgeMuted{color:var(--dsw-alias-label-tertiary)}.r1eXuW_badgeError{color:var(--dsw-alias-state-error-primary)}.r1eXuW_deletedBadge{color:var(--dsw-alias-state-error-primary);white-space:nowrap;border-radius:999px;flex:none;padding:0 6px;font-size:11px;line-height:18px}.r1eXuW_smallButton{border-radius:var(--dsw-radius-sm);height:24px;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;white-space:nowrap;background:0 0;border:0;flex:none;padding:0 8px;font-size:12px}.r1eXuW_smallButton:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.r1eXuW_smallButton:disabled{cursor:progress;opacity:.55}.r1eXuW_editorButton{margin-left:auto}.r1eXuW_diffWrap{border-top:.5px solid var(--dsw-alias-border-l1);overflow:hidden}.r1eXuW_reviewDiff{padding-bottom:8px}.r1eXuW_diffUnavailable{color:var(--dsw-alias-label-tertiary);margin:0;padding:10px 12px;font-size:12px}.r1eXuW_archiveSection{margin:0 8px 10px}.r1eXuW_archiveHeader{width:100%;color:var(--dsw-alias-label-tertiary);cursor:pointer;font:inherit;text-align:left;background:0 0;border:0;align-items:center;gap:4px;padding:8px 2px;font-size:12px;display:inline-flex}.r1eXuW_archiveHeader:hover{color:var(--dsw-alias-label-primary)}.r1eXuW_archiveTitle{min-width:0}.r1eXuW_archiveLoadMore{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);width:100%;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;background:0 0;margin-top:6px;padding:6px;font-size:12px;display:block}.r1eXuW_archiveLoadMore:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}@container (width<=260px){.r1eXuW_counts{display:none}}";
6780
+ const css$2 = ".r1eXuW_root{height:100%;min-height:0;color:var(--dsw-alias-label-primary);flex-direction:column;display:flex;container-type:inline-size}.r1eXuW_header{box-sizing:border-box;border-bottom:.5px solid var(--dsw-alias-border-l3);flex:none;align-items:center;gap:6px;height:38px;padding:0 6px 0 8px;display:flex}.r1eXuW_selectorLabel{text-overflow:ellipsis;white-space:nowrap;flex:auto;min-width:0;font-size:12px;overflow:hidden}.r1eXuW_selector{flex:0 auto;min-width:0}.r1eXuW_selectorButton{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;height:28px;color:var(--dsw-alias-label-primary);cursor:pointer;font:inherit;background:0 0;border:0;align-items:center;gap:4px;padding:0 6px 0 8px;font-size:12px;line-height:20px;display:inline-flex}.r1eXuW_selectorButton:hover,.r1eXuW_selectorButton[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover)}.r1eXuW_selectorButton svg{flex:none;display:block}.r1eXuW_item{justify-content:space-between;align-items:center;gap:12px;min-width:0;display:flex}.r1eXuW_itemPath{text-overflow:ellipsis;white-space:nowrap;min-width:0;line-height:20px;overflow:hidden}.r1eXuW_itemCounts{color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code);flex:none;align-items:center;gap:6px;font-size:12px;line-height:20px;display:inline-flex}.r1eXuW_counts{min-width:0;color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code);align-items:center;gap:6px;margin-right:auto;font-size:12px;line-height:20px;display:inline-flex}.r1eXuW_added{color:var(--dsw-alias-state-success-primary)}.r1eXuW_deleted{color:var(--dsw-alias-state-error-primary)}.r1eXuW_label{color:var(--dsw-alias-label-tertiary)}.r1eXuW_tools{flex:none;align-items:center;gap:2px;margin-left:auto;display:inline-flex}.r1eXuW_tool{border-radius:var(--dsw-radius-sm);width:28px;height:28px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:0;flex:none;justify-content:center;align-items:center;padding:6px;display:inline-flex}.r1eXuW_tool svg{width:15px;height:15px}.r1eXuW_tool:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.r1eXuW_tool[aria-pressed=true] .r1eXuW_compareIcon{transform:rotate(90deg)}.r1eXuW_tool:disabled{cursor:progress}.r1eXuW_tool[data-pending] svg{animation:.9s linear infinite r1eXuW_reviewToolSpin}@keyframes r1eXuW_reviewToolSpin{to{transform:rotate(360deg)}}@media (prefers-reduced-motion:reduce){.r1eXuW_tool[data-pending] svg{animation:none}}.r1eXuW_tool[data-error]{color:var(--dsw-alias-state-error-primary)}.r1eXuW_notice{border-radius:var(--dsw-radius-sm);flex:none;margin:8px 10px 0;padding:6px 10px;font-size:12px}.r1eXuW_noticeSuccess{color:var(--dsw-alias-state-success-primary);background:var(--dsw-alias-bg-layer-1);border:.5px solid var(--dsw-alias-border-l2)}.r1eXuW_noticeError{color:var(--dsw-alias-state-error-primary);background:var(--dsw-alias-bg-layer-1);border:.5px solid var(--dsw-alias-border-l2)}.r1eXuW_body{flex:1;min-height:0;padding:8px 0 16px;overflow-y:auto}.r1eXuW_empty{color:var(--dsw-alias-label-tertiary);text-align:center;padding:24px 12px}.r1eXuW_turnGroup{--changes-fill:var(--dsw-static-neutral-50);border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-1);margin:0 8px 8px;overflow:hidden}body[data-ds-dark-theme] .r1eXuW_turnGroup{--changes-fill:var(--dsw-static-neutral-850)}.r1eXuW_turnHeader{background:var(--changes-fill);flex-wrap:wrap;align-items:center;gap:4px 8px;min-height:34px;padding:0 8px 0 10px;display:flex}.r1eXuW_turnTitle{white-space:nowrap;font-weight:500}.r1eXuW_liveBadge{color:var(--dsw-alias-state-warning-primary,#d9a13b);white-space:nowrap;border-radius:999px;padding:0 6px;font-size:11px;line-height:18px}.r1eXuW_turnCount{color:var(--dsw-alias-label-tertiary);white-space:nowrap}.r1eXuW_stats{font-family:var(--ds-font-family-code);gap:6px;font-size:12px;display:inline-flex}.r1eXuW_removed{color:var(--dsw-alias-state-error-primary)}.r1eXuW_actionButton{border-radius:var(--dsw-radius-sm);height:24px;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;white-space:nowrap;background:0 0;border:0;flex:none;align-items:center;gap:4px;padding:0 8px;font-size:12px;display:inline-flex}.r1eXuW_actionButton:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.r1eXuW_actionButton:disabled{cursor:progress;opacity:.55}.r1eXuW_buttonIcon{fill:none;stroke:currentColor;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round;width:14px;height:14px}.r1eXuW_fileList{border-top:.5px solid var(--dsw-alias-border-l2);margin:0;padding:0;list-style:none}.r1eXuW_fileItem{border-top:.5px solid var(--dsw-alias-border-l1)}.r1eXuW_fileItem:first-child{border-top:0}.r1eXuW_fileRow{align-items:center;gap:8px;min-height:30px;padding:0 8px 0 0;display:flex}.r1eXuW_fileRow:hover{background:var(--dsw-alias-interactive-bg-hover)}.r1eXuW_rowToggle{min-width:0;min-height:30px;color:inherit;cursor:pointer;font:inherit;text-align:left;background:0 0;border:0;flex:auto;align-items:center;gap:8px;padding:0 0 0 10px;display:flex}.r1eXuW_rowToggle:focus-visible{box-shadow:inset 0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline:none}.r1eXuW_chevron{fill:none;width:12px;height:12px;stroke:var(--dsw-alias-label-tertiary);stroke-width:2px;stroke-linecap:round;stroke-linejoin:round;flex:none;transition:transform .12s}.r1eXuW_chevronOpen{transform:rotate(90deg)}.r1eXuW_fileName{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}.r1eXuW_stateBadge{white-space:nowrap;border-radius:999px;flex:none;padding:0 6px;font-size:11px;line-height:18px}.r1eXuW_badgeUndone,.r1eXuW_badgeMuted{color:var(--dsw-alias-label-tertiary)}.r1eXuW_badgeError{color:var(--dsw-alias-state-error-primary)}.r1eXuW_deletedBadge{color:var(--dsw-alias-state-error-primary);white-space:nowrap;border-radius:999px;flex:none;padding:0 6px;font-size:11px;line-height:18px}.r1eXuW_smallButton{border-radius:var(--dsw-radius-sm);height:24px;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;white-space:nowrap;background:0 0;border:0;flex:none;padding:0 8px;font-size:12px}.r1eXuW_smallButton:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.r1eXuW_smallButton:disabled{cursor:progress;opacity:.55}.r1eXuW_editorButton{margin-left:auto}.r1eXuW_diffWrap{border-top:.5px solid var(--dsw-alias-border-l1);overflow:hidden}.r1eXuW_reviewDiff{padding-bottom:8px}.r1eXuW_diffUnavailable{color:var(--dsw-alias-label-tertiary);margin:0;padding:10px 12px;font-size:12px}.r1eXuW_archiveSection{margin:0 8px 10px}.r1eXuW_archiveHeader{width:100%;color:var(--dsw-alias-label-tertiary);cursor:pointer;font:inherit;text-align:left;background:0 0;border:0;align-items:center;gap:4px;padding:8px 2px;font-size:12px;display:inline-flex}.r1eXuW_archiveHeader:hover{color:var(--dsw-alias-label-primary)}.r1eXuW_archiveTitle{min-width:0}.r1eXuW_archiveLoadMore{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);width:100%;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;background:0 0;margin-top:6px;padding:6px;font-size:12px;display:block}.r1eXuW_archiveLoadMore:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}@container (width<=260px){.r1eXuW_counts{display:none}}";
6138
6781
  const styleId$2 = "@whybebabo/dsh-file-review-tab/FileReviewTab.module.css";
6139
6782
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(styleId$2) + "]") === null) {
6140
6783
  const style = document.createElement("style");
@@ -6182,6 +6825,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6182
6825
  "reviewDiff": "r1eXuW_reviewDiff",
6183
6826
  "reviewToolSpin": "r1eXuW_reviewToolSpin",
6184
6827
  "root": "r1eXuW_root",
6828
+ "rowToggle": "r1eXuW_rowToggle",
6185
6829
  "selector": "r1eXuW_selector",
6186
6830
  "selectorButton": "r1eXuW_selectorButton",
6187
6831
  "selectorLabel": "r1eXuW_selectorLabel",
@@ -6205,9 +6849,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6205
6849
  function stateKey(turn, path) {
6206
6850
  return `${turn}|${path}`;
6207
6851
  }
6208
- /** A change group is reversible only with complete contextual hunks. */
6852
+ /**
6853
+ * A change group is reversible only with complete contextual hunks — the same
6854
+ * rule the Host applies before touching disk (see `src/reversible.ts`), so the
6855
+ * rows and turn batches this tab offers are exactly the ones it will accept.
6856
+ */
6209
6857
  function isReversible(file) {
6210
- return file.diffs.length > 0 && file.diffs.every((diff) => diff.path === file.path && diff.oldText !== null && diff.oldText !== diff.newText && (diff.oldText !== "" || diff.oldStart !== void 0) && (diff.newText !== "" || diff.newStart !== void 0));
6858
+ return changeReversible(file.path, file.diffs);
6211
6859
  }
6212
6860
  function addStats$1(left, right) {
6213
6861
  return {
@@ -6341,9 +6989,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6341
6989
  const subscribe = (0, react.useCallback)((listener) => conversationSource?.subscribe(listener) ?? (() => {}), [conversationSource]);
6342
6990
  const snapshot = (0, react.useSyncExternalStore)(subscribe, () => conversationSource?.getSnapshot() ?? null);
6343
6991
  const roots = (0, react.useMemo)(() => snapshot === null ? [] : deriveSessionRoots(snapshot), [snapshot]);
6344
- const rootsKey = (0, react.useMemo)(() => roots.map((root) => root.rootCallId).join("|"), [roots]);
6992
+ const rootsKey = (0, react.useMemo)(() => roots.map((root) => `${root.rootCallId}:${root.progress}`).join("|"), [roots]);
6345
6993
  const [recorded, setRecorded] = (0, react.useState)(() => []);
6346
6994
  const [recordedPending, setRecordedPending] = (0, react.useState)(false);
6995
+ const recordedFetchAnchorRef = (0, react.useRef)(null);
6347
6996
  (0, react.useEffect)(() => {
6348
6997
  if (!visible || roots.length === 0) {
6349
6998
  setRecordedPending(false);
@@ -6351,6 +7000,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6351
7000
  }
6352
7001
  let active = true;
6353
7002
  setRecordedPending(true);
7003
+ const now = Date.now();
7004
+ if (recordedFetchAnchorRef.current === null) recordedFetchAnchorRef.current = now;
6354
7005
  const timer = window.setTimeout(() => {
6355
7006
  const scope = sessions.scope(sessionId);
6356
7007
  const remote = scope?.get("remote.fileReview");
@@ -6363,9 +7014,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6363
7014
  if (!result.ok || !active) return;
6364
7015
  setRecorded(result.value.mutations);
6365
7016
  }).catch(() => {}).finally(() => {
7017
+ recordedFetchAnchorRef.current = Date.now();
6366
7018
  if (active) setRecordedPending(false);
6367
7019
  });
6368
- }, 200);
7020
+ }, recordedFetchDelay(recordedFetchAnchorRef.current, now));
6369
7021
  return () => {
6370
7022
  active = false;
6371
7023
  window.clearTimeout(timer);
@@ -6382,6 +7034,25 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6382
7034
  roots,
6383
7035
  recorded
6384
7036
  ]);
7037
+ const anchorCallIds = (0, react.useMemo)(() => turns.flatMap((turn) => turn.files.flatMap((file) => file.diffs.flatMap((diff) => diff.callId === void 0 ? [] : [diff.callId]))), [turns]);
7038
+ const anchorCalls$1 = (0, react.useMemo)(() => new Map(turns.flatMap((turn) => turn.files.flatMap((file) => anchorCalls(file.diffs).map((call) => [call.callId, call])))), [turns]);
7039
+ const anchors = useHunkAnchors(sessionId, anchorCallIds, (0, react.useCallback)(async (callIds) => {
7040
+ const scope = sessions.scope(sessionId);
7041
+ const remote = scope?.get("remote.fileReview");
7042
+ if (scope === void 0 || remote === void 0) throw new Error("File review Remote is unavailable");
7043
+ const calls = callIds.flatMap((id) => {
7044
+ const call = anchorCalls$1.get(id);
7045
+ return call === void 0 ? [] : [call];
7046
+ });
7047
+ if (calls.length === 0) return [];
7048
+ const result = await remote.anchors({ calls });
7049
+ if (!result.ok) throw new Error(result.error.message);
7050
+ return result.value.anchors;
7051
+ }, [
7052
+ sessions,
7053
+ sessionId,
7054
+ anchorCalls$1
7055
+ ]), visible);
6385
7056
  const { main: mainTurns, archived: archivedTurns } = (0, react.useMemo)(() => splitArchivedTurns(turns), [turns]);
6386
7057
  const [archiveOpen, setArchiveOpen] = (0, react.useState)(false);
6387
7058
  const [archivePages, setArchivePages] = (0, react.useState)(1);
@@ -6425,8 +7096,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6425
7096
  const flatKey = (0, react.useMemo)(() => flat.map((item) => `${item.turn}|${item.path}|${item.diffs.length}`).join(";"), [flat]);
6426
7097
  const canRefresh = roots.length > 0 || inspectable.length > 0;
6427
7098
  const refreshing = recordedPending || statusPending;
6428
- const flatRef = (0, react.useRef)(flat);
6429
- flatRef.current = flat;
6430
7099
  const turnsRef = (0, react.useRef)(turns);
6431
7100
  turnsRef.current = turns;
6432
7101
  const archivedTurnsRef = (0, react.useRef)(archivedTurns);
@@ -6458,24 +7127,19 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6458
7127
  } : summarizeDiffs(selected.diffs), [selected]);
6459
7128
  const replayLink = (0, react.useCallback)((paths, targetTurn) => {
6460
7129
  if (paths.length === 0) return;
6461
- const ownerTurn = targetTurn !== void 0 ? turnsRef.current.find((turn) => turn.turn === targetTurn) : turnsRef.current.find((turn) => turn.files.some((file) => paths.includes(file.path)));
6462
- if (ownerTurn !== void 0 && ownerTurn.live !== true) {
6463
- const archivedIndex = archivedTurnsRef.current.findIndex((turn) => turn.turn === ownerTurn.turn);
6464
- if (archivedIndex !== -1) {
6465
- setArchiveOpen(true);
6466
- setArchivePages((current) => Math.max(current, Math.ceil((archivedIndex + 1) / 10)));
6467
- }
7130
+ const plan = planDeepLink(turnsRef.current, archivedTurnsRef.current, paths, targetTurn);
7131
+ if (plan.archive !== null) {
7132
+ setArchiveOpen(true);
7133
+ setArchivePages((current) => Math.max(current, plan.archive.pages));
6468
7134
  }
6469
- const matches = (item) => paths.includes(item.path) && (targetTurn === void 0 || item.turn === targetTurn);
6470
7135
  setExpanded((current) => {
6471
7136
  const next = new Set(current);
6472
- for (const item of flatRef.current) if (matches(item)) next.add(stateKey(item.turn, item.path));
7137
+ for (const key of plan.expanded) next.add(key);
6473
7138
  return next;
6474
7139
  });
6475
- const first = flatRef.current.find((item) => matches(item));
6476
- pendingScrollRef.current = first === void 0 ? null : {
6477
- rowKey: stateKey(first.turn, first.path),
6478
- turn: paths.length > 1 ? first.turn : null
7140
+ pendingScrollRef.current = plan.first === null ? null : {
7141
+ rowKey: stateKey(plan.first.turn, plan.first.path),
7142
+ turn: paths.length > 1 ? plan.first.turn : null
6479
7143
  };
6480
7144
  }, []);
6481
7145
  (0, react.useEffect)(() => {
@@ -6695,7 +7359,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6695
7359
  disabled: statusPending || busyKey !== null || reversible.length === 0,
6696
7360
  title: reversible.length === 0 ? t("toggleUnavailable") : void 0,
6697
7361
  onClick: () => {
6698
- runToggle(turnKey, turn.files.filter((file) => file.deleted !== true).map((file) => ({
7362
+ runToggle(turnKey, reversible.map((file) => ({
6699
7363
  turn: turn.turn,
6700
7364
  path: file.path,
6701
7365
  diffs: file.diffs
@@ -6719,7 +7383,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6719
7383
  const fileAction = state === "undone" ? "redo" : "undo";
6720
7384
  const fileBusy = busyKey === key;
6721
7385
  const stats = summarizeDiffs(file.diffs);
6722
- const hunks = isOpen ? toNativeHunks(file.diffs, 3) : [];
7386
+ const hunks = isOpen ? toNativeHunks(file.diffs, 3, anchors) : [];
7387
+ const diffId = `file-review-diff-${turn.turn}-${encodeURIComponent(file.path)}`;
6723
7388
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", {
6724
7389
  className: FileReviewTab_module_css_default.fileItem,
6725
7390
  ref: (element) => {
@@ -6728,35 +7393,35 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6728
7393
  },
6729
7394
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6730
7395
  className: FileReviewTab_module_css_default.fileRow,
6731
- role: "button",
6732
- tabIndex: 0,
6733
- title: file.path,
6734
- "aria-expanded": isOpen,
6735
- onClick: () => {
6736
- toggleExpanded(key);
6737
- },
6738
- onKeyDown: (event) => {
6739
- if (event.key === "Enter" || event.key === " ") {
6740
- event.preventDefault();
6741
- toggleExpanded(key);
6742
- }
6743
- },
7396
+ "data-review-row": file.path,
6744
7397
  children: [
6745
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Chevron, { open: isOpen }),
6746
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
6747
- className: FileReviewTab_module_css_default.fileName,
6748
- children: basename$1(file.path)
7398
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
7399
+ type: "button",
7400
+ className: FileReviewTab_module_css_default.rowToggle,
7401
+ "data-review-row-toggle": "",
7402
+ "aria-expanded": isOpen,
7403
+ "aria-controls": isOpen ? diffId : void 0,
7404
+ title: file.path,
7405
+ onClick: () => {
7406
+ toggleExpanded(key);
7407
+ },
7408
+ children: [
7409
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Chevron, { open: isOpen }),
7410
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
7411
+ className: FileReviewTab_module_css_default.fileName,
7412
+ children: basename$1(file.path)
7413
+ }),
7414
+ file.deleted === true ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
7415
+ className: FileReviewTab_module_css_default.deletedBadge,
7416
+ children: t("deleted")
7417
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Stats, { stats }),
7418
+ file.deleted !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StateBadge, { state })
7419
+ ]
6749
7420
  }),
6750
- file.deleted === true ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
6751
- className: FileReviewTab_module_css_default.deletedBadge,
6752
- children: t("deleted")
6753
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Stats, { stats }),
6754
- file.deleted !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StateBadge, { state }),
6755
7421
  file.deleted !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
6756
7422
  type: "button",
6757
7423
  className: `${FileReviewTab_module_css_default.smallButton} ${FileReviewTab_module_css_default.editorButton}`,
6758
- onClick: (event) => {
6759
- event.stopPropagation();
7424
+ onClick: () => {
6760
7425
  openInEditor(file.path);
6761
7426
  },
6762
7427
  children: t("openInEditor")
@@ -6766,8 +7431,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6766
7431
  className: FileReviewTab_module_css_default.smallButton,
6767
7432
  disabled: statusPending || busyKey !== null || !reversible,
6768
7433
  title: file.deleted === true ? t("deletedHint") : !reversible ? t("toggleUnavailable") : void 0,
6769
- onClick: (event) => {
6770
- event.stopPropagation();
7434
+ onClick: () => {
6771
7435
  runToggle(key, [{
6772
7436
  turn: turn.turn,
6773
7437
  path: file.path,
@@ -6779,6 +7443,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6779
7443
  ]
6780
7444
  }), isOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
6781
7445
  className: FileReviewTab_module_css_default.diffWrap,
7446
+ id: diffId,
6782
7447
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LazyDiff, { children: file.deleted === true || file.diffs.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NativeDiff, {
6783
7448
  hunks: [],
6784
7449
  path: file.path,
@@ -6997,15 +7662,17 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6997
7662
  if (produced.seq > seq) continue;
6998
7663
  const review = byPath.get(produced.path);
6999
7664
  if (review === void 0) {
7665
+ const diffs = [];
7666
+ appendMutation(diffs, produced.diffs, produced.seq);
7000
7667
  const created = {
7001
7668
  path: produced.path,
7002
- diffs: [...produced.diffs],
7669
+ diffs,
7003
7670
  ...produced.deleted === true ? { deleted: true } : {}
7004
7671
  };
7005
7672
  byPath.set(produced.path, created);
7006
7673
  reviews.push(created);
7007
7674
  } else {
7008
- review.diffs.push(...produced.diffs);
7675
+ appendMutation(review.diffs, produced.diffs, produced.seq);
7009
7676
  if (produced.deleted === true) review.deleted = true;
7010
7677
  else delete review.deleted;
7011
7678
  }
@@ -7077,10 +7744,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7077
7744
  const additions = [];
7078
7745
  if (intent.path !== null) {
7079
7746
  const own = applied === null ? intent.diffs : applied.filter((diff) => diff.path === intent.path);
7747
+ const diffs = own.length > 0 ? own : intent.diffs;
7080
7748
  additions.push({
7081
7749
  seq,
7082
7750
  path: intent.path,
7083
- diffs: own.length > 0 ? own : intent.diffs
7751
+ diffs: diffs.map((diff) => ({
7752
+ ...diff,
7753
+ callId: result.callId
7754
+ }))
7084
7755
  });
7085
7756
  }
7086
7757
  for (const path of intent.deletions) additions.push({
@@ -7396,9 +8067,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7396
8067
  });
7397
8068
  }
7398
8069
  /** The hover preview: path label plus the same comparison the sidebar shows. */
7399
- function ChangedFilePreview({ display, reviews, t }) {
8070
+ function ChangedFilePreview({ display, reviews, reviewSessionId, loadHunkAnchors, t }) {
7400
8071
  const diffs = reviews.flatMap((review) => review.diffs);
7401
- const hunks = toNativeHunks(diffs, 2);
8072
+ const calls = (0, react.useMemo)(() => anchorCalls(diffs), [diffs]);
8073
+ const callIds = (0, react.useMemo)(() => calls.map((call) => call.callId), [calls]);
8074
+ const callsRef = (0, react.useRef)(calls);
8075
+ callsRef.current = calls;
8076
+ const load = (0, react.useMemo)(() => loadHunkAnchors === void 0 ? void 0 : (ids) => loadHunkAnchors(callsRef.current.filter((call) => ids.includes(call.callId))), [loadHunkAnchors]);
8077
+ const hunks = toNativeHunks(diffs, 2, useHunkAnchors(reviewSessionId ?? "", callIds, load, reviewSessionId !== void 0 && loadHunkAnchors !== void 0));
7402
8078
  const note = diffNote(diffs, hunks, reviews.every((review) => review.deleted === true));
7403
8079
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
7404
8080
  className: ProducedCard_module_css_default.preview,
@@ -7453,7 +8129,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7453
8129
  * The card itself: the native ChangedFiles layout plus the two action buttons
7454
8130
  * in the header's top-right corner.
7455
8131
  */
7456
- function ProducedFilesCard({ reviews, openFile, turn: turnLocation, projectRoot, reviewSessionId, inspectChanges = unavailableChanges, applyChanges = unavailableChanges, openInSidebarTab, t }) {
8132
+ function ProducedFilesCard({ reviews, openFile, turn: turnLocation, projectRoot, reviewSessionId, inspectChanges = unavailableChanges, applyChanges = unavailableChanges, loadHunkAnchors, openInSidebarTab, t }) {
7457
8133
  const turnNumber = turnLocation.turn;
7458
8134
  const [expanded, setExpanded] = (0, react.useState)(false);
7459
8135
  const [toggleAction, setToggleAction] = (0, react.useState)("undo");
@@ -7471,12 +8147,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7471
8147
  added: 0,
7472
8148
  removed: 0
7473
8149
  }), [reviewsWithStats]);
7474
- const toggleFiles = (0, react.useMemo)(() => reviews.filter((review) => review.deleted !== true).map((review) => ({
8150
+ const toggleFiles = (0, react.useMemo)(() => reviews.filter((review) => review.deleted !== true && changeReversible(review.path, review.diffs)).map((review) => ({
7475
8151
  path: review.path,
7476
8152
  diffs: review.diffs
7477
8153
  })), [reviews]);
7478
- const reversiblePaths = (0, react.useMemo)(() => new Set(reviews.filter((review) => review.diffs.length > 0 && review.diffs.every((diff) => diff.path === review.path && diff.oldText !== null && diff.oldText !== diff.newText && (diff.oldText !== "" || diff.oldStart !== void 0) && (diff.newText !== "" || diff.newStart !== void 0))).map((review) => review.path)), [reviews]);
7479
- const hasReversibleFiles = reversiblePaths.size > 0;
8154
+ const reversiblePaths = (0, react.useMemo)(() => new Set(toggleFiles.map((file) => file.path)), [toggleFiles]);
8155
+ const hasReversibleFiles = toggleFiles.length > 0;
7480
8156
  const singleFile = reviewsWithStats.length === 1 ? reviewsWithStats[0] : void 0;
7481
8157
  const foldable = reviewsWithStats.length > COLLAPSED_ROWS;
7482
8158
  const rows = foldable && !expanded ? reviewsWithStats.slice(0, COLLAPSED_ROWS) : reviewsWithStats;
@@ -7504,15 +8180,24 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7504
8180
  const target = currentAction === "undo" ? "undone" : "applied";
7505
8181
  return [...reversiblePaths].every((path) => byPath.get(path)?.state === target) ? currentAction === "undo" ? "redo" : "undo" : currentAction;
7506
8182
  }, [reversiblePaths]);
8183
+ const toggleKey = (0, react.useMemo)(() => toggleFiles.map((file) => `${file.path}\u0000${file.diffs.length}`).join(""), [toggleFiles]);
8184
+ const inspectRef = (0, react.useRef)(inspectChanges);
8185
+ inspectRef.current = inspectChanges;
7507
8186
  (0, react.useEffect)(() => {
8187
+ if (toggleKey === "") {
8188
+ setStatusPending(false);
8189
+ setToggleAction("undo");
8190
+ return;
8191
+ }
7508
8192
  let active = true;
7509
8193
  setStatusPending(true);
7510
- inspectChanges({
8194
+ const files = toggleFiles;
8195
+ inspectRef.current({
7511
8196
  action: "undo",
7512
- files: toggleFiles
8197
+ files
7513
8198
  }).then((result) => {
7514
8199
  if (!active) return;
7515
- const allUndone = reversiblePaths.size > 0 && [...reversiblePaths].every((path) => result.files.find((file) => file.path === path)?.state === "undone");
8200
+ const allUndone = files.length > 0 && files.every((file) => result.files.find((entry) => entry.path === file.path)?.state === "undone");
7516
8201
  setToggleAction(allUndone ? "redo" : "undo");
7517
8202
  }).catch(() => {}).finally(() => {
7518
8203
  if (active) setStatusPending(false);
@@ -7520,12 +8205,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7520
8205
  return () => {
7521
8206
  active = false;
7522
8207
  };
7523
- }, [
7524
- inspectChanges,
7525
- reversiblePaths,
7526
- statusVersion,
7527
- toggleFiles
7528
- ]);
8208
+ }, [toggleKey, statusVersion]);
7529
8209
  const runToggle = (0, react.useCallback)(() => {
7530
8210
  if (statusPending || togglePending || !hasReversibleFiles) return;
7531
8211
  const action = toggleAction;
@@ -7635,6 +8315,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7635
8315
  content: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChangedFilePreview, {
7636
8316
  display: displayPath(projectRoot, singleFile.review.path),
7637
8317
  reviews: [singleFile.review],
8318
+ reviewSessionId,
8319
+ loadHunkAnchors,
7638
8320
  t
7639
8321
  })
7640
8322
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -7667,6 +8349,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7667
8349
  content: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChangedFilePreview, {
7668
8350
  display: displayPath(projectRoot, review.path),
7669
8351
  reviews: [review],
8352
+ reviewSessionId,
8353
+ loadHunkAnchors,
7670
8354
  t
7671
8355
  }),
7672
8356
  anchor: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
@@ -7966,6 +8650,20 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7966
8650
  if (!result.ok) throw new Error(result.error.message);
7967
8651
  return result.value;
7968
8652
  };
8653
+ /**
8654
+ * Line coordinates for the calls the card's hover preview draws. The
8655
+ * conversation snapshot only carries context fragments, so without these
8656
+ * the preview would number every hunk from 1.
8657
+ */
8658
+ const loadHunkAnchors = async (calls) => {
8659
+ if (calls.length === 0) return [];
8660
+ const scope = sessions.scope(sessionId);
8661
+ const fileReview = scope?.get("remote.fileReview");
8662
+ if (scope === void 0 || fileReview === void 0) throw new Error("File review Remote is unavailable");
8663
+ const result = await fileReview.anchors({ calls });
8664
+ if (!result.ok) throw new Error(result.error.message);
8665
+ return result.value.anchors;
8666
+ };
7969
8667
  return {
7970
8668
  projectRoot,
7971
8669
  reviewSessionId: sessionId,
@@ -7975,6 +8673,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
7975
8673
  publishFileReviewInvalidation(sessionId);
7976
8674
  return result;
7977
8675
  },
8676
+ loadHunkAnchors,
7978
8677
  openInSidebarTab: (paths, turn) => {
7979
8678
  const sidebar = ctx.betterSidebar;
7980
8679
  if (sidebar === void 0 || paths.length === 0) return;