@dybai/dsh-editor 0.4.0 → 0.8.0

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/client.js CHANGED
@@ -507,6 +507,433 @@ window.__ModuleLoader__.load({
507
507
  return module.exports;
508
508
  })();
509
509
 
510
+ /* src/view-state.js */
511
+ const viewState = (function () {
512
+ var module = { exports: {} };
513
+ var exports = module.exports;
514
+ const { lineOfOffsetFast, offsetOfLine } = lines;
515
+
516
+ /**
517
+ * Pure view-state model for cursor/scroll restore. No DOM, no Host RPC: this
518
+ * module only defines the identity of a remembered view, validates the shapes
519
+ * persisted with it, and maps between machine selection offsets and the
520
+ * 1-based line/column positions stored in a record.
521
+ */
522
+
523
+
524
+ /**
525
+ * Normalize a path for key comparison: backslashes become slashes.
526
+ * @param {string} value
527
+ * @returns {string}
528
+ */
529
+ function normalizeSlashes(value) {
530
+ return value.replace(/\\/g, '/');
531
+ }
532
+
533
+ /**
534
+ * Trim trailing slashes, keeping `/` itself meaningful.
535
+ * @param {string} value
536
+ * @returns {string}
537
+ */
538
+ function trimTrailingSlashes(value) {
539
+ let end = value.length;
540
+ while (end > 1 && value[end - 1] === '/') end--;
541
+ return value.slice(0, end);
542
+ }
543
+
544
+ /**
545
+ * A path is absolute when it is POSIX-rooted, UNC, or drive-rooted.
546
+ * @param {string} value
547
+ * @returns {boolean}
548
+ */
549
+ function isAbsolutePath(value) {
550
+ return value.startsWith('/') || /^[A-Za-z]:\//.test(value);
551
+ }
552
+
553
+ /**
554
+ * The identity a remembered cursor/scroll is stored under: the workspace root
555
+ * plus the file path. Absolute paths are already self-identifying and win over
556
+ * `cwd`; a missing `cwd` falls back to the session (`session:<id>/<path>`).
557
+ * Windows drive and UNC keys are case-folded (their filesystems are
558
+ * case-insensitive); POSIX keys keep their case.
559
+ * @param {string | undefined} cwd
560
+ * @param {string | undefined} sessionId
561
+ * @param {string | undefined} path
562
+ * @returns {string | undefined}
563
+ */
564
+ function viewStateKey(cwd, sessionId, path) {
565
+ if (typeof path !== 'string') return undefined;
566
+ const normalizedPath = normalizeSlashes(path);
567
+ if (normalizedPath === '') return undefined;
568
+
569
+ let key;
570
+ if (isAbsolutePath(normalizedPath)) {
571
+ key = normalizedPath;
572
+ } else if (typeof cwd === 'string' && cwd !== '') {
573
+ const root = trimTrailingSlashes(normalizeSlashes(cwd));
574
+ key = root === '/' ? `/${normalizedPath}` : `${root}/${normalizedPath}`;
575
+ } else if (typeof sessionId === 'string' && sessionId !== '') {
576
+ key = `session:${sessionId}/${normalizedPath}`;
577
+ } else {
578
+ return undefined;
579
+ }
580
+
581
+ return /^[A-Za-z]:\//.test(key) || key.startsWith('//') ? key.toLowerCase() : key;
582
+ }
583
+
584
+ /**
585
+ * A 1-based document position: both `line` and `column` are integers `>= 1`.
586
+ * @param {unknown} value
587
+ * @returns {boolean}
588
+ */
589
+ function isPosition(value) {
590
+ return (
591
+ value !== null &&
592
+ typeof value === 'object' &&
593
+ !Array.isArray(value) &&
594
+ Number.isInteger(value.line) &&
595
+ value.line >= 1 &&
596
+ Number.isInteger(value.column) &&
597
+ value.column >= 1
598
+ );
599
+ }
600
+
601
+ /**
602
+ * A persisted selection: `null` (nothing to restore) or an ordered pair of
603
+ * positions (`start` is not after `end`).
604
+ * @param {unknown} value
605
+ * @returns {boolean}
606
+ */
607
+ function isSelectionRecord(value) {
608
+ if (value === null) return true;
609
+ if (value === undefined || typeof value !== 'object' || Array.isArray(value)) return false;
610
+ if (!isPosition(value.start) || !isPosition(value.end)) return false;
611
+ return (
612
+ value.start.line < value.end.line ||
613
+ (value.start.line === value.end.line && value.start.column <= value.end.column)
614
+ );
615
+ }
616
+
617
+ /**
618
+ * Convert a machine selection (`{ start, end, lineStart, lineEnd, text }`,
619
+ * offsets plus the lines those offsets fall on) into the persisted
620
+ * line/column record. Endpoints are reordered when the offsets run backwards.
621
+ * @param {string} draft
622
+ * @param {{ start: number, end: number, lineStart: number, lineEnd: number, text: string | null } | null} selection
623
+ * @returns {{ start: { line: number, column: number }, end: { line: number, column: number } } | null}
624
+ */
625
+ function selectionRecordFromSnapshot(draft, selection) {
626
+ if (typeof draft !== 'string') return null;
627
+ if (selection === null || typeof selection !== 'object') return null;
628
+ const { start, end, lineStart, lineEnd } = selection;
629
+ if (!Number.isInteger(start) || !Number.isInteger(end)) return null;
630
+ if (!Number.isInteger(lineStart) || lineStart < 1) return null;
631
+ if (!Number.isInteger(lineEnd) || lineEnd < 1) return null;
632
+
633
+ const at = (offset, line) => ({
634
+ line,
635
+ column: Math.max(1, offset - offsetOfLine(draft, line) + 1)
636
+ });
637
+ let startPosition = at(start, lineStart);
638
+ let endPosition = at(end, lineEnd);
639
+ if (
640
+ startPosition.line > endPosition.line ||
641
+ (startPosition.line === endPosition.line && startPosition.column > endPosition.column)
642
+ ) {
643
+ [startPosition, endPosition] = [endPosition, startPosition];
644
+ }
645
+ return { start: startPosition, end: endPosition };
646
+ }
647
+
648
+ /**
649
+ * Convert a persisted line/column selection back to machine offsets against the
650
+ * current text. Out-of-range lines and columns are clamped to the document, and
651
+ * reversed endpoints are normalized. The selected text is included only for a
652
+ * non-empty range. A `\r` is an ordinary character (not a line break).
653
+ * @param {string} text
654
+ * @param {{ start: { line: number, column: number }, end: { line: number, column: number } } | null} selection
655
+ * @returns {{ start: number, end: number, lineStart: number, lineEnd: number, text: string | null } | null}
656
+ */
657
+ function selectionFromViewState(text, selection) {
658
+ if (typeof text !== 'string' || selection === null || typeof selection !== 'object') return null;
659
+ // Endpoints may be reversed here: they are normalized below rather than rejected.
660
+ if (!isPosition(selection.start) || !isPosition(selection.end)) return null;
661
+
662
+ const lineCount = text.split('\n').length;
663
+ const offsetOf = (position) => {
664
+ const line = Math.min(Math.max(position.line, 1), lineCount);
665
+ const lineStart = offsetOfLine(text, line);
666
+ const newline = text.indexOf('\n', lineStart);
667
+ const contentLength = (newline === -1 ? text.length : newline) - lineStart;
668
+ const column = Math.min(Math.max(position.column, 1), contentLength + 1);
669
+ return lineStart + column - 1;
670
+ };
671
+
672
+ let start = offsetOf(selection.start);
673
+ let end = offsetOf(selection.end);
674
+ if (start > end) [start, end] = [end, start];
675
+ return {
676
+ start,
677
+ end,
678
+ lineStart: lineOfOffsetFast(text, start),
679
+ lineEnd: lineOfOffsetFast(text, end),
680
+ text: start === end ? null : text.slice(start, end)
681
+ };
682
+ }
683
+
684
+ /**
685
+ * Whether a pending scroll target can be applied now: the element must be
686
+ * attached, and a non-zero target on an axis needs that axis to have a size.
687
+ * @param {{ top: number, left: number } | null} pending
688
+ * @param {{ attached: boolean, clientHeight: number, clientWidth: number }} view
689
+ * @returns {boolean}
690
+ */
691
+ function canApplyScroll(pending, view) {
692
+ if (pending === null || typeof pending !== 'object') return false;
693
+ if (view === null || typeof view !== 'object' || view.attached !== true) return false;
694
+ if (!Number.isFinite(pending.top) || !Number.isFinite(pending.left)) return false;
695
+ if (pending.top > 0 && !(view.clientHeight > 0)) return false;
696
+ if (pending.left > 0 && !(view.clientWidth > 0)) return false;
697
+ return true;
698
+ }
699
+
700
+ /**
701
+ * Whether the element's actual scroll offset still differs from the desired
702
+ * one by more than `tolerance` pixels on either axis. A missing target (or a
703
+ * non-finite measurement) is not a difference to correct.
704
+ * @param {{ top: number, left: number }} actual
705
+ * @param {{ top: number, left: number } | null} desired
706
+ * @param {number} [tolerance]
707
+ * @returns {boolean}
708
+ */
709
+ function scrollDiffers(actual, desired, tolerance = 1) {
710
+ if (desired === null || typeof desired !== 'object') return false;
711
+ if (actual === null || typeof actual !== 'object') return false;
712
+ if (!Number.isFinite(actual.top) || !Number.isFinite(actual.left)) return false;
713
+ if (!Number.isFinite(desired.top) || !Number.isFinite(desired.left)) return false;
714
+ const limit = Number.isFinite(tolerance) ? tolerance : 1;
715
+ return Math.abs(actual.top - desired.top) > limit || Math.abs(actual.left - desired.left) > limit;
716
+ }
717
+
718
+ /**
719
+ * Whether a freshly loaded draft should apply its remembered view. A pending
720
+ * navigation (for example "go to line") owns the caret and suppresses the
721
+ * restore until a mode switch asks for the view back.
722
+ * @param {{ loaded: boolean, navigationLine: number | null, modeSwitched: boolean }} input
723
+ * @returns {boolean}
724
+ */
725
+ function shouldRestoreViewState(input) {
726
+ if (input === null || typeof input !== 'object') return false;
727
+ return (
728
+ input.loaded === true &&
729
+ (input.modeSwitched === true || input.navigationLine === null || input.navigationLine === undefined)
730
+ );
731
+ }
732
+
733
+ /**
734
+ * Whether the editor should take focus when it becomes ready. Restoring the
735
+ * caret without focus leaves the active-line bar visible while typing still
736
+ * goes to the previously focused element — the exact "caret looks restored
737
+ * but the editor is dead" symptom. Focus only when the editor is visible, is
738
+ * not already focused, and focus is not inside another text entry (the chat
739
+ * composer), so opening a file never steals keystrokes from a field the user
740
+ * is typing in.
741
+ * @param {{ attached: boolean, activeIsSelf: boolean, activeIsTextEntry: boolean } | null} input
742
+ * @returns {boolean}
743
+ */
744
+ function shouldFocusEditorOnOpen(input) {
745
+ if (input === null || typeof input !== 'object') return false;
746
+ return input.attached === true && input.activeIsSelf !== true && input.activeIsTextEntry !== true;
747
+ }
748
+
749
+ Object.assign(module.exports, { viewStateKey, isPosition, isSelectionRecord, selectionRecordFromSnapshot, selectionFromViewState, canApplyScroll, scrollDiffers, shouldRestoreViewState, shouldFocusEditorOnOpen });
750
+ return module.exports;
751
+ })();
752
+
753
+ /* src/view-state-store.js */
754
+ const viewStateStore = (function () {
755
+ var module = { exports: {} };
756
+ var exports = module.exports;
757
+ const { isSelectionRecord } = viewState;
758
+
759
+ /**
760
+ * View-state persistence over an injected storage adapter (never touches
761
+ * `window`). It mirrors `ViewState` records keyed by `viewStateKey` under a
762
+ * single storage key: `get`/`update` only touch the in-memory map and schedule
763
+ * a debounced write, `flush` writes immediately, and `prune` applies the
764
+ * 90-day expiry and 200-entry retention limits. Every storage failure is
765
+ * swallowed so the in-memory state stays authoritative and the next successful
766
+ * write repairs durability.
767
+ */
768
+
769
+
770
+ const VIEW_STATE_STORAGE_KEY = 'dsh-editor.view-state';
771
+ const MAX_ENTRIES = 200;
772
+ const EXPIRY_MS = 90 * 24 * 60 * 60 * 1000;
773
+
774
+ /**
775
+ * @typedef {{ start: { line: number, column: number }, end: { line: number, column: number } }} SelectionRecord
776
+ * @typedef {{ selection: SelectionRecord | null, scrollTop: number, scrollLeft: number, savedAt: number }} ViewState
777
+ */
778
+
779
+ /**
780
+ * A JSON-like object: non-null, not an array.
781
+ * @param {unknown} value
782
+ * @returns {boolean}
783
+ */
784
+ function isRecordObject(value) {
785
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
786
+ }
787
+
788
+ /**
789
+ * A scroll offset must be a finite number `>= 0`.
790
+ * @param {unknown} value
791
+ * @returns {boolean}
792
+ */
793
+ function isScrollOffset(value) {
794
+ return Number.isFinite(value) && value >= 0;
795
+ }
796
+
797
+ /**
798
+ * Copy a validated selection so callers cannot mutate the stored endpoints.
799
+ * @param {SelectionRecord | null} selection
800
+ * @returns {SelectionRecord | null}
801
+ */
802
+ function cloneSelection(selection) {
803
+ if (selection === null) return null;
804
+ return {
805
+ start: { line: selection.start.line, column: selection.start.column },
806
+ end: { line: selection.end.line, column: selection.end.column }
807
+ };
808
+ }
809
+
810
+ /**
811
+ * Normalize one stored value into a `ViewState`, or `undefined` when invalid.
812
+ * Missing `selection` means "nothing to restore"; missing scroll offsets mean
813
+ * "top-left"; `savedAt` is required.
814
+ * @param {unknown} value
815
+ * @returns {ViewState | undefined}
816
+ */
817
+ function normalizeViewState(value) {
818
+ if (!isRecordObject(value)) return undefined;
819
+ const selection = value.selection === undefined ? null : value.selection;
820
+ const scrollTop = value.scrollTop === undefined ? 0 : value.scrollTop;
821
+ const scrollLeft = value.scrollLeft === undefined ? 0 : value.scrollLeft;
822
+ if (!isSelectionRecord(selection)) return undefined;
823
+ if (!isScrollOffset(scrollTop) || !isScrollOffset(scrollLeft)) return undefined;
824
+ if (!Number.isFinite(value.savedAt)) return undefined;
825
+ return { selection: cloneSelection(selection), scrollTop, scrollLeft, savedAt: value.savedAt };
826
+ }
827
+
828
+ /**
829
+ * Create a view-state store over `storage`.
830
+ *
831
+ * State lives in an in-memory map mirroring the stored JSON map
832
+ * `viewStateKey -> ViewState`. `update` replaces only the provided fields and
833
+ * schedules a debounced persist; `get` returns a copy; `prune` drops entries
834
+ * expired at 90 days and all but the 200 most-recent (by `savedAt`). Every
835
+ * public method is total: bad arguments are ignored and storage failures are
836
+ * swallowed, leaving the in-memory state authoritative.
837
+ * @param {{ getItem(key: string): string | null, setItem(key: string, value: string): void, removeItem(key: string): void }} storage
838
+ * @param {() => number} [now] injectable clock, used for `savedAt` and expiry
839
+ * @param {number} [delay] debounce window in milliseconds
840
+ * @returns {{ get(key: string): ViewState | undefined, update(key: string, patch: { selection?: SelectionRecord | null, scrollTop?: number, scrollLeft?: number }): void, flush(): void, prune(): void }}
841
+ */
842
+ function createViewStateStore(storage, now = Date.now, delay = 500) {
843
+ const clock = typeof now === 'function' ? now : Date.now;
844
+ const delayMs = Number.isFinite(delay) && delay >= 0 ? delay : 500;
845
+ const entries = new Map(load());
846
+ let timer = null;
847
+
848
+ function load() {
849
+ try {
850
+ const raw = storage.getItem(VIEW_STATE_STORAGE_KEY);
851
+ if (typeof raw !== 'string' || raw === '') return [];
852
+ const parsed = JSON.parse(raw);
853
+ if (!isRecordObject(parsed)) return [];
854
+ const loaded = [];
855
+ for (const [key, value] of Object.entries(parsed)) {
856
+ const record = normalizeViewState(value);
857
+ if (record !== undefined) loaded.push([key, record]);
858
+ }
859
+ return loaded;
860
+ } catch {
861
+ return [];
862
+ }
863
+ }
864
+
865
+ function persist() {
866
+ timer = null;
867
+ try {
868
+ if (entries.size === 0) storage.removeItem(VIEW_STATE_STORAGE_KEY);
869
+ else storage.setItem(VIEW_STATE_STORAGE_KEY, JSON.stringify(Object.fromEntries(entries)));
870
+ } catch {
871
+ // Best-effort: a read-only, full, or absent storage keeps the in-memory
872
+ // state authoritative; the next successful write repairs durability.
873
+ }
874
+ }
875
+
876
+ function schedule() {
877
+ if (timer !== null) clearTimeout(timer);
878
+ timer = setTimeout(persist, delayMs);
879
+ }
880
+
881
+ return {
882
+ get(key) {
883
+ if (typeof key !== 'string') return undefined;
884
+ const record = entries.get(key);
885
+ if (record === undefined) return undefined;
886
+ return {
887
+ selection: cloneSelection(record.selection),
888
+ scrollTop: record.scrollTop,
889
+ scrollLeft: record.scrollLeft,
890
+ savedAt: record.savedAt
891
+ };
892
+ },
893
+ update(key, patch) {
894
+ if (typeof key !== 'string' || !isRecordObject(patch)) return;
895
+ const current = entries.get(key);
896
+ const next = current === undefined
897
+ ? { selection: null, scrollTop: 0, scrollLeft: 0 }
898
+ : { selection: current.selection, scrollTop: current.scrollTop, scrollLeft: current.scrollLeft };
899
+ if (Object.prototype.hasOwnProperty.call(patch, 'selection')) {
900
+ if (!isSelectionRecord(patch.selection)) return;
901
+ next.selection = cloneSelection(patch.selection);
902
+ }
903
+ if (Object.prototype.hasOwnProperty.call(patch, 'scrollTop')) {
904
+ if (!isScrollOffset(patch.scrollTop)) return;
905
+ next.scrollTop = patch.scrollTop;
906
+ }
907
+ if (Object.prototype.hasOwnProperty.call(patch, 'scrollLeft')) {
908
+ if (!isScrollOffset(patch.scrollLeft)) return;
909
+ next.scrollLeft = patch.scrollLeft;
910
+ }
911
+ next.savedAt = clock();
912
+ entries.set(key, next);
913
+ schedule();
914
+ },
915
+ flush() {
916
+ if (timer !== null) clearTimeout(timer);
917
+ persist();
918
+ },
919
+ prune() {
920
+ const current = clock();
921
+ const kept = [...entries]
922
+ .filter(([, record]) => current - record.savedAt < EXPIRY_MS)
923
+ .sort((a, b) => b[1].savedAt - a[1].savedAt)
924
+ .slice(0, MAX_ENTRIES);
925
+ entries.clear();
926
+ for (const [key, record] of kept) entries.set(key, record);
927
+ if (timer !== null) clearTimeout(timer);
928
+ persist();
929
+ }
930
+ };
931
+ }
932
+
933
+ Object.assign(module.exports, { VIEW_STATE_STORAGE_KEY, createViewStateStore });
934
+ return module.exports;
935
+ })();
936
+
510
937
  /* src/service.js */
511
938
  const service = (function () {
512
939
  var module = { exports: {} };
@@ -920,6 +1347,119 @@ window.__ModuleLoader__.load({
920
1347
  return module.exports;
921
1348
  })();
922
1349
 
1350
+ /* src/line-numbers.js */
1351
+ const lineNumbers = (function () {
1352
+ var module = { exports: {} };
1353
+ var exports = module.exports;
1354
+ /**
1355
+ * Line-number gutter math — the pure model behind the editor's
1356
+ * "show line numbers beside the content" affordance.
1357
+ *
1358
+ * Three functions, no DOM:
1359
+ *
1360
+ * - `lineNumbersText(lineCount)` — the gutter's whole content as ONE text
1361
+ * block (`"1\n2\n…\nN"`), rendered into a pre-styled element whose
1362
+ * line-height matches the textarea's. Valid only because the plain-text
1363
+ * textarea never wraps (`wrap: 'off'` + `white-space: pre`), so logical
1364
+ * line k sits exactly k lineHeights down — the same precondition as
1365
+ * src/active-line.js.
1366
+ * - `lineNumberDigits(lineCount)` — the widest number's digit count, clamped
1367
+ * to the minimum 2-column gutter so a one-line file doesn't jump width.
1368
+ * - `gutterWidthCh(lineCount)` — the gutter's total width in `ch` units
1369
+ * (digits + the inter-column gap), the number the DOM layer applies to
1370
+ * both the gutter element and the textarea's extra `padding-left`. `ch`
1371
+ * is exact here: the editor area is monospace, so one ch is one digit.
1372
+ *
1373
+ * All three normalize defensively (floor fractional counts, clamp to ≥ 1,
1374
+ * degrade invalid input to the one-line / two-column minimum) so the DOM
1375
+ * layer can pipe untrusted values straight in — malformed input can never
1376
+ * crash or shrink the editor.
1377
+ *
1378
+ * Zero imports: pure functions only, unit-testable without DOM.
1379
+ *
1380
+ * @module @dybai/dsh-editor/line-numbers
1381
+ */
1382
+
1383
+ /** Gap between the numbers and the boundary rule, in `ch` units. MUST stay
1384
+ * in sync with `.dsh-editor-gutter-text`'s `padding-right` (src/client-entry.js
1385
+ * STYLES) — the CSS value positions the digits inside the gutter, this value
1386
+ * places the rule. */
1387
+ const GUTTER_GAP_CH = 1.5;
1388
+
1389
+ /** Gap between the boundary rule and the first content column, in `ch`
1390
+ * units. The textarea's `padding-left` exceeds the gutter width by exactly
1391
+ * this amount, so the content keeps its distance from the rule — and the
1392
+ * opaque gutter covers the whole band, so horizontally-scrolled glyphs can
1393
+ * never touch it. */
1394
+ const CONTENT_GAP_CH = 2;
1395
+
1396
+ /** Minimum gutter columns so a short file keeps a stable width. */
1397
+ const MIN_DIGITS = 2;
1398
+
1399
+ /**
1400
+ * Normalize a line count into a usable integer (≥ 1); anything invalid
1401
+ * degrades to 1.
1402
+ * @param {any} lineCount - the caller's count (usually the draft's line total).
1403
+ * @returns {number} a positive integer.
1404
+ */
1405
+ function normalizedLineCount(lineCount) {
1406
+ const count = typeof lineCount === 'number' && Number.isFinite(lineCount) ? Math.floor(lineCount) : 1;
1407
+ return count >= 1 ? count : 1;
1408
+ }
1409
+
1410
+ /**
1411
+ * The gutter's content: one number per line, 1 through N.
1412
+ * @param {any} lineCount - the draft's line total (invalid degrades to 1).
1413
+ * @returns {string} the text block for the pre-styled gutter element.
1414
+ */
1415
+ function lineNumbersText(lineCount) {
1416
+ const count = normalizedLineCount(lineCount);
1417
+ if (count === 1) return '1';
1418
+ const numbers = new Array(count);
1419
+ for (let index = 0; index < count; index += 1) numbers[index] = String(index + 1);
1420
+ return numbers.join('\n');
1421
+ }
1422
+
1423
+ /**
1424
+ * The widest number's digit count, clamped to the two-column minimum.
1425
+ * @param {any} lineCount - the draft's line total (invalid degrades to 1).
1426
+ * @returns {number} columns, at least 2.
1427
+ */
1428
+ function lineNumberDigits(lineCount) {
1429
+ const count = normalizedLineCount(lineCount);
1430
+ return Math.max(MIN_DIGITS, String(count).length);
1431
+ }
1432
+
1433
+ /**
1434
+ * The gutter's width in `ch` units: the digit columns plus the
1435
+ * numbers-to-rule gap. The DOM layer places the boundary rule at this exact
1436
+ * offset inside the (wider) gutter band — the rule does NOT sit at the
1437
+ * band's right edge.
1438
+ * @param {any} lineCount - the draft's line total (invalid degrades to 1).
1439
+ * @returns {number} the width in ch units.
1440
+ */
1441
+ function gutterWidthCh(lineCount) {
1442
+ return lineNumberDigits(lineCount) + GUTTER_GAP_CH;
1443
+ }
1444
+
1445
+ /**
1446
+ * The whole reserved band's width in `ch` units — the textarea's matching
1447
+ * `padding-left`, and the gutter element's width: digit columns plus BOTH
1448
+ * gaps (numbers-to-rule and rule-to-content). Exceeding `gutterWidthCh` by
1449
+ * the rule-to-content gap is what keeps the content away from the rule; the
1450
+ * DOM layer applies this to BOTH the gutter element and the textarea so the
1451
+ * opaque band covers every pixel of the reservation.
1452
+ * @param {any} lineCount - the draft's line total (invalid degrades to 1).
1453
+ * @returns {number} the width in ch units.
1454
+ */
1455
+ function contentPaddingCh(lineCount) {
1456
+ return lineNumberDigits(lineCount) + GUTTER_GAP_CH + CONTENT_GAP_CH;
1457
+ }
1458
+
1459
+ Object.assign(module.exports, { lineNumbersText, lineNumberDigits, gutterWidthCh, contentPaddingCh });
1460
+ return module.exports;
1461
+ })();
1462
+
923
1463
  /* src/tab-machine.js */
924
1464
  const tabMachine = (function () {
925
1465
  var module = { exports: {} };
@@ -1749,8 +2289,9 @@ window.__ModuleLoader__.load({
1749
2289
  /**
1750
2290
  * Framework self-managed keymap — pure key-combo model (spec §6).
1751
2291
  *
1752
- * The three editor actions save / saveAll / deleteLines are NOT registered
1753
- * through `ctx.shortcuts` (whose web runtime whitelists browser-owned combos
2292
+ * The framework actions save / saveAll / deleteLines / gotoLine are NOT
2293
+ * registered through `ctx.shortcuts` (whose web runtime whitelists
2294
+ * browser-owned combos
1754
2295
  * away from page-level defaults). Instead the editor tab's ROOT element
1755
2296
  * intercepts keydown and calls `preventDefault()` itself — a page-level
1756
2297
  * preventDefault works for ANY combination, so the natural keys
@@ -1773,7 +2314,7 @@ window.__ModuleLoader__.load({
1773
2314
  */
1774
2315
 
1775
2316
  /** The framework actions owned by the self-managed keymap channel. */
1776
- const KEYMAP_ACTIONS = ['save', 'saveAll', 'deleteLines'];
2317
+ const KEYMAP_ACTIONS = ['save', 'saveAll', 'deleteLines', 'gotoLine'];
1777
2318
 
1778
2319
  /** Storable `KeyboardEvent.code` alphabet: letters and digits only. */
1779
2320
  const CODE_RE = /^(Key[A-Z]|Digit[0-9])$/;
@@ -1782,33 +2323,30 @@ window.__ModuleLoader__.load({
1782
2323
  const ALLOWED_MODIFIERS = ['primary', 'control', 'alt', 'shift', 'meta'];
1783
2324
 
1784
2325
  /**
1785
- * The built-in keymap: Ctrl+S / Ctrl+Shift+S / Ctrl+D.
2326
+ * The built-in keymap: Ctrl+S / Ctrl+Shift+S / Ctrl+D / Ctrl+G (v0.6.0).
1786
2327
  * @returns a fresh keymap object (callers may mutate their copy).
1787
2328
  */
1788
2329
  function defaultKeymap() {
1789
2330
  return {
1790
2331
  save: { code: 'KeyS', modifiers: ['primary'] },
1791
2332
  saveAll: { code: 'KeyS', modifiers: ['primary', 'shift'] },
1792
- deleteLines: { code: 'KeyD', modifiers: ['primary'] }
2333
+ deleteLines: { code: 'KeyD', modifiers: ['primary'] },
2334
+ gotoLine: { code: 'KeyG', modifiers: ['primary'] }
1793
2335
  };
1794
2336
  }
1795
2337
 
1796
2338
  /**
1797
- * Validate and normalize a keymap.
1798
- *
1799
- * Accepts either shape:
1800
- * - the object form `{ save: {code, modifiers}, … }` (one entry per action);
1801
- * - the wire form `[{ action, code, modifiers }]` (`dshEditor/getKeymap`
1802
- * records, any subset order).
1803
- *
1804
- * Rules: all three actions present, `code` from the storable alphabet,
1805
- * `modifiers` an array within the allowed vocabulary, and no two actions
1806
- * sharing one (code, modifier-set) combination.
2339
+ * The shared entry-validation walk behind `normalizeKeymap` and
2340
+ * `completeKeymap`: accept either shape (object or wire form), validate
2341
+ * every entry — known action, `code` from the storable alphabet,
2342
+ * `modifiers` within the allowed vocabulary, no duplicate action, no two
2343
+ * entries sharing one (code, modifier-set) combination — and collect the
2344
+ * ADOPTED partial map with its taken-combo set.
1807
2345
  * @param {any} raw
1808
- * @returns `{ save, saveAll, deleteLines }` with copied modifier arrays, or
1809
- * `undefined` when anything is invalid.
2346
+ * @returns {{ adopted: object, taken: Set<string> }} or `undefined` when
2347
+ * anything is structurally invalid.
1810
2348
  */
1811
- function normalizeKeymap(raw) {
2349
+ function adoptEntries(raw) {
1812
2350
  if (raw === null || typeof raw !== 'object') return undefined;
1813
2351
  let entries;
1814
2352
  if (Array.isArray(raw)) {
@@ -1818,13 +2356,13 @@ window.__ModuleLoader__.load({
1818
2356
  raw[action] === null || typeof raw[action] !== 'object' ? null : { action, ...raw[action] }
1819
2357
  );
1820
2358
  }
1821
- const normalized = {};
1822
- const combos = new Set();
2359
+ const adopted = {};
2360
+ const taken = new Set();
1823
2361
  for (const entry of entries) {
1824
2362
  if (entry === null || typeof entry !== 'object') return undefined;
1825
2363
  const { action, code, modifiers } = entry;
1826
2364
  if (typeof action !== 'string' || !KEYMAP_ACTIONS.includes(action)) return undefined;
1827
- if (Object.prototype.hasOwnProperty.call(normalized, action)) return undefined; // duplicate action
2365
+ if (Object.prototype.hasOwnProperty.call(adopted, action)) return undefined; // duplicate action
1828
2366
  if (typeof code !== 'string' || !CODE_RE.test(code)) return undefined;
1829
2367
  if (!Array.isArray(modifiers)) return undefined;
1830
2368
  const set = [];
@@ -1833,14 +2371,81 @@ window.__ModuleLoader__.load({
1833
2371
  if (!set.includes(modifier)) set.push(modifier);
1834
2372
  }
1835
2373
  const combo = `${code}|${[...set].sort().join('+')}`;
1836
- if (combos.has(combo)) return undefined; // duplicate combination
1837
- combos.add(combo);
1838
- normalized[action] = { code, modifiers: set };
2374
+ if (taken.has(combo)) return undefined; // duplicate combination
2375
+ taken.add(combo);
2376
+ adopted[action] = { code, modifiers: set };
1839
2377
  }
2378
+ return { adopted, taken };
2379
+ }
2380
+
2381
+ /**
2382
+ * Validate and normalize a COMPLETE keymap.
2383
+ *
2384
+ * Accepts either shape:
2385
+ * - the object form `{ save: {code, modifiers}, … }` (one entry per action);
2386
+ * - the wire form `[{ action, code, modifiers }]` (`dshEditor/getKeymap`
2387
+ * records, any subset order).
2388
+ *
2389
+ * Rules: every framework action present, `code` from the storable alphabet,
2390
+ * `modifiers` an array within the allowed vocabulary, and no two actions
2391
+ * sharing one (code, modifier-set) combination.
2392
+ * @param {any} raw
2393
+ * @returns the complete keymap with copied modifier arrays, or
2394
+ * `undefined` when anything is invalid (including a missing action —
2395
+ * use `completeKeymap` when partial stores must be migrated).
2396
+ */
2397
+ function normalizeKeymap(raw) {
2398
+ const walk = adoptEntries(raw);
2399
+ if (walk === undefined) return undefined;
1840
2400
  for (const action of KEYMAP_ACTIONS) {
1841
- if (normalized[action] === undefined) return undefined; // action missing
2401
+ if (walk.adopted[action] === undefined) return undefined; // action missing
1842
2402
  }
1843
- return normalized;
2403
+ return walk.adopted;
2404
+ }
2405
+
2406
+ /**
2407
+ * The candidate bindings a MISSING action is filled with, in order: the
2408
+ * action's default binding, then default+shift, then default+alt (for
2409
+ * `gotoLine`: Ctrl+G → Ctrl+Shift+G → Ctrl+Alt+G). For defaults that
2410
+ * already carry shift/alt a later candidate can repeat an earlier combo —
2411
+ * harmless, the walk always prefers the first free candidate.
2412
+ * @param {{ code: string, modifiers: string[] }} defaultBinding
2413
+ * @returns {{ code: string, modifiers: string[] }[]}
2414
+ */
2415
+ function fillCandidates(defaultBinding) {
2416
+ const { code, modifiers } = defaultBinding;
2417
+ const candidates = [defaultBinding];
2418
+ if (!modifiers.includes('shift')) candidates.push({ code, modifiers: [...modifiers, 'shift'] });
2419
+ if (!modifiers.includes('alt')) candidates.push({ code, modifiers: [...modifiers, 'alt'] });
2420
+ return candidates;
2421
+ }
2422
+
2423
+ /**
2424
+ * Migrate a PARTIAL persisted keymap (v0.6.0): the same entry validation as
2425
+ * `normalizeKeymap`, but completeness is REPAIRED instead of required —
2426
+ * missing actions (a pre-0.6 store predates `gotoLine`) are filled from
2427
+ * default-first candidates that stay collision-free with the adopted
2428
+ * records. When every candidate of some action collides, the WHOLE
2429
+ * migration is rejected (`undefined`) so the caller keeps its complete
2430
+ * fallback cache instead of ever holding an incomplete map.
2431
+ * @param {any} raw - a possibly-incomplete keymap (object or wire form).
2432
+ * @returns a complete normalized keymap, or `undefined` when the records
2433
+ * are structurally invalid or the fill is impossible.
2434
+ */
2435
+ function completeKeymap(raw) {
2436
+ const walk = adoptEntries(raw);
2437
+ if (walk === undefined) return undefined;
2438
+ const completed = walk.adopted;
2439
+ for (const action of KEYMAP_ACTIONS) {
2440
+ if (completed[action] !== undefined) continue;
2441
+ const binding = fillCandidates(defaultKeymap()[action]).find(
2442
+ (candidate) => !walk.taken.has(`${candidate.code}|${[...candidate.modifiers].sort().join('+')}`)
2443
+ );
2444
+ if (binding === undefined) return undefined;
2445
+ completed[action] = { code: binding.code, modifiers: binding.modifiers.slice() };
2446
+ walk.taken.add(`${completed[action].code}|${[...completed[action].modifiers].sort().join('+')}`);
2447
+ }
2448
+ return completed;
1844
2449
  }
1845
2450
 
1846
2451
  /**
@@ -1990,7 +2595,58 @@ window.__ModuleLoader__.load({
1990
2595
  }));
1991
2596
  }
1992
2597
 
1993
- Object.assign(module.exports, { KEYMAP_ACTIONS, defaultKeymap, normalizeKeymap, comboOf, matchAction, bindingsForDisplay, isReservedCombo, bindingsOfKeymap });
2598
+ Object.assign(module.exports, { KEYMAP_ACTIONS, defaultKeymap, normalizeKeymap, completeKeymap, comboOf, matchAction, bindingsForDisplay, isReservedCombo, bindingsOfKeymap });
2599
+ return module.exports;
2600
+ })();
2601
+
2602
+ /* src/goto-line.js */
2603
+ const gotoLine = (function () {
2604
+ var module = { exports: {} };
2605
+ var exports = module.exports;
2606
+ /**
2607
+ * Go-to-line input model — the pure parser behind the jump popover (v0.6.0).
2608
+ *
2609
+ * One function: `parseGotoLine(raw, lineCount)` turns the popover's input
2610
+ * into a concrete 1-based target line, or rejects it. VALID numbers are
2611
+ * CLAMPED into `[1, lineCount]` (out-of-range input jumps to the nearest
2612
+ * existing line instead of erroring — the dominant editor convention);
2613
+ * empty, non-numeric and non-finite input is rejected so Enter on an empty
2614
+ * field never jumps.
2615
+ *
2616
+ * Zero imports: pure functions only, unit-testable without DOM.
2617
+ *
2618
+ * @module @dybai/dsh-editor/goto-line
2619
+ */
2620
+
2621
+ /**
2622
+ * Parse a go-to-line input into a concrete 1-based target line.
2623
+ *
2624
+ * Accepts a string (the input field's value — surrounding whitespace is
2625
+ * tolerated, an empty/whitespace-only value is NOT) or a number. Fractional
2626
+ * values floor, the same semantics the navigation path applies downstream.
2627
+ * @param {string|number} raw - the input value.
2628
+ * @param {number} lineCount - the draft's line total (`>= 1`; garbage rejects).
2629
+ * @returns {{ ok: true, line: number } | { ok: false }} `line` clamped to
2630
+ * `[1, lineCount]`.
2631
+ */
2632
+ function parseGotoLine(raw, lineCount) {
2633
+ let asNumber;
2634
+ if (typeof raw === 'number') {
2635
+ asNumber = raw;
2636
+ } else if (typeof raw === 'string') {
2637
+ const trimmed = raw.trim();
2638
+ if (trimmed.length === 0) return { ok: false }; // Number('') is 0 — never jump on empty
2639
+ asNumber = Number(trimmed);
2640
+ } else {
2641
+ return { ok: false };
2642
+ }
2643
+ if (!Number.isFinite(asNumber)) return { ok: false };
2644
+ if (typeof lineCount !== 'number' || !Number.isFinite(lineCount) || lineCount < 1) return { ok: false };
2645
+ const line = Math.min(Math.max(Math.floor(asNumber), 1), lineCount);
2646
+ return { ok: true, line };
2647
+ }
2648
+
2649
+ Object.assign(module.exports, { parseGotoLine });
1994
2650
  return module.exports;
1995
2651
  })();
1996
2652
 
@@ -2000,11 +2656,14 @@ window.__ModuleLoader__.load({
2000
2656
  var exports = module.exports;
2001
2657
  const { basenameOf, isEditablePath, parseFileAddress } = address;
2002
2658
  const { activeLineBar, lineHeightPxOf } = activeLine;
2659
+ const { gutterWidthCh, contentPaddingCh, lineNumbersText } = lineNumbers;
2003
2660
  const { lineOfOffset, lineOfOffsetFast, caretOffsetOfSelection, offsetOfLine } = lines;
2004
2661
  const { createTabController } = tabMachine;
2005
2662
  const { createDiskWatch } = diskWatch;
2006
2663
  const { resolveModeId } = ranking;
2007
2664
  const { matchAction, comboOf, normalizeKeymap, defaultKeymap, isReservedCombo } = keymap;
2665
+ const { parseGotoLine } = gotoLine;
2666
+ const { canApplyScroll, scrollDiffers, selectionFromViewState, selectionRecordFromSnapshot, shouldFocusEditorOnOpen, shouldRestoreViewState, viewStateKey } = viewState;
2008
2667
 
2009
2668
  /**
2010
2669
  * Editor framework UI components — the browser half's React layer.
@@ -2032,8 +2691,8 @@ window.__ModuleLoader__.load({
2032
2691
  * - `KeymapPopover` — the status-bar keyboard button's panel: record /
2033
2692
  * restore-default for the three self-managed bindings (spec §6).
2034
2693
  * - `SettingsPopover` — the status-bar gear button's panel: the behavior
2035
- * toggles (v0.3 `autoReloadClean`, v0.4 `highlightActiveLine`), persisted
2036
- * via `dshEditor/get|setSettings`.
2694
+ * toggles (v0.3 `autoReloadClean`, v0.4 `highlightActiveLine`, v0.5
2695
+ * `showLineNumbers`), persisted via `dshEditor/get|setSettings`.
2037
2696
  * - `EditorTabTitle` — the `sidebar.right.pane.tab.title` occupant: paints
2038
2697
  * the tab's file name red + strikethrough while the file is externally
2039
2698
  * deleted.
@@ -2173,7 +2832,9 @@ window.__ModuleLoader__.load({
2173
2832
 
2174
2833
  /**
2175
2834
  * Keep one broken render from silently deleting the editor: the boundary logs
2176
- * the failure and drops only the body it guards.
2835
+ * the failure through the injected persistent channel (the `log` prop
2836
+ * createEditorComponents threads in, scope 'render') and drops only the body
2837
+ * it guards.
2177
2838
  */
2178
2839
  const EditorBoundary =
2179
2840
  typeof React.Component === 'function'
@@ -2186,7 +2847,11 @@ window.__ModuleLoader__.load({
2186
2847
  return { failed: true };
2187
2848
  }
2188
2849
  componentDidCatch(error) {
2189
- console.error('[dsh-editor] editor body render failed:', error);
2850
+ try {
2851
+ this.props.log?.error('render', 'editor body render failed:', error);
2852
+ } catch {
2853
+ // the boundary itself must never throw
2854
+ }
2190
2855
  }
2191
2856
  render() {
2192
2857
  return this.state.failed ? null : this.props.children;
@@ -2247,7 +2912,7 @@ window.__ModuleLoader__.load({
2247
2912
 
2248
2913
  /**
2249
2914
  * The built-in `plain-text` mode: one controlled textarea over an
2250
- * active-line highlight backdrop.
2915
+ * active-line highlight backdrop and a line-number gutter.
2251
2916
  *
2252
2917
  * Obligations (spec §5.5): renders the draft, reports edits via
2253
2918
  * `controller.applyEdit` and selections via `controller.applySelection`
@@ -2256,6 +2921,13 @@ window.__ModuleLoader__.load({
2256
2921
  * mirrors machine-written selections (framework `setContent` commands) into
2257
2922
  * the DOM. Never reads or writes files itself.
2258
2923
  *
2924
+ * View-state adapter (0.8.0): `initialScroll` (`{ top, left }` or null) is a
2925
+ * one-shot restore target applied once the textarea is attached and sized;
2926
+ * `onScrollChange` reports the offsets a visible, loaded textarea actually
2927
+ * reaches (user scroll and navigation). Both are optional and absent-safe:
2928
+ * without them the mode behaves exactly as before, apart from healing a
2929
+ * scroll offset a hidden subtree discarded.
2930
+ *
2259
2931
  * Active-line highlight (0.4.0, the `highlightActiveLine` preference): the
2260
2932
  * textarea renders transparent over a backdrop layer that marks the caret
2261
2933
  * line with top/bottom hairlines (VS Code-style line border; a multi-line
@@ -2268,10 +2940,35 @@ window.__ModuleLoader__.load({
2268
2940
  * the React effect fallback are the only other writers. The mark stays
2269
2941
  * visible without focus: it shows where the caret is, not where the
2270
2942
  * keyboard is.
2943
+ *
2944
+ * Line-number gutter (0.5.0, the `showLineNumbers` preference): an
2945
+ * absolutely-positioned band beside the content carrying a 1px gray hairline
2946
+ * (the boundary rule, ALWAYS painted) and — while the preference is on — ONE
2947
+ * text block (`1\n2\n…\nN`, src/line-numbers.js) whose line-height and top
2948
+ * padding match the textarea's (exact for the same no-wrap reason the
2949
+ * highlight is). Geometry, in exact `ch` of the shared monospace font:
2950
+ * [digits] --1.5ch--> [rule] --2ch--> [content]. The band spans the whole
2951
+ * reservation and the textarea's matching `padding-left` never changes with
2952
+ * the preference, so toggling shows/hides ONLY the numbers — the rule, the
2953
+ * band and the content position are constant. The band paints above BOTH
2954
+ * the highlight backdrop and the overlay textarea (z-index 2 vs 1 — with
2955
+ * wrap:'off' a horizontal scroll would otherwise sweep glyphs across it),
2956
+ * and ignores pointer events (clicks fall through to the textarea); the
2957
+ * text block follows vertical scroll by translating against `scrollTop` in
2958
+ * the same onScroll handler the highlight uses. Width tracks the widest
2959
+ * line number so crossing a power of ten reflows once, not per keystroke
2960
+ * (the text block memoizes on the line count).
2271
2961
  */
2272
2962
  function PlainTextMode(props) {
2273
2963
  const controller = props.controller;
2274
2964
  const highlightEnabled = props.highlightActiveLine !== false;
2965
+ const gutterEnabled = props.showLineNumbers !== false;
2966
+ // View-state adapter (0.8.0): the one-shot restore target and the reporter
2967
+ // for the offset a user actually reached. `undefined` means "no restore",
2968
+ // exactly like `null`; the reporter is optional and type-guarded at every
2969
+ // call site so third-party modes are unaffected.
2970
+ const initialScroll = props.initialScroll === undefined ? null : props.initialScroll;
2971
+ const onScrollChange = props.onScrollChange;
2275
2972
  const state = useControllerState(controller);
2276
2973
  // Attached to the textarea below — the single DOM handle every selection
2277
2974
  // path reads (reportSelection, onNavigate, the mirror effect, and the
@@ -2282,6 +2979,44 @@ window.__ModuleLoader__.load({
2282
2979
  const areaRef = React.useRef(null);
2283
2980
  const barRef = React.useRef(null);
2284
2981
  const metricsRef = React.useRef(null);
2982
+ // Gutter scroll sync: the inner text block translates against scrollTop.
2983
+ const gutterTextRef = React.useRef(null);
2984
+ // View-state scroll restoration. `pendingScrollRef` holds the target until
2985
+ // the textarea can accept it (attached and, for a non-zero axis, sized);
2986
+ // `scrollRestoreConsumedRef` makes `initialScroll` one-shot per mount;
2987
+ // `lastVisibleScrollRef` is the last offset a MEASURED, loaded textarea
2988
+ // reported (heal source); `wasMeasurableRef` detects the first measurable
2989
+ // ResizeObserver notification after a non-measurable one (a hidden subtree
2990
+ // can discard scrollTop silently).
2991
+ const pendingScrollRef = React.useRef(null);
2992
+ const scrollRestoreConsumedRef = React.useRef(false);
2993
+ const lastVisibleScrollRef = React.useRef(null);
2994
+ const wasMeasurableRef = React.useRef(false);
2995
+
2996
+ // The gutter's content and width, re-derived only when the line total
2997
+ // actually changes — typing within a line (the common keystroke) reuses
2998
+ // the memoized text block even on a 100k-line draft.
2999
+ // The reservation is CONSTANT: both widths derive from the line total
3000
+ // whether or not the gutter renders, and the textarea keeps its matching
3001
+ // padding-left either way — toggling the preference never shifts the
3002
+ // content sideways; only the numbers and the boundary rule appear/disappear.
3003
+ // Geometry: [digits] --1.5ch--> [rule] --2ch--> [content]; the gutter band
3004
+ // spans the WHOLE reservation (digits + both gaps) so its opaque
3005
+ // background also covers the rule-to-content strip against glyph sweeps.
3006
+ const lineCount = state.draft.length === 0 ? 1 : state.draft.split('\n').length;
3007
+ const gutterText = React.useMemo(() => (gutterEnabled ? lineNumbersText(lineCount) : ''), [gutterEnabled, lineCount]);
3008
+ const ruleOffset = gutterWidthCh(lineCount);
3009
+ const bandWidth = contentPaddingCh(lineCount);
3010
+
3011
+ // Vertical scroll sync for the gutter: translate the text block against
3012
+ // the textarea's scrollTop. Same trigger points as the highlight's scroll
3013
+ // handling — one onScroll handler drives both.
3014
+ const syncGutter = React.useCallback(() => {
3015
+ const area = areaRef.current;
3016
+ const text = gutterTextRef.current;
3017
+ if (area === null || text === null) return;
3018
+ text.style.transform = `translateY(${-area.scrollTop}px)`;
3019
+ }, []);
2285
3020
 
2286
3021
  // Measure the textarea's highlight geometry, at most once per rendered
2287
3022
  // mount. Every input is a computed value (rendering-independent — the
@@ -2377,12 +3112,65 @@ window.__ModuleLoader__.load({
2377
3112
  paintCaretLine();
2378
3113
  }, [controller, paintCaretLine]);
2379
3114
 
3115
+ // Apply the pending restore target as soon as the textarea can take it.
3116
+ // `canApplyScroll` is the tested Task-1 decision: the area must be attached,
3117
+ // and a non-zero target on an axis needs that axis to have a size. A hidden
3118
+ // textarea simply keeps the target pending — the phase/draft layout effect
3119
+ // and the ResizeObserver retry. The browser clamps writes, so the value
3120
+ // remembered as visible is the ACTUAL post-write offset, never the request.
3121
+ const applyPendingScroll = React.useCallback(() => {
3122
+ // Short-circuit BEFORE any layout read: this runs on every draft commit,
3123
+ // and the common case (no restore pending) must not force a reflow.
3124
+ const pending = pendingScrollRef.current;
3125
+ if (pending === null) return;
3126
+ const area = areaRef.current;
3127
+ if (area === null) return;
3128
+ const view = {
3129
+ attached: area.offsetParent !== null,
3130
+ clientHeight: area.clientHeight,
3131
+ clientWidth: area.clientWidth
3132
+ };
3133
+ if (!canApplyScroll(pending, view)) return;
3134
+ area.scrollTop = pending.top;
3135
+ area.scrollLeft = pending.left;
3136
+ lastVisibleScrollRef.current = { top: area.scrollTop, left: area.scrollLeft };
3137
+ pendingScrollRef.current = null;
3138
+ }, []);
3139
+
3140
+ // A hidden subtree can discard scrollTop WITHOUT firing a scroll event, so
3141
+ // the first measurable ResizeObserver notification after a non-measurable
3142
+ // one is the only chance to put the last visible offset back. Without a
3143
+ // remembered offset (nothing scrolled yet, or a never-measured mount) there
3144
+ // is nothing to heal.
3145
+ const healScrollOnReveal = React.useCallback(() => {
3146
+ const area = areaRef.current;
3147
+ if (area === null) return;
3148
+ const measurable = area.offsetParent !== null && (area.clientHeight > 0 || area.clientWidth > 0);
3149
+ if (!measurable) {
3150
+ wasMeasurableRef.current = false;
3151
+ return;
3152
+ }
3153
+ if (wasMeasurableRef.current) return;
3154
+ wasMeasurableRef.current = true;
3155
+ const actual = { top: area.scrollTop, left: area.scrollLeft };
3156
+ const lastVisible = lastVisibleScrollRef.current;
3157
+ if (lastVisible === null || !scrollDiffers(actual, lastVisible)) return;
3158
+ area.scrollTop = lastVisible.top;
3159
+ area.scrollLeft = lastVisible.left;
3160
+ }, []);
3161
+
2380
3162
  // The latest sync for passive observers — the ResizeObserver below must
2381
- // not be torn down and rebuilt on every selection change.
3163
+ // not be torn down and rebuilt on every selection change. One sync for
3164
+ // both paint surfaces: the caret-line bar AND the gutter's scroll
3165
+ // translation (a hidden subtree can discard scrollTop without firing a
3166
+ // scroll event on re-show — the observer retry must heal the gutter too).
2382
3167
  const syncRef = React.useRef(paintCaretLine);
2383
3168
  React.useEffect(() => {
2384
- syncRef.current = paintCaretLine;
2385
- }, [paintCaretLine]);
3169
+ syncRef.current = () => {
3170
+ paintCaretLine();
3171
+ syncGutter();
3172
+ };
3173
+ }, [paintCaretLine, syncGutter]);
2386
3174
 
2387
3175
  // Reposition in the LAYOUT phase on mount/toggle only. Deliberately NOT
2388
3176
  // re-keyed on machine selection publishes: state.selection is normalized
@@ -2397,6 +3185,48 @@ window.__ModuleLoader__.load({
2397
3185
  paintCaretLine();
2398
3186
  }, [highlightEnabled, paintCaretLine]);
2399
3187
 
3188
+ // The gutter mounts (or re-mounts on toggle-on) against a possibly
3189
+ // already-scrolled textarea: land its transform on the CURRENT scrollTop
3190
+ // in the layout phase, before the first paint shows stale numbers.
3191
+ useLayoutEffectSafe(() => {
3192
+ if (!gutterEnabled) return;
3193
+ syncGutter();
3194
+ }, [gutterEnabled, syncGutter]);
3195
+
3196
+ // One-shot view-state restore. The target is consumed exactly once per
3197
+ // mount and then held in the ref until the textarea can accept it; a late
3198
+ // `initialScroll` can never override an explicit navigation because
3199
+ // `onNavigate` consumes and clears it before moving the caret. Layout
3200
+ // phase: the textarea's value is already committed, so a hidden mount
3201
+ // leaves the target pending for the phase/draft effect or the observer.
3202
+ useLayoutEffectSafe(() => {
3203
+ if (initialScroll === null || scrollRestoreConsumedRef.current) return;
3204
+ scrollRestoreConsumedRef.current = true;
3205
+ pendingScrollRef.current = { top: initialScroll.top, left: initialScroll.left };
3206
+ applyPendingScroll();
3207
+ }, [initialScroll, applyPendingScroll]);
3208
+
3209
+ // Draft/phase commits are the moments the pending target may have become
3210
+ // applicable: the loaded text is in the textarea and the box has a size.
3211
+ useLayoutEffectSafe(() => {
3212
+ applyPendingScroll();
3213
+ }, [state.phase, state.draft, applyPendingScroll]);
3214
+
3215
+ // Scroll restore/heal observer — deliberately INDEPENDENT of the
3216
+ // highlight/gutter observer above (that one is preference-gated and
3217
+ // repaints). `observe()` dispatches an initial notification, which doubles
3218
+ // as the post-layout retry for a target that was not applicable yet.
3219
+ React.useEffect(() => {
3220
+ const area = areaRef.current;
3221
+ if (area === null || typeof ResizeObserver !== 'function') return undefined;
3222
+ const observer = new ResizeObserver(() => {
3223
+ applyPendingScroll();
3224
+ healScrollOnReveal();
3225
+ });
3226
+ observer.observe(area);
3227
+ return () => observer.disconnect();
3228
+ }, [applyPendingScroll, healScrollOnReveal]);
3229
+
2400
3230
  // Size/visibility restoration: an editor mounted (or toggled on) inside a
2401
3231
  // hidden session subtree caches no metrics (the guard above), so the
2402
3232
  // observer fires the retry the moment the textarea gains a real box —
@@ -2404,13 +3234,13 @@ window.__ModuleLoader__.load({
2404
3234
  // observe() also dispatches an initial notification, doubling as a
2405
3235
  // post-layout resync on the very first mount.
2406
3236
  React.useEffect(() => {
2407
- if (!highlightEnabled) return undefined;
3237
+ if (!highlightEnabled && !gutterEnabled) return undefined;
2408
3238
  const area = areaRef.current;
2409
3239
  if (area === null || typeof ResizeObserver !== 'function') return undefined;
2410
3240
  const observer = new ResizeObserver(() => syncRef.current());
2411
3241
  observer.observe(area);
2412
3242
  return () => observer.disconnect();
2413
- }, [highlightEnabled]);
3243
+ }, [highlightEnabled, gutterEnabled]);
2414
3244
 
2415
3245
  // THE caret-follower: document-level `selectionchange` fires synchronously
2416
3246
  // with EVERY caret move — arrow keys included. The element-level events
@@ -2435,14 +3265,58 @@ window.__ModuleLoader__.load({
2435
3265
  if (area === null) return false;
2436
3266
  const target = Math.max(1, Math.floor(Number(line)));
2437
3267
  const offset = offsetOfLine(area.value, target);
3268
+ // An explicit jump owns the caret AND the scroll position from this
3269
+ // point on: consume the one-shot restore and drop any still-pending
3270
+ // target BEFORE moving, so a late `initialScroll` (or a queued
3271
+ // observer retry) cannot drag the viewport back.
3272
+ scrollRestoreConsumedRef.current = true;
3273
+ pendingScrollRef.current = null;
2438
3274
  area.focus();
2439
3275
  area.setSelectionRange(offset, offset);
2440
3276
  const landed = lineOfOffset(area.value, offset);
2441
3277
  area.scrollTop = Math.max(0, (landed - 6) * 20);
3278
+ // The jump is a legitimate visible scroll: remember and report it the
3279
+ // same way a user scroll does — but only from a measured, loaded
3280
+ // textarea. A hidden or still-loading textarea reads back 0/0, and
3281
+ // storing that would poison the heal source and persist scrollTop 0.
3282
+ if ((state.phase === 'ready' || state.phase === 'saving') && area.offsetParent !== null) {
3283
+ const next = { top: area.scrollTop, left: area.scrollLeft };
3284
+ lastVisibleScrollRef.current = next;
3285
+ if (typeof onScrollChange === 'function') onScrollChange(next);
3286
+ }
2442
3287
  reportSelection();
2443
3288
  return true;
2444
3289
  });
2445
- }, [controller, reportSelection]);
3290
+ // `state.phase` is read by the guard above: re-subscribe when it changes
3291
+ // so the handler cannot act on a stale phase (loading vs ready/saving).
3292
+ }, [controller, reportSelection, onScrollChange, state.phase]);
3293
+
3294
+ // A machine selection is only VISIBLE once the textarea owns focus:
3295
+ // setSelectionRange on an unfocused textarea paints the active-line bar but
3296
+ // leaves the caret invisible and routes typing elsewhere. Focus on the
3297
+ // editor's first ready render (below), not on every selection change, so
3298
+ // programmatic writes never steal focus from a field the user is using.
3299
+ const focusAreaIfAllowed = React.useCallback(() => {
3300
+ const area = areaRef.current;
3301
+ if (area === null) return;
3302
+ const active = typeof document !== 'undefined' ? document.activeElement : null;
3303
+ const activeIsSelf = active === area;
3304
+ const activeIsTextEntry =
3305
+ active !== null &&
3306
+ !activeIsSelf &&
3307
+ (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable === true);
3308
+ const attached = area.offsetParent !== null;
3309
+ if (!shouldFocusEditorOnOpen({ attached, activeIsSelf, activeIsTextEntry })) return;
3310
+ try {
3311
+ area.focus({ preventScroll: true });
3312
+ } catch {
3313
+ try {
3314
+ area.focus();
3315
+ } catch {
3316
+ // detached node
3317
+ }
3318
+ }
3319
+ }, []);
2446
3320
 
2447
3321
  // Mirror machine-written selections (deleteLines and friends) into the
2448
3322
  // DOM; user-driven selections already match, so nothing fights. Painting
@@ -2463,6 +3337,20 @@ window.__ModuleLoader__.load({
2463
3337
  paintCaretLine();
2464
3338
  }, [state.selection, paintCaretLine]);
2465
3339
 
3340
+ // Focus the editor once it is loaded and visible. Opening a file should
3341
+ // leave the caret ready for typing; a restored selection makes the old
3342
+ // unfocused state especially confusing (the line is highlighted but the
3343
+ // editor is dead). Never steal focus from the chat composer or another
3344
+ // text entry, and never focus a hidden tab.
3345
+ const readyFocusRef = React.useRef(false);
3346
+ useLayoutEffectSafe(() => {
3347
+ if (readyFocusRef.current) return;
3348
+ if (state.phase !== 'ready' && state.phase !== 'saving') return;
3349
+ if (areaRef.current === null) return;
3350
+ readyFocusRef.current = true;
3351
+ focusAreaIfAllowed();
3352
+ }, [state.phase, focusAreaIfAllowed]);
3353
+
2466
3354
  return h(
2467
3355
  'div',
2468
3356
  { className: `${CLASS}-inputwrap` },
@@ -2473,9 +3361,47 @@ window.__ModuleLoader__.load({
2473
3361
  h('div', { className: `${CLASS}-highlight-bar`, ref: barRef })
2474
3362
  )
2475
3363
  : null,
3364
+ // The band ALWAYS paints — opaque cover + boundary rule persist
3365
+ // regardless of the preference, so toggling shows/hides ONLY the
3366
+ // numbers and never moves the layout. The band paints above the
3367
+ // highlight backdrop AND the overlay textarea (z-index 2 vs 1) so
3368
+ // horizontally-scrolled glyphs cannot sweep across it; pointer-events
3369
+ // none keeps clicks falling through to the textarea's padding region.
3370
+ // The rule sits INSIDE the band at the digits+gap offset, so the
3371
+ // strip right of it stays covered background too.
3372
+ h(
3373
+ 'div',
3374
+ {
3375
+ className: `${CLASS}-gutter`,
3376
+ 'aria-hidden': true,
3377
+ style: { width: `${bandWidth}ch` }
3378
+ },
3379
+ h('div', {
3380
+ className: `${CLASS}-gutter-rule`,
3381
+ 'aria-hidden': true,
3382
+ style: { left: `${ruleOffset}ch` }
3383
+ }),
3384
+ gutterEnabled
3385
+ ? h(
3386
+ 'div',
3387
+ {
3388
+ className: `${CLASS}-gutter-text`,
3389
+ ref: gutterTextRef,
3390
+ // The digits' sub-band: border-box width = ruleOffset so
3391
+ // the CSS padding-right (1.5ch) sits INSIDE the box and
3392
+ // the right-aligned digits end exactly GUTTER_GAP_CH
3393
+ // left of the rule. (Content-box would push the digits'
3394
+ // right edge TO the rule — width + padding, not width.)
3395
+ style: { width: `${ruleOffset}ch`, boxSizing: 'border-box' }
3396
+ },
3397
+ gutterText
3398
+ )
3399
+ : null
3400
+ ),
2476
3401
  h('textarea', {
2477
3402
  ref: areaRef,
2478
3403
  className: highlightEnabled ? `${CLASS}-area ${CLASS}-area-overlay` : `${CLASS}-area`,
3404
+ style: { paddingLeft: `${bandWidth}ch` },
2479
3405
  value: state.draft,
2480
3406
  spellCheck: false,
2481
3407
  wrap: 'off',
@@ -2485,7 +3411,20 @@ window.__ModuleLoader__.load({
2485
3411
  onSelect: reportSelection,
2486
3412
  onClick: reportSelection,
2487
3413
  onKeyUp: reportSelection,
2488
- onScroll: paintCaretLine
3414
+ onScroll: () => {
3415
+ paintCaretLine();
3416
+ syncGutter();
3417
+ // Report only a MEASURED, loaded textarea. While loading (or
3418
+ // hidden) the DOM offset is meaningless and must not overwrite
3419
+ // the last visible value the heal path depends on.
3420
+ const area = areaRef.current;
3421
+ if (area === null) return;
3422
+ if (state.phase !== 'ready' && state.phase !== 'saving') return;
3423
+ if (area.offsetParent === null) return;
3424
+ const next = { top: area.scrollTop, left: area.scrollLeft };
3425
+ lastVisibleScrollRef.current = next;
3426
+ if (typeof onScrollChange === 'function') onScrollChange(next);
3427
+ }
2489
3428
  })
2490
3429
  );
2491
3430
  }
@@ -2662,13 +3601,14 @@ window.__ModuleLoader__.load({
2662
3601
 
2663
3602
  /**
2664
3603
  * The keymap popover (spec §6): opens from the status-bar keyboard icon.
2665
- * Three rows (保存 / 保存全部 / 删行), each showing the current combo plus a
3604
+ * Four rows (保存 / 保存全部 / 删行 / 跳转到行), each showing the current
3605
+ * combo plus a
2666
3606
  * 「录制」button; recording captures the NEXT keydown at document-capture
2667
3607
  * level (any combination is admissible — the root-element interception
2668
3608
  * preventDefaults browser-reserved combos like Ctrl+S itself — and composing
2669
3609
  * states are ignored during recording per the task ruling; Escape cancels).
2670
- * The footer restores the default bindings (Ctrl+S / Ctrl+Shift+S / Ctrl+D).
2671
- * Writes go through the runtime's `dshEditor/setKeymap` bridge; a successful
3610
+ * The footer restores the default bindings (Ctrl+S / Ctrl+Shift+S / Ctrl+D /
3611
+ * Ctrl+G). Writes go through the runtime's `dshEditor/setKeymap` bridge; a successful
2672
3612
  * write updates the shared cache so every mounted editor tab immediately
2673
3613
  * matches the new keys.
2674
3614
  */
@@ -2787,7 +3727,8 @@ window.__ModuleLoader__.load({
2787
3727
  const rows = [
2788
3728
  { action: 'save', label: t('keymap.save') },
2789
3729
  { action: 'saveAll', label: t('keymap.saveAll') },
2790
- { action: 'deleteLines', label: t('keymap.deleteLines') }
3730
+ { action: 'deleteLines', label: t('keymap.deleteLines') },
3731
+ { action: 'gotoLine', label: t('keymap.gotoLine') }
2791
3732
  ].map(({ action, label }) => {
2792
3733
  const binding = runtime.getKeymap()[action];
2793
3734
  const isRecording = recording === action;
@@ -2842,15 +3783,151 @@ window.__ModuleLoader__.load({
2842
3783
  h(
2843
3784
  'button',
2844
3785
  {
2845
- className: `${CLASS}-keymap-reset`,
3786
+ className: `${CLASS}-keymap-reset`,
3787
+ type: 'button',
3788
+ disabled: busy || recording !== null,
3789
+ title: t('keymap.resetTitle'),
3790
+ onClick: runReset
3791
+ },
3792
+ t('keymap.reset')
3793
+ )
3794
+ )
3795
+ );
3796
+ }
3797
+
3798
+ /* ------------------------------------------------------ goto panel -- */
3799
+
3800
+ /**
3801
+ * The go-to-line popover (v0.6.0): opened by the `gotoLine` self-managed
3802
+ * binding (default Ctrl+G, recordable in the keymap panel). Anchored to the
3803
+ * status bar's LEFT edge above the Ln/Col indicator (the keymap/settings
3804
+ * popovers take the right edge). The input starts EMPTY and is focused on
3805
+ * open; Enter or the jump button parse it through `parseGotoLine`
3806
+ * (out-of-range clamps to the nearest existing line; empty/non-numeric
3807
+ * shows the inline range error instead of jumping) and deliver the jump via
3808
+ * `controller.requestNavigate` — which lands the caret at the TARGET LINE'S
3809
+ * START (offsetOfLine semantics) and returns focus to the textarea. During
3810
+ * `loading` the jump stays enabled (the machine defers delivery to after
3811
+ * ready); `failed`/no-controller disables it. A repeat Ctrl+G while open
3812
+ * re-focuses the input (`focusTick`). Every open/close/parse/jump step
3813
+ * emits a `[dsh-editor] goto-line` debug trace (src/debug-log.js) so the
3814
+ * hotkey path's state is diagnosable from the verbose console.
3815
+ */
3816
+ function GoToLinePopover(props) {
3817
+ const t = props.t;
3818
+ const controller = props.controller;
3819
+ const navable = props.navable === true; // controller present and not failed
3820
+ const loading = props.phase === 'loading';
3821
+ const lineCount = typeof props.lineCount === 'number' && props.lineCount >= 1 ? props.lineCount : 1;
3822
+ const currentLine = typeof props.currentLine === 'number' && props.currentLine >= 1 ? props.currentLine : 1;
3823
+ const panelRef = React.useRef(null);
3824
+ const inputRef = React.useRef(null);
3825
+ const [value, setValue] = React.useState('');
3826
+ const [invalid, setInvalid] = React.useState(false);
3827
+
3828
+ // Open (and repeat-Ctrl+G refocus) lands the caret in the input at the
3829
+ // layout phase, pre-paint; select() so typing replaces any previous value.
3830
+ useLayoutEffectSafe(() => {
3831
+ const input = inputRef.current;
3832
+ if (input === null) return;
3833
+ input.focus();
3834
+ input.select();
3835
+ }, [props.focusTick]);
3836
+
3837
+ // Close on outside pointer-down and on Escape — same surface rules as the
3838
+ // other popovers, each close carrying its reason in the debug trace.
3839
+ React.useEffect(() => {
3840
+ if (typeof document === 'undefined' || document === null) return undefined;
3841
+ const onPointerDown = (event) => {
3842
+ const panel = panelRef.current;
3843
+ if (panel === null || event.target === null || event.target === undefined) return;
3844
+ if (!panel.contains(event.target)) {
3845
+ props.log?.debug('goto-line', 'close (outside click)');
3846
+ props.onClose();
3847
+ }
3848
+ };
3849
+ const onKeyDown = (event) => {
3850
+ if (event.key === 'Escape') {
3851
+ props.log?.debug('goto-line', 'close (escape)');
3852
+ props.onClose();
3853
+ }
3854
+ };
3855
+ document.addEventListener('mousedown', onPointerDown);
3856
+ document.addEventListener('keydown', onKeyDown);
3857
+ return () => {
3858
+ document.removeEventListener('mousedown', onPointerDown);
3859
+ document.removeEventListener('keydown', onKeyDown);
3860
+ };
3861
+ }, [props.onClose]);
3862
+
3863
+ const jump = () => {
3864
+ if (!navable) return;
3865
+ const parsed = parseGotoLine(value, lineCount);
3866
+ if (!parsed.ok) {
3867
+ setInvalid(true);
3868
+ props.log?.debug('goto-line', 'invalid input', JSON.stringify(value));
3869
+ return;
3870
+ }
3871
+ const accepted = controller.requestNavigate(parsed.line);
3872
+ props.log?.debug('goto-line', 'jump', parsed.line, accepted ? 'accepted' : 'rejected');
3873
+ if (accepted) props.onClose();
3874
+ };
3875
+
3876
+ const maxText = String(lineCount);
3877
+ return h(
3878
+ 'div',
3879
+ { className: `${CLASS}-goto`, ref: panelRef, role: 'group', 'aria-label': t('goto.title') },
3880
+ h(
3881
+ 'div',
3882
+ { key: 'head', className: `${CLASS}-goto-head` },
3883
+ h('span', { key: 'title', className: `${CLASS}-goto-title` }, t('goto.title')),
3884
+ h(
3885
+ 'span',
3886
+ { key: 'ctx', className: `${CLASS}-goto-context`, title: t('goto.context').replace('{line}', String(currentLine)).replace('{max}', maxText) },
3887
+ t('goto.context').replace('{line}', String(currentLine)).replace('{max}', maxText)
3888
+ )
3889
+ ),
3890
+ h(
3891
+ 'div',
3892
+ { key: 'row', className: `${CLASS}-goto-row` },
3893
+ h('input', {
3894
+ key: 'input',
3895
+ ref: inputRef,
3896
+ className: `${CLASS}-goto-input`,
3897
+ type: 'text',
3898
+ inputMode: 'numeric',
3899
+ value,
3900
+ placeholder: t('goto.placeholder').replace('{max}', maxText),
3901
+ 'aria-label': t('goto.title'),
3902
+ spellCheck: false,
3903
+ onChange: (event) => {
3904
+ setValue(event.target.value);
3905
+ setInvalid(false); // typing clears the error
3906
+ },
3907
+ onKeyDown: (event) => {
3908
+ if (event.key === 'Enter') {
3909
+ event.preventDefault();
3910
+ jump();
3911
+ }
3912
+ }
3913
+ }),
3914
+ h(
3915
+ 'button',
3916
+ {
3917
+ key: 'jump',
3918
+ className: `${CLASS}-goto-jump`,
2846
3919
  type: 'button',
2847
- disabled: busy || recording !== null,
2848
- title: t('keymap.resetTitle'),
2849
- onClick: runReset
3920
+ disabled: !navable,
3921
+ title: t('goto.jumpTitle'),
3922
+ onClick: jump
2850
3923
  },
2851
- t('keymap.reset')
3924
+ t('goto.jump')
2852
3925
  )
2853
- )
3926
+ ),
3927
+ loading ? h('div', { key: 'loading', className: `${CLASS}-goto-note` }, t('goto.loading')) : null,
3928
+ invalid
3929
+ ? h('div', { key: 'error', className: `${CLASS}-goto-note ${CLASS}-goto-error` }, t('goto.invalid').replace('{max}', maxText))
3930
+ : null
2854
3931
  );
2855
3932
  }
2856
3933
 
@@ -2862,8 +3939,8 @@ window.__ModuleLoader__.load({
2862
3939
  * `dshEditor/get|setSettings` bridge (Host KV table `settings`, SHARED
2863
3940
  * `updatedAt` CAS token — a conflicting write refetches and surfaces the
2864
3941
  * retry notice, exactly like the keymap recorder). One row per known setting
2865
- * (`SETTINGS_ROWS`); the note line explains the one setting whose reach
2866
- * crosses modes.
3942
+ * (`SETTINGS_ROWS`); a row may carry its own explanatory note (`noteKey`,
3943
+ * rendered under it — currently the one setting whose reach crosses modes).
2867
3944
  */
2868
3945
 
2869
3946
  /** The popover's rows, in display order: setting key + locale stems. */
@@ -2872,7 +3949,13 @@ window.__ModuleLoader__.load({
2872
3949
  {
2873
3950
  key: 'highlightActiveLine',
2874
3951
  labelKey: 'settings.highlightActiveLine',
2875
- titleKey: 'settings.highlightActiveLineTitle'
3952
+ titleKey: 'settings.highlightActiveLineTitle',
3953
+ noteKey: 'settings.highlightActiveLineNote'
3954
+ },
3955
+ {
3956
+ key: 'showLineNumbers',
3957
+ labelKey: 'settings.showLineNumbers',
3958
+ titleKey: 'settings.showLineNumbersTitle'
2876
3959
  }
2877
3960
  ];
2878
3961
 
@@ -2937,31 +4020,32 @@ window.__ModuleLoader__.load({
2937
4020
  : `${t('settings.writeFailed')}: ${error.message}`
2938
4021
  )
2939
4022
  : null,
2940
- SETTINGS_ROWS.map((row) => {
4023
+ SETTINGS_ROWS.flatMap((row) => {
2941
4024
  const on = settings[row.key] === true;
2942
- return h(
2943
- 'div',
2944
- { key: row.key, className: `${CLASS}-settings-row` },
2945
- h('span', { className: `${CLASS}-settings-label`, title: t(row.titleKey) }, t(row.labelKey)),
4025
+ const cells = [
2946
4026
  h(
2947
- 'button',
2948
- {
2949
- className: `${CLASS}-settings-toggle${on ? ' on' : ''}`,
2950
- type: 'button',
2951
- disabled: busy,
2952
- title: t(row.titleKey),
2953
- 'aria-pressed': on ? 'true' : 'false',
2954
- onClick: () => runToggle(row.key, on)
2955
- },
2956
- on ? t('settings.on') : t('settings.off')
4027
+ 'div',
4028
+ { key: row.key, className: `${CLASS}-settings-row` },
4029
+ h('span', { className: `${CLASS}-settings-label`, title: t(row.titleKey) }, t(row.labelKey)),
4030
+ h(
4031
+ 'button',
4032
+ {
4033
+ className: `${CLASS}-settings-toggle${on ? ' on' : ''}`,
4034
+ type: 'button',
4035
+ disabled: busy,
4036
+ title: t(row.titleKey),
4037
+ 'aria-pressed': on ? 'true' : 'false',
4038
+ onClick: () => runToggle(row.key, on)
4039
+ },
4040
+ on ? t('settings.on') : t('settings.off')
4041
+ )
2957
4042
  )
2958
- );
2959
- }),
2960
- h(
2961
- 'div',
2962
- { key: 'note', className: `${CLASS}-settings-note` },
2963
- t('settings.highlightActiveLineNote')
2964
- )
4043
+ ];
4044
+ if (typeof row.noteKey === 'string') {
4045
+ cells.push(h('div', { key: `${row.key}-note`, className: `${CLASS}-settings-note` }, t(row.noteKey)));
4046
+ }
4047
+ return cells;
4048
+ })
2965
4049
  );
2966
4050
  }
2967
4051
 
@@ -2975,6 +4059,13 @@ window.__ModuleLoader__.load({
2975
4059
  * with the mounted mode component (a conflict banner sits above it). Mode
2976
4060
  * switches re-resolve and swap the mode component only — draft, version and
2977
4061
  * dirty live in the machine and survive untouched.
4062
+ *
4063
+ * View state (0.8.0): every committed selection is persisted into the shared
4064
+ * runtime view-state store keyed by workspace root + path; the first loaded
4065
+ * render restores that caret and the remembered scroll once. An explicit
4066
+ * navigation suppresses the restore (it owns the caret); a mode switch instead
4067
+ * repositions the new mode from the last offset the previous mode reported,
4068
+ * without ever re-applying the caret.
2978
4069
  */
2979
4070
  function EditorTab(props) {
2980
4071
  const t = props.t;
@@ -2997,6 +4088,7 @@ window.__ModuleLoader__.load({
2997
4088
  if (!valid) return undefined;
2998
4089
  try {
2999
4090
  runtime.draftStore.prune();
4091
+ runtime.viewStateStore.prune();
3000
4092
  } catch {
3001
4093
  // best-effort LRU/expiry housekeeping
3002
4094
  }
@@ -3130,6 +4222,12 @@ window.__ModuleLoader__.load({
3130
4222
  const [keymapOpen, setKeymapOpen] = React.useState(false);
3131
4223
  const closeKeymap = React.useCallback(() => setKeymapOpen(false), []);
3132
4224
 
4225
+ // The go-to-line popover (v0.6.0, the `gotoLine` binding): `gotoFocusTick`
4226
+ // bumps on a repeat Ctrl+G while open so the panel re-focuses its input.
4227
+ const [gotoOpen, setGotoOpen] = React.useState(false);
4228
+ const closeGoto = React.useCallback(() => setGotoOpen(false), []);
4229
+ const [gotoFocusTick, setGotoFocusTick] = React.useState(0);
4230
+
3133
4231
  // The settings popover (gear icon) follows the same visibility rule as the
3134
4232
  // keymap popover: a hidden tab always drops it (outside-click handlers
3135
4233
  // belong to the visible surface only).
@@ -3152,6 +4250,7 @@ window.__ModuleLoader__.load({
3152
4250
  // it disarms the recorder through its effect cleanup).
3153
4251
  React.useEffect(() => {
3154
4252
  if (!visible) setKeymapOpen(false);
4253
+ if (!visible) setGotoOpen(false);
3155
4254
  }, [visible]);
3156
4255
 
3157
4256
  const onRootKeyDown = React.useCallback(
@@ -3164,6 +4263,7 @@ window.__ModuleLoader__.load({
3164
4263
  // combination (Ctrl+S page save, Ctrl+D bookmark, …) even when
3165
4264
  // the business action below gates itself out.
3166
4265
  event.preventDefault();
4266
+ runtime.log?.debug('keymap', 'dispatch', action, comboOf(runtime.getKeymap()[action]));
3167
4267
  if (action === 'save') {
3168
4268
  if (controller === null) return; // no-op, combo still suppressed
3169
4269
  const snapshot = controller.getState();
@@ -3186,9 +4286,25 @@ window.__ModuleLoader__.load({
3186
4286
  if (sessionId !== null) runtime.saveAllOfSession(sessionId);
3187
4287
  } else if (action === 'deleteLines') {
3188
4288
  if (controller !== null) runtime.deleteLinesFor({ controller });
4289
+ } else if (action === 'gotoLine') {
4290
+ if (controller === null) {
4291
+ runtime.log?.debug('goto-line', 'bail: no controller');
4292
+ return;
4293
+ }
4294
+ const snapshot = controller.getState();
4295
+ if (snapshot.phase === 'failed') {
4296
+ runtime.log?.debug('goto-line', 'bail: phase=failed');
4297
+ return; // no draft to navigate; combo still suppressed
4298
+ }
4299
+ if (gotoOpen) {
4300
+ setGotoFocusTick((tick) => tick + 1); // already open: re-focus the input
4301
+ return;
4302
+ }
4303
+ runtime.log?.debug('goto-line', 'open', `phase=${snapshot.phase}`, comboOf(runtime.getKeymap().gotoLine));
4304
+ setGotoOpen(true);
3189
4305
  }
3190
4306
  },
3191
- [controller, runtime, sessionId, confirmRecreate]
4307
+ [controller, runtime, sessionId, confirmRecreate, gotoOpen]
3192
4308
  );
3193
4309
 
3194
4310
  // --- machine state + derived chrome values ---
@@ -3196,6 +4312,159 @@ window.__ModuleLoader__.load({
3196
4312
  const dirty = state.dirty === true;
3197
4313
  const deleted = state.external === 'deleted';
3198
4314
 
4315
+ // --- view state (0.8.0): the identity, persistence and one-shot restore of
4316
+ // this tab's remembered caret + scroll. One store instance lives on the
4317
+ // runtime (single localStorage key); every read/write path here is
4318
+ // best-effort and must never disturb the editor. ---
4319
+ const resolveViewStateKey = React.useCallback(() => {
4320
+ // Defensive on purpose: `sessionCwdOf` is optional runtime surface and
4321
+ // may legitimately be absent, throw, or only become available after
4322
+ // load — any of those must leave the session-id fallback in place.
4323
+ try {
4324
+ if (sessionId === null || targetPath === null) return undefined;
4325
+ const sessionCwd =
4326
+ typeof runtime.sessionCwdOf === 'function' ? runtime.sessionCwdOf(sessionId) : undefined;
4327
+ return viewStateKey(sessionCwd, sessionId, targetPath);
4328
+ } catch {
4329
+ return undefined;
4330
+ }
4331
+ }, [runtime, sessionId, targetPath]);
4332
+ const viewStateKeyValue = React.useMemo(() => resolveViewStateKey(), [resolveViewStateKey]);
4333
+
4334
+ // The FIRST resolved mode is the baseline; any later change marks a mode
4335
+ // switch (the one event that asks for a remembered view even while
4336
+ // navigation owns the caret). These refs are updated during render BEFORE
4337
+ // the memos below so the switch render already sees `modeSwitched`.
4338
+ const firstModeIdRef = React.useRef(undefined);
4339
+ const hasModeSwitchedRef = React.useRef(false);
4340
+ if (state.modeId !== undefined) {
4341
+ if (firstModeIdRef.current === undefined) firstModeIdRef.current = state.modeId;
4342
+ else if (state.modeId !== firstModeIdRef.current) hasModeSwitchedRef.current = true;
4343
+ }
4344
+ const modeSwitched = hasModeSwitchedRef.current;
4345
+
4346
+ const loaded = state.phase === 'ready' || state.phase === 'saving';
4347
+ const restoreViewState = shouldRestoreViewState({ loaded, navigationLine, modeSwitched });
4348
+
4349
+ // The remembered record, re-read whenever the mode changes (a switch must
4350
+ // see what the previously mounted mode reported) and null while the tab is
4351
+ // loading, has no key, or navigation owns the caret.
4352
+ const initialViewState = React.useMemo(() => {
4353
+ if (!restoreViewState || viewStateKeyValue === undefined) return null;
4354
+ try {
4355
+ return runtime.viewStateStore.get(viewStateKeyValue) ?? null;
4356
+ } catch {
4357
+ return null;
4358
+ }
4359
+ }, [restoreViewState, viewStateKeyValue, state.modeId, runtime]);
4360
+
4361
+ // The last offset a mounted mode reported; after a mode switch the new
4362
+ // mode's initial position comes from this live value, not the stale record.
4363
+ const lastKnownScrollRef = React.useRef(null);
4364
+ const initialScroll = React.useMemo(() => {
4365
+ if (!restoreViewState) return null;
4366
+ if (modeSwitched) {
4367
+ if (lastKnownScrollRef.current !== null) return lastKnownScrollRef.current;
4368
+ // Explicit navigation owns the viewport: when no visible scroll
4369
+ // report was observed, a remembered offset must not be re-applied
4370
+ // over the jump when the mode switches.
4371
+ if (navigationLine !== null) return null;
4372
+ return initialViewState === null
4373
+ ? null
4374
+ : { top: initialViewState.scrollTop, left: initialViewState.scrollLeft };
4375
+ }
4376
+ if (initialViewState === null) return null;
4377
+ const target = { top: initialViewState.scrollTop, left: initialViewState.scrollLeft };
4378
+ // Seed the heal source before the mode reports a real offset, so a
4379
+ // hidden subtree that discards scrollTop can be restored on reveal.
4380
+ if (lastKnownScrollRef.current === null) lastKnownScrollRef.current = target;
4381
+ return target;
4382
+ }, [restoreViewState, modeSwitched, initialViewState, navigationLine]);
4383
+
4384
+ // Selection persistence: every committed, loaded selection is mirrored into
4385
+ // the shared store, deduped on the four offset fields. The key is resolved
4386
+ // INSIDE the handler (never from the memo) so a late-arriving workspace
4387
+ // root is honored instead of a stale key.
4388
+ const lastPersistedSelectionRef = React.useRef(null);
4389
+ React.useEffect(() => {
4390
+ if (controller === null) return undefined;
4391
+ lastPersistedSelectionRef.current = null;
4392
+ const persistSelection = (snapshot) => {
4393
+ if (snapshot.phase !== 'ready' && snapshot.phase !== 'saving') return;
4394
+ const selection = snapshot.selection;
4395
+ if (selection === null || typeof selection !== 'object') return;
4396
+ const last = lastPersistedSelectionRef.current;
4397
+ if (
4398
+ last !== null &&
4399
+ last.start === selection.start &&
4400
+ last.end === selection.end &&
4401
+ last.lineStart === selection.lineStart &&
4402
+ last.lineEnd === selection.lineEnd
4403
+ ) {
4404
+ return; // same caret/range already persisted: nothing to write
4405
+ }
4406
+ const key = resolveViewStateKey();
4407
+ if (key === undefined) return;
4408
+ const record = selectionRecordFromSnapshot(snapshot.draft, selection);
4409
+ if (record === null) return;
4410
+ try {
4411
+ runtime.viewStateStore.update(key, { selection: record });
4412
+ } catch {
4413
+ // best-effort: persistence never blocks the editor
4414
+ }
4415
+ lastPersistedSelectionRef.current = {
4416
+ start: selection.start,
4417
+ end: selection.end,
4418
+ lineStart: selection.lineStart,
4419
+ lineEnd: selection.lineEnd
4420
+ };
4421
+ };
4422
+ persistSelection(controller.getState());
4423
+ return controller.subscribe(persistSelection);
4424
+ }, [controller, resolveViewStateKey, runtime]);
4425
+
4426
+ // Selection restore: exactly once per tab, on the first loaded render. A
4427
+ // mode switch never re-applies it (the mode component mirrors the machine
4428
+ // selection), and an explicit navigation already suppressed the restore by
4429
+ // that render, so this never fights a jump. Layout phase: the caret lands
4430
+ // before the first paint, alongside the scroll the mode restores.
4431
+ const selectionRestoredRef = React.useRef(false);
4432
+ useLayoutEffectSafe(() => {
4433
+ if (!loaded || selectionRestoredRef.current) return;
4434
+ selectionRestoredRef.current = true;
4435
+ if (!restoreViewState || controller === null || initialViewState === null) return;
4436
+ const record = initialViewState.selection;
4437
+ if (record === null || record === undefined) return;
4438
+ const selection = selectionFromViewState(state.draft, record);
4439
+ if (selection === null) return;
4440
+ controller.applySelection(selection);
4441
+ }, [loaded, restoreViewState, controller, initialViewState, state.draft]);
4442
+
4443
+ // Scroll reporting: the mounted mode reports the offset it actually
4444
+ // reached. Only a loaded machine writes (a loading or hidden textarea reads
4445
+ // 0/0), and only the two validated fields go into the patch — an explicit
4446
+ // `undefined` own property would be rejected by the store.
4447
+ const onScrollChange = React.useCallback(
4448
+ (next) => {
4449
+ if (controller === null) return;
4450
+ const snapshot = controller.getState();
4451
+ if (snapshot.phase !== 'ready' && snapshot.phase !== 'saving') return;
4452
+ if (next === null || typeof next !== 'object') return;
4453
+ const top = next.top;
4454
+ const left = next.left;
4455
+ if (!Number.isFinite(top) || top < 0 || !Number.isFinite(left) || left < 0) return;
4456
+ lastKnownScrollRef.current = { top, left };
4457
+ const key = resolveViewStateKey();
4458
+ if (key === undefined) return;
4459
+ try {
4460
+ runtime.viewStateStore.update(key, { scrollTop: top, scrollLeft: left });
4461
+ } catch {
4462
+ // best-effort: persistence never blocks scrolling
4463
+ }
4464
+ },
4465
+ [controller, resolveViewStateKey, runtime]
4466
+ );
4467
+
3199
4468
  // 布防解除:任何语义状态变化(编辑、外部状态翻转、相位变化)都让两段式
3200
4469
  // 确认回到初始态。
3201
4470
  React.useEffect(() => {
@@ -3465,7 +4734,15 @@ window.__ModuleLoader__.load({
3465
4734
  // handed to every mounted mode; modes that declared
3466
4735
  // `activeLine` (contracts §5.1) draw the highlight, others
3467
4736
  // ignore the prop harmlessly.
3468
- highlightActiveLine: runtime.getSettings().highlightActiveLine !== false
4737
+ highlightActiveLine: runtime.getSettings().highlightActiveLine !== false,
4738
+ // The line-numbers contract (0.5.0): same shape, same reach —
4739
+ // modes honoring the preference draw the gutter, others ignore.
4740
+ showLineNumbers: runtime.getSettings().showLineNumbers !== false,
4741
+ // The view-state adapter (0.8.0): the framework's read-once
4742
+ // restore target and the best-effort scroll reporter. Both are
4743
+ // optional; modes that ignore them are unaffected.
4744
+ initialScroll,
4745
+ onScrollChange
3469
4746
  })
3470
4747
  ];
3471
4748
  }
@@ -3556,6 +4833,20 @@ window.__ModuleLoader__.load({
3556
4833
  notice.text
3557
4834
  )
3558
4835
  : null,
4836
+ gotoOpen
4837
+ ? h(GoToLinePopover, {
4838
+ key: 'goto-popover',
4839
+ t,
4840
+ controller,
4841
+ log: runtime.log,
4842
+ navable: controller !== null && state.phase !== 'failed',
4843
+ phase: state.phase,
4844
+ currentLine: caret.line,
4845
+ lineCount,
4846
+ focusTick: gotoFocusTick,
4847
+ onClose: closeGoto
4848
+ })
4849
+ : null,
3559
4850
  h(
3560
4851
  'button',
3561
4852
  {
@@ -3689,10 +4980,10 @@ window.__ModuleLoader__.load({
3689
4980
 
3690
4981
  /* ------------------------------------------------------------- export -- */
3691
4982
 
3692
- /** Wrap one component with the render boundary. */
3693
- function guard(Component) {
4983
+ /** Wrap one component with the render boundary (logging through `log`). */
4984
+ function guard(Component, log) {
3694
4985
  return function Guarded(props) {
3695
- return h(EditorBoundary, null, h(Component, props));
4986
+ return h(EditorBoundary, { log }, h(Component, props));
3696
4987
  };
3697
4988
  }
3698
4989
 
@@ -3700,26 +4991,29 @@ window.__ModuleLoader__.load({
3700
4991
  * Build the component set for one plugin activation. `runtime` is injected
3701
4992
  * into the tab/edit-button components' props here (the framework supplies
3702
4993
  * only its own standard props when rendering them).
3703
- * @param {{ draftStore, loadFile, writeFile, modeRegistry, subscribeModes,
4994
+ * @param {{ draftStore, viewStateStore, sessionCwdOf, log, loadFile, writeFile,
4995
+ * modeRegistry, subscribeModes,
3704
4996
  * getAssociations, subscribeAssociations, refreshAssociations, setDefaultMode,
3705
4997
  * resetAssociationsFor, registerTab, subscribeMounted, registerModeMenuOpener,
3706
4998
  * addLiveController, removeLiveController, openFromPreview, getKeymap,
3707
4999
  * subscribeKeymap, setKeymap, getSettings, subscribeSettings, setSettings,
3708
5000
  * saveAllOfSession, requestSaveTab, deleteLinesFor }} runtime
3709
- * the live-context capabilities owned by the client entry.
5001
+ * the live-context capabilities owned by the client entry; `log` is the
5002
+ * persistent log channel (scope-tagged debug/warn/error calls).
3710
5003
  */
3711
5004
  function createEditorComponents(runtime) {
5005
+ const log = runtime.log;
3712
5006
  const withRuntime = (Component) =>
3713
5007
  function WithRuntime(props) {
3714
5008
  return h(Component, { ...props, runtime });
3715
5009
  };
3716
5010
  return {
3717
5011
  EditorTab: withRuntime(EditorTab),
3718
- EditorTabGuarded: guard(withRuntime(EditorTab)),
5012
+ EditorTabGuarded: guard(withRuntime(EditorTab), log),
3719
5013
  EditorTabTitle: withRuntime(EditorTabTitle),
3720
- EditorTabTitleGuarded: guard(withRuntime(EditorTabTitle)),
5014
+ EditorTabTitleGuarded: guard(withRuntime(EditorTabTitle), log),
3721
5015
  EditButton: withRuntime(EditButton),
3722
- EditButtonGuarded: guard(withRuntime(EditButton)),
5016
+ EditButtonGuarded: guard(withRuntime(EditButton), log),
3723
5017
  PlainTextMode
3724
5018
  };
3725
5019
  }
@@ -3747,6 +5041,10 @@ window.__ModuleLoader__.load({
3747
5041
  * off). Modes honoring the active-line contract (descriptor `activeLine`,
3748
5042
  * contracts §5.1) read the same preference via their `highlightActiveLine`
3749
5043
  * component prop.
5044
+ * - `showLineNumbers` — render the line-number gutter beside the content
5045
+ * (default `true`: a presentation affordance, on unless the user turns it
5046
+ * off). Modes honoring the line-numbers contract (contracts §5.1) read the
5047
+ * same preference via their `showLineNumbers` component prop.
3750
5048
  *
3751
5049
  * `normalizeSettings` accepts the wire payload `{ [name]: boolean }` (the
3752
5050
  * Host reports only stored settings) and merges it over the defaults.
@@ -3760,14 +5058,14 @@ window.__ModuleLoader__.load({
3760
5058
  */
3761
5059
 
3762
5060
  /** Setting names this build knows (mirrors the Host validator's allow-list). */
3763
- const SETTINGS_KEYS = ['autoReloadClean', 'highlightActiveLine'];
5061
+ const SETTINGS_KEYS = ['autoReloadClean', 'highlightActiveLine', 'showLineNumbers'];
3764
5062
 
3765
5063
  /**
3766
5064
  * The built-in settings: behavior opt-ins off, presentation defaults on.
3767
5065
  * @returns a fresh settings object (callers may mutate their copy).
3768
5066
  */
3769
5067
  function defaultSettings() {
3770
- return { autoReloadClean: false, highlightActiveLine: true };
5068
+ return { autoReloadClean: false, highlightActiveLine: true, showLineNumbers: true };
3771
5069
  }
3772
5070
 
3773
5071
  /**
@@ -3791,15 +5089,606 @@ window.__ModuleLoader__.load({
3791
5089
  return module.exports;
3792
5090
  })();
3793
5091
 
5092
+ /* src/serialize-log.js */
5093
+ const serializeLog = (function () {
5094
+ var module = { exports: {} };
5095
+ var exports = module.exports;
5096
+ /**
5097
+ * Safe single-line serialization of log arguments — the stringifier the
5098
+ * persistent log channel (log-manager) builds its lines with. Arguments are
5099
+ * stringified one by one, joined with single spaces, then capped at
5100
+ * `maxChars` (default 2000); a capped line ends with `…(truncated)`.
5101
+ *
5102
+ * Iron rule: `serializeLogArgs` NEVER throws, whatever it is handed. Every
5103
+ * failure mode degrades to a placeholder instead: circular references render
5104
+ * as `[circular]`, unserializable members (throwing getters, hostile proxies,
5105
+ * stack-depth overflows) as `[unserializable]`, and bigint / function /
5106
+ * symbol values as their dedicated placeholders (`123n` form, `[function]`,
5107
+ * `[symbol]`). Line breaks inside string arguments become the literal two
5108
+ * characters `\n`, so the output is always a single line.
5109
+ *
5110
+ * Primitive values render exactly like `JSON.stringify` (including `undefined`
5111
+ * members being skipped and `NaN`/`Infinity` degrading to `null`); only the
5112
+ * placeholders and cycle handling differ, since plain `JSON.stringify` cannot
5113
+ * express either.
5114
+ *
5115
+ * Zero imports: pure functions only, unit-testable without DOM.
5116
+ *
5117
+ * @module @dybai/dsh-editor/serialize-log
5118
+ */
5119
+
5120
+ /** Line cap before truncation; the brief's default for the log channel. */
5121
+ const DEFAULT_MAX_CHARS = 2000;
5122
+
5123
+ /** Appended to a cut line; the truncated result stays within `maxChars`. */
5124
+ const TRUNCATION_MARKER = '…(truncated)';
5125
+
5126
+ /** Line breaks (CRLF, LF, CR) collapse to the literal two characters `\n`. */
5127
+ const LINE_BREAKS = /\r\n|\r|\n/g;
5128
+
5129
+ /**
5130
+ * Serialize log arguments into one safe single-line string.
5131
+ * @param {unknown[]} args - the arguments as passed to the logger.
5132
+ * @param {{ maxChars?: number }} [opts] - `maxChars` caps the returned line
5133
+ * (default 2000); a non-finite or negative value falls back to the default.
5134
+ * @returns {string} a single line of at most `maxChars` characters; cut lines
5135
+ * end with `…(truncated)`. Never throws on any input.
5136
+ */
5137
+ function serializeLogArgs(args, opts) {
5138
+ const maxChars =
5139
+ typeof opts?.maxChars === 'number' && Number.isFinite(opts.maxChars) && opts.maxChars >= 0
5140
+ ? opts.maxChars
5141
+ : DEFAULT_MAX_CHARS;
5142
+ let line;
5143
+ try {
5144
+ line = args.map(stringifyArg).join(' ');
5145
+ } catch {
5146
+ line = '[unserializable]'; // 铁律兜底:任何输入都不得抛出
5147
+ }
5148
+ if (line.length > maxChars) {
5149
+ line = line.slice(0, Math.max(0, maxChars - TRUNCATION_MARKER.length)) + TRUNCATION_MARKER;
5150
+ }
5151
+ return line;
5152
+ }
5153
+
5154
+ /**
5155
+ * Stringify one argument; string arguments keep their text with line breaks
5156
+ * replaced by literal `\n`, everything else goes through the placeholder-safe
5157
+ * value serializer. Any failure degrades to `[unserializable]`.
5158
+ * @param {unknown} arg
5159
+ * @returns {string}
5160
+ */
5161
+ function stringifyArg(arg) {
5162
+ if (typeof arg === 'string') return arg.replace(LINE_BREAKS, '\\n');
5163
+ try {
5164
+ return stringifyValue(arg, new Set());
5165
+ } catch {
5166
+ return '[unserializable]';
5167
+ }
5168
+ }
5169
+
5170
+ /**
5171
+ * JSON.stringify-shaped value serializer: same primitive rendering as
5172
+ * `JSON.stringify`, plus type-dispatch placeholders for bigint / function /
5173
+ * symbol, on-stack cycle detection and per-member getter guards.
5174
+ * @param {unknown} value
5175
+ * @param {Set<object>} seen - objects on the current serialization stack.
5176
+ * @returns {string}
5177
+ * @throws nothing on plain values; hostile `toJSON`/proxies propagate to the
5178
+ * per-argument guard in `stringifyArg`.
5179
+ */
5180
+ function stringifyValue(value, seen) {
5181
+ if (typeof value === 'string') return JSON.stringify(value);
5182
+ if (typeof value === 'function') return '[function]';
5183
+ if (typeof value === 'symbol') return '[symbol]';
5184
+ if (typeof value === 'bigint') return `${value}n`;
5185
+ if (typeof value === 'object') return value === null ? 'null' : stringifyObject(value, seen);
5186
+ if (typeof value === 'undefined') return 'undefined';
5187
+ // number / boolean: finite numbers render like `JSON.stringify`, which
5188
+ // also renders NaN and the infinities as `null`.
5189
+ return typeof value === 'number' && !Number.isFinite(value) ? 'null' : String(value);
5190
+ }
5191
+
5192
+ /**
5193
+ * Serialize an object, array or exotic container (Map/Set/Date/…). Cycles are
5194
+ * detected against the on-stack `seen` set only, so the same object visited
5195
+ * twice across sibling branches still serializes in full. A `toJSON` method
5196
+ * is honoured first, exactly like `JSON.stringify` does (this also gives
5197
+ * `Date` its ISO-string rendering).
5198
+ * @param {object} value
5199
+ * @param {Set<object>} seen
5200
+ * @returns {string}
5201
+ */
5202
+ function stringifyObject(value, seen) {
5203
+ if (seen.has(value)) return '[circular]';
5204
+ seen.add(value);
5205
+ try {
5206
+ if (typeof value.toJSON === 'function') return stringifyValue(value.toJSON(), seen);
5207
+ if (Array.isArray(value)) return `[${arrayMembers(value, seen).join(',')}]`;
5208
+ return `{${objectMembers(value, seen).join(',')}}`;
5209
+ } finally {
5210
+ seen.delete(value);
5211
+ }
5212
+ }
5213
+
5214
+ /** Array members; JSON.stringify renders in-array `undefined` as `null`. */
5215
+ function arrayMembers(value, seen) {
5216
+ const parts = [];
5217
+ for (let i = 0; i < value.length; i++) {
5218
+ let member;
5219
+ try {
5220
+ member = value[i];
5221
+ } catch {
5222
+ parts.push('[unserializable]'); // 元素读取抛错(如 Proxy 陷阱)
5223
+ continue;
5224
+ }
5225
+ parts.push(member === undefined ? 'null' : stringifyValue(member, seen));
5226
+ }
5227
+ return parts;
5228
+ }
5229
+
5230
+ /** Own enumerable members; undefined-valued keys are skipped like JSON.stringify. */
5231
+ function objectMembers(value, seen) {
5232
+ const parts = [];
5233
+ for (const key of Object.keys(value)) {
5234
+ let member;
5235
+ try {
5236
+ member = value[key];
5237
+ } catch {
5238
+ parts.push(`${JSON.stringify(key)}:[unserializable]`); // getter 抛错
5239
+ continue;
5240
+ }
5241
+ if (member === undefined) continue;
5242
+ parts.push(`${JSON.stringify(key)}:${stringifyValue(member, seen)}`);
5243
+ }
5244
+ return parts;
5245
+ }
5246
+
5247
+ Object.assign(module.exports, { serializeLogArgs });
5248
+ return module.exports;
5249
+ })();
5250
+
5251
+ /* src/debug-log.js */
5252
+ const debugLog = (function () {
5253
+ var module = { exports: {} };
5254
+ var exports = module.exports;
5255
+ const { serializeLogArgs } = serializeLog;
5256
+
5257
+ /**
5258
+ * Debug logging — the `[dsh-editor]`-prefixed console channel shared by the
5259
+ * self-managed keymap dispatch path, the go-to-line popover and the keymap
5260
+ * migration (v0.6.0). Debug level only: browsers hide it unless "verbose" is
5261
+ * enabled, so the traces never pollute a normal console yet stay available
5262
+ * when diagnosing what state the hotkey path saw (dispatch, bail reason,
5263
+ * parse result, navigation verdict, migration fills).
5264
+ *
5265
+ * `createDebugLog(sink)` injects the console (unit-testable); the module
5266
+ * default `debugLog` binds to the global console and degrades to a silent
5267
+ * no-op when no console exists.
5268
+ *
5269
+ * v2 adds `createLogChannel(deps)`: the leveled (debug/info/warn/error)
5270
+ * persistent log channel the log-manager assembles. Every call mirrors to
5271
+ * the injected console-like sink (prefixed, per-level method) AND enqueues
5272
+ * one entry (`{ ts, level, source: 'client', scope, text }`, text via
5273
+ * `serializeLogArgs`) for the bounded buffer / flush orchestrator. Iron
5274
+ * rule: the four channel methods NEVER throw — a throwing or missing sink
5275
+ * method, a throwing enqueue (one `sink.warn` drop notice, itself guarded)
5276
+ * and any argument values all degrade silently.
5277
+ *
5278
+ * Single import (`serializeLogArgs`): pure functions only, unit-testable
5279
+ * without DOM.
5280
+ *
5281
+ * @module @dybai/dsh-editor/debug-log
5282
+ */
5283
+
5284
+
5285
+ /** Prefix every console line carries, shared by the debug logger and the channel. */
5286
+ const PREFIX = '[dsh-editor]';
5287
+
5288
+ /** Scope cap: longer scopes are sliced to this many characters. */
5289
+ const MAX_SCOPE_CHARS = 64;
5290
+
5291
+ /** Scope recorded when the caller passes a non-string scope. */
5292
+ const UNKNOWN_SCOPE = 'unknown';
5293
+
5294
+ /** Log levels the channel exposes; each maps to the sink method of the same name. */
5295
+ const LEVELS = ['debug', 'info', 'warn', 'error'];
5296
+
5297
+ /**
5298
+ * Build a prefixed debug logger over an injected console-like sink.
5299
+ * @param {{ debug?: (...args: any[]) => void } | null} [sink] - the console
5300
+ * to write through; `null`/`undefined`/debug-less sinks degrade to a
5301
+ * silent no-op.
5302
+ * @returns {(scope: string, ...args: any[]) => void}
5303
+ */
5304
+ function createDebugLog(sink) {
5305
+ const debug =
5306
+ sink !== null && typeof sink === 'object' && typeof sink.debug === 'function' ? sink.debug.bind(sink) : null;
5307
+ return function debugLog(scope, ...args) {
5308
+ if (debug === null) return;
5309
+ debug('[dsh-editor]', scope, ...args);
5310
+ };
5311
+ }
5312
+
5313
+ /**
5314
+ * Build the leveled persistent log channel: each call mirrors to the
5315
+ * console-like sink's same-named method (missing method → console skipped,
5316
+ * entry still enqueued) and enqueues exactly one entry shaped
5317
+ * `{ ts: now(), level, source: 'client', scope, text: serializeLogArgs(args) }`.
5318
+ *
5319
+ * Scope normalization: non-string or empty string → `'unknown'`; longer
5320
+ * than 64 chars → sliced to 64 (both the console line and the entry carry
5321
+ * the normalized scope; length > 0 strings keep their value, no trim).
5322
+ *
5323
+ * Iron rule: `debug`/`info`/`warn`/`error` NEVER throw. A throwing (or
5324
+ * property-reading-broken) sink method is swallowed; a throwing `enqueue`
5325
+ * is swallowed after one guarded `sink.warn` drop notice that is itself
5326
+ * wrapped in try/catch.
5327
+ *
5328
+ * @param {{ sink?: Console-like; enqueue?: (entry: object) => void; now?: () => number }} [deps]
5329
+ * - `sink`: console-like object with optional debug/info/warn/error methods.
5330
+ * - `enqueue`: receives each entry (the bounded log buffer's `push`).
5331
+ * - `now`: timestamp source for `entry.ts` (defaults to `Date.now`).
5332
+ * @returns {{ debug(scope: string, ...args: unknown[]): void; info(...): void;
5333
+ * warn(...): void; error(...): void }}
5334
+ */
5335
+ function createLogChannel(deps) {
5336
+ const sink = deps?.sink ?? null;
5337
+ const enqueue = deps?.enqueue ?? null;
5338
+ const now = deps?.now ?? Date.now;
5339
+
5340
+ /** Non-string or empty-string scope → 'unknown';超 64 字符截到 64(长度 >0 一律保留原值,不 trim)。纯字符串操作,不会抛。 */
5341
+ const normalizeScope = (scope) =>
5342
+ typeof scope === 'string' && scope.length > 0
5343
+ ? scope.length > MAX_SCOPE_CHARS
5344
+ ? scope.slice(0, MAX_SCOPE_CHARS)
5345
+ : scope
5346
+ : UNKNOWN_SCOPE;
5347
+
5348
+ /** 单级别发射:console 镜像 + 入队;任何一步故障都不得向调用方外抛。 */
5349
+ const emit = (level, scope, args) => {
5350
+ const normalizedScope = normalizeScope(scope);
5351
+ // console 侧:方法缺失即跳过(含属性读取抛错的病态 sink,一并吞掉)
5352
+ try {
5353
+ const method = sink?.[level];
5354
+ if (typeof method === 'function') method.call(sink, PREFIX, normalizedScope, ...args);
5355
+ } catch {
5356
+ // 铁律:console 抛错直接吞掉,不影响入队
5357
+ }
5358
+ const entry = { ts: now(), level, source: 'client', scope: normalizedScope, text: serializeLogArgs(args) };
5359
+ try {
5360
+ enqueue(entry);
5361
+ } catch {
5362
+ // 铁律:入队失败不得外抛;尝试 sink.warn 提示一次,该提示本身也包 try/catch
5363
+ try {
5364
+ const warn = sink?.warn;
5365
+ if (typeof warn === 'function') warn.call(sink, PREFIX, normalizedScope, '[log-channel] enqueue failed; entry dropped');
5366
+ } catch {
5367
+ // 连提示通道也坏了:彻底沉默
5368
+ }
5369
+ }
5370
+ };
5371
+
5372
+ const channel = {};
5373
+ for (const level of LEVELS) {
5374
+ channel[level] = (scope, ...args) => emit(level, scope, args);
5375
+ }
5376
+ return channel;
5377
+ }
5378
+
5379
+ /** The shared production logger (global console; silent when unavailable). */
5380
+ const debugLog = createDebugLog(typeof console !== 'undefined' ? console : null);
5381
+
5382
+ Object.assign(module.exports, { createDebugLog, createLogChannel, debugLog });
5383
+ return module.exports;
5384
+ })();
5385
+
5386
+ /* src/log-buffer.js */
5387
+ const logBuffer = (function () {
5388
+ var module = { exports: {} };
5389
+ var exports = module.exports;
5390
+ /**
5391
+ * Bounded in-memory ring buffer for pending log entries — the queue the
5392
+ * persistent log channel flush orchestrator (Task 6) drains from. Entries are
5393
+ * opaque: the buffer stores whatever it is handed untouched (the channel
5394
+ * guarantees shape) and validates nothing.
5395
+ *
5396
+ * Ordering contract:
5397
+ * - `push` appends a new entry at the tail.
5398
+ * - `requeue(entries)` prepends a whole flush batch back at the head in its
5399
+ * original order, restoring the global timeline after a failed flush.
5400
+ * - `drain` returns every buffered entry in FIFO order and empties the buffer.
5401
+ * - `size` reports the current entry count.
5402
+ *
5403
+ * Whenever the buffer would exceed `cap` (default 500) the OLDEST entries are
5404
+ * dropped — after a `requeue` prepend that means the entries pushed earliest.
5405
+ * A plain array with `shift` eviction is plenty at this scale (≤500); no deque.
5406
+ *
5407
+ * @module @dybai/dsh-editor/log-buffer
5408
+ */
5409
+
5410
+ /** cap 默认 500:超过即丢最老。 */
5411
+ const DEFAULT_CAP = 500;
5412
+
5413
+ /**
5414
+ * Create a bounded FIFO log buffer.
5415
+ * @param {{ cap?: number }} [opts] - `cap` bounds the buffer (default 500);
5416
+ * `cap: undefined` falls back to the default.
5417
+ * @returns {{ push(entry): void; requeue(entries: unknown[]): void;
5418
+ * drain(): unknown[]; size(): number }}
5419
+ */
5420
+ function createLogBuffer(opts) {
5421
+ const cap = opts?.cap ?? DEFAULT_CAP;
5422
+ const entries = [];
5423
+
5424
+ /** 超出 cap 从最老端(数组头部)丢弃。 */
5425
+ const trim = () => {
5426
+ while (entries.length > cap) entries.shift();
5427
+ };
5428
+
5429
+ return {
5430
+ push(entry) {
5431
+ entries.push(entry);
5432
+ trim();
5433
+ },
5434
+ requeue(list) {
5435
+ entries.unshift(...list); // 按原序前插回缓冲头部(flush 失败恢复时序用)
5436
+ trim();
5437
+ },
5438
+ drain() {
5439
+ return entries.splice(0); // FIFO 全量返回并清空
5440
+ },
5441
+ size() {
5442
+ return entries.length;
5443
+ },
5444
+ };
5445
+ }
5446
+
5447
+ Object.assign(module.exports, { createLogBuffer });
5448
+ return module.exports;
5449
+ })();
5450
+
5451
+ /* src/log-flush.js */
5452
+ const logFlush = (function () {
5453
+ var module = { exports: {} };
5454
+ var exports = module.exports;
5455
+ /**
5456
+ * Client-side flush orchestrator for the persistent log channel: debounced
5457
+ * (5 s, reset on every push) or immediate-at-batchSize (50) drains of the
5458
+ * Task 2 ring buffer into the Host RPC endpoint `dshEditor/appendLogs`.
5459
+ *
5460
+ * Everything time- or transport-shaped is INJECTED (`call`, `schedule`,
5461
+ * `cancel`, `now`) so tests drive the clock and the wire by hand; Task 7
5462
+ * binds them to `rpcCall`, `setTimeout`/`clearTimeout` and `Date.now`.
5463
+ *
5464
+ * Ordering contract (spec §6/§8):
5465
+ * - single flight — at most ONE `call` in flight; entries pushed meanwhile
5466
+ * queue in the buffer, and after the in-flight send settles a follow-up
5467
+ * flush drains them (order preserved: an unsent remainder is `requeue`d
5468
+ * BEFORE entries pushed during the flight, because requeue prepends);
5469
+ * - each flush drains once and sends in ≤200-entry CHUNKS (the Host rejects
5470
+ * oversized RPC payloads as `logs/invalid` — one drain must never become
5471
+ * one call);
5472
+ * - on a transport-style failure the unsent remainder (failed chunk + every
5473
+ * later chunk, original order) goes back to the buffer head for the NEXT
5474
+ * round — never a hot retry loop.
5475
+ *
5476
+ * Failure semantics (spec §8 铁律: the flusher NEVER throws to its caller):
5477
+ * - envelope `ok === true` → chunk sent; a fully settled sequence without a
5478
+ * transport failure resets the consecutive-failure counter;
5479
+ * - `ok === false` whose `error.code`/`error.message` matches
5480
+ * `/logs\/invalid/` → only that CHUNK is dropped (invalid payloads are
5481
+ * never retried) with exactly one `onWarn` per flush; the sequence
5482
+ * continues with the next chunk;
5483
+ * - anything else (transport rejection, `ok === false` with another code,
5484
+ * a malformed envelope) → `buffer.requeue` of the unsent remainder and
5485
+ * the counter advances ONCE per flush, warning on the 1st and then every
5486
+ * 50th failure (1, 50, 100, …).
5487
+ *
5488
+ * `dispose()` cancels the pending debounce timer (wired into the plugin's
5489
+ * effect cleanup by Task 7).
5490
+ *
5491
+ * @module @dybai/dsh-editor/log-flush
5492
+ */
5493
+
5494
+ /** 防抖默认 5000ms:每次 push 重置。 */
5495
+ const DEFAULT_DEBOUNCE_MS = 5000;
5496
+ /** 满批立即 flush 的默认批量。 */
5497
+ const DEFAULT_BATCH_SIZE = 50;
5498
+ /** 单次 RPC 条目上限(Host 契约):超出按 logs/invalid 整批拒绝。 */
5499
+ const MAX_RPC_ENTRIES = 200;
5500
+ /** 无效载荷判别:Host `logs/invalid` 拒绝码。 */
5501
+ const INVALID_PATTERN = /logs\/invalid/;
5502
+ /** 连续失败 warn 节流步长:第 1 次与之后每 50 次。 */
5503
+ const WARN_EVERY = 50;
5504
+
5505
+ /**
5506
+ * Create the flush orchestrator.
5507
+ * @param deps - injected collaborators:
5508
+ * `call(endpoint, args)` → the RPC gateway envelope
5509
+ * `{ ok: true } | { ok: false, error: { code?; message? } }`;
5510
+ * `buffer` — a Task 2 `createLogBuffer()` instance;
5511
+ * `schedule(fn, ms)` → timer handle / `cancel(handle)` (setTimeout pair);
5512
+ * `now()` — injected clock, accepted for the deps contract (all flusher
5513
+ * timing itself flows through schedule/cancel);
5514
+ * `onWarn(msg)` — degrade sink (default `console.warn`);
5515
+ * `debounceMs` (default 5000), `batchSize` (default 50).
5516
+ * @returns the flusher: `{ push(entry), flush(), dispose() }`.
5517
+ */
5518
+ function createLogFlusher(deps) {
5519
+ const {
5520
+ call,
5521
+ buffer,
5522
+ schedule,
5523
+ cancel,
5524
+ now,
5525
+ onWarn = (message) => console.warn(message),
5526
+ debounceMs = DEFAULT_DEBOUNCE_MS,
5527
+ batchSize = DEFAULT_BATCH_SIZE
5528
+ } = deps;
5529
+
5530
+ /** 当前防抖计时器句柄;timerArmed 区分「0 号句柄」与「无计时器」。 */
5531
+ let timerHandle;
5532
+ let timerArmed = false;
5533
+ /** 单飞行:正在跑的 flush 周期 promise;null 表示空闲。 */
5534
+ let inFlight = null;
5535
+ /** 连续失败计数;任何成功清零。 */
5536
+ let failures = 0;
5537
+
5538
+ /**
5539
+ * 上报一次降级告警。铁律:上报通道自身失败只吞不抛。
5540
+ * @param message - 告警文本。
5541
+ */
5542
+ function warn(message) {
5543
+ try {
5544
+ onWarn(message);
5545
+ } catch {
5546
+ // 铁律:onWarn 抛出不得外溢
5547
+ }
5548
+ }
5549
+
5550
+ /** 重置防抖计时:先撤销旧计时器再排新的。 */
5551
+ function armTimer() {
5552
+ if (timerArmed) {
5553
+ timerArmed = false;
5554
+ cancel(timerHandle);
5555
+ }
5556
+ timerHandle = schedule(() => {
5557
+ timerArmed = false;
5558
+ void flush();
5559
+ }, debounceMs);
5560
+ timerArmed = true;
5561
+ }
5562
+
5563
+ /**
5564
+ * 信封是否为 `logs/invalid` 拒绝(code 或 message 命中即算)。
5565
+ * @param result - call 的返回值(可能畸形)。
5566
+ * @returns 是否为无效载荷拒绝。
5567
+ */
5568
+ function isInvalidRejection(result) {
5569
+ if (result === null || typeof result !== 'object' || result.ok !== false) return false;
5570
+ const error = result.error;
5571
+ if (error === null || typeof error !== 'object') return false;
5572
+ const code = typeof error.code === 'string' ? error.code : '';
5573
+ const message = typeof error.message === 'string' ? error.message : '';
5574
+ return INVALID_PATTERN.test(code) || INVALID_PATTERN.test(message);
5575
+ }
5576
+
5577
+ /**
5578
+ * 一个 flush 周期:drain 一次 → 按 Host 单次 RPC ≤200 条拆块顺序发送。
5579
+ * 单飞行覆盖整个块序列(中途新 push 只入缓冲等待)。块级语义:
5580
+ * - 成功 → 继续下一块;整个序列落定且无传输失败 → 成功清零计数,
5581
+ * 缓冲仍非空(飞行期间新 push)时自动续排,直到缓冲排空;
5582
+ * - `logs/invalid` → 只丢本块(无效载荷不重试),按 flush 事件只
5583
+ * onWarn 一次,序列继续;
5584
+ * - 其他失败(reject / ok:false 不匹配 / 畸形信封)→ 失败块连同后续
5585
+ * 未发送块原序 requeue 前插恢复全局时序,本轮终止——下轮触发再试,
5586
+ * 绝不热重试;计数整个 flush 只加一。
5587
+ * 周期整体包在 try/catch 里:铁律,flush 永不 reject。
5588
+ */
5589
+ async function runCycle() {
5590
+ try {
5591
+ for (;;) {
5592
+ const entries = buffer.drain();
5593
+ if (!Array.isArray(entries) || entries.length === 0) return;
5594
+ /** 本轮是否已为 invalid 丢弃告警过(按 flush 事件只一次)。 */
5595
+ let invalidWarned = false;
5596
+ for (let offset = 0; offset < entries.length; offset += MAX_RPC_ENTRIES) {
5597
+ const chunk = entries.slice(offset, offset + MAX_RPC_ENTRIES);
5598
+ let result;
5599
+ try {
5600
+ result = await call('dshEditor/appendLogs', { entries: chunk });
5601
+ } catch {
5602
+ result = undefined; // 传输层 reject:归入其他失败
5603
+ }
5604
+ if (result !== null && typeof result === 'object' && result.ok === true) {
5605
+ continue; // 本块已送达,继续下一块
5606
+ }
5607
+ if (isInvalidRejection(result)) {
5608
+ if (!invalidWarned) {
5609
+ invalidWarned = true;
5610
+ warn(`dsh-editor log-flush: appendLogs rejected ${chunk.length} entries as logs/invalid; chunk dropped`);
5611
+ }
5612
+ continue; // 只丢本块,序列继续
5613
+ }
5614
+ // 其他失败:失败块 + 后续未发送块原序前插,本轮终止
5615
+ failures += 1;
5616
+ if (failures === 1 || failures % WARN_EVERY === 0) {
5617
+ warn(`dsh-editor log-flush: appendLogs failed (${failures} consecutive failures); entries requeued for the next flush`);
5618
+ }
5619
+ buffer.requeue(entries.slice(offset));
5620
+ return;
5621
+ }
5622
+ failures = 0; // 序列全部落定且无传输失败(含 invalid 丢弃)→ 成功清零
5623
+ continue; // 缓冲非空 → 自动续排(保序)
5624
+ }
5625
+ } catch {
5626
+ // 铁律:周期内任何意外(含 buffer 故障)都不得外抛
5627
+ } finally {
5628
+ inFlight = null;
5629
+ }
5630
+ }
5631
+
5632
+ /**
5633
+ * 手动触发一次 flush(防抖到期 / 满批 / hide 事件共用)。单飞行:
5634
+ * 已有周期在跑时搭现有班次(其循环会捞走新缓冲条目)。永不 reject。
5635
+ * @returns 周期结束后 resolve 的 promise。
5636
+ */
5637
+ function flush() {
5638
+ if (inFlight !== null) return inFlight;
5639
+ inFlight = runCycle();
5640
+ return inFlight;
5641
+ }
5642
+
5643
+ return {
5644
+ /**
5645
+ * 入一条日志:进缓冲并重置防抖计时;满 batchSize 时立即 flush。
5646
+ * 铁律:永不 throw(单飞行期间的立即 flush 由续排兜住)。
5647
+ * @param entry - 已过 channel 校验的条目(对本模块不透明)。
5648
+ */
5649
+ push(entry) {
5650
+ try {
5651
+ buffer.push(entry);
5652
+ armTimer(); // 每次 push 重置防抖
5653
+ if (buffer.size() >= batchSize) {
5654
+ void flush(); // 满批立即发(flush 永不 reject)
5655
+ }
5656
+ } catch {
5657
+ // 铁律:push 永不外抛
5658
+ }
5659
+ },
5660
+
5661
+ flush,
5662
+
5663
+ /**
5664
+ * 取消挂起的防抖计时器(插件 effect 清理时调用)。
5665
+ */
5666
+ dispose() {
5667
+ if (timerArmed) {
5668
+ timerArmed = false;
5669
+ cancel(timerHandle);
5670
+ }
5671
+ }
5672
+ };
5673
+ }
5674
+
5675
+ Object.assign(module.exports, { createLogFlusher });
5676
+ return module.exports;
5677
+ })();
5678
+
3794
5679
  /* src/client-entry.js (entry; inlined: require() is in scope here) */
3795
5680
  const { MAX_EDIT_CHARS, basenameOf, isEditablePath, parseFileAddress, sessionAddressFor } = address;
3796
5681
  const { deleteLines: deleteLinesOp, offsetOfLine } = lines;
3797
5682
  const { globMatches } = ranking;
3798
5683
  const { createDraftStore } = draftStore;
5684
+ const { createViewStateStore } = viewStateStore;
3799
5685
  const { createEditorService } = service;
3800
5686
  const { createEditorComponents } = components;
3801
- const { defaultKeymap, normalizeKeymap, bindingsOfKeymap } = keymap;
5687
+ const { KEYMAP_ACTIONS, comboOf, defaultKeymap, normalizeKeymap, completeKeymap, bindingsOfKeymap } = keymap;
3802
5688
  const { defaultSettings, normalizeSettings } = settings;
5689
+ const { createLogChannel } = debugLog;
5690
+ const { createLogBuffer } = logBuffer;
5691
+ const { createLogFlusher } = logFlush;
3803
5692
 
3804
5693
  /**
3805
5694
  * @dybai/dsh-editor — the editor framework's browser half (client entry).
@@ -3807,11 +5696,15 @@ window.__ModuleLoader__.load({
3807
5696
  * Bundled by scripts/build.mjs into `client.js` in the `__ModuleLoader__`
3808
5697
  * shape; exports `apply(ctx)` + `inject`. This entry owns the WIRING only —
3809
5698
  * all logic lives in the tested sibling modules (tab-machine, service,
3810
- * ranking, lines, address, draft-store) and the React layer in
3811
- * `src/components.js`.
5699
+ * ranking, lines, address, draft-store, view-state, view-state-store) and the
5700
+ * React layer in `src/components.js`.
3812
5701
  *
3813
5702
  * `apply(ctx)` composes, in order:
3814
5703
  *
5704
+ * 0. the persistent log channel (0.7.0): a bounded 500-entry buffer, the
5705
+ * leveled channel (console mirror + enqueue) and the debounced flusher
5706
+ * draining into the Host `dshEditor/appendLogs` endpoint; hide events
5707
+ * (the draft flush-on-hide block) also flush it early;
3815
5708
  * 1. locale dictionaries + styles;
3816
5709
  * 2. the `dshEditorModes` registry (provide) with the built-in `plain-text`
3817
5710
  * mode registered by this package;
@@ -3827,11 +5720,16 @@ window.__ModuleLoader__.load({
3827
5720
  * 6. the preview-toolbar edit button (`sidebar.right.tab.document.actions`);
3828
5721
  * 7. crash-safety plumbing: the shared draft store with flush-on-hide
3829
5722
  * listeners (visibilitychange/beforeunload/pagehide while any tab
3830
- * controller exists), the mode-preference cache (fetched once at apply,
5723
+ * controller exists), the shared view-state store (0.8.0 — the cursor and
5724
+ * scroll remembered per workspace path, pruned by every new tab controller
5725
+ * and flushed alongside the drafts on hide; `runtime.viewStateStore` plus
5726
+ * `runtime.sessionCwdOf` are what the tab layer keys it by), the
5727
+ * mode-preference cache (fetched once at apply,
3831
5728
  * refetched on every menu open), the self-managed keymap cache, the
3832
5729
  * behavior settings cache (read by every tab machine at notice time and
3833
5730
  * by the mode components at render time — the active-line highlight
3834
- * preference, 0.4.0), and per-tab disk watches (Host
5731
+ * preference, 0.4.0, and the line-number gutter preference, 0.5.0), and
5732
+ * per-tab disk watches (Host
3835
5733
  * `workspaceFiles/changes` push; manual `stat` fallback swept on
3836
5734
  * focus/visibility);
3837
5735
  * 8. the one remaining shortcuts command (`dshEditor.modeMenu`, unbound);
@@ -3851,7 +5749,7 @@ window.__ModuleLoader__.load({
3851
5749
  const NS = 'dshEditor';
3852
5750
  const EDITOR_KIND = 'editor';
3853
5751
  const SERVICE_KEY = 'dshEditor';
3854
- const VERSION = '0.4.0';
5752
+ const VERSION = '0.8.0';
3855
5753
  const STYLE_ID = 'dsh-editor-styles';
3856
5754
 
3857
5755
  /* ---------------------------------------------------------- locale -- */
@@ -3901,12 +5799,20 @@ window.__ModuleLoader__.load({
3901
5799
  'keymap.record': '录制',
3902
5800
  'keymap.recording': '按下新组合…(Esc 取消)',
3903
5801
  'keymap.reset': '恢复默认',
3904
- 'keymap.resetTitle': '把三个动作的键位恢复为默认(Ctrl+S / Ctrl+Shift+S / Ctrl+D)',
5802
+ 'keymap.gotoLine': '跳转到行',
5803
+ 'keymap.resetTitle': '把四个动作的键位恢复为默认(Ctrl+S / Ctrl+Shift+S / Ctrl+D / Ctrl+G)',
3905
5804
  'keymap.duplicate': '该组合已被其他动作占用,请换一个组合。',
3906
5805
  'keymap.reserved': '该组合被浏览器保留(如关闭/新建标签页),无法录制',
3907
5806
  'keymap.reservedHint': '浏览器保留组合(Ctrl/⌘+W、T、N、Q 等)无法录制',
3908
5807
  'keymap.writeFailed': '保存快捷键失败',
3909
5808
  'keymap.conflict': '快捷键已被其他位置修改,已重新读取,请重试。',
5809
+ 'goto.title': '跳转到行',
5810
+ 'goto.context': '当前 {line} 行 · 共 {max} 行',
5811
+ 'goto.placeholder': '行号(1–{max})',
5812
+ 'goto.jump': '跳转',
5813
+ 'goto.jumpTitle': '跳转到输入的行(Enter)',
5814
+ 'goto.invalid': '请输入 1–{max} 之间的行号',
5815
+ 'goto.loading': '正在加载文件…',
3910
5816
  'external.modified': '文件已被外部修改。是否重新加载?',
3911
5817
  'external.deleted': '文件已被外部删除。是否关闭页签?',
3912
5818
  'external.reload': '重新加载',
@@ -3925,6 +5831,8 @@ window.__ModuleLoader__.load({
3925
5831
  'settings.highlightActiveLine': '高亮光标所在行',
3926
5832
  'settings.highlightActiveLineTitle': '在光标(或选区触及)的行背后绘制高亮色带',
3927
5833
  'settings.highlightActiveLineNote': '内置纯文本模式始终支持;其他编辑模式可经描述符 activeLine 声明遵循同一开关。',
5834
+ 'settings.showLineNumbers': '显示行号',
5835
+ 'settings.showLineNumbersTitle': '在内容左侧显示行号列',
3928
5836
  'settings.on': '开',
3929
5837
  'settings.off': '关',
3930
5838
  'settings.writeFailed': '保存设置失败',
@@ -3979,12 +5887,20 @@ window.__ModuleLoader__.load({
3979
5887
  'keymap.record': 'Record',
3980
5888
  'keymap.recording': 'Press the new combo… (Esc to cancel)',
3981
5889
  'keymap.reset': 'Restore defaults',
3982
- 'keymap.resetTitle': 'Restore the default keys (Ctrl+S / Ctrl+Shift+S / Ctrl+D)',
5890
+ 'keymap.gotoLine': 'Go to line',
5891
+ 'keymap.resetTitle': 'Restore the default keys (Ctrl+S / Ctrl+Shift+S / Ctrl+D / Ctrl+G)',
3983
5892
  'keymap.duplicate': 'That combo is already used by another action; pick another one.',
3984
5893
  'keymap.reserved': 'This combination is reserved by the browser (e.g. close/new tab) and cannot be recorded',
3985
5894
  'keymap.reservedHint': 'Browser-reserved combos (Ctrl/⌘+W, T, N, Q, …) cannot be recorded',
3986
5895
  'keymap.writeFailed': 'Failed to save shortcuts',
3987
5896
  'keymap.conflict': 'Shortcuts changed elsewhere; reloaded, please retry.',
5897
+ 'goto.title': 'Go to line',
5898
+ 'goto.context': 'Ln {line} of {max}',
5899
+ 'goto.placeholder': 'Line (1–{max})',
5900
+ 'goto.jump': 'Go',
5901
+ 'goto.jumpTitle': 'Jump to the entered line (Enter)',
5902
+ 'goto.invalid': 'Enter a line between 1 and {max}',
5903
+ 'goto.loading': 'Loading the file…',
3988
5904
  'external.modified': 'The file was modified externally. Reload it?',
3989
5905
  'external.deleted': 'The file was deleted externally. Close this tab?',
3990
5906
  'external.reload': 'Reload',
@@ -4003,6 +5919,8 @@ window.__ModuleLoader__.load({
4003
5919
  'settings.highlightActiveLine': 'Highlight active line',
4004
5920
  'settings.highlightActiveLineTitle': 'Draw a highlight band behind the caret line (or every line the selection touches)',
4005
5921
  'settings.highlightActiveLineNote': 'The built-in plain-text mode always honors this; other editor modes may declare support via their descriptor.',
5922
+ 'settings.showLineNumbers': 'Show line numbers',
5923
+ 'settings.showLineNumbersTitle': 'Draw the line-number column beside the content',
4006
5924
  'settings.on': 'On',
4007
5925
  'settings.off': 'Off',
4008
5926
  'settings.writeFailed': 'Failed to save settings',
@@ -4100,6 +6018,47 @@ window.__ModuleLoader__.load({
4100
6018
  .dsh-editor-settings-toggle:disabled { opacity: 0.45; cursor: default; }
4101
6019
  .dsh-editor-settings-note { padding: 4px 6px 2px; font-size: 11px; color: var(--dsw-alias-label-secondary); opacity: 0.8; }
4102
6020
  .dsh-editor-settings-error { padding: 6px; font-size: 11px; color: var(--dsw-alias-state-error-primary); overflow: hidden; text-overflow: ellipsis; }
6021
+ /* Go-to-line popover (0.6.0): anchored to the status bar's LEFT edge (above
6022
+ * the Ln/Col indicator — the keymap/settings popovers take the right edge).
6023
+ * Absolute against .dsh-editor-status's position:relative, same bottom
6024
+ * overhang and elevation tokens as the other popovers. */
6025
+ .dsh-editor-goto { position: absolute; bottom: calc(100% + 4px); left: 10px; z-index: 40; width: 250px; padding: 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px; background: var(--dsw-alias-bg-layer-2); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18); display: flex; flex-direction: column; gap: 6px; }
6026
+ .dsh-editor-goto-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; font-size: 11px; color: var(--dsw-alias-label-secondary); min-width: 0; }
6027
+ .dsh-editor-goto-title { flex: none; font-weight: 600; color: var(--dsw-alias-label-primary); }
6028
+ .dsh-editor-goto-context { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
6029
+ .dsh-editor-goto-row { display: flex; gap: 6px; }
6030
+ .dsh-editor-goto-input { flex: 1 1 auto; min-width: 0; height: 24px; padding: 0 8px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); font-size: 12px; font-family: var(--dsh-font-mono, ui-monospace, monospace); }
6031
+ .dsh-editor-goto-input:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }
6032
+ .dsh-editor-goto-jump { flex: none; height: 24px; padding: 0 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; background: transparent; color: var(--dsw-alias-label-secondary); font-size: 11px; cursor: pointer; white-space: nowrap; }
6033
+ .dsh-editor-goto-jump:hover:not(:disabled) { color: var(--dsw-alias-label-primary); border-color: var(--dsw-alias-border-l2); }
6034
+ .dsh-editor-goto-jump:disabled { opacity: 0.45; cursor: default; }
6035
+ .dsh-editor-goto-note { font-size: 11px; }
6036
+ .dsh-editor-goto-note.dsh-editor-goto-error { color: var(--dsw-alias-state-error-primary); }
6037
+ /* Line-number gutter (0.5.0): the MONO 13px font lives on the container so
6038
+ * its inline 'ch' widths (src/line-numbers.js) resolve in the SAME font as
6039
+ * the textarea's matching 'padding-left' — a sans-inherited ch clips the
6040
+ * numbers' leading digits. font-size / line-height / padding-top stay
6041
+ * identical to .dsh-editor-area's (13px / 1.5 / 10px) so number k sits
6042
+ * exactly k lines down, same precondition as the highlight backdrop.
6043
+ * z-index 2 paints ABOVE the overlay textarea (z-index 1): with wrap:'off'
6044
+ * a horizontal scroll sweeps glyphs across the padding band and the opaque
6045
+ * gutter must cover them; pointer-events:none keeps clicks falling through
6046
+ * to the textarea (tradeoff: it also covers the scrollbar's left strip).
6047
+ * Geometry: the band spans digits + 1.5 + 2 (ch); the rule
6048
+ * (.dsh-editor-gutter-rule) sits INSIDE the band at digits + 1.5 — the 2ch
6049
+ * right of the rule is covered background keeping the content away from it.
6050
+ * -gutter-text's inline width equals that same rule offset (the digits'
6051
+ * sub-band): right-aligned inside it with the 1.5ch padding-right below
6052
+ * (= GUTTER_GAP_CH, src/line-numbers.js), the widest number ends exactly
6053
+ * 1.5ch left of the rule. CONTENT_GAP_CH (2ch) has no CSS twin — it exists
6054
+ * only as band width minus rule offset.
6055
+ * The RESERVATION is constant: the textarea keeps its padding-left and the
6056
+ * rule and band ALWAYS paint — toggling the preference shows/hides only the
6057
+ * numbers, never moving content or the boundary.
6058
+ * The text block translates against scrollTop at the DOM layer. */
6059
+ .dsh-editor-gutter { position: absolute; left: 0; top: 0; bottom: 0; z-index: 2; overflow: hidden; background: var(--dsw-alias-bg-base); pointer-events: none; font-family: var(--dsw-font-mono, ui-monospace, monospace); font-size: 13px; line-height: 1.5; }
6060
+ .dsh-editor-gutter-rule { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--dsw-alias-border-l1); }
6061
+ .dsh-editor-gutter-text { padding: 10px 1.5ch 0 0; text-align: right; white-space: pre; color: var(--dsw-alias-label-secondary); opacity: 0.8; }
4103
6062
  `;
4104
6063
 
4105
6064
  /**
@@ -4123,6 +6082,13 @@ window.__ModuleLoader__.load({
4123
6082
  /** The plugin apply context and captured service handles, set by apply(). */
4124
6083
  let facade = null;
4125
6084
 
6085
+ /**
6086
+ * The persistent log channel for the current activation, set by apply() and
6087
+ * read by the module-level helpers (keymap migration, tab close/open,
6088
+ * command registration); `null` before the first activation.
6089
+ */
6090
+ let log = null;
6091
+
4126
6092
  /** The Session's workspace root from the sessions facade snapshot. */
4127
6093
  function sessionCwdOf(sessionId) {
4128
6094
  try {
@@ -4459,7 +6425,7 @@ window.__ModuleLoader__.load({
4459
6425
  * read once at apply through `dshEditor/getKeymap` (a failed/short read keeps
4460
6426
  * the defaults), rewritten after every recorder write. Every mounted editor
4461
6427
  * tab matches keydown against this cache — the shortcuts service never sees
4462
- * the three actions.
6428
+ * the framework actions.
4463
6429
  */
4464
6430
  const keymapState = { keymap: defaultKeymap(), updatedAt: undefined, listeners: new Set() };
4465
6431
 
@@ -4502,8 +6468,23 @@ window.__ModuleLoader__.load({
4502
6468
  }
4503
6469
  const value = result.value;
4504
6470
  if (value !== null && Array.isArray(value.bindings)) {
4505
- const normalized = normalizeKeymap(value.bindings);
4506
- if (normalized !== undefined) keymapState.keymap = normalized;
6471
+ // 完整集直接采纳;缺动作的旧版存储(v0.5 及更早没有 gotoLine)经
6472
+ // completeKeymap 迁移补缺——自定义键位保留,缺失动作按候选链填充
6473
+ // (Ctrl+G → Ctrl+Shift+G → Ctrl+Alt+G),迁移不回写 Host。
6474
+ const complete = normalizeKeymap(value.bindings);
6475
+ if (complete !== undefined) {
6476
+ keymapState.keymap = complete;
6477
+ } else {
6478
+ const migrated = completeKeymap(value.bindings);
6479
+ if (migrated !== undefined) {
6480
+ const stored = new Set(value.bindings.map((binding) => (binding !== null && typeof binding === 'object' ? binding.action : null)));
6481
+ const filled = KEYMAP_ACTIONS.filter((action) => !stored.has(action))
6482
+ .map((action) => `${action}=${comboOf(migrated[action]) || '(无空闲候选)'}`)
6483
+ .join(', ');
6484
+ log?.debug('keymap', 'migrated partial store; filled', filled);
6485
+ keymapState.keymap = migrated;
6486
+ }
6487
+ }
4507
6488
  }
4508
6489
  keymapState.updatedAt =
4509
6490
  value !== null && typeof value === 'object' && typeof value.updatedAt === 'number' ? value.updatedAt : undefined;
@@ -4513,8 +6494,8 @@ window.__ModuleLoader__.load({
4513
6494
  /**
4514
6495
  * Persist a new keymap through `dshEditor/setKeymap` (compare-and-set against
4515
6496
  * the cached token, which the mode-association store SHARES — see the Host
4516
- * module doc). Accepts the object form `{ save, saveAll, deleteLines }` or
4517
- * the wire bindings array; invalid input rejects before any RPC. On success
6497
+ * module doc). Accepts the object form `{ save, saveAll, deleteLines, gotoLine }`
6498
+ * or the wire bindings array; invalid input rejects before any RPC. On success
4518
6499
  * the local cache updates and every mounted editor tab immediately matches
4519
6500
  * the new keys. A conflicting write refetches and rejects with
4520
6501
  * `error.conflict === true`.
@@ -4822,7 +6803,7 @@ window.__ModuleLoader__.load({
4822
6803
  // try the next candidate
4823
6804
  }
4824
6805
  }
4825
- console.warn('[dsh-editor] closing a tab is not supported by this sidebar-right build');
6806
+ log?.warn('lifecycle', 'closing a tab is not supported by this sidebar-right build');
4826
6807
  }
4827
6808
 
4828
6809
  /** Subscribe to `ctx.sidebarRight.mounted` changes (session switches). */
@@ -4836,13 +6817,13 @@ window.__ModuleLoader__.load({
4836
6817
  function openFromPreview(sessionId, absolutePath) {
4837
6818
  const sidebarRight = facade === null ? undefined : facade.sidebarRight;
4838
6819
  if (sidebarRight === undefined || sidebarRight === null || typeof sidebarRight.openResource !== 'function') {
4839
- console.warn('[dsh-editor] the right-Sidebar service is unavailable');
6820
+ log?.warn('lifecycle', 'the right-Sidebar service is unavailable');
4840
6821
  return;
4841
6822
  }
4842
6823
  try {
4843
6824
  sidebarRight.openResource(sessionAddressFor(sessionCwdOf(sessionId), sessionId, absolutePath), { kind: EDITOR_KIND });
4844
6825
  } catch (error) {
4845
- console.warn('[dsh-editor] opening the editor failed:', error);
6826
+ log?.warn('lifecycle', 'opening the editor failed:', error);
4846
6827
  }
4847
6828
  }
4848
6829
 
@@ -4859,20 +6840,20 @@ window.__ModuleLoader__.load({
4859
6840
  const dispose = shortcuts.register({ ...command, defaults: {} });
4860
6841
  return typeof dispose === 'function' ? dispose : undefined;
4861
6842
  } catch (fallbackError) {
4862
- console.warn('[dsh-editor] registering command', command.id, 'failed:', fallbackError);
6843
+ log?.warn('commands', 'registering command', command.id, 'failed:', fallbackError);
4863
6844
  return undefined;
4864
6845
  }
4865
6846
  }
4866
- console.warn('[dsh-editor] registering command', command.id, 'failed:', error);
6847
+ log?.warn('commands', 'registering command', command.id, 'failed:', error);
4867
6848
  return undefined;
4868
6849
  }
4869
6850
  }
4870
6851
 
4871
6852
  /**
4872
6853
  * The ONE remaining shortcuts command (spec §6): `dshEditor.modeMenu`, no
4873
- * default key (user-bindable). save / saveAll / deleteLines LEFT this
4874
- * surface on purpose — the web runtime's whitelist refuses browser-owned
4875
- * combos as page-level defaults, so the three actions moved to the
6854
+ * default key (user-bindable). save / saveAll / deleteLines / gotoLine LEFT
6855
+ * this surface on purpose — the web runtime's whitelist refuses browser-owned
6856
+ * combos as page-level defaults, so the framework actions moved to the
4876
6857
  * framework's SELF-MANAGED keymap: the editor root element intercepts
4877
6858
  * keydown and calls preventDefault itself (valid for ANY combo, whitelist
4878
6859
  * not applicable), with bindings persisted via `dshEditor/get|setKeymap`.
@@ -4923,6 +6904,9 @@ window.__ModuleLoader__.load({
4923
6904
  /** One shared draft store for every tab machine (single storage key). */
4924
6905
  const editorDraftStore = createDraftStore(resolveStorageAdapter());
4925
6906
 
6907
+ /** One shared view-state store for every tab (single storage key). */
6908
+ const editorViewStateStore = createViewStateStore(resolveStorageAdapter());
6909
+
4926
6910
  /* ----------------------------------------------------------- apply -- */
4927
6911
 
4928
6912
  /**
@@ -4938,6 +6922,23 @@ window.__ModuleLoader__.load({
4938
6922
  ? ctx.locale.bind(NS)
4939
6923
  : (key) => key;
4940
6924
 
6925
+ // 0. persistent log channel (0.7.0): every leveled call mirrors to the
6926
+ // console and lands in a bounded buffer the flusher drains (debounced,
6927
+ // batch-50) into the Host `dshEditor/appendLogs` endpoint; the
6928
+ // flush-on-hide block below flushes it early. The channel is created
6929
+ // FIRST so every helper below (keymap migration, tab close/open, command
6930
+ // registration, components) can log through it.
6931
+ const logBuffer = createLogBuffer({ cap: 500 });
6932
+ const logFlusher = createLogFlusher({
6933
+ call: (endpoint, args) => rpcCall(endpoint, args),
6934
+ buffer: logBuffer,
6935
+ schedule: (fn, ms) => setTimeout(fn, ms),
6936
+ cancel: (handle) => clearTimeout(handle),
6937
+ now: Date.now,
6938
+ onWarn: (message) => console.warn('[dsh-editor]', message)
6939
+ });
6940
+ log = createLogChannel({ sink: console, enqueue: (entry) => logFlusher.push(entry), now: Date.now });
6941
+
4941
6942
  // 1. locale + styles
4942
6943
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-editor: dictionaries');
4943
6944
  ctx.effect(() => ensureStyles(), 'dsh-editor: styles');
@@ -4963,6 +6964,14 @@ window.__ModuleLoader__.load({
4963
6964
 
4964
6965
  const componentRuntime = {
4965
6966
  draftStore: editorDraftStore,
6967
+ // view-state store (0.8.0): the one shared cursor/scroll memory. Tabs
6968
+ // key it through the session's workspace root, which is why the
6969
+ // module-level resolver is part of the runtime too.
6970
+ viewStateStore: editorViewStateStore,
6971
+ sessionCwdOf,
6972
+ // the persistent log channel (0.7.0): components log through
6973
+ // runtime.log so their traces persist with the same scopes
6974
+ log,
4966
6975
  loadFile,
4967
6976
  writeFile,
4968
6977
  modeRegistry: modeRegistryObj,
@@ -5103,6 +7112,12 @@ window.__ModuleLoader__.load({
5103
7112
  ctx.effect(() => {
5104
7113
  const flushNow = () => {
5105
7114
  if (liveControllers.size > 0) editorDraftStore.flush();
7115
+ // View-state writes are debounced like drafts: flush unconditionally
7116
+ // (the store is a no-op when nothing is pending).
7117
+ editorViewStateStore.flush();
7118
+ // Persistent log channel: fire-and-forget flush (the flusher
7119
+ // itself never throws; the catch guards the returned promise).
7120
+ logFlusher.flush().catch(() => {});
5106
7121
  };
5107
7122
  const onVisibility = () => {
5108
7123
  try {
@@ -5124,8 +7139,11 @@ window.__ModuleLoader__.load({
5124
7139
  window.removeEventListener('beforeunload', flushNow);
5125
7140
  window.removeEventListener('pagehide', flushNow);
5126
7141
  }
7142
+ // Cancel the flusher's pending debounce timer with the block it
7143
+ // flushes alongside (log-flush.js wires dispose here by contract).
7144
+ logFlusher.dispose();
5127
7145
  };
5128
- }, 'dsh-editor: draft flush on hide');
7146
+ }, 'dsh-editor: draft and log flush on hide');
5129
7147
 
5130
7148
  // 8. the one remaining shortcuts command (modeMenu, unbound); the three
5131
7149
  // editor actions are self-managed keymap bindings (see editorCommands).