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

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,11 @@ 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()
4042
4046
  });
4043
4047
  const requestSchema = object({
4044
4048
  action: _enum(["undo", "redo"]),
@@ -4173,6 +4177,72 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4173
4177
  ]);
4174
4178
  /** PowerShell parameters whose NEXT argument is the path, not an option value. */
4175
4179
  const PATH_PARAMETERS = /^-(path|literalpath)$/i;
4180
+ /**
4181
+ * Options whose NEXT token is a VALUE, not a path (`shred -n 3 file` — `3` is an
4182
+ * iteration count). Keyed by command, because `-n` means different things to
4183
+ * different tools; an option absent here is assumed valueless.
4184
+ *
4185
+ * Options that carry their value inline (`--iterations=3`) need no entry: they
4186
+ * are consumed as a single token.
4187
+ */
4188
+ const VALUE_OPTIONS = /* @__PURE__ */ new Map([["shred", /* @__PURE__ */ new Set([
4189
+ "n",
4190
+ "iterations",
4191
+ "s",
4192
+ "size"
4193
+ ])], ["trash", /* @__PURE__ */ new Set(["trash-dir"])]]);
4194
+ /**
4195
+ * cmd.exe `/x` switches, per command. `del /q file` deletes `file`, so `/q` is a
4196
+ * switch and not a path.
4197
+ *
4198
+ * The lists are EXACTLY what each cmd builtin defines, because these command
4199
+ * names also exist in PowerShell, where `/tmp/x` is an absolute path and not a
4200
+ * switch at all. Accepting any `/letters` token would silently swallow such a
4201
+ * path (`rd /tmp` is a real deletion in PowerShell); accepting only the real
4202
+ * switches keeps both shells correct.
4203
+ */
4204
+ const SLASH_SWITCHES = /* @__PURE__ */ new Map([
4205
+ ["del", /* @__PURE__ */ new Set([
4206
+ "p",
4207
+ "f",
4208
+ "s",
4209
+ "q",
4210
+ "a"
4211
+ ])],
4212
+ ["erase", /* @__PURE__ */ new Set([
4213
+ "p",
4214
+ "f",
4215
+ "s",
4216
+ "q",
4217
+ "a"
4218
+ ])],
4219
+ ["rd", /* @__PURE__ */ new Set(["s", "q"])],
4220
+ ["rmdir", /* @__PURE__ */ new Set(["s", "q"])]
4221
+ ]);
4222
+ /**
4223
+ * The option name one `/…` token declares, or null when it is a path.
4224
+ *
4225
+ * `/a` may carry an attached value (`/a:h`, `/a:-r`), so a `:value` suffix is
4226
+ * allowed; the name is what precedes the colon.
4227
+ */
4228
+ function slashSwitchName(command, token) {
4229
+ const match = /^\/([A-Za-z]+)(?::[^\s]*)?$/.exec(token);
4230
+ if (match === null) return null;
4231
+ const name = match[1].toLowerCase();
4232
+ return SLASH_SWITCHES.get(command)?.has(name) === true ? name : null;
4233
+ }
4234
+ /**
4235
+ * The option name a token declares, lowercased, with the switch prefix and any
4236
+ * inline value removed, or null when the token is not an option at all.
4237
+ * @param token - One argument.
4238
+ * @param command - The command it was passed to.
4239
+ * @returns The bare option name, or null for a path.
4240
+ */
4241
+ function optionName(token, command) {
4242
+ if (token.startsWith("-")) return token.replace(/^-+/, "").split("=")[0].toLowerCase();
4243
+ if (token.startsWith("/")) return slashSwitchName(command, token);
4244
+ return null;
4245
+ }
4176
4246
  /** Arguments never treated as paths: glob/expansion-bearing or self/parent refs. */
4177
4247
  function isPathlike(token) {
4178
4248
  if (token === "" || token === "." || token === "..") return false;
@@ -4226,21 +4296,34 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4226
4296
  return segments;
4227
4297
  }
4228
4298
  /**
4229
- * Shell-like tokenization of one segment, quotes joined into the token.
4299
+ * Shell-like tokenization of one segment. Quotes are joined into the token and
4300
+ * recorded, because quote boundaries decide whether a comma separates paths.
4301
+ *
4230
4302
  * Backslash semantics follow the Windows-relevant reading: inside SINGLE
4231
4303
  * quotes (bash/PowerShell alike) everything is literal, and unquoted
4232
4304
  * backslashes stay literal too (PowerShell paths); only inside DOUBLE quotes
4233
4305
  * does a backslash escape the closing quote or itself (bash). A trailing open
4234
4306
  * quote still yields the tokens gathered so far.
4307
+ *
4308
+ * Each token is returned as its comma-separated PARTS: PowerShell passes a list
4309
+ * as `'a.txt','b.txt'`, which is one whitespace token but two paths. Only an
4310
+ * UNQUOTED comma splits, so a comma that is part of a filename survives —
4311
+ * `rm 'a,b.txt'` is one path, not two.
4235
4312
  */
4236
4313
  function tokenize$1(segment) {
4237
4314
  const tokens = [];
4315
+ let parts = [];
4238
4316
  let current = "";
4239
4317
  let quote = null;
4240
- const flush = () => {
4241
- if (current !== "") tokens.push(current);
4318
+ const flushPart = () => {
4319
+ if (current !== "") parts.push(current);
4242
4320
  current = "";
4243
4321
  };
4322
+ const flushToken = () => {
4323
+ flushPart();
4324
+ if (parts.length > 0) tokens.push(parts);
4325
+ parts = [];
4326
+ };
4244
4327
  for (let at = 0; at < segment.length; at += 1) {
4245
4328
  const char = segment[at];
4246
4329
  if (char === void 0) break;
@@ -4267,12 +4350,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4267
4350
  continue;
4268
4351
  }
4269
4352
  if (/\s/.test(char)) {
4270
- flush();
4353
+ flushToken();
4354
+ continue;
4355
+ }
4356
+ if (char === ",") {
4357
+ flushPart();
4271
4358
  continue;
4272
4359
  }
4273
4360
  current += char;
4274
4361
  }
4275
- flush();
4362
+ flushToken();
4276
4363
  return tokens;
4277
4364
  }
4278
4365
  /**
@@ -4284,37 +4371,65 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4284
4371
  const paths = [];
4285
4372
  const seen = /* @__PURE__ */ new Set();
4286
4373
  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
- }
4374
+ if (!isPathlike(raw) || seen.has(raw)) return;
4375
+ seen.add(raw);
4376
+ paths.push(raw);
4377
+ };
4378
+ /** Accept every path a token names (a PowerShell list carries several). */
4379
+ const acceptAll = (token) => {
4380
+ for (const part of token) accept(part);
4292
4381
  };
4382
+ /**
4383
+ * The token's text when it is a single argument, or undefined when it is a
4384
+ * comma-separated LIST. Only single-part tokens can be options: an unquoted
4385
+ * comma always separated paths, and no option in these commands takes one.
4386
+ */
4387
+ const optionToken = (token) => token.length === 1 ? token[0] : void 0;
4293
4388
  for (const segment of splitSegments(command)) {
4294
4389
  if (segment.includes("$(") || segment.includes("`") || segment.includes("<(")) continue;
4295
4390
  const tokens = tokenize$1(segment);
4296
4391
  let at = 0;
4297
4392
  while (at < tokens.length) {
4298
- const head = tokens[at];
4393
+ const head = tokens[at] === void 0 ? void 0 : optionToken(tokens[at]);
4299
4394
  if (head === void 0 || !/^[A-Za-z_][A-Za-z0-9_]*=/.test(head)) break;
4300
4395
  at += 1;
4301
4396
  }
4302
- const commandWord = tokens[at];
4397
+ const commandWord = tokens[at] === void 0 ? void 0 : optionToken(tokens[at]);
4303
4398
  if (commandWord === void 0) continue;
4304
- const basename = commandWord.slice(Math.max(commandWord.lastIndexOf("/"), commandWord.lastIndexOf("\\")) + 1);
4305
- if (!DELETERS.has(basename.toLowerCase())) continue;
4399
+ const command = commandWord.slice(Math.max(commandWord.lastIndexOf("/"), commandWord.lastIndexOf("\\")) + 1).toLowerCase();
4400
+ if (!DELETERS.has(command)) continue;
4401
+ const valueOptions = VALUE_OPTIONS.get(command);
4402
+ let optionsEnded = false;
4306
4403
  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
- }
4404
+ const parts = tokens[index];
4405
+ if (parts === void 0) continue;
4406
+ const token = optionToken(parts);
4407
+ if (optionsEnded || token === void 0) {
4408
+ acceptAll(parts);
4409
+ continue;
4410
+ }
4411
+ if (token === "--") {
4412
+ optionsEnded = true;
4413
+ continue;
4414
+ }
4415
+ if (PATH_PARAMETERS.test(token) && index + 1 < tokens.length) {
4416
+ index += 1;
4417
+ const named = tokens[index];
4418
+ if (named !== void 0) acceptAll(named);
4419
+ continue;
4420
+ }
4421
+ const inlinePath = /^-(?:path|literalpath):(.*)$/i.exec(token);
4422
+ if (inlinePath !== null) {
4423
+ const named = inlinePath[1];
4424
+ if (named !== void 0 && named !== "") accept(named);
4425
+ continue;
4426
+ }
4427
+ const option = optionName(token, command);
4428
+ if (option !== null) {
4429
+ if (!token.includes("=") && token !== "-" && valueOptions?.has(option) === true) index += 1;
4315
4430
  continue;
4316
4431
  }
4317
- accept(token);
4432
+ acceptAll(parts);
4318
4433
  }
4319
4434
  }
4320
4435
  return paths;
@@ -4449,6 +4564,106 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
4449
4564
  return out;
4450
4565
  }
4451
4566
  //#endregion
4567
+ //#region src/mutation-order.ts
4568
+ /**
4569
+ * Append one settlement's hunks, stamping them with the coordinate space they
4570
+ * were recorded in and the event sequence that orders them.
4571
+ *
4572
+ * The stamp is the accumulator's current length, which is strictly increasing
4573
+ * per path, so two settlements can never share one — that uniqueness is what
4574
+ * lets {@link mutationGroups} split a path's hunks back into settlements.
4575
+ *
4576
+ * `seq` is the ordering key: the conversation node's sequence for a
4577
+ * snapshot-derived settlement, or the owning `run_code` root's sequence for a
4578
+ * Host-recorded one. It is recorded separately from `mutation` because the two
4579
+ * answer different questions — a chain of nested dispatches produces several
4580
+ * distinct settlements that all share one node sequence.
4581
+ *
4582
+ * @param target - The path's accumulated hunks, mutated in place.
4583
+ * @param diffs - One settlement's hunks, all anchored in the same text.
4584
+ * @param seq - Event sequence that orders this settlement, when known.
4585
+ */
4586
+ function appendMutation(target, diffs, seq) {
4587
+ const mutation = target.length;
4588
+ for (const diff of diffs) target.push(seq === void 0 ? {
4589
+ ...diff,
4590
+ mutation
4591
+ } : {
4592
+ ...diff,
4593
+ mutation,
4594
+ seq
4595
+ });
4596
+ }
4597
+ /**
4598
+ * Order settlements by their recorded event sequence, so undo/redo walk the
4599
+ * file's history in the order it actually happened.
4600
+ *
4601
+ * This is what keeps a `run_code` mutation and a model-direct edit to the same
4602
+ * file from being applied out of order: the two arrive through different
4603
+ * channels (the conversation snapshot vs. the Host recorder) and are merged
4604
+ * asynchronously, so the array order is a merge artifact rather than history.
4605
+ *
4606
+ * Only when EVERY entry carries a sequence is the order provable. A partially
4607
+ * stamped list keeps its incoming order, which is the conservative choice —
4608
+ * guessing at the position of an unstamped settlement could silently corrupt a
4609
+ * file. The sort is stable, so entries sharing one sequence (a single
4610
+ * `run_code` root's nested dispatch chain) keep their dispatch order.
4611
+ *
4612
+ * @param entries - Settlements or events carrying an optional `seq`.
4613
+ * @returns A new array in ascending event order, or the same order when unprovable.
4614
+ */
4615
+ function orderBySequence(entries) {
4616
+ if (entries.some((entry) => entry.seq === void 0)) return [...entries];
4617
+ return [...entries].sort((left, right) => left.seq - right.seq);
4618
+ }
4619
+ /**
4620
+ * Recover the settlements one path's flat hunk list was built from.
4621
+ * @param diffs - One path's accumulated hunks.
4622
+ * @returns One entry per coordinate space, in the order they were appended.
4623
+ */
4624
+ function settlementsOf(diffs) {
4625
+ return mutationGroups(diffs).map((group) => ({
4626
+ seq: group[0]?.seq,
4627
+ diffs: group
4628
+ }));
4629
+ }
4630
+ /**
4631
+ * Re-stamp a settlement list back into one flat hunk list, in event order.
4632
+ *
4633
+ * Stamps are reassigned rather than preserved because they encode POSITION
4634
+ * (`mutation` is the append offset), and reordering invalidates the old values;
4635
+ * leaving them stale would make {@link mutationGroups} split the same
4636
+ * coordinate space into several groups.
4637
+ *
4638
+ * @param settlements - Settlements, in any order.
4639
+ * @returns The flat hunk list, ordered by `seq` with fresh stamps.
4640
+ */
4641
+ function flattenSettlements(settlements) {
4642
+ const out = [];
4643
+ for (const settlement of orderBySequence(settlements)) appendMutation(out, settlement.diffs, settlement.seq);
4644
+ return out;
4645
+ }
4646
+ /**
4647
+ * Split one path's hunks into contiguous same-coordinate groups, in settlement
4648
+ * order. Hunks that carry no `mutation` form a single group.
4649
+ * @param diffs - One path's accumulated hunks, in settlement order.
4650
+ * @returns The groups, in settlement order.
4651
+ */
4652
+ function mutationGroups(diffs) {
4653
+ const groups = [];
4654
+ let current = null;
4655
+ let currentStamp;
4656
+ for (const diff of diffs) {
4657
+ if (current === null || diff.mutation !== currentStamp) {
4658
+ current = [];
4659
+ currentStamp = diff.mutation;
4660
+ groups.push(current);
4661
+ }
4662
+ current.push(diff);
4663
+ }
4664
+ return groups;
4665
+ }
4666
+ //#endregion
4452
4667
  //#region src/client/snapshot-compat.ts
4453
4668
  /** Structural view-source guard: a store with a callable `get`. */
4454
4669
  function viewStore(value) {
@@ -5063,15 +5278,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5063
5278
  if (!change.removed && !change.added) {
5064
5279
  const run = change.value;
5065
5280
  if (hunk !== null) {
5066
- const beforeLen = hunk.old.length;
5281
+ const oldKept = hunk.old.length + CONTEXT_LINES;
5282
+ const newKept = hunk.new.length + CONTEXT_LINES;
5067
5283
  hunk.old.push(...run);
5068
5284
  hunk.new.push(...run);
5069
5285
  oldCursor += run.length;
5070
5286
  newCursor += run.length;
5071
5287
  if (run.length > 6) {
5072
- const target = beforeLen + CONTEXT_LINES;
5073
- hunk.old.length = target;
5074
- hunk.new.length = target;
5288
+ hunk.old.length = oldKept;
5289
+ hunk.new.length = newKept;
5075
5290
  contextBuffer = run.slice(-3);
5076
5291
  hunk = null;
5077
5292
  }
@@ -5163,7 +5378,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5163
5378
  });
5164
5379
  return changes;
5165
5380
  }
5166
- /** Settled changes for a tool block tree (the block itself plus `subCalls`). */
5381
+ /**
5382
+ * Settled changes for a tool block tree (the block itself plus `subCalls`).
5383
+ *
5384
+ * The tree contributes one settlement per top-level node, NOT one per nested
5385
+ * dispatch: the Host recorder attributes a `run_code` root's mutations to the
5386
+ * ROOT's seq (a nested dispatch it observes carries no separate conversation
5387
+ * sequence of its own). Ordering the two channels against different clocks
5388
+ * would be comparing incomparable numbers, and a child's seq could also fall
5389
+ * past the turn boundary that owns its root.
5390
+ */
5167
5391
  function collectChanges(block, out) {
5168
5392
  if (block.kind === "tool-result") for (const change of blockChanges(block)) out.push(change);
5169
5393
  const subCalls = block.subCalls;
@@ -5204,41 +5428,58 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5204
5428
  const changes = [];
5205
5429
  collectChanges(node, changes);
5206
5430
  if (changes.length === 0) continue;
5431
+ const seq = typeof node.seq === "number" ? node.seq : void 0;
5207
5432
  const { turn, live } = attribute(node.seq);
5208
5433
  let group = byTurn.get(turn);
5209
5434
  if (group === void 0) {
5210
5435
  group = {
5211
5436
  live,
5212
- files: /* @__PURE__ */ new Map()
5437
+ changes: []
5213
5438
  };
5214
5439
  byTurn.set(turn, group);
5215
5440
  }
5216
- for (const change of changes) {
5217
- const existing = group.files.get(change.path);
5441
+ for (const change of changes) group.changes.push({
5442
+ seq,
5443
+ change
5444
+ });
5445
+ }
5446
+ return [...byTurn.entries()].sort((a, b) => a[0] - b[0]).map(([turn, group]) => {
5447
+ const files = /* @__PURE__ */ new Map();
5448
+ for (const { seq, change } of orderBySequence(group.changes)) {
5449
+ const existing = files.get(change.path);
5218
5450
  if (change.deleted === true) {
5219
- if (existing === void 0) group.files.set(change.path, {
5451
+ if (existing === void 0) files.set(change.path, {
5220
5452
  diffs: [],
5221
- deleted: true
5453
+ deleted: true,
5454
+ deletedSeq: seq
5222
5455
  });
5223
- else existing.deleted = true;
5456
+ else {
5457
+ existing.deleted = true;
5458
+ existing.deletedSeq = seq;
5459
+ }
5224
5460
  continue;
5225
5461
  }
5226
- if (existing === void 0) group.files.set(change.path, { diffs: [...change.diffs] });
5227
- else {
5228
- existing.diffs.push(...change.diffs);
5462
+ if (existing === void 0) {
5463
+ const diffs = [];
5464
+ appendMutation(diffs, change.diffs, seq);
5465
+ files.set(change.path, { diffs });
5466
+ } else {
5467
+ appendMutation(existing.diffs, change.diffs, seq);
5229
5468
  delete existing.deleted;
5469
+ delete existing.deletedSeq;
5230
5470
  }
5231
5471
  }
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
- }));
5472
+ return {
5473
+ turn,
5474
+ live: group.live,
5475
+ files: [...files.entries()].map(([path, own]) => ({
5476
+ path,
5477
+ diffs: own.diffs,
5478
+ ...own.deleted === true ? { deleted: true } : {},
5479
+ ...own.deletedSeq !== void 0 ? { deletedSeq: own.deletedSeq } : {}
5480
+ }))
5481
+ };
5482
+ });
5242
5483
  }
5243
5484
  /**
5244
5485
  * Snapshot-identity cache: the sidebar badge runs this derivation on every
@@ -5264,32 +5505,49 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5264
5505
  if (node.kind !== "tool-result" || node.isError) continue;
5265
5506
  if (node.subCalls.length === 0) continue;
5266
5507
  const nested = [];
5267
- for (const child of node.subCalls) if (child.kind === "tool-result") collectChanges(child, nested);
5508
+ let settled = 0;
5509
+ for (const child of node.subCalls) {
5510
+ if (child.kind !== "tool-result") continue;
5511
+ settled += 1;
5512
+ collectChanges(child, nested);
5513
+ }
5268
5514
  if (nested.some((change) => change.diffs.length > 0)) continue;
5269
5515
  const { turn, live } = attribute(node.seq);
5516
+ const seq = typeof node.seq === "number" ? node.seq : void 0;
5270
5517
  roots.push({
5271
5518
  turn,
5272
5519
  live,
5273
- rootCallId: node.callId
5520
+ rootCallId: node.callId,
5521
+ seq,
5522
+ progress: settled
5274
5523
  });
5275
5524
  }
5276
5525
  return roots;
5277
5526
  }
5278
5527
  /**
5279
5528
  * 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.
5529
+ * hunks rebuilt from the full before/after are inserted into the owning turn's
5530
+ * file groups at the position their EVENT SEQUENCE puts them (same-path entries
5531
+ * stay one row), so the tab's diff rendering, status inspection and undo all
5532
+ * work on programmatic edits exactly like model-direct ones.
5533
+ *
5534
+ * Ordering is by sequence rather than "snapshot first, recorded after": the two
5535
+ * sources are separate channels merged asynchronously, so appending recorded
5536
+ * mutations could invert them. A `run_code` insert at the top of a file followed
5537
+ * by a model-direct edit near its end must replay in that order — reversed, the
5538
+ * rear edit's line anchors describe text the front insert already shifted, and
5539
+ * BOTH undo and redo fail on a file that was perfectly reviewable.
5540
+ *
5541
+ * All inputs are immutable; the result is a fresh array only when a recorded
5542
+ * mutation matched a visible root.
5286
5543
  */
5287
5544
  function mergeRecordedTurns(turns, roots, recorded) {
5288
5545
  if (recorded.length === 0 || roots.length === 0) return turns;
5289
5546
  const rootTurns = /* @__PURE__ */ new Map();
5290
5547
  for (const root of roots) rootTurns.set(root.rootCallId, {
5291
5548
  turn: root.turn,
5292
- live: root.live
5549
+ live: root.live,
5550
+ seq: root.seq
5293
5551
  });
5294
5552
  const byRoot = /* @__PURE__ */ new Map();
5295
5553
  for (const mutation of recorded) {
@@ -5303,46 +5561,76 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5303
5561
  break;
5304
5562
  }
5305
5563
  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
- }
5564
+ const pending = /* @__PURE__ */ new Map();
5318
5565
  for (const [rootCallId, mutations] of byRoot) {
5319
5566
  const owner = rootTurns.get(rootCallId);
5320
5567
  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);
5568
+ let paths = pending.get(owner.turn);
5569
+ if (paths === void 0) {
5570
+ paths = /* @__PURE__ */ new Map();
5571
+ pending.set(owner.turn, paths);
5328
5572
  }
5329
5573
  for (const mutation of mutations) {
5330
5574
  const diffs = diffsFromBeforeAfter(mutation.path, mutation.before, mutation.after);
5331
5575
  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);
5576
+ const list = paths.get(mutation.path);
5577
+ if (list === void 0) paths.set(mutation.path, [{
5578
+ seq: owner.seq,
5579
+ diffs
5580
+ }]);
5581
+ else list.push({
5582
+ seq: owner.seq,
5583
+ diffs
5584
+ });
5335
5585
  }
5336
5586
  }
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
- }));
5587
+ const merge = (existing, extra) => {
5588
+ const diffs = flattenSettlements([...settlementsOf(existing?.diffs ?? []), ...extra.map((entry) => ({
5589
+ seq: entry.seq,
5590
+ diffs: entry.diffs
5591
+ }))]);
5592
+ const lastRecordedSeq = extra.reduce((highest, entry) => entry.seq === void 0 ? highest : Math.max(highest ?? entry.seq, entry.seq), void 0);
5593
+ if (diffs.length > 0 && lastRecordedSeq !== void 0 && (existing?.deletedSeq === void 0 || lastRecordedSeq > existing.deletedSeq) || existing?.deleted !== true) return { diffs };
5594
+ return {
5595
+ diffs,
5596
+ deleted: true,
5597
+ ...existing.deletedSeq !== void 0 ? { deletedSeq: existing.deletedSeq } : {}
5598
+ };
5599
+ };
5600
+ const out = [];
5601
+ for (const turn of turns) {
5602
+ const paths = pending.get(turn.turn);
5603
+ const files = /* @__PURE__ */ new Map();
5604
+ for (const file of turn.files) files.set(file.path, {
5605
+ diffs: [...file.diffs],
5606
+ ...file.deleted === true ? { deleted: true } : {},
5607
+ ...file.deletedSeq !== void 0 ? { deletedSeq: file.deletedSeq } : {}
5608
+ });
5609
+ if (paths !== void 0) for (const [path, extra] of paths) files.set(path, merge(files.get(path), extra));
5610
+ out.push({
5611
+ turn: turn.turn,
5612
+ live: turn.live,
5613
+ files: [...files.entries()].map(([path, own]) => ({
5614
+ path,
5615
+ diffs: own.diffs,
5616
+ ...own.deleted === true ? { deleted: true } : {},
5617
+ ...own.deletedSeq !== void 0 ? { deletedSeq: own.deletedSeq } : {}
5618
+ }))
5619
+ });
5620
+ }
5621
+ for (const [turn, paths] of pending) {
5622
+ if (turns.some((entry) => entry.turn === turn)) continue;
5623
+ const owner = roots.find((root) => root.turn === turn);
5624
+ out.push({
5625
+ turn,
5626
+ live: owner?.live ?? true,
5627
+ files: [...paths.entries()].map(([path, extra]) => ({
5628
+ path,
5629
+ ...merge(void 0, extra)
5630
+ }))
5631
+ });
5632
+ }
5633
+ return out.sort((a, b) => a.turn - b.turn);
5346
5634
  }
5347
5635
  /** Count distinct changed paths across every turn (the sidebar badge count). */
5348
5636
  function countChangedFiles(turns) {
@@ -5563,6 +5851,17 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
5563
5851
  function toNativeHunks(diffs, contextLines = 3) {
5564
5852
  return diffs.flatMap((diff) => comparisonToHunks(diff, contextLines));
5565
5853
  }
5854
+ /**
5855
+ * Delay before the next `recorded` fetch.
5856
+ * @param anchor - Timestamp of the last completed fetch, or of the moment the
5857
+ * fetch was first armed when none has completed yet. Must never be a value that
5858
+ * an incoming update can reset, or the fetch starves.
5859
+ * @param now - Current timestamp.
5860
+ * @returns Milliseconds to wait; 0 once the interval has already elapsed.
5861
+ */
5862
+ function recordedFetchDelay(anchor, now) {
5863
+ return Math.max(0, 200 - (now - anchor));
5864
+ }
5566
5865
  //#endregion
5567
5866
  //#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
5867
  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)}";
@@ -6094,6 +6393,72 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6094
6393
  }
6095
6394
  //#endregion
6096
6395
  //#region src/client/deep-link.ts
6396
+ /**
6397
+ * Chat → sidebar deep-link channel.
6398
+ *
6399
+ * The chat turn-tail row knows which paths (and which turn) the user wants to
6400
+ * inspect, but better-sidebar's native right Sidebar mints its own tab ids and
6401
+ * does not refresh an already-open tab's `meta` (dsh-better-sidebar #632 /
6402
+ * 0.19.1 adapter behaviour). Passing a `path` seed is also unsafe there: the
6403
+ * native surface routes path-bearing opens to the file editor, so the review
6404
+ * tab would never mount.
6405
+ *
6406
+ * The channel therefore carries the seed inside this plugin: the chat row
6407
+ * publishes it and then opens the tab by type; the tab body subscribes and
6408
+ * replays whatever arrived, whether it mounted just now or was already open.
6409
+ * Sessions are keyed separately, and each publish gets a monotonic nonce so a
6410
+ * replay can never be mistaken for a fresh link.
6411
+ */
6412
+ /** State-map key for one (turn, file) change group. */
6413
+ function rowKey(turn, path) {
6414
+ return `${turn}|${path}`;
6415
+ }
6416
+ /**
6417
+ * Resolve a deep link against EVERY change the tab can render, including turns
6418
+ * still hidden behind a closed archive section.
6419
+ *
6420
+ * The target is deliberately resolved against the full change set rather than
6421
+ * the currently mounted rows. A link into an archived turn is replayed in the
6422
+ * same commit that opens the archive, so at that moment its rows are not
6423
+ * mounted yet; resolving against the mounted set made the match fail, the
6424
+ * pending scroll get cleared, and the link land nowhere with no retry.
6425
+ *
6426
+ * @param turns - Every turn, ascending (the source of truth for all rows).
6427
+ * @param archivedTurns - The auto-archived subset, newest first.
6428
+ * @param paths - Paths the link targets.
6429
+ * @param targetTurn - Turn anchor, or undefined for a path-only (legacy) link.
6430
+ * @returns The expand set, the scroll target, and the archive reveal to apply.
6431
+ */
6432
+ function planDeepLink(turns, archivedTurns, paths, targetTurn) {
6433
+ const expanded = [];
6434
+ let first = null;
6435
+ for (let index = turns.length - 1; index >= 0; index -= 1) {
6436
+ const turn = turns[index];
6437
+ if (turn === void 0) continue;
6438
+ for (const file of turn.files) {
6439
+ if (!paths.includes(file.path)) continue;
6440
+ if (targetTurn !== void 0 && turn.turn !== targetTurn) continue;
6441
+ expanded.push(rowKey(turn.turn, file.path));
6442
+ first ??= {
6443
+ turn: turn.turn,
6444
+ path: file.path
6445
+ };
6446
+ }
6447
+ }
6448
+ let archive = null;
6449
+ if (first !== null) {
6450
+ const owner = turns.find((turn) => turn.turn === first.turn);
6451
+ if (owner !== void 0 && owner.live !== true) {
6452
+ const archivedIndex = archivedTurns.findIndex((turn) => turn.turn === first.turn);
6453
+ if (archivedIndex !== -1) archive = { pages: Math.ceil((archivedIndex + 1) / 10) };
6454
+ }
6455
+ }
6456
+ return {
6457
+ expanded,
6458
+ first,
6459
+ archive
6460
+ };
6461
+ }
6097
6462
  const latest = /* @__PURE__ */ new Map();
6098
6463
  const listeners = /* @__PURE__ */ new Set();
6099
6464
  const invalidationListeners = /* @__PURE__ */ new Set();
@@ -6341,9 +6706,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6341
6706
  const subscribe = (0, react.useCallback)((listener) => conversationSource?.subscribe(listener) ?? (() => {}), [conversationSource]);
6342
6707
  const snapshot = (0, react.useSyncExternalStore)(subscribe, () => conversationSource?.getSnapshot() ?? null);
6343
6708
  const roots = (0, react.useMemo)(() => snapshot === null ? [] : deriveSessionRoots(snapshot), [snapshot]);
