Skip to content

refactor(dashboard): replace Monaco editor with stream-diffs surfaces - #11352

Draft
Simon-He95 wants to merge 3 commits into
AstrBotDevs:masterfrom
Simon-He95:feat/dashboard-replace-monaco-with-stream-diffs
Draft

Simon-He95 wants to merge 3 commits into
AstrBotDevs:masterfrom
Simon-He95:feat/dashboard-replace-monaco-with-stream-diffs

Conversation

@Simon-He95

@Simon-He95 Simon-He95 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Status: draft, blocked on an upstream bug. The editor this PR moves to has a
select-all defect in @pierre/diffs that this branch mitigates but cannot fix
(see “Upstream select-all bug” below, filed as pierrecomputer/pierre#1338
with a standalone repro).
Please treat the merge decision as open: section 4 below lays out the trade-offs,
and closing this PR is an acceptable outcome.

⚠️ Three capability regressions (read this before reviewing)

These are the only things the new surface does not do. All three were on by default in Monaco, so they are visible in production today even though nobody configured them.

Lost Where it was actually visible On this branch
Minimap on by default; explicitly disabled in 5 places, but left on in /config (ConfigPage), the plugin config dialog (AstrBotConfig), the V4 dialog (AstrBotConfigV4) and inline editor_mode items (ConfigItemRenderer) not available
Code folding on by default in every editor not available
JSON schema diagnostics Monaco's JSON language service: precise error squiggles while typing replaced by one coarse inline hint (core.common.editor.jsonError) plus host-side JSON.parse checks on save

If you use any of these, the right answer is to keep Monaco and close this PR — that is a legitimate outcome. If you never touch them, the trade is a 15.5% smaller build and ~6× faster keystrokes. The full comparison table is in “Why replace Monaco” → “3. Capabilities: what you keep, what you lose” further down, and the middle-ground option is in “4. How to decide” right after it.

What this does

Replaces every monaco-editor usage in the dashboard with a thin wrapper over the stream-diffs File surface that the dashboard already ships for chat code blocks, then removes Monaco entirely.

AstrBot only used Monaco as a syntax-highlighted text box: read-only views plus small editors. It never used LSP, completion, hover, diff views, multi-cursor or getAction APIs — except one editor.action.formatDocument call in the conversation history editor, which is now a debounced host-side JSON.parse/stringify + applyAll replacement.

