@dybai/dsh-editor 0.5.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: {} };
@@ -1862,8 +2289,9 @@ window.__ModuleLoader__.load({
1862
2289
  /**
1863
2290
  * Framework self-managed keymap — pure key-combo model (spec §6).
1864
2291
  *
1865
- * The three editor actions save / saveAll / deleteLines are NOT registered
1866
- * 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
1867
2295
  * away from page-level defaults). Instead the editor tab's ROOT element
1868
2296
  * intercepts keydown and calls `preventDefault()` itself — a page-level
1869
2297
  * preventDefault works for ANY combination, so the natural keys
@@ -1886,7 +2314,7 @@ window.__ModuleLoader__.load({
1886
2314
  */
1887
2315
 
1888
2316
  /** The framework actions owned by the self-managed keymap channel. */
1889
- const KEYMAP_ACTIONS = ['save', 'saveAll', 'deleteLines'];
2317
+ const KEYMAP_ACTIONS = ['save', 'saveAll', 'deleteLines', 'gotoLine'];
1890
2318
 
1891
2319
  /** Storable `KeyboardEvent.code` alphabet: letters and digits only. */
1892
2320
  const CODE_RE = /^(Key[A-Z]|Digit[0-9])$/;
@@ -1895,33 +2323,30 @@ window.__ModuleLoader__.load({
1895
2323
  const ALLOWED_MODIFIERS = ['primary', 'control', 'alt', 'shift', 'meta'];
1896
2324
 
1897
2325
  /**
1898
- * 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).
1899
2327
  * @returns a fresh keymap object (callers may mutate their copy).
1900
2328
  */
1901
2329
  function defaultKeymap() {
1902
2330
  return {
1903
2331
  save: { code: 'KeyS', modifiers: ['primary'] },
1904
2332
  saveAll: { code: 'KeyS', modifiers: ['primary', 'shift'] },
1905
- deleteLines: { code: 'KeyD', modifiers: ['primary'] }
2333
+ deleteLines: { code: 'KeyD', modifiers: ['primary'] },
2334
+ gotoLine: { code: 'KeyG', modifiers: ['primary'] }
1906
2335
  };
1907
2336
  }
1908
2337
 
1909
2338
  /**
1910
- * Validate and normalize a keymap.
1911
- *
1912
- * Accepts either shape:
1913
- * - the object form `{ save: {code, modifiers}, … }` (one entry per action);
1914
- * - the wire form `[{ action, code, modifiers }]` (`dshEditor/getKeymap`
1915
- * records, any subset order).
1916
- *
1917
- * Rules: all three actions present, `code` from the storable alphabet,
1918
- * `modifiers` an array within the allowed vocabulary, and no two actions
1919
- * 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.
1920
2345
  * @param {any} raw
1921
- * @returns `{ save, saveAll, deleteLines }` with copied modifier arrays, or
1922
- * `undefined` when anything is invalid.
2346
+ * @returns {{ adopted: object, taken: Set<string> }} or `undefined` when
2347
+ * anything is structurally invalid.
1923
2348
  */
1924
- function normalizeKeymap(raw) {
2349
+ function adoptEntries(raw) {
1925
2350
  if (raw === null || typeof raw !== 'object') return undefined;
1926
2351
  let entries;
1927
2352
  if (Array.isArray(raw)) {
@@ -1931,13 +2356,13 @@ window.__ModuleLoader__.load({
1931
2356
  raw[action] === null || typeof raw[action] !== 'object' ? null : { action, ...raw[action] }
1932
2357
  );
1933
2358
  }
1934
- const normalized = {};
1935
- const combos = new Set();
2359
+ const adopted = {};
2360
+ const taken = new Set();
1936
2361
  for (const entry of entries) {
1937
2362
  if (entry === null || typeof entry !== 'object') return undefined;
1938
2363
  const { action, code, modifiers } = entry;
1939
2364
  if (typeof action !== 'string' || !KEYMAP_ACTIONS.includes(action)) return undefined;
1940
- if (Object.prototype.hasOwnProperty.call(normalized, action)) return undefined; // duplicate action
2365
+ if (Object.prototype.hasOwnProperty.call(adopted, action)) return undefined; // duplicate action
1941
2366
  if (typeof code !== 'string' || !CODE_RE.test(code)) return undefined;
1942
2367
  if (!Array.isArray(modifiers)) return undefined;
1943
2368
  const set = [];
@@ -1946,14 +2371,81 @@ window.__ModuleLoader__.load({
1946
2371
  if (!set.includes(modifier)) set.push(modifier);
1947
2372
  }
1948
2373
  const combo = `${code}|${[...set].sort().join('+')}`;
1949
- if (combos.has(combo)) return undefined; // duplicate combination
1950
- combos.add(combo);
1951
- normalized[action] = { code, modifiers: set };
2374
+ if (taken.has(combo)) return undefined; // duplicate combination
2375
+ taken.add(combo);
2376
+ adopted[action] = { code, modifiers: set };
1952
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;
1953
2400
  for (const action of KEYMAP_ACTIONS) {
1954
- if (normalized[action] === undefined) return undefined; // action missing
2401
+ if (walk.adopted[action] === undefined) return undefined; // action missing
1955
2402
  }
1956
- 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;
1957
2449
  }
1958
2450
 
1959
2451
  /**
@@ -2103,7 +2595,58 @@ window.__ModuleLoader__.load({
2103
2595
  }));
2104
2596
  }
2105
2597
 
2106
- 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 });
2107
2650
  return module.exports;
2108
2651
  })();
2109
2652
 
@@ -2119,6 +2662,8 @@ window.__ModuleLoader__.load({
2119
2662
  const { createDiskWatch } = diskWatch;
2120
2663
  const { resolveModeId } = ranking;
2121
2664
  const { matchAction, comboOf, normalizeKeymap, defaultKeymap, isReservedCombo } = keymap;
2665
+ const { parseGotoLine } = gotoLine;
2666
+ const { canApplyScroll, scrollDiffers, selectionFromViewState, selectionRecordFromSnapshot, shouldFocusEditorOnOpen, shouldRestoreViewState, viewStateKey } = viewState;
2122
2667
 
2123
2668
  /**
2124
2669
  * Editor framework UI components — the browser half's React layer.
@@ -2287,7 +2832,9 @@ window.__ModuleLoader__.load({
2287
2832
 
2288
2833
  /**
2289
2834
  * Keep one broken render from silently deleting the editor: the boundary logs
2290
- * 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.
2291
2838
  */
2292
2839
  const EditorBoundary =
2293
2840
  typeof React.Component === 'function'
@@ -2300,7 +2847,11 @@ window.__ModuleLoader__.load({
2300
2847
  return { failed: true };
2301
2848
  }
2302
2849
  componentDidCatch(error) {
2303
- 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
+ }
2304
2855
  }
2305
2856
  render() {
2306
2857
  return this.state.failed ? null : this.props.children;
@@ -2370,6 +2921,13 @@ window.__ModuleLoader__.load({
2370
2921
  * mirrors machine-written selections (framework `setContent` commands) into
2371
2922
  * the DOM. Never reads or writes files itself.
2372
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
+ *
2373
2931
  * Active-line highlight (0.4.0, the `highlightActiveLine` preference): the
2374
2932
  * textarea renders transparent over a backdrop layer that marks the caret
2375
2933
  * line with top/bottom hairlines (VS Code-style line border; a multi-line
@@ -2405,6 +2963,12 @@ window.__ModuleLoader__.load({
2405
2963
  const controller = props.controller;
2406
2964
  const highlightEnabled = props.highlightActiveLine !== false;
2407
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;
2408
2972
  const state = useControllerState(controller);
2409
2973
  // Attached to the textarea below — the single DOM handle every selection
2410
2974
  // path reads (reportSelection, onNavigate, the mirror effect, and the
@@ -2417,6 +2981,17 @@ window.__ModuleLoader__.load({
2417
2981
  const metricsRef = React.useRef(null);
2418
2982
  // Gutter scroll sync: the inner text block translates against scrollTop.
2419
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);
2420
2995
 
2421
2996
  // The gutter's content and width, re-derived only when the line total
2422
2997
  // actually changes — typing within a line (the common keystroke) reuses
@@ -2537,6 +3112,53 @@ window.__ModuleLoader__.load({
2537
3112
  paintCaretLine();
2538
3113
  }, [controller, paintCaretLine]);
2539
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
+
2540
3162
  // The latest sync for passive observers — the ResizeObserver below must
2541
3163
  // not be torn down and rebuilt on every selection change. One sync for
2542
3164
  // both paint surfaces: the caret-line bar AND the gutter's scroll
@@ -2571,6 +3193,40 @@ window.__ModuleLoader__.load({
2571
3193
  syncGutter();
2572
3194
  }, [gutterEnabled, syncGutter]);
2573
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
+
2574
3230
  // Size/visibility restoration: an editor mounted (or toggled on) inside a
2575
3231
  // hidden session subtree caches no metrics (the guard above), so the
2576
3232
  // observer fires the retry the moment the textarea gains a real box —
@@ -2609,14 +3265,58 @@ window.__ModuleLoader__.load({
2609
3265
  if (area === null) return false;
2610
3266
  const target = Math.max(1, Math.floor(Number(line)));
2611
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;
2612
3274
  area.focus();
2613
3275
  area.setSelectionRange(offset, offset);
2614
3276
  const landed = lineOfOffset(area.value, offset);
2615
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
+ }
2616
3287
  reportSelection();
2617
3288
  return true;
2618
3289
  });
2619
- }, [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
+ }, []);
2620
3320
 
2621
3321
  // Mirror machine-written selections (deleteLines and friends) into the
2622
3322
  // DOM; user-driven selections already match, so nothing fights. Painting
@@ -2637,6 +3337,20 @@ window.__ModuleLoader__.load({
2637
3337
  paintCaretLine();
2638
3338
  }, [state.selection, paintCaretLine]);
2639
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
+
2640
3354
  return h(
2641
3355
  'div',
2642
3356
  { className: `${CLASS}-inputwrap` },
@@ -2700,6 +3414,16 @@ window.__ModuleLoader__.load({
2700
3414
  onScroll: () => {
2701
3415
  paintCaretLine();
2702
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);
2703
3427
  }
2704
3428
  })
2705
3429
  );
@@ -2877,13 +3601,14 @@ window.__ModuleLoader__.load({
2877
3601
 
2878
3602
  /**
2879
3603
  * The keymap popover (spec §6): opens from the status-bar keyboard icon.
2880
- * Three rows (保存 / 保存全部 / 删行), each showing the current combo plus a
3604
+ * Four rows (保存 / 保存全部 / 删行 / 跳转到行), each showing the current
3605
+ * combo plus a
2881
3606
  * 「录制」button; recording captures the NEXT keydown at document-capture
2882
3607
  * level (any combination is admissible — the root-element interception
2883
3608
  * preventDefaults browser-reserved combos like Ctrl+S itself — and composing
2884
3609
  * states are ignored during recording per the task ruling; Escape cancels).
2885
- * The footer restores the default bindings (Ctrl+S / Ctrl+Shift+S / Ctrl+D).
2886
- * 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
2887
3612
  * write updates the shared cache so every mounted editor tab immediately
2888
3613
  * matches the new keys.
2889
3614
  */
@@ -3002,7 +3727,8 @@ window.__ModuleLoader__.load({
3002
3727
  const rows = [
3003
3728
  { action: 'save', label: t('keymap.save') },
3004
3729
  { action: 'saveAll', label: t('keymap.saveAll') },
3005
- { action: 'deleteLines', label: t('keymap.deleteLines') }
3730
+ { action: 'deleteLines', label: t('keymap.deleteLines') },
3731
+ { action: 'gotoLine', label: t('keymap.gotoLine') }
3006
3732
  ].map(({ action, label }) => {
3007
3733
  const binding = runtime.getKeymap()[action];
3008
3734
  const isRecording = recording === action;
@@ -3052,20 +3778,156 @@ window.__ModuleLoader__.load({
3052
3778
  ...rows,
3053
3779
  h(
3054
3780
  'div',
3055
- { key: 'footer', className: `${CLASS}-keymap-footer` },
3056
- h('span', { key: 'note', className: `${CLASS}-keymap-note` }, t('keymap.reservedHint')),
3781
+ { key: 'footer', className: `${CLASS}-keymap-footer` },
3782
+ h('span', { key: 'note', className: `${CLASS}-keymap-note` }, t('keymap.reservedHint')),
3783
+ h(
3784
+ 'button',
3785
+ {
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
+ }),
3057
3914
  h(
3058
3915
  'button',
3059
3916
  {
3060
- className: `${CLASS}-keymap-reset`,
3917
+ key: 'jump',
3918
+ className: `${CLASS}-goto-jump`,
3061
3919
  type: 'button',
3062
- disabled: busy || recording !== null,
3063
- title: t('keymap.resetTitle'),
3064
- onClick: runReset
3920
+ disabled: !navable,
3921
+ title: t('goto.jumpTitle'),
3922
+ onClick: jump
3065
3923
  },
3066
- t('keymap.reset')
3924
+ t('goto.jump')
3067
3925
  )
3068
- )
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
3069
3931
  );
3070
3932
  }
3071
3933
 
@@ -3197,6 +4059,13 @@ window.__ModuleLoader__.load({
3197
4059
  * with the mounted mode component (a conflict banner sits above it). Mode
3198
4060
  * switches re-resolve and swap the mode component only — draft, version and
3199
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.
3200
4069
  */
3201
4070
  function EditorTab(props) {
3202
4071
  const t = props.t;
@@ -3219,6 +4088,7 @@ window.__ModuleLoader__.load({
3219
4088
  if (!valid) return undefined;
3220
4089
  try {
3221
4090
  runtime.draftStore.prune();
4091
+ runtime.viewStateStore.prune();
3222
4092
  } catch {
3223
4093
  // best-effort LRU/expiry housekeeping
3224
4094
  }
@@ -3352,6 +4222,12 @@ window.__ModuleLoader__.load({
3352
4222
  const [keymapOpen, setKeymapOpen] = React.useState(false);
3353
4223
  const closeKeymap = React.useCallback(() => setKeymapOpen(false), []);
3354
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
+
3355
4231
  // The settings popover (gear icon) follows the same visibility rule as the
3356
4232
  // keymap popover: a hidden tab always drops it (outside-click handlers
3357
4233
  // belong to the visible surface only).
@@ -3374,6 +4250,7 @@ window.__ModuleLoader__.load({
3374
4250
  // it disarms the recorder through its effect cleanup).
3375
4251
  React.useEffect(() => {
3376
4252
  if (!visible) setKeymapOpen(false);
4253
+ if (!visible) setGotoOpen(false);
3377
4254
  }, [visible]);
3378
4255
 
3379
4256
  const onRootKeyDown = React.useCallback(
@@ -3386,6 +4263,7 @@ window.__ModuleLoader__.load({
3386
4263
  // combination (Ctrl+S page save, Ctrl+D bookmark, …) even when
3387
4264
  // the business action below gates itself out.
3388
4265
  event.preventDefault();
4266
+ runtime.log?.debug('keymap', 'dispatch', action, comboOf(runtime.getKeymap()[action]));
3389
4267
  if (action === 'save') {
3390
4268
  if (controller === null) return; // no-op, combo still suppressed
3391
4269
  const snapshot = controller.getState();
@@ -3408,9 +4286,25 @@ window.__ModuleLoader__.load({
3408
4286
  if (sessionId !== null) runtime.saveAllOfSession(sessionId);
3409
4287
  } else if (action === 'deleteLines') {
3410
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);
3411
4305
  }
3412
4306
  },
3413
- [controller, runtime, sessionId, confirmRecreate]
4307
+ [controller, runtime, sessionId, confirmRecreate, gotoOpen]
3414
4308
  );
3415
4309
 
3416
4310
  // --- machine state + derived chrome values ---
@@ -3418,6 +4312,159 @@ window.__ModuleLoader__.load({
3418
4312
  const dirty = state.dirty === true;
3419
4313
  const deleted = state.external === 'deleted';
3420
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
+
3421
4468
  // 布防解除:任何语义状态变化(编辑、外部状态翻转、相位变化)都让两段式
3422
4469
  // 确认回到初始态。
3423
4470
  React.useEffect(() => {
@@ -3690,7 +4737,12 @@ window.__ModuleLoader__.load({
3690
4737
  highlightActiveLine: runtime.getSettings().highlightActiveLine !== false,
3691
4738
  // The line-numbers contract (0.5.0): same shape, same reach —
3692
4739
  // modes honoring the preference draw the gutter, others ignore.
3693
- showLineNumbers: runtime.getSettings().showLineNumbers !== false
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
3694
4746
  })
3695
4747
  ];
3696
4748
  }
@@ -3781,6 +4833,20 @@ window.__ModuleLoader__.load({
3781
4833
  notice.text
3782
4834
  )
3783
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,
3784
4850
  h(
3785
4851
  'button',
3786
4852
  {
@@ -3914,10 +4980,10 @@ window.__ModuleLoader__.load({
3914
4980
 
3915
4981
  /* ------------------------------------------------------------- export -- */
3916
4982
 
3917
- /** Wrap one component with the render boundary. */
3918
- function guard(Component) {
4983
+ /** Wrap one component with the render boundary (logging through `log`). */
4984
+ function guard(Component, log) {
3919
4985
  return function Guarded(props) {
3920
- return h(EditorBoundary, null, h(Component, props));
4986
+ return h(EditorBoundary, { log }, h(Component, props));
3921
4987
  };
3922
4988
  }
3923
4989
 
@@ -3925,26 +4991,29 @@ window.__ModuleLoader__.load({
3925
4991
  * Build the component set for one plugin activation. `runtime` is injected
3926
4992
  * into the tab/edit-button components' props here (the framework supplies
3927
4993
  * only its own standard props when rendering them).
3928
- * @param {{ draftStore, loadFile, writeFile, modeRegistry, subscribeModes,
4994
+ * @param {{ draftStore, viewStateStore, sessionCwdOf, log, loadFile, writeFile,
4995
+ * modeRegistry, subscribeModes,
3929
4996
  * getAssociations, subscribeAssociations, refreshAssociations, setDefaultMode,
3930
4997
  * resetAssociationsFor, registerTab, subscribeMounted, registerModeMenuOpener,
3931
4998
  * addLiveController, removeLiveController, openFromPreview, getKeymap,
3932
4999
  * subscribeKeymap, setKeymap, getSettings, subscribeSettings, setSettings,
3933
5000
  * saveAllOfSession, requestSaveTab, deleteLinesFor }} runtime
3934
- * 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).
3935
5003
  */
3936
5004
  function createEditorComponents(runtime) {
5005
+ const log = runtime.log;
3937
5006
  const withRuntime = (Component) =>
3938
5007
  function WithRuntime(props) {
3939
5008
  return h(Component, { ...props, runtime });
3940
5009
  };
3941
5010
  return {
3942
5011
  EditorTab: withRuntime(EditorTab),
3943
- EditorTabGuarded: guard(withRuntime(EditorTab)),
5012
+ EditorTabGuarded: guard(withRuntime(EditorTab), log),
3944
5013
  EditorTabTitle: withRuntime(EditorTabTitle),
3945
- EditorTabTitleGuarded: guard(withRuntime(EditorTabTitle)),
5014
+ EditorTabTitleGuarded: guard(withRuntime(EditorTabTitle), log),
3946
5015
  EditButton: withRuntime(EditButton),
3947
- EditButtonGuarded: guard(withRuntime(EditButton)),
5016
+ EditButtonGuarded: guard(withRuntime(EditButton), log),
3948
5017
  PlainTextMode
3949
5018
  };
3950
5019
  }
@@ -4020,15 +5089,606 @@ window.__ModuleLoader__.load({
4020
5089
  return module.exports;
4021
5090
  })();
4022
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
+
4023
5679
  /* src/client-entry.js (entry; inlined: require() is in scope here) */
4024
5680
  const { MAX_EDIT_CHARS, basenameOf, isEditablePath, parseFileAddress, sessionAddressFor } = address;
4025
5681
  const { deleteLines: deleteLinesOp, offsetOfLine } = lines;
4026
5682
  const { globMatches } = ranking;
4027
5683
  const { createDraftStore } = draftStore;
5684
+ const { createViewStateStore } = viewStateStore;
4028
5685
  const { createEditorService } = service;
4029
5686
  const { createEditorComponents } = components;
4030
- const { defaultKeymap, normalizeKeymap, bindingsOfKeymap } = keymap;
5687
+ const { KEYMAP_ACTIONS, comboOf, defaultKeymap, normalizeKeymap, completeKeymap, bindingsOfKeymap } = keymap;
4031
5688
  const { defaultSettings, normalizeSettings } = settings;
5689
+ const { createLogChannel } = debugLog;
5690
+ const { createLogBuffer } = logBuffer;
5691
+ const { createLogFlusher } = logFlush;
4032
5692
 
4033
5693
  /**
4034
5694
  * @dybai/dsh-editor — the editor framework's browser half (client entry).
@@ -4036,11 +5696,15 @@ window.__ModuleLoader__.load({
4036
5696
  * Bundled by scripts/build.mjs into `client.js` in the `__ModuleLoader__`
4037
5697
  * shape; exports `apply(ctx)` + `inject`. This entry owns the WIRING only —
4038
5698
  * all logic lives in the tested sibling modules (tab-machine, service,
4039
- * ranking, lines, address, draft-store) and the React layer in
4040
- * `src/components.js`.
5699
+ * ranking, lines, address, draft-store, view-state, view-state-store) and the
5700
+ * React layer in `src/components.js`.
4041
5701
  *
4042
5702
  * `apply(ctx)` composes, in order:
4043
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;
4044
5708
  * 1. locale dictionaries + styles;
4045
5709
  * 2. the `dshEditorModes` registry (provide) with the built-in `plain-text`
4046
5710
  * mode registered by this package;
@@ -4056,7 +5720,11 @@ window.__ModuleLoader__.load({
4056
5720
  * 6. the preview-toolbar edit button (`sidebar.right.tab.document.actions`);
4057
5721
  * 7. crash-safety plumbing: the shared draft store with flush-on-hide
4058
5722
  * listeners (visibilitychange/beforeunload/pagehide while any tab
4059
- * 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,
4060
5728
  * refetched on every menu open), the self-managed keymap cache, the
4061
5729
  * behavior settings cache (read by every tab machine at notice time and
4062
5730
  * by the mode components at render time — the active-line highlight
@@ -4081,7 +5749,7 @@ window.__ModuleLoader__.load({
4081
5749
  const NS = 'dshEditor';
4082
5750
  const EDITOR_KIND = 'editor';
4083
5751
  const SERVICE_KEY = 'dshEditor';
4084
- const VERSION = '0.5.0';
5752
+ const VERSION = '0.8.0';
4085
5753
  const STYLE_ID = 'dsh-editor-styles';
4086
5754
 
4087
5755
  /* ---------------------------------------------------------- locale -- */
@@ -4131,12 +5799,20 @@ window.__ModuleLoader__.load({
4131
5799
  'keymap.record': '录制',
4132
5800
  'keymap.recording': '按下新组合…(Esc 取消)',
4133
5801
  'keymap.reset': '恢复默认',
4134
- 'keymap.resetTitle': '把三个动作的键位恢复为默认(Ctrl+S / Ctrl+Shift+S / Ctrl+D)',
5802
+ 'keymap.gotoLine': '跳转到行',
5803
+ 'keymap.resetTitle': '把四个动作的键位恢复为默认(Ctrl+S / Ctrl+Shift+S / Ctrl+D / Ctrl+G)',
4135
5804
  'keymap.duplicate': '该组合已被其他动作占用,请换一个组合。',
4136
5805
  'keymap.reserved': '该组合被浏览器保留(如关闭/新建标签页),无法录制',
4137
5806
  'keymap.reservedHint': '浏览器保留组合(Ctrl/⌘+W、T、N、Q 等)无法录制',
4138
5807
  'keymap.writeFailed': '保存快捷键失败',
4139
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': '正在加载文件…',
4140
5816
  'external.modified': '文件已被外部修改。是否重新加载?',
4141
5817
  'external.deleted': '文件已被外部删除。是否关闭页签?',
4142
5818
  'external.reload': '重新加载',
@@ -4211,12 +5887,20 @@ window.__ModuleLoader__.load({
4211
5887
  'keymap.record': 'Record',
4212
5888
  'keymap.recording': 'Press the new combo… (Esc to cancel)',
4213
5889
  'keymap.reset': 'Restore defaults',
4214
- '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)',
4215
5892
  'keymap.duplicate': 'That combo is already used by another action; pick another one.',
4216
5893
  'keymap.reserved': 'This combination is reserved by the browser (e.g. close/new tab) and cannot be recorded',
4217
5894
  'keymap.reservedHint': 'Browser-reserved combos (Ctrl/⌘+W, T, N, Q, …) cannot be recorded',
4218
5895
  'keymap.writeFailed': 'Failed to save shortcuts',
4219
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…',
4220
5904
  'external.modified': 'The file was modified externally. Reload it?',
4221
5905
  'external.deleted': 'The file was deleted externally. Close this tab?',
4222
5906
  'external.reload': 'Reload',
@@ -4334,6 +6018,22 @@ window.__ModuleLoader__.load({
4334
6018
  .dsh-editor-settings-toggle:disabled { opacity: 0.45; cursor: default; }
4335
6019
  .dsh-editor-settings-note { padding: 4px 6px 2px; font-size: 11px; color: var(--dsw-alias-label-secondary); opacity: 0.8; }
4336
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); }
4337
6037
  /* Line-number gutter (0.5.0): the MONO 13px font lives on the container so
4338
6038
  * its inline 'ch' widths (src/line-numbers.js) resolve in the SAME font as
4339
6039
  * the textarea's matching 'padding-left' — a sans-inherited ch clips the
@@ -4382,6 +6082,13 @@ window.__ModuleLoader__.load({
4382
6082
  /** The plugin apply context and captured service handles, set by apply(). */
4383
6083
  let facade = null;
4384
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
+
4385
6092
  /** The Session's workspace root from the sessions facade snapshot. */
4386
6093
  function sessionCwdOf(sessionId) {
4387
6094
  try {
@@ -4718,7 +6425,7 @@ window.__ModuleLoader__.load({
4718
6425
  * read once at apply through `dshEditor/getKeymap` (a failed/short read keeps
4719
6426
  * the defaults), rewritten after every recorder write. Every mounted editor
4720
6427
  * tab matches keydown against this cache — the shortcuts service never sees
4721
- * the three actions.
6428
+ * the framework actions.
4722
6429
  */
4723
6430
  const keymapState = { keymap: defaultKeymap(), updatedAt: undefined, listeners: new Set() };
4724
6431
 
@@ -4761,8 +6468,23 @@ window.__ModuleLoader__.load({
4761
6468
  }
4762
6469
  const value = result.value;
4763
6470
  if (value !== null && Array.isArray(value.bindings)) {
4764
- const normalized = normalizeKeymap(value.bindings);
4765
- 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
+ }
4766
6488
  }
4767
6489
  keymapState.updatedAt =
4768
6490
  value !== null && typeof value === 'object' && typeof value.updatedAt === 'number' ? value.updatedAt : undefined;
@@ -4772,8 +6494,8 @@ window.__ModuleLoader__.load({
4772
6494
  /**
4773
6495
  * Persist a new keymap through `dshEditor/setKeymap` (compare-and-set against
4774
6496
  * the cached token, which the mode-association store SHARES — see the Host
4775
- * module doc). Accepts the object form `{ save, saveAll, deleteLines }` or
4776
- * 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
4777
6499
  * the local cache updates and every mounted editor tab immediately matches
4778
6500
  * the new keys. A conflicting write refetches and rejects with
4779
6501
  * `error.conflict === true`.
@@ -5081,7 +6803,7 @@ window.__ModuleLoader__.load({
5081
6803
  // try the next candidate
5082
6804
  }
5083
6805
  }
5084
- 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');
5085
6807
  }
5086
6808
 
5087
6809
  /** Subscribe to `ctx.sidebarRight.mounted` changes (session switches). */
@@ -5095,13 +6817,13 @@ window.__ModuleLoader__.load({
5095
6817
  function openFromPreview(sessionId, absolutePath) {
5096
6818
  const sidebarRight = facade === null ? undefined : facade.sidebarRight;
5097
6819
  if (sidebarRight === undefined || sidebarRight === null || typeof sidebarRight.openResource !== 'function') {
5098
- console.warn('[dsh-editor] the right-Sidebar service is unavailable');
6820
+ log?.warn('lifecycle', 'the right-Sidebar service is unavailable');
5099
6821
  return;
5100
6822
  }
5101
6823
  try {
5102
6824
  sidebarRight.openResource(sessionAddressFor(sessionCwdOf(sessionId), sessionId, absolutePath), { kind: EDITOR_KIND });
5103
6825
  } catch (error) {
5104
- console.warn('[dsh-editor] opening the editor failed:', error);
6826
+ log?.warn('lifecycle', 'opening the editor failed:', error);
5105
6827
  }
5106
6828
  }
5107
6829
 
@@ -5118,20 +6840,20 @@ window.__ModuleLoader__.load({
5118
6840
  const dispose = shortcuts.register({ ...command, defaults: {} });
5119
6841
  return typeof dispose === 'function' ? dispose : undefined;
5120
6842
  } catch (fallbackError) {
5121
- console.warn('[dsh-editor] registering command', command.id, 'failed:', fallbackError);
6843
+ log?.warn('commands', 'registering command', command.id, 'failed:', fallbackError);
5122
6844
  return undefined;
5123
6845
  }
5124
6846
  }
5125
- console.warn('[dsh-editor] registering command', command.id, 'failed:', error);
6847
+ log?.warn('commands', 'registering command', command.id, 'failed:', error);
5126
6848
  return undefined;
5127
6849
  }
5128
6850
  }
5129
6851
 
5130
6852
  /**
5131
6853
  * The ONE remaining shortcuts command (spec §6): `dshEditor.modeMenu`, no
5132
- * default key (user-bindable). save / saveAll / deleteLines LEFT this
5133
- * surface on purpose — the web runtime's whitelist refuses browser-owned
5134
- * 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
5135
6857
  * framework's SELF-MANAGED keymap: the editor root element intercepts
5136
6858
  * keydown and calls preventDefault itself (valid for ANY combo, whitelist
5137
6859
  * not applicable), with bindings persisted via `dshEditor/get|setKeymap`.
@@ -5182,6 +6904,9 @@ window.__ModuleLoader__.load({
5182
6904
  /** One shared draft store for every tab machine (single storage key). */
5183
6905
  const editorDraftStore = createDraftStore(resolveStorageAdapter());
5184
6906
 
6907
+ /** One shared view-state store for every tab (single storage key). */
6908
+ const editorViewStateStore = createViewStateStore(resolveStorageAdapter());
6909
+
5185
6910
  /* ----------------------------------------------------------- apply -- */
5186
6911
 
5187
6912
  /**
@@ -5197,6 +6922,23 @@ window.__ModuleLoader__.load({
5197
6922
  ? ctx.locale.bind(NS)
5198
6923
  : (key) => key;
5199
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
+
5200
6942
  // 1. locale + styles
5201
6943
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-editor: dictionaries');
5202
6944
  ctx.effect(() => ensureStyles(), 'dsh-editor: styles');
@@ -5222,6 +6964,14 @@ window.__ModuleLoader__.load({
5222
6964
 
5223
6965
  const componentRuntime = {
5224
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,
5225
6975
  loadFile,
5226
6976
  writeFile,
5227
6977
  modeRegistry: modeRegistryObj,
@@ -5362,6 +7112,12 @@ window.__ModuleLoader__.load({
5362
7112
  ctx.effect(() => {
5363
7113
  const flushNow = () => {
5364
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(() => {});
5365
7121
  };
5366
7122
  const onVisibility = () => {
5367
7123
  try {
@@ -5383,8 +7139,11 @@ window.__ModuleLoader__.load({
5383
7139
  window.removeEventListener('beforeunload', flushNow);
5384
7140
  window.removeEventListener('pagehide', flushNow);
5385
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();
5386
7145
  };
5387
- }, 'dsh-editor: draft flush on hide');
7146
+ }, 'dsh-editor: draft and log flush on hide');
5388
7147
 
5389
7148
  // 8. the one remaining shortcuts command (modeMenu, unbound); the three
5390
7149
  // editor actions are self-managed keymap bindings (see editorCommands).