6344
- const rootsKey = (0, react.useMemo)(() => roots.map((root) => root.rootCallId).join("|"), [roots]);
6709
+ const rootsKey = (0, react.useMemo)(() => roots.map((root) => `${root.rootCallId}:${root.progress}`).join("|"), [roots]);
6345
6710
  const [recorded, setRecorded] = (0, react.useState)(() => []);
6346
6711
  const [recordedPending, setRecordedPending] = (0, react.useState)(false);
6712
+ const recordedFetchAnchorRef = (0, react.useRef)(null);
6347
6713
  (0, react.useEffect)(() => {
6348
6714
  if (!visible || roots.length === 0) {
6349
6715
  setRecordedPending(false);
@@ -6351,6 +6717,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6351
6717
  }
6352
6718
  let active = true;
6353
6719
  setRecordedPending(true);
6720
+ const now = Date.now();
6721
+ if (recordedFetchAnchorRef.current === null) recordedFetchAnchorRef.current = now;
6354
6722
  const timer = window.setTimeout(() => {
6355
6723
  const scope = sessions.scope(sessionId);
6356
6724
  const remote = scope?.get("remote.fileReview");
@@ -6363,9 +6731,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6363
6731
  if (!result.ok || !active) return;
6364
6732
  setRecorded(result.value.mutations);
6365
6733
  }).catch(() => {}).finally(() => {
6734
+ recordedFetchAnchorRef.current = Date.now();
6366
6735
  if (active) setRecordedPending(false);
6367
6736
  });
6368
- }, 200);
6737
+ }, recordedFetchDelay(recordedFetchAnchorRef.current, now));
6369
6738
  return () => {
6370
6739
  active = false;
6371
6740
  window.clearTimeout(timer);
@@ -6425,8 +6794,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6425
6794
  const flatKey = (0, react.useMemo)(() => flat.map((item) => `${item.turn}|${item.path}|${item.diffs.length}`).join(";"), [flat]);
6426
6795
  const canRefresh = roots.length > 0 || inspectable.length > 0;
6427
6796
  const refreshing = recordedPending || statusPending;
6428
- const flatRef = (0, react.useRef)(flat);
6429
- flatRef.current = flat;
6430
6797
  const turnsRef = (0, react.useRef)(turns);
6431
6798
  turnsRef.current = turns;
6432
6799
  const archivedTurnsRef = (0, react.useRef)(archivedTurns);
@@ -6458,24 +6825,19 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6458
6825
  } : summarizeDiffs(selected.diffs), [selected]);
6459
6826
  const replayLink = (0, react.useCallback)((paths, targetTurn) => {
6460
6827
  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
- }
6828
+ const plan = planDeepLink(turnsRef.current, archivedTurnsRef.current, paths, targetTurn);
6829
+ if (plan.archive !== null) {
6830
+ setArchiveOpen(true);
6831
+ setArchivePages((current) => Math.max(current, plan.archive.pages));
6468
6832
  }
6469
- const matches = (item) => paths.includes(item.path) && (targetTurn === void 0 || item.turn === targetTurn);
6470
6833
  setExpanded((current) => {
6471
6834
  const next = new Set(current);
6472
- for (const item of flatRef.current) if (matches(item)) next.add(stateKey(item.turn, item.path));
6835
+ for (const key of plan.expanded) next.add(key);
6473
6836
  return next;
6474
6837
  });
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
6838
+ pendingScrollRef.current = plan.first === null ? null : {
6839
+ rowKey: stateKey(plan.first.turn, plan.first.path),
6840
+ turn: paths.length > 1 ? plan.first.turn : null
6479
6841
  };
6480
6842
  }, []);
6481
6843
  (0, react.useEffect)(() => {
@@ -6997,15 +7359,17 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6997
7359
  if (produced.seq > seq) continue;
6998
7360
  const review = byPath.get(produced.path);
6999
7361
  if (review === void 0) {
7362
+ const diffs = [];
7363
+ appendMutation(diffs, produced.diffs, produced.seq);
7000
7364
  const created = {
7001
7365
  path: produced.path,
7002
- diffs: [...produced.diffs],
7366
+ diffs,
7003
7367
  ...produced.deleted === true ? { deleted: true } : {}
7004
7368
  };
7005
7369
  byPath.set(produced.path, created);
7006
7370
  reviews.push(created);
7007
7371
  } else {
7008
- review.diffs.push(...produced.diffs);
7372
+ appendMutation(review.diffs, produced.diffs, produced.seq);
7009
7373
  if (produced.deleted === true) review.deleted = true;
7010
7374
  else delete review.deleted;
7011
7375
  }