Changes

  • New dashboard/src/components/shared/StreamDiffsEditor.vue — v-model, readonly, themeType, language, fontSize, editStateKey, and an exposed replaceAll() for host-driven formatting. Themes reuse the chat code-block palette (github-light/github-dark), sizes map to --diffs-font-size / --diffs-line-height / --diffs-tab-size.
  • Migrated 9 call sites
    1. views/ConfigPage.vue — profile/system JSON editor
    2. components/shared/AstrBotConfig.vue — plugin/platform config dialog
    3. components/shared/AstrBotConfigV4.vue — V4 config dialog
    4. components/shared/ConfigItemRenderer.vue — inline editor_mode items
    5. components/extension/McpServersSection.vue — MCP server JSON
    6. components/shared/T2ITemplateEditor.vue — T2I HTML template
    7. components/extension/SkillsSection.vue — skills file editor (multi-language, dynamic read-only)
    8. views/ConversationPage.vue — conversation history editor (+ auto-format)
    9. views/conversation/ConversationWorkspacePage.vue — read-only raw history
  • Interaction contracts preserved: dirty tracking (@change → fileDirty), MCP JSON validation messages, config dirty state, read-only raw data, edit/preview toggle.
  • Removed: monaco-editor, @guolao/vue-monaco-editor, LazyMonacoEditor.ts, plugins/monaco.ts, and the now-orphaned .monaco-* / .editor-container / .editor-fullscreen-btn CSS in the two config dialogs plus stale comments.
  • Dependency bump: stream-diffs 0.0.2 → 0.0.5 (0.0.2 has no ./edit entry point). This also moves the transitive @pierre/diffs 1.6.4 → 1.7.1, so chat code blocks are affected — see verification below.
  • i18n: one new key core.common.editor.jsonError in all four locales (the inline JSON hint that Monaco's diagnostics used to provide).

Why replace Monaco: measured numbers

Everything below was measured on this machine against master (841295f) and this branch, using fresh pnpm build output and the same headless Chromium. Where a number is noisy I say so instead of picking the flattering run.

1. Bundle and download size

metric master (Monaco) this branch delta
dashboard/dist 29,328 KB 24,788 KB −4,540 KB (−15.5%)
dist/assets files 700 664 −36
editor.api chunk 2,295.71 kB (595.23 kB gzip) — gone
dist/assets files matching monaco 3 0 gone
monaco-editor in node_modules 98 MB, 1,467 files — removed

Transfer measured on the same flow (open /data/conversations/legacy, view a conversation, edit its history; median of 3 runs): 4,060,002 bytes over 60 JS responses → 2,539,811 bytes over 51 — about 1.5 MB less (−37%), because that route no longer pulls the Monaco chunk and its workers.

2. Runtime

Same flow, 202-line JSON document, production build, median of 3 runs (each run's keystroke figure is itself the median of 15 keystrokes):

metric master (Monaco) this branch reading
click "Edit" → editor accepts typing 464 ms 309 ms ranges 408–580 vs 224–838 ms — noisy, not conclusive
keystroke → updated text on screen 57 ms 9 ms consistent across runs, both branches accepted input 3/3
long tasks during the flow 4 3–4 no meaningful difference
total blocking time 163–300 ms 147–269 ms no meaningful difference

Honest summary: the clear runtime win is per-keystroke latency (syntax highlighting is already on the main-thread token cache instead of a separate editor instance), and a smaller initial download. Load-time main-thread blocking is essentially unchanged — this PR is not a fix for slow page loads.

3. Capabilities: what you keep, what you lose

"Monaco had it" vs "configured in this repo": several Monaco features were on by default but never configured, so they were present in production.

capability Monaco (before) this branch Actually relied on?
minimap on by default; explicitly disabled in 5 places, left on in the config dialogs (ConfigPage, AstrBotConfig, AstrBotConfigV4, inline ConfigItemRenderer) not available Disabled wherever someone thought about it; still on by default in the config dialogs
code folding on by default not available Never configured; AstrBotConfig's "folding" is config-group UI, unrelated to editor folding
JSON schema validation, inline squiggles yes (JSON language service) not available — replaced by a coarse inline hint (core.common.editor.jsonError) and host-side JSON.parse checks Progressively yes: the MCP dialog and inline config items show validation messages
hover, completion, LSP yes not available No
find / replace (⌘/Ctrl+F, ⌘/Ctrl+Alt+F) yes yes (editor search + replace panel) Not configured, but available in both
multi-cursor yes yes (⌘/Ctrl+click) No
bracket matching yes yes No
indent / outdent, comment toggle, move / copy line, undo / redo yes yes (same keymap) No
format document built-in host-side JSON.parse + JSON.stringify + replaceAll() One call site (conversation history)
themes vs-light / vs-dark github-light / github-dark, same palette as chat code blocks Two config dialogs were hard-coded light before

So the feature set that genuinely regresses is: minimap, code folding, and precise JSON diagnostics. Everything else is either preserved or was never used.

4. How to decide

  • Merge if: a smaller bundle and snappier keystrokes are worth it, and nobody expects a minimap, code folding, or squiggle-level JSON diagnostics in the config editors.
  • Keep Monaco and close this PR if: the config dialogs' minimap or code folding is something users rely on, or precise JSON diagnostics matter more than the size/latency win. Closing this is a perfectly reasonable outcome — the branch is self-contained and nothing else depends on it.
  • Middle ground: keep this PR for the non-JSON surfaces (skills files, T2I templates) and keep Monaco where a JSON schema is genuinely useful. That would need a second wrapper, so I did not do it here.

Verification performed

  • pnpm run build (includes vue-tsc --noEmit) — pass.
  • pnpm run i18n:check — pass (all four locales, no drift).
  • Chat code-block regression for the dependency bump: rendered JSON / diff / long-line blocks through the real MarkdownMessagePart before and after the bump; screenshots are byte-identical in both dark and light themes (cmp clean).
  • Local Playwright (not committed) against the dev server with mocked /api/**:
    • config JSON editor: mounts, loads the document, accepts input, marks dirty, and re-mounts correctly when the store value is written back (revert);
    • inline config editor: mounts, loads the value, shows the JSON error hint for invalid input and clears it when valid, exposes the fullscreen action;
    • fullscreen config dialog: mounts, loads the value, accepts input (verified through a component harness with real props);
    • MCP: editor mounts in the add-server dialog, invalid JSON surfaces the host validation message, valid JSON clears it;
    • workspace raw history: mounts and stays read-only (no contenteditable);
    • skills file editor: mounts;
    • legacy conversation page: view action present (see unverified items).

Reviewer checklist before merge (please actually run the branch)

  1. Rendering & interaction on every replaced surface — dev server, then walk: /config (floating {} button → editor, revert, apply), /config inline editor_mode item + fullscreen dialog, /extension/mcp add-server JSON, /extension/skills file editor, /data/conversations raw-data dialog, /data/conversations/legacy history edit + preview toggle, T2I template editor.
  2. Light/dark themes for each editor (previously vs-light/vs-dark; now themeType), especially the two config dialogs which were hard-coded light.
  3. Read-only behaviour: workspace raw data must not accept input or show a caret.
  4. JSON validation paths: MCP invalid/valid, inline item hint, config apply/revert snackbars.
  5. Chat code blocks (dependency bump side effect): fenced JSON, diff, and very long lines in both themes — this is the riskiest part of the PR.
  6. Confirm the benefit numbers above by running pnpm build on master and on this branch.

Upstream select-all bug: root cause found, mitigated here, still open upstream

Short version: the bug is real, it is upstream, and this branch now mitigates it. Filed as pierrecomputer/pierre#1338, with a standalone repro that depends only on @pierre/diffs@1.7.1 (pierre-diffs-selectall-repro) — a plain File component plus an Editor, no wrapper and no framework.

What actually goes wrong

@pierre/diffs auto-surrounds any non-collapsed selection, including one that spans the whole document: typing { after cmd/ctrl+A produces {<whole document>} instead of replacing it. The caret then sits right after the inserted opener, so every following character is inserted near the start of the buffer while the original content stays. Monaco never did this, so the behaviour only appeared after the migration.

A/B on this branch, same harness, on the conversation history editor (/data/conversations/legacy → view → Edit Conversation), real Chromium, mocked /api/**, seeded with JSON.stringify(history, null, 2), select-all then typing {"b":2} one character at a time:

document lines default autoSurround autoSurround: 'never'
7 87 stale chars, save rejected {"b":2} → formatted → saved
12 2 stale chars, save rejected saved
27 2 stale chars, save rejected saved
62 1,047 stale chars, save rejected saved
202 3,525 stale chars, save rejected saved

Typing { alone over the select-all: default wraps the whole document (document length +1), 'never' replaces it (document length 1). That case is deterministic, and so is 'never'. The amount of stale text in the top row is not: the standalone repro has produced both a short tail and the whole document from identical input, so the invariant to read from that column is "replaced: no", not the exact character count.

"Save rejected" is saveHistoryChanges() failing JSON.parse before it calls conversationApi.replaceMessages — no request is sent. With 'never', every size saved successfully (one request each, valid JSON).

The mitigation in this PR

StreamDiffsEditor.vue now passes autoSurround: 'never' to startEditing(). It removes the whole symptom above and matches the Monaco behaviour being replaced. It is a mitigation, not a fix: the surprising default is still upstream, and this option is worth keeping only until #1338 is resolved.

Correction to an earlier version of this description

An earlier revision of this PR described a second failure mode — a selectionchange read-back race in #runCommand('selectAll') losing the whole-document selection. That observation came from a hacked local build (I had forced the auto-surround helper to return early), not from the public option. With autoSurround: 'never' the select-all path behaved correctly at every size, three runs in a row. Those code paths (#suppressNativeSelectionSync being cleared on keydown, the collapsing focus() inside selectAll) are still worth upstream attention, but this PR makes no claim that they misbehave on their own.

Residual risk after the mitigation

  • Everything above was measured on the conversation history editor. The other eight surfaces share the same wrapper and therefore the same option, but I re-measured only the history editor.
  • The T2I template editor and the skills text editor have no JSON gate; a corrupted document there would still save silently. Not re-driven end-to-end after this change.

Not verified by automation (please eyeball)

  • T2I template editor dialog was not driven end-to-end (it has no public trigger in isolation).
  • The legacy conversation page's dialog is driven end-to-end by the select-all A/B run (view → Edit Conversation → type → Save Changes), including a successful save; its preview/edit toggle and reformat-on-settle path were not re-driven after the autoSurround change.
  • IME input and mobile/narrow viewports for the new surfaces.
  • pnpm lint is not runnable in this repo (no ESLint config present); dashboard CI runs i18n:check + build only.

Summary by Sourcery

Replace Monaco-based dashboard editors with stream-diffs surfaces while preserving editing workflows and reducing the dashboard bundle footprint.

New Features:

  • Add a reusable stream-diffs editor component supporting editable and read-only surfaces, language and theme selection, two-way binding, and host-driven document replacement.

Bug Fixes:

  • Preserve JSON validation feedback for inline configuration editing and MCP server configuration without Monaco diagnostics.
  • Replace conversation-history formatting with debounced JSON pretty-printing while retaining existing editing behavior.

Enhancements:

  • Migrate dashboard configuration, extension, template, skills, conversation, and raw-history editors from Monaco to stream-diffs surfaces.
  • Unify editor syntax highlighting with the chat code-block stack and preserve existing dirty-state, validation, preview, and read-only interaction contracts.
  • Remove Monaco integration, related styles, and dependencies from the dashboard, reducing the built dashboard size and dependency footprint.

Build:

  • Upgrade stream-diffs to support editable file surfaces and remove Monaco packages from dashboard dependencies.

Tests:

  • Verify dashboard builds and locale checks pass, including regression checks for chat code-block rendering after the highlighter dependency update.

Chores:

  • Add localized JSON editor error messaging across all supported locales.

Every Monaco usage is a read-only code view or a small text editor, so the
editor is replaced with a thin wrapper over the stream-diffs File surface
that the dashboard already ships for chat code blocks.

- add StreamDiffsEditor.vue (v-model, read-only, theme/language, replaceAll)
- migrate all 9 call sites: config profiles/system config, inline config
  items, plugin config dialogs, MCP server JSON, skills file editor, T2I
template editor, conversation history editor and workspace raw data
- keep the previous interaction contracts: dirty tracking, JSON validation,
  auto-format of conversation history and read-only raw data
- remove monaco-editor, @guolao/vue-monaco-editor, LazyMonacoEditor and
  plugins/monaco.ts, plus the CSS and class names they left behind
- upgrade stream-diffs 0.0.2 -> 0.0.5 (0.0.2 has no edit entry point)

Benefits measured on this branch: dashboard dist 29,328 KB -> 24,788 KB
(-4,540 KB, -15.5%), assets 700 -> 664 files, and the Monaco chunks
(editor.api 2.30 MB, json/css/html workers, 3 monaco contributions) are gone.
The dependency tree drops monaco-editor (98.8 MB unpacked, 1467 files).

Verification: vue-tsc, pnpm build and i18n:check pass; chat code blocks
render byte-identically before/after the dependency bump (dark and light);
local Playwright runs cover the migrated surfaces.

Known limitation: @pierre/diffs 1.7.1 replace-on-typing keeps the last
tokens of a select-all selection when several characters are typed in a row
(one input event, or paste/IME, replaces correctly). It reproduces on a bare
surface without this wrapper and needs a fix in stream-diffs upstream.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="dashboard/src/components/shared/StreamDiffsEditor.vue" line_range="166" />
<code_context>
+        onChange: (event) => {
+          const text = event.file.contents;
+          if (text === knownText) return;
+          knownText = text;
+          emit('update:modelValue', text);
+          emit('change', text);
</code_context>
<issue_to_address>
**Formatted history is not saved**

When valid history JSON is reformatted, `replaceAllDocument` sets `knownText` before `applyEdits`, so the change handler suppresses the formatted value instead of updating `editedHistory`. `saveHistoryChanges` then saves the stale value, and reopening or toggling edit mode makes the formatting appear to revert.

Ensure the formatted text updates `editedHistory` and the bound model when `replaceAllDocument` applies it.

Also at `dashboard/src/views/ConversationPage.vue:662`.
</issue_to_address>

### Comment 2
<location path="dashboard/package.json" line_range="41" />
<code_context>
     "qrcode": "^1.5.4",
     "shiki": "^3.23.0",
-    "stream-diffs": "0.0.2",
+    "stream-diffs": "0.0.5",
     "vee-validate": "4.11.3",
     "vite-plugin-vuetify": "2.1.3",
</code_context>
<issue_to_address>
**Select-all edits retain old text**

When a user selects all editor contents and types several characters consecutively, the edit callback accepts the surface's contents without correcting the known select-all replacement defect, so typing several characters after selecting all leaves trailing tokens from the previous document in the editor; users can save corrupted text.

Upgrade or patch the underlying edit surface so select-all followed by consecutive typing fully replaces the selection before enabling this editor in the dashboard.

Also at `dashboard/src/components/shared/StreamDiffsEditor.vue:96-98`.
</issue_to_address>

### Comment 3
<location path="dashboard/src/views/ConversationPage.vue" line_range="644" />
<code_context>
         this.fetchConversations();
     },

+    beforeUnmount() {
+        if (this.historyFormatTimer) clearTimeout(this.historyFormatTimer);
+    },
</code_context>
<issue_to_address>
**List requests survive navigation**

When the page unmounts while a list-filter debounce or request is pending, the later `beforeUnmount` option replaces the earlier hook, so it clears the formatting timer but never cancels `debouncedApplyFilters` or aborts `listAbortController`; pending list work continues and updates the abandoned page instance.

Combine the formatting-timer cleanup with the existing list-request cleanup in one `beforeUnmount` hook.
</issue_to_address>

### Comment 4
<location path="dashboard/src/components/shared/StreamDiffsEditor.vue" line_range="213-217" />
<code_context>
+  editing = false;
+});
+
+watch(
+  () => props.modelValue,
+  (value) => {
+    if (value === knownText) return;
+    knownText = value;
+    // `update()`/`updateFile()` end an active edit session, so an externally
+    // replaced document is re-mounted instead of patched in place.
+    void mountSurface();
+  },
+);
+
</code_context>
<issue_to_address>
**New files keep old syntax highlighting**

When the selected file's language changes but its text stays the same, `StreamDiffsEditor` does not watch `props.language`, so the mounted surface keeps the previous grammar when the model value does not change. The new file is displayed with incorrect syntax highlighting.

Watch language changes in `StreamDiffsEditor` and update or remount the surface with the new grammar.

Also at `dashboard/src/components/extension/SkillsSection.vue:895-897`, `dashboard/src/components/shared/StreamDiffsEditor.vue:64-66`, `dashboard/src/components/shared/StreamDiffsEditor.vue:73`.
</issue_to_address>

### Comment 5
<location path="dashboard/src/components/shared/StreamDiffsEditor.vue" line_range="141" />
<code_context>
+    if (token !== mountToken) return;
+    if (!forcePlainText) {
+      // An unknown highlight grammar must not leave the editor blank.
+      forcePlainText = true;
+      surface.dispose();
+      await mountSurface();
</code_context>
<issue_to_address>
**Later files lose syntax highlighting**

When a surface mount fails once and the same component later opens a file with a supported language, `forcePlainText` remains true after the plain-text retry, so later mounts resolve every file to `text`. Supported files then appear without syntax highlighting.

Limit the plain-text fallback to the failed mount retry instead of retaining it for later mounts.
</issue_to_address>

### Comment 6
<location path="dashboard/src/components/shared/ConfigItemRenderer.vue" line_range="146" />
<code_context>
+      <StreamDiffsEditor
+        :theme-type="itemMeta?.editor_theme === 'vs-dark' ? 'dark' : 'light'"
         :language="itemMeta?.editor_language || 'json'"
-        style="min-height: 100px; flex-grow: 1; border: 1px solid rgba(0, 0, 0, 0.1);"
-        :value="modelValue"
-        @update:value="emitUpdate"
</code_context>
<issue_to_address>
**Inline editing area is too small**

When an inline editor contains an empty or short value, the inline editor container has no defined height or minimum height, so the surface collapses to roughly its content height; long values can also expand the config form. Short values leave users with a difficult-to-use editing area.

Give the inline editor a constrained height or a 100px minimum height.

Also at `dashboard/src/components/shared/ConfigItemRenderer.vue:143`, `dashboard/src/components/shared/StreamDiffsEditor.vue:223`.
</issue_to_address>

### Comment 7
<location path="dashboard/src/components/extension/McpServersSection.vue" line_range="329" />
<code_context>
-                tabSize: 2
-              }" @change="validateJson" />
+            <div class="server-config-editor" style="margin-top: 16px;">
+              <StreamDiffsEditor v-model="serverConfigJson" language="json" theme-type="dark" :font-size="13" @change="validateJson" />
             </div>

</code_context>
<issue_to_address>
**Template replacement leaves stale JSON error**

When the user first enters invalid JSON and then selects a valid configuration template, `setConfigTemplate` changes `serverConfigJson` externally, causing the editor to remount without emitting `change`; `validateJson` therefore does not clear the previous error. The editor contains valid JSON while the dialog still displays the invalid-JSON message.

Validate JSON when the template action replaces the text, or watch `serverConfigJson` to keep its validation state synchronized.
</issue_to_address>

### Comment 8
<location path="dashboard/src/components/shared/StreamDiffsEditor.vue" line_range="108-110" />
<code_context>
+  try {
+    JSON.parse(value)
+    return ''
+  } catch (error) {
+    return t('core.common.editor.jsonError', {
+      error: error instanceof Error ? error.message : String(error),
</code_context>
<issue_to_address>
**Editor silently stops accepting input**

When `controller.startEditing()` rejects, `startEditing()` resets `editing` and only writes a console warning, so the surface remains mounted but non-editable and the user gets no indication that editing failed.

Expose and render an editing error, or emit a failure event so the caller can show that the editor is unavailable.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and if the replacement editor emits or applies incorrect text, users could save bad configuration or skill-file contents that remain after reverting the editor change. Those values are bounded and can generally be corrected by editing them again.

Blocking findings: dashboard/src/components/shared/StreamDiffsEditor.vue:166, dashboard/package.json:41, dashboard/src/components/shared/StreamDiffsEditor.vue:217, dashboard/src/components/shared/StreamDiffsEditor.vue:141, dashboard/src/components/shared/ConfigItemRenderer.vue:146, and 1 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread dashboard/package.json
"qrcode": "^1.5.4",
"shiki": "^3.23.0",
"stream-diffs": "0.0.2",
"stream-diffs": "0.0.5",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Select-all edits retain old text

When a user selects all editor contents and types several characters consecutively, the edit callback accepts the surface's contents without correcting the known select-all replacement defect, so typing several characters after selecting all leaves trailing tokens from the previous document in the editor; users can save corrupted text.

Upgrade or patch the underlying edit surface so select-all followed by consecutive typing fully replaces the selection before enabling this editor in the dashboard.

Also at dashboard/src/components/shared/StreamDiffsEditor.vue:96-98.

Prompt for AI agents
In `dashboard/package.json` at line 41:

**Select-all edits retain old text**

When a user selects all editor contents and types several characters consecutively, the edit callback accepts the surface's contents without correcting the known select-all replacement defect, so typing several characters after selecting all leaves trailing tokens from the previous document in the editor; users can save corrupted text.

Upgrade or patch the underlying edit surface so select-all followed by consecutive typing fully replaces the selection before enabling this editor in the dashboard.

Also at `dashboard/src/components/shared/StreamDiffsEditor.vue:96-98`.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed here on purpose — this is an upstream @pierre/diffs 1.7.1 defect, not something this wrapper introduced, and it is already documented in the PR description under "Known limitation".

Repro on a bare createDiffSurface with no Vue wrapper and no app code: select-all, then per-key typing leaves the trailing characters of the previous document; a single key press over the same selection replaces correctly, and paste/IME (insertText) replaces correctly. A setEdges/selection workaround was tried and made it worse (text inserted at the start of the document), so I dropped it rather than ship a hack.

The auto-format path is not exposed to this: replaceAll() applies one explicit full-range edit, and applyEdits is exact. So the blast radius is "user selects all and types several characters by hand" in the 8 editable surfaces.

Agreed this needs a fix, but the fix belongs in stream-diffs. Happy to keep this PR open until that lands if you would rather gate the merge on it — just say which you prefer.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for confirming it reproduces on the bare surface. Please keep the PR gated until stream-diffs fixes this or there’s a reliable workaround: the bug affects the editable surfaces and can leave stale text in content users may save, so documenting it alone isn’t enough. Once addressed upstream, please add a regression check for select-all followed by consecutive typing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updating this thread with new evidence — my first reply undersold the bug, and the PR description has been rewritten accordingly.

It reproduces in the real dashboard, on the File surface, at every document size. Driven end-to-end on this branch (/data/conversations/legacy → view → Edit Conversation), real Chromium, mocked /api/**, seeded with JSON.stringify(history, null, 2), select-all then typing {"b":2} character by character:

history messages document lines rows rendered text after typing leftover
1 7 7 {"b":2}"} 2 chars
2 12 12 {"b":2}"} 2 chars
5 27 27 {"b":2} + the whole original document 433 chars
12 62 62 {"b":2} + the whole original document 1,046 chars
40 202 202 {"b":2} + the whole original document 3,525 chars

rows rendered == document lines in every row, so my earlier assumption that this needed a virtualized surface was wrong. This is not a rendering artifact either — the editor model is corrupted: pressing Save Changes shows "Invalid JSON format" and sends no request, while the control case (same select-all, content delivered as one insertText) formats and saves normally via PUT /api/v1/conversations/{cid}/messages.

It is upstream, and not reachable from either wrapper. stream-diffs has no select-all code at all (grep -rn selectAll src/ dist/ → nothing); src/edit.ts is export * from '@pierre/diffs/edit', and DiffSurfaceController.startEditing() only constructs the upstream Editor and calls editor.edit(instance). cmd/ctrl+A is an upstream keybinding command (dist/editor/command.js maps it to selectAll; the editor's own keydown listener runs the private #runCommand('selectAll')). The race is inside @pierre/diffs: selectAll sets the whole-document selection, then focus() collapses the native selection, then it widens the native selection only to the rendered range with #suppressNativeSelectionSync = true — and the keydown handler clears that flag as its first statement, so a queued selectionchange dispatched after the first keystroke is read back over #selections. #selections, #suppressNativeSelectionSync and #runCommand are all #private, so neither stream-diffs nor StreamDiffsEditor.vue can fix or shim it; a programmatic setEditorSelections substitute was tried and made it worse (text inserted at the start of the document), which is why I did not ship one.

On your gating request: agreed, and I am not asking to merge around it. An upstream issue is being filed with this repro and the proposed fix (stop clearing the suppression flag on keydown, clear it once the edit completes, and stop selectAll from being collapsed by its own focus()), plus a regression check that types several characters over a select-all selection at 7 / 27 / 202 lines as you asked. The PR description now carries the evidence table, the mechanism, the blast radius (JSON surfaces block the save; the T2I template and skills editors have no JSON gate and are unverified — flagged as a risk), and an explicit "merge only if you accept this, or wait for the upstream fix" note.

I would rather this PR stayed blocked until the upstream fix lands. If a reviewer prefers to take it earlier, the honest framing is that it moves nine dashboard editors onto a known data-integrity bug.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Root cause found and mitigated in 77c94f5 — and one correction to my previous reply.

The root cause is auto-surround, not a selection race. @pierre/diffs auto-surrounds any non-collapsed selection, including one spanning the whole document: typing { after cmd/ctrl+A produces {<whole document>} instead of replacing it, and the caret then sits just after the inserted opener, so every following character lands near the start of the buffer while the original content stays.

A/B on the same harness (history editor, real Chromium, mocked /api/**, select-all then typing {"b":2} one key at a time), three consecutive runs with identical results:

document lines default autoSurround autoSurround: 'never'
7 87 stale chars, save rejected (Invalid JSON format, 0 requests) {"b":2} → formatted → saved
12 2 stale chars, rejected saved
27 2 stale chars, rejected saved
62 1,047 stale chars, rejected saved
202 3,525 stale chars, rejected saved

Typing { alone over the select-all: default wraps the whole document (length +1), 'never' replaces it (length 1).

The fix in this PR: StreamDiffsEditor.vue now passes autoSurround: 'never' to startEditing(). It removes the symptom entirely and matches Monaco's behaviour (Monaco never wrapped a selection), so it is not a behaviour change users would notice. It is a mitigation — the surprising default is still upstream, tracked in pierrecomputer/pierre#1338 with this evidence and a suggested fix.

Correction: my previous reply described a second defect — a selectionchange read-back race in #runCommand('selectAll'). That came from a hacked local build where I had forced the auto-surround helper to return early, not from the public option. With autoSurround: 'never' the select-all path behaved correctly at every size. I have corrected the PR description too: those code paths are worth upstream attention, but this PR makes no claim that they misbehave on their own. Mode B was my instrumentation, not your product.

Residual risk, stated plainly: the A/B was measured on the conversation history editor; the other eight surfaces share the same wrapper and therefore the same option but were not re-measured. The T2I template editor and skills editor have no JSON gate, so a corrupted document there would still save silently — not re-driven after this change.

Gates on the pushed commit: pnpm run i18n:check PASS, pnpm run build (includes vue-tsc --noEmit) exit 0.

Given the symptom is now gone and the mechanism is understood, I would treat the gating request as satisfiable by this commit plus the upstream issue — but say the word if you would rather keep it blocked until #1338 ships.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current wrapper sets autoSurround: 'never' for every edit session, addressing the select-all replacement failure. This resolves my gating concern for this PR; thanks for the reproduction and follow-up evidence.

Scope the plain-text fallback to the failing mount so later files keep
their grammar, remount when the language changes under an unchanged
document, and publish replaceAll() results back through v-model so the
formatted history is what gets saved. Restore the inline editor's 100px
minimum height, re-validate the MCP JSON after a template switch, and
fold the history-format timer into the existing beforeUnmount hook so the
list cleanup still runs on navigation.
@Simon-He95
Simon-He95 marked this pull request as draft November 24, 2026 08:11
Upstream's default auto-surround wraps any non-collapsed selection, so a
select-all followed by typing a bracket or quote produced
`{<whole document>}` and every following keystroke landed near the start.
The document then failed JSON.parse and the history editor refused to save.

Monaco never wrapped a selection, so `autoSurround: 'never'` also restores
the previous behaviour. Measured on the history editor at 7/12/27/62/202
document lines: with the default, typing `{"b":2}` over a select-all left
2-3525 stale characters and every save was rejected; with 'never', all
five sizes produced valid JSON and saved.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant