dsh-edit-turn 0.1.1 → 0.2.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/README.md CHANGED
@@ -25,6 +25,7 @@ DSH 的会话日志是 append-only 的事件流:说错的提示词、问偏的
25
25
  - **默认零上下文污染** —— 替换事件的载体是一个**空的 `system/message`**。官方格式文档里空的后置 system 节点是「dormant,不投影成任何消息」,所以回退后模型看到的上下文,和「对话真的停在那一点」完全一致,不会多出任何标记文本。
26
26
  - **轮边界安全** —— 遮蔽窗口右端固定为日志最后一个 surface 节点,左端固定为目标消息节点,因此助手消息(内含 tool_use)与它产生的 tool/result 永远一起走,**不可能留下悬空的调用/结果对**。
27
27
  - **重跑走官方准入路径** —— `ctx.sessionController.prompt()` 是唯一的口径:它会自己 resume 冷会话,并恰好开一个新轮次。
28
+ - **模型回答也能编辑** —— 回答无法被"替换":官方格式禁止 `assistant/message` 携带 `sourceEventSeqs`(已在真实校验器上验证)。做法是回退该回答及其后的内容,再**追加**一条带改写文本的助手消息——模型会把改写后的内容当成自己说过的话,对话可以继续。`source.editedBy` 会如实记录这段文字由插件写入。
28
29
  - **一次点击即执行** —— 保存后不再有二次确认。编辑器本身已经是用户主动打开的动作,面板里也写明了保存会丢弃哪些内容;想恢复两步确认可在 profile 里一行开启(`confirm: true`)。
29
30
  - **中英双语 UI**,跟随 DSH 当前语言。
30
31
  - **皮肤友好** —— 编辑器面板自带不透明表面(`--dshet-panel`)而不是借用主题的表面色变量。皮肤的本意就是让表面半透明、把插画透出来,而它只会给**自己的**元素补可读背景,插件类名不在其中;借用皮肤变量的面板会变成全透明,文字直接压在插画上。暗色分支走官方属性 `body[data-ds-dark-theme]`(与 `dsh-client-ui-theme` 及多个官方 UI 包一致),并用 `backdrop-filter` 与皮肤融合。
@@ -53,6 +54,10 @@ dsh plugin --profile web add /path/to/dsh-edit-turn
53
54
 
54
55
  编辑器里如果提示「这条消息包含图片或文件附件」,说明改写只保留文字,附件会被丢弃。
55
56
 
57
+ **编辑模型的回答**:悬停任意一条模型回复,同样会出现编辑入口。改完点「保存替换」——这条回答被替换为你写的内容,它之后的内容一并移除,模型从此把你写的内容当成自己说过的话,对话可以继续下去。
58
+
59
+ 注意:回答里的**工具调用与思考过程**无法保留(替换后只留文字,编辑器会提示),因为工具调用的结果已经不再成立。
60
+
56
61
  ### 配置
57
62
 
58
63
  写在 profile 里即可覆盖默认值:
@@ -109,11 +114,13 @@ await ctx.sessionController.prompt({ requestId, sessionId, mode: 'queue', conten
109
114
 
110
115
  | 验证 | 命令 | 结果 |
111
116
  |---|---|---|
112
- | 官方 append 契约(真实校验器,进程内) | `npm run verify:contract` | 46 项通过:替换事件被接受、派生历史真的收缩、日志 append-only、工具结果与调用同进同退、空 system 载体不产生模型消息、**连续两次回退都被接受** |
113
- | 纯逻辑 + 宿主集成 + 客户端 DOM 行为(真 HTTP、真校验器、桩服务、DOM 桩) | `npm test` | 63 项通过 |
114
- | 客户端半部静态检查(注册、i18n 完整性、样式、**皮肤可读性**、版本三处同步、线协议) | `npm run verify:client` | 全部通过 |
115
- | 实机前端产物校验(运行中的 DSH 是否在下发当前代码) | `npm run verify:live -- --token-file ~/path/to/dsh.log` | 全部通过 |
117
+ | 运行中的实例是否真的挂载了本插件(只读路由守卫探针,无需 token) | `npm run probe:loaded [端口]` | 通过:`/state` 返 400、`/apply` 返 405 —— 这两个状态码只有本插件会返回 |
118
+ | 官方 append 契约(真实校验器,进程内) | `npm run verify:contract` | 61 项通过:替换事件被接受、派生历史真的收缩、日志 append-only、工具结果与调用同进同退、空 system 载体不产生模型消息、**连续两次回退都被接受**、**编辑模型回答的完整机制被接受** |
119
+ | 纯逻辑 + 宿主集成 + 客户端 DOM 行为(真 HTTP、真校验器、桩服务、DOM 桩) | `npm test` | 83 项通过 |
120
+ | 客户端半部静态检查(注册、i18n 完整性、样式、皮肤可读性、版本三处同步、线协议) | `npm run verify:client` | 全部通过 |
121
+ | 实机前端产物校验(运行中的 DSH 是否在下发当前代码) | `npm run verify:live -- --token-file ~/path/to/dsh.log` | 全部通过(含**宿主节点形状锚点**) |
116
122
  | 真实 profile 安装 / 补丁合成 / 启动 / 工具契约 / 路由守卫 | `npm run verify:profile` | 全部通过 |
123
+ | **真实浏览器端到端**(agent-browser 驱动 Chrome 打开运行实例) | 手动 | 已完成:模型回答行出现「编辑这条回答」、点开编辑器预填真实回复原文、取消后网络层 0 个 apply 请求。截图见 `docs/reply-editor-in-browser.png` |
117
124
 
118
125
  `verify:live` 针对**正在运行的实例**:用 DSH 启动时打印的 token 换取鉴权 cookie,读启动页里的客户端模块组,把含本插件的那一组下载下来,断言插件自己的标记确实在其中。它证明的是「浏览器刷新后会拿到当前代码」,而不是「源码看起来没问题」——前端改动后这是唯一能确认已生效的自动手段。
119
126
 
@@ -133,7 +140,9 @@ ln -s /path/to/dsh-install/node_modules ./node_modules
133
140
 
134
141
  ### 已知限制
135
142
 
136
- - **只支持人类输入的消息**。注入的上下文行、助手消息、系统提示词都不提供编辑入口。
143
+ - 可以编辑**你自己输入的消息**与**模型的回答**;注入的上下文行与系统提示词没有编辑入口。
144
+ - 编辑一条回答会把它替换为**纯文本**:该回答里的工具调用与思考过程会被移除(编辑器会提示),因为它们的结果已不再成立。
145
+ - 编辑一条用户消息会重跑那一轮;编辑一条模型回答只替换内容,**不会**重新问模型。
137
146
  - **编辑会丢弃该消息之后的全部轮次**(MVP 语义,和 ChatGPT 的编辑一致)。想保留原文形成分支,需要走 `sessionController.fork({ sessionId, atSeq })`,尚未实现。
138
147
  - **只改写文本**。消息里含图片/文件附件时,改写后只保留文字(编辑器会提示)。
139
148
  - **会话必须当前在 DSH 中打开**,否则返回 `409 session-not-active`。
@@ -182,6 +191,7 @@ This plugin adds it:
182
191
  - **Zero context pollution by default.** The replacement carrier is an **empty `system/message`**. The official format documents empty later system nodes as dormant, projecting to no message, so the context after an edit is exactly what it would be had the conversation really stopped there - no marker text is added.
183
192
  - **Turn-boundary safe.** The shadow window always ends at the last surface node and always opens at the addressed message, so an assistant message (which carries its own tool_use blocks) and the tool/result it produced are shadowed together. A dangling call/result pair is impossible.
184
193
  - **Official re-run.** `ctx.sessionController.prompt()` is the only prompt admission path; it resumes a cold Session itself and opens exactly one new turn.
194
+ - **The model's replies are editable too.** A reply cannot be swapped in place: the format refuses `sourceEventSeqs` on an `assistant/message` (verified against the real validator). The answer is rolled back together with everything after it, and the corrected text is **appended** as a fresh reply - the model goes on treating it as its own. `source.editedBy` records honestly that the plugin wrote those words.
185
195
  - **One click applies** - no second confirmation. The editor is already an explicit action the user opened, and the panel states what saving discards; a profile can restore the two-step flow with `confirm: true`.
186
196
  - **Bilingual UI** that follows the current DSH locale.
187
197
  - **Skin-friendly** - the editor paints its own opaque surface (`--dshet-panel`) instead of borrowing the theme's surface colours. A skin exists to make surfaces translucent so its artwork shows through, and it only compensates for *its own* elements; a plugin's class names are not on that list, so a panel that borrows those variables can end up fully transparent with text sitting straight on the art. The dark branch uses the official `body[data-ds-dark-theme]` hook (the same one `dsh-client-ui-theme` and several official UI packages use) and blends in with `backdrop-filter`.
@@ -211,6 +221,15 @@ Restart the DSH process that serves that profile to pick it up.
211
221
  If the editor warns that the message carries attachments, the rewrite keeps the
212
222
  text only and drops them.
213
223
 
224
+ **Editing what the model said.** Hover any model reply and the same edit action
225
+ appears. Click "Save replacement" - the reply is replaced with your text,
226
+ everything after it is removed, and the model goes on treating your words as its
227
+ own, so the conversation can continue from there.
228
+
229
+ Note that **tool calls and reasoning inside that reply cannot survive** the
230
+ replacement (only text is kept, and the editor warns first): their results are no
231
+ longer valid once you have changed what the model said.
232
+
214
233
  ### Configuration
215
234
 
216
235
  ```yaml
@@ -276,11 +295,13 @@ Verified against DSH `0.1.6-alpha.2`, entirely **without model calls**:
276
295
 
277
296
  | Check | Command | Result |
278
297
  |---|---|---|
279
- | Official append contract against the real validator, in process | `npm run verify:contract` | 46 checks pass: the replacement is accepted, the derived history really shrinks, the log stays append-only, a tool result leaves with its call, the empty system carrier adds no model message, **two consecutive rollbacks are both accepted** |
280
- | Pure logic, host integration and browser-half DOM behaviour (real HTTP, real validator, stubbed services, DOM stub) | `npm test` | 63 tests pass |
298
+ | Is the plugin actually mounted in a running instance? (read-only route-guard probe, no token needed) | `npm run probe:loaded [port]` | pass: `/state` answers 400 and `/apply` answers 405 - status codes only this plugin produces |
299
+ | Official append contract against the real validator, in process | `npm run verify:contract` | 61 checks pass: the replacement is accepted, the derived history really shrinks, the log stays append-only, a tool result leaves with its call, the empty system carrier adds no model message, **two consecutive rollbacks are both accepted**, **the whole reply-editing mechanism is accepted** |
300
+ | Pure logic, host integration and browser-half DOM behaviour (real HTTP, real validator, stubbed services, DOM stub) | `npm test` | 83 tests pass |
281
301
  | Browser-half static checks (registration, i18n completeness, styles, skin legibility, three-way version sync, wire contract) | `npm run verify:client` | all pass |
282
- | Live client artifact (is the running DSH serving the current code?) | `npm run verify:live -- --token-file ~/path/to/dsh.log` | all pass |
302
+ | Live client artifact (is the running DSH serving the current code?) | `npm run verify:live -- --token-file ~/path/to/dsh.log` | all pass, **including anchors on the host's node shapes** |
283
303
  | Real profile: install, patch composition, boot, tool contract, route guards | `npm run verify:profile` | all pass |
304
+ | **Real browser, end to end** (agent-browser drives Chrome at a running instance) | manual | done: an edit action appears on model reply rows, the editor opens pre-filled with the real reply, and cancelling leaves zero `apply` requests. See `docs/reply-editor-in-browser.png` |
284
305
 
285
306
  `verify:live` targets an instance that is **already running**: it exchanges the
286
307
  token DSH printed on boot for an auth cookie, reads the client module groups out
@@ -319,7 +340,9 @@ ln -s /path/to/dsh-install/node_modules ./node_modules
319
340
 
320
341
  ### Known limitations
321
342
 
322
- - **Human messages only.** Injected context rows, assistant messages and the system prompt offer no edit entry.
343
+ - **Human prompts and model replies** are both editable; injected context rows and the system prompt offer no edit entry.
344
+ - **Editing a reply replaces it with plain text**: the tool calls and reasoning inside it are removed (the editor warns first), because their results are no longer valid.
345
+ - **Editing a user message re-runs that turn; editing a model reply does not ask the model again** - it only replaces the text.
323
346
  - **An edit discards every later turn** (the MVP semantic, matching ChatGPT's edit). Keeping the original as a branch needs `sessionController.fork({ sessionId, atSeq })`, which is not implemented.
324
347
  - **Text only.** A message carrying image or file attachments keeps its text and drops them (the editor warns first).
325
348
  - **The session must be open in DSH**, otherwise the route answers `409 session-not-active`.
package/lib/client.js CHANGED
@@ -30,22 +30,28 @@ window.__ModuleLoader__.load({
30
30
  const ROUTE_PREFIX = '/dsh-edit-turn'
31
31
 
32
32
  /** Keep in sync with package.json and lib/index.js. */
33
- const PLUGIN_VERSION = '0.1.1'
33
+ const PLUGIN_VERSION = '0.2.0'
34
34
 
35
35
  // --- copy -----------------------------------------------------------------
36
36
 
37
37
  const zh = {
38
38
  'action.edit': '编辑这条消息并重跑',
39
+ 'action.edit-reply': '编辑这条回答',
39
40
  'editor.title': '编辑这条消息',
40
- 'editor.placeholder': '修改后确认,会话将回退到这条消息之前并重新跑这一轮。',
41
+ 'editor.title-reply': '编辑这条回答',
42
+ 'editor.placeholder': '修改后保存,会话将回退到这条消息之前并重新跑这一轮。',
43
+ 'editor.placeholder-reply': '改成你希望模型说过的内容,保存后它就成为这条回答。',
41
44
  'editor.save': '保存并重跑',
42
- 'editor.review': '确认回退',
45
+ 'editor.save-reply': '保存替换',
46
+ 'editor.review': '确认执行',
43
47
  'editor.cancel': '取消',
44
- 'editor.pending': '正在回退并重跑…',
48
+ 'editor.pending': '正在执行…',
45
49
  'editor.warn.attachments': '这条消息包含图片或文件附件,改写会丢弃它们,只保留文字。',
50
+ 'editor.warn-reply': '这条回答包含工具调用或思考过程,替换后它们会被一并移除。',
46
51
  'editor.hint': '保存后,这条消息之后的全部内容(含当轮回复与工具调用)会从模型上下文中移除,并从这里重新开始。原始会话日志不会改写。',
47
- 'confirm.title': '确认回退并重跑?',
48
- 'confirm.body': '这条消息之后的全部内容会从模型上下文中移除,然后用你改写后的内容重新跑这一轮。原始会话日志保持不变。',
52
+ 'editor.hint-reply': '保存后,这条回答会被替换为你写的内容,它之后的内容一并移除。模型会把你写的内容当成自己说过的话,对话可以继续下去。原始会话日志不会改写。',
53
+ 'confirm.title': '确认执行?',
54
+ 'confirm.body': '确认后会立即执行:这条消息之后的内容会从模型上下文中移除。原始会话日志不会改写。',
49
55
  'error.invalid': '请求无效,请刷新后重试。',
50
56
  'error.session-not-active': '这个会话当前未激活,请先打开该会话再编辑。',
51
57
  'error.session-not-found': '找不到该会话的日志。',
@@ -57,22 +63,29 @@ window.__ModuleLoader__.load({
57
63
  'error.method': '请求方式不被接受,请刷新后重试。',
58
64
  'error.generic': '编辑失败,请重试。',
59
65
  'error.prompt': '已回退,但重跑没有启动。请手动发送改写后的内容。',
66
+ 'error.reply': '已回退,但替换没有落地。请重试。',
60
67
  'error.empty': '改写后的内容不能为空。',
61
68
  'error.internal': '服务器内部错误,请稍后重试。',
62
69
  }
63
70
 
64
71
  const en = {
65
72
  'action.edit': 'Edit this message and re-run',
73
+ 'action.edit-reply': 'Edit this reply',
66
74
  'editor.title': 'Edit this message',
67
- 'editor.placeholder': 'Confirm after editing: the conversation rolls back to just before this message and this turn runs again.',
75
+ 'editor.title-reply': 'Edit this reply',
76
+ 'editor.placeholder': 'Saving rolls the conversation back to just before this message and this turn runs again.',
77
+ 'editor.placeholder-reply': 'Write what you want the model to have said; saving makes it this reply.',
68
78
  'editor.save': 'Save and re-run',
69
- 'editor.review': 'Confirm rollback',
79
+ 'editor.save-reply': 'Save replacement',
80
+ 'editor.review': 'Confirm',
70
81
  'editor.cancel': 'Cancel',
71
- 'editor.pending': 'Rolling back and re-running...',
82
+ 'editor.pending': 'Working...',
72
83
  'editor.warn.attachments': 'This message carries image or file attachments; rewriting keeps the text only.',
84
+ 'editor.warn-reply': 'This reply carries tool calls or reasoning; replacing it removes them.',
73
85
  'editor.hint': 'Saving removes everything after this message (including that turn\'s reply and tool calls) from the model context and starts again from here. The original session log is never rewritten.',
74
- 'confirm.title': 'Roll back and re-run?',
75
- 'confirm.body': 'Everything after this message leaves the model context, then this turn runs again from your revised text. The original session log stays untouched.',
86
+ 'editor.hint-reply': 'Saving replaces this reply with your text and removes everything after it. The model goes on treating your words as its own, so the conversation can continue from here. The original session log is never rewritten.',
87
+ 'confirm.title': 'Confirm?',
88
+ 'confirm.body': 'Confirming applies right away: everything after this message leaves the model context. The original session log is never rewritten.',
76
89
  'error.invalid': 'Invalid request; refresh and try again.',
77
90
  'error.session-not-active': 'This session is not open in DSH; open it first.',
78
91
  'error.session-not-found': 'No session log was found for this id.',
@@ -84,6 +97,7 @@ window.__ModuleLoader__.load({
84
97
  'error.method': 'The request method is not accepted; refresh and try again.',
85
98
  'error.generic': 'The edit failed; try again.',
86
99
  'error.prompt': 'Rolled back, but the re-run did not start. Send the revised text manually.',
100
+ 'error.reply': 'Rolled back, but the replacement did not land. Try again.',
87
101
  'error.empty': 'The revised message cannot be empty.',
88
102
  'error.internal': 'The host hit an internal error; try again shortly.',
89
103
  }
@@ -201,6 +215,7 @@ window.__ModuleLoader__.load({
201
215
  this.view = Object.freeze({
202
216
  hidden: new Map(),
203
217
  editable: new Map(),
218
+ replies: new Map(),
204
219
  editing: null,
205
220
  draft: '',
206
221
  confirming: false,
@@ -259,9 +274,17 @@ window.__ModuleLoader__.load({
259
274
  for (const turn of Array.isArray(data.turns) ? data.turns : []) {
260
275
  if (turn && typeof turn.seq === 'number') editable.set(turn.seq, turn)
261
276
  }
277
+ // The model's replies are editable too, as a separate list: they are
278
+ // rewritten rather than re-run, so the editor words the consequence
279
+ // differently.
280
+ const replies = new Map()
281
+ for (const reply of Array.isArray(data.replies) ? data.replies : []) {
282
+ if (reply && typeof reply.seq === 'number') replies.set(reply.seq, reply)
283
+ }
262
284
  this.publish({
263
285
  hidden,
264
286
  editable,
287
+ replies,
265
288
  surfaceReady: true,
266
289
  loaded: true,
267
290
  loadError: false,
@@ -350,6 +373,13 @@ window.__ModuleLoader__.load({
350
373
  for (const entry of editable.values()) {
351
374
  if (hidden.has(entry.seq)) editable.delete(entry.seq)
352
375
  }
376
+ // A reply edit shadows its own reply too, so it leaves the editable
377
+ // replies here and re-enters through the next /state refresh (the
378
+ // appended correction is itself an editable reply).
379
+ const replies = new Map(this.view.replies)
380
+ for (const entry of replies.values()) {
381
+ if (hidden.has(entry.seq)) replies.delete(entry.seq)
382
+ }
353
383
  this.animateOnce = true
354
384
  this.editor = null
355
385
  this.editorDraft = ''
@@ -361,11 +391,13 @@ window.__ModuleLoader__.load({
361
391
  confirming: false,
362
392
  hidden,
363
393
  editable,
394
+ replies,
364
395
  failure: null,
365
396
  })
366
397
  // The rollback has landed, so the editor is gone with its row: a
367
- // failed re-run has to be reported somewhere that survives that.
368
- if (data.promptAccepted === false) this.notify('prompt')
398
+ // failed second half has to be reported somewhere that survives that.
399
+ if (data.kind === 'reply' && data.applied === false) this.notify('reply')
400
+ if (data.kind !== 'reply' && data.promptAccepted === false) this.notify('prompt')
369
401
  } catch {
370
402
  this.publish({ pending: false, failure: 'generic' })
371
403
  }
@@ -396,23 +428,44 @@ window.__ModuleLoader__.load({
396
428
 
397
429
  // --- row targets ----------------------------------------------------------
398
430
 
399
- // The editable target of a Chat view node, or null when the row is not a
400
- // human prompt the user can rewrite.
401
- function targetFor(node, editable, hidden) {
402
- if (!node || node.kind !== 'user') return null
431
+ // The editable target of a Chat view node, or null when the row stands for
432
+ // something that cannot be rewritten.
433
+ //
434
+ // Two kinds are offered: a human prompt (rewritten, then the turn re-runs)
435
+ // and a model reply (rewritten in place, discarding everything after it).
436
+ // A step row can span several surface nodes, and the reply seq sits on
437
+ // `finalNode` for an assistant step while a user row carries it on `data`,
438
+ // so both candidates are tried rather than assumed.
439
+ function targetFor(node, view) {
440
+ if (!node) return null
403
441
  const data = node.data || {}
404
- const seq = typeof data.seq === 'number' ? data.seq : node.anchorSeq
405
- if (typeof seq !== 'number') return null
406
- if (hidden.has(seq)) return null
407
- const entry = editable.get(seq)
408
- if (!entry) return null
409
- return {
410
- seq,
411
- turn: entry.turn,
412
- messageId: entry.messageId,
413
- text: typeof entry.text === 'string' ? entry.text : '',
414
- attachments: typeof entry.attachments === 'number' ? entry.attachments : 0,
442
+ const candidates = []
443
+ const push = (value) => {
444
+ if (typeof value === 'number' && !candidates.includes(value)) candidates.push(value)
445
+ }
446
+ if (node.kind === 'user') {
447
+ push(data.seq)
448
+ push(node.anchorSeq)
449
+ } else if (node.kind === 'assistant-step') {
450
+ push(data.finalNode && data.finalNode.seq)
451
+ push(node.anchorSeq)
452
+ } else {
453
+ return null
415
454
  }
455
+ for (const seq of candidates) {
456
+ if (view.hidden.has(seq)) continue
457
+ const entry = view.editable.get(seq) || view.replies.get(seq)
458
+ if (!entry) continue
459
+ return {
460
+ seq,
461
+ mode: view.editable.has(seq) ? 'prompt' : 'reply',
462
+ turn: entry.turn,
463
+ messageId: entry.messageId,
464
+ text: typeof entry.text === 'string' ? entry.text : '',
465
+ attachments: typeof entry.attachments === 'number' ? entry.attachments : 0,
466
+ }
467
+ }
468
+ return null
416
469
  }
417
470
 
418
471
  // Every surface seq a row stands for, so one rollback can hide the rows it
@@ -507,7 +560,7 @@ window.__ModuleLoader__.load({
507
560
  }
508
561
 
509
562
  function injectRowAction(row, target, controller, t) {
510
- const label = t('action.edit')
563
+ const label = t(target.mode === 'reply' ? 'action.edit-reply' : 'action.edit')
511
564
  let entry = rowActions.get(row)
512
565
  if (!entry) {
513
566
  const host = document.createElement('span')
@@ -567,8 +620,23 @@ window.__ModuleLoader__.load({
567
620
  ].join('|')
568
621
  }
569
622
 
623
+ // Every string the editor shows depends on what is being edited: a prompt is
624
+ // re-run, a reply is replaced. Keeping them in one place keeps the two modes
625
+ // from drifting apart in wording.
626
+ function editorTexts(t, target) {
627
+ const reply = target.mode === 'reply'
628
+ return {
629
+ title: t(reply ? 'editor.title-reply' : 'editor.title'),
630
+ placeholder: t(reply ? 'editor.placeholder-reply' : 'editor.placeholder'),
631
+ hint: t(reply ? 'editor.hint-reply' : 'editor.hint'),
632
+ warn: t(reply ? 'editor.warn-reply' : 'editor.warn.attachments'),
633
+ save: t(reply ? 'editor.save-reply' : 'editor.save'),
634
+ }
635
+ }
636
+
570
637
  function renderEditor(row, controller, view, t) {
571
638
  const target = view.editing
639
+ const texts = editorTexts(t, target)
572
640
  const marker = editorMarker(target, view)
573
641
  const existing = row.querySelector('.dshet-editor')
574
642
  if (existing && existing.dataset.dshetFor === marker) return
@@ -580,7 +648,7 @@ window.__ModuleLoader__.load({
580
648
 
581
649
  const title = document.createElement('p')
582
650
  title.className = 'dshet-editor-title'
583
- title.textContent = view.confirming ? t('confirm.title') : t('editor.title')
651
+ title.textContent = view.confirming ? t('confirm.title') : texts.title
584
652
  box.appendChild(title)
585
653
 
586
654
  const area = document.createElement('textarea')
@@ -588,20 +656,20 @@ window.__ModuleLoader__.load({
588
656
  area.value = controller.editorDraft
589
657
  area.disabled = view.pending || view.confirming
590
658
  area.spellcheck = false
591
- area.setAttribute('aria-label', t('editor.title'))
592
- if (!view.confirming) area.placeholder = t('editor.placeholder')
659
+ area.setAttribute('aria-label', texts.title)
660
+ if (!view.confirming) area.placeholder = texts.placeholder
593
661
  area.addEventListener('input', () => controller.setDraft(area.value))
594
662
  box.appendChild(area)
595
663
 
596
664
  const note = document.createElement('p')
597
665
  note.className = 'dshet-note'
598
- note.textContent = view.confirming ? t('confirm.body') : t('editor.hint')
666
+ note.textContent = view.confirming ? t('confirm.body') : texts.hint
599
667
  box.appendChild(note)
600
668
 
601
669
  if (target.attachments > 0) {
602
670
  const warn = document.createElement('p')
603
671
  warn.className = 'dshet-warn'
604
- warn.textContent = t('editor.warn.attachments')
672
+ warn.textContent = texts.warn
605
673
  box.appendChild(warn)
606
674
  }
607
675
  if (typeof view.failure === 'string' && view.failure !== '') {
@@ -634,7 +702,7 @@ window.__ModuleLoader__.load({
634
702
  ? t('editor.pending')
635
703
  : view.confirming
636
704
  ? t('editor.review')
637
- : t('editor.save')
705
+ : texts.save
638
706
  submit.disabled = view.pending
639
707
  submit.onclick = (event) => {
640
708
  event.preventDefault()
@@ -685,7 +753,7 @@ window.__ModuleLoader__.load({
685
753
  if (!node) continue
686
754
  const hidden = isRowHidden(view.hidden, seqsFor(node))
687
755
  setRowHidden(row, hidden, animate)
688
- const target = hidden ? null : targetFor(node, view.editable, view.hidden)
756
+ const target = hidden ? null : targetFor(node, view)
689
757
  if (target !== null) injectRowAction(row, target, controller, t)
690
758
  else removeRowAction(row)
691
759
  if (
package/lib/index.js CHANGED
@@ -48,7 +48,7 @@ export const PLUGIN_ID = 'dsh-edit-turn'
48
48
  export const name = PLUGIN_ID
49
49
 
50
50
  /** Keep in sync with package.json and lib/client.js. */
51
- export const PLUGIN_VERSION = '0.1.1'
51
+ export const PLUGIN_VERSION = '0.2.0'
52
52
 
53
53
  const ROUTE_PREFIX = '/dsh-edit-turn'
54
54
  const SESSION_ID_RE = /^(session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
@@ -219,6 +219,23 @@ export function isHumanPrompt(event) {
219
219
  return Boolean(data && data.source && data.source.kind === 'user')
220
220
  }
221
221
 
222
+ /**
223
+ * Whether an event is a reply the model produced.
224
+ *
225
+ * Editing one of these is a different operation from editing a prompt: the
226
+ * official append contract refuses to let an `assistant/message` carry
227
+ * `sourceEventSeqs` ("assistant/message embeds its source stream"), so a reply
228
+ * can never be the replacement carrier of a rollback. The rollback is therefore
229
+ * followed by appending the corrected text as a new assistant message, and the
230
+ * model goes on seeing it as its own answer.
231
+ *
232
+ * @param event - raw session event.
233
+ * @returns true for an assistant reply.
234
+ */
235
+ export function isAssistantReply(event) {
236
+ return Boolean(event) && event.type === 'assistant/message'
237
+ }
238
+
222
239
  /**
223
240
  * Read the plain text of a message payload, plus how many non-text parts it
224
241
  * carries. Editing is text-only, so a caller must be told when a rewrite would
@@ -228,7 +245,11 @@ export function isHumanPrompt(event) {
228
245
  */
229
246
  export function readMessageText(event) {
230
247
  const data = (event && event.data) || {}
231
- const blocks = Array.isArray(data.content) ? data.content : []
248
+ // `user/message` carries its message fields on `data`; the other three surface
249
+ // types nest them under `data.message`. Both shapes have to read the same way
250
+ // now that the model's replies are editable too.
251
+ const message = data.message && typeof data.message === 'object' ? data.message : data
252
+ const blocks = Array.isArray(message.content) ? message.content : []
232
253
  let text = ''
233
254
  let attachments = 0
234
255
  for (const block of blocks) {
@@ -260,7 +281,7 @@ export function rollbackLedger(events) {
260
281
  const event = bySeq.get(replacement.seq)
261
282
  const data = event && event.data
262
283
  const source = data && (data.source || (data.message && data.message.source))
263
- if (!source || source.kind !== 'plugin' || source.plugin !== PLUGIN_ID) continue
284
+ if (!(source && (source.kind === `plugin:${PLUGIN_ID}` || (source.kind === 'plugin' && source.plugin === PLUGIN_ID)))) continue
264
285
  for (const seq of replacement.shadowed) {
265
286
  const turn = turnOf.get(seq)
266
287
  hidden.push({ seq, turn: typeof turn === 'number' ? turn : null, replacement: replacement.seq })
@@ -336,8 +357,8 @@ function resolveTarget(events, request) {
336
357
  *
337
358
  * @param events - complete contiguous raw event log.
338
359
  * @param surfaceNodes - current surface seqs in model order.
339
- * @param request - `{ seq?, messageId?, turn? }`.
340
- * @returns `{ targetSeq, startSeq, endSeq, shadowed, turn, original, attachments }`.
360
+ * @param request - `{ seq?, messageId?, turn? }` (`turn` addresses a prompt only).
361
+ * @returns `{ targetSeq, messageId, startSeq, endSeq, shadowed, mode, turn, step, provider, model, original, attachments }`.
341
362
  * @throws {EditPlanError} with a stable code when the target cannot be planned.
342
363
  */
343
364
  export function planRollback(events, surfaceNodes, request) {
@@ -352,8 +373,11 @@ export function planRollback(events, surfaceNodes, request) {
352
373
  if (target.seq === surfaceNodes[0]) {
353
374
  throw new EditPlanError('not-editable', 'the system prompt head cannot be edited')
354
375
  }
355
- if (!isHumanPrompt(target)) {
356
- throw new EditPlanError('not-editable', 'only messages you typed can be edited and re-run')
376
+ // Two editable kinds, two outcomes: rewriting a prompt re-runs the turn;
377
+ // rewriting a reply replaces the answer and lets the conversation continue.
378
+ const mode = isHumanPrompt(target) ? 'prompt' : isAssistantReply(target) ? 'reply' : null
379
+ if (mode === null) {
380
+ throw new EditPlanError('not-editable', 'only your own messages and the model replies can be edited')
357
381
  }
358
382
  const startIdx = nodeIndex.get(target.seq)
359
383
  const shadowed = surfaceNodes.slice(startIdx)
@@ -362,13 +386,22 @@ export function planRollback(events, surfaceNodes, request) {
362
386
  }
363
387
  const { text, attachments } = readMessageText(target)
364
388
  const turn = turnOf.get(target.seq)
389
+ const data = target.data && typeof target.data === 'object' ? target.data : {}
390
+ const message = data.message && typeof data.message === 'object' ? data.message : data
391
+ const source = message.source && typeof message.source === 'object' ? message.source : null
365
392
  return {
366
393
  targetSeq: target.seq,
367
394
  messageId: messageIdOf(target),
368
395
  startSeq: shadowed[0],
369
396
  endSeq: shadowed[shadowed.length - 1],
370
397
  shadowed,
398
+ mode,
371
399
  turn: typeof turn === 'number' ? turn : null,
400
+ // The appended correction is keyed by turn:step in the client's reducer, so a
401
+ // missing step would make two corrections collide on "undefined:undefined".
402
+ step: typeof data.step === 'number' ? data.step : 1,
403
+ provider: source && typeof source.provider === 'string' ? source.provider : null,
404
+ model: source && typeof source.model === 'string' ? source.model : null,
372
405
  original: text,
373
406
  attachments,
374
407
  }
@@ -407,6 +440,42 @@ export function editableTurns(events, surfaceNodes) {
407
440
  return out
408
441
  }
409
442
 
443
+ /**
444
+ * Every model reply that can currently be rewritten.
445
+ *
446
+ * Replies with no text at all are skipped: a step that only produced tool calls
447
+ * has nothing to put in a text editor. A reply that carries tool calls *and*
448
+ * text is offered, because replacing it drops those calls along with it - the
449
+ * client warns about that, and the calls cannot survive a rewrite anyway.
450
+ *
451
+ * @param events - complete contiguous raw event log.
452
+ * @param surfaceNodes - current surface seqs in model order.
453
+ * @returns one entry per editable reply, in conversation order.
454
+ */
455
+ export function editableReplies(events, surfaceNodes) {
456
+ const nodeIndex = new Map(surfaceNodes.map((seq, index) => [seq, index]))
457
+ const turnOf = turnIndex(events)
458
+ const head = surfaceNodes[0]
459
+ const out = []
460
+ for (const event of events) {
461
+ if (!isAssistantReply(event)) continue
462
+ if (!nodeIndex.has(event.seq)) continue
463
+ if (event.seq === head) continue
464
+ const { text, attachments } = readMessageText(event)
465
+ if (text.trim() === '') continue
466
+ const turn = turnOf.get(event.seq)
467
+ out.push({
468
+ seq: event.seq,
469
+ turn: typeof turn === 'number' ? turn : null,
470
+ messageId: messageIdOf(event) ?? null,
471
+ text,
472
+ // For a reply these are the non-text blocks: tool calls and reasoning.
473
+ attachments,
474
+ })
475
+ }
476
+ return out
477
+ }
478
+
410
479
  // ---------------------------------------------------------------------------
411
480
  // host service plumbing
412
481
  // ---------------------------------------------------------------------------
@@ -535,6 +604,7 @@ async function stateOf(ctx, sessionId, config) {
535
604
  edits: ledger.edits.length,
536
605
  surface: folded.nodes,
537
606
  turns: editableTurns(events, folded.nodes),
607
+ replies: editableReplies(events, folded.nodes),
538
608
  live: Boolean(live),
539
609
  busy: isBusy(events),
540
610
  lastSeq: events.length > 0 ? events[events.length - 1].seq : -1,
@@ -564,7 +634,7 @@ export function buildCarrier(plan, lastTurn, config) {
564
634
  id: randomUUID(),
565
635
  role: 'system',
566
636
  content: [],
567
- source: { kind: 'plugin', plugin: PLUGIN_ID },
637
+ source: { kind: `plugin:${PLUGIN_ID}` },
568
638
  },
569
639
  },
570
640
  }
@@ -575,7 +645,43 @@ export function buildCarrier(plan, lastTurn, config) {
575
645
  id: randomUUID(),
576
646
  role: 'user',
577
647
  content: [{ type: 'text', text: config.markerText }],
578
- source: { kind: 'plugin', plugin: PLUGIN_ID },
648
+ source: { kind: `plugin:${PLUGIN_ID}` },
649
+ },
650
+ }
651
+ }
652
+
653
+ /**
654
+ * The new assistant message that carries an edited reply.
655
+ *
656
+ * A reply cannot be swapped in place - the validator refuses `sourceEventSeqs`
657
+ * on an `assistant/message` - so the correction is appended as a fresh reply.
658
+ * `turn`/`step` are always set because the client keys a reply node by
659
+ * `turn:step`; leaving them out would make two corrections collide.
660
+ *
661
+ * `source.kind` stays `model` so the entry renders and projects exactly like an
662
+ * ordinary reply, while `editedBy` records honestly that the text was written by
663
+ * the plugin and not produced by the model.
664
+ *
665
+ * @param plan - the planned window, for the original's turn/step/provider.
666
+ * @param text - the replacement text.
667
+ * @returns `{ type, data }` for `session.append`, to be marked `surfaceOp: 'append'`.
668
+ */
669
+ export function buildCorrection(plan, text) {
670
+ const source = { kind: 'model', editedBy: PLUGIN_ID }
671
+ if (typeof plan.provider === 'string' && plan.provider !== '') source.provider = plan.provider
672
+ if (typeof plan.model === 'string' && plan.model !== '') source.model = plan.model
673
+ return {
674
+ type: 'assistant/message',
675
+ data: {
676
+ turn: typeof plan.turn === 'number' ? plan.turn : 0,
677
+ step: typeof plan.step === 'number' ? plan.step : 1,
678
+ message: {
679
+ id: randomUUID(),
680
+ role: 'assistant',
681
+ content: [{ type: 'text', text }],
682
+ source,
683
+ },
684
+ stream: [],
579
685
  },
580
686
  }
581
687
  }
@@ -632,11 +738,47 @@ async function applyEdit(ctx, sessionId, body, config) {
632
738
  }
633
739
  const flush = await flushSession(ctx, session)
634
740
 
635
- // Step two: admit the revised prompt. This is the only official prompt path,
636
- // so it also resumes a cold Session and starts exactly one new turn.
741
+ // Step two depends on what was edited.
742
+ //
743
+ // Rewriting a reply cannot swap the text in place - an `assistant/message` may
744
+ // never carry `sourceEventSeqs`, so it can never be a replacement carrier
745
+ // (checked against the real validator, not assumed). The correction is
746
+ // appended instead, in the same shape the agent loop records a reply, so the
747
+ // model goes on seeing the edited text as its own answer and the conversation
748
+ // continues from there. Nothing is re-run: the answer was fixed, the model was
749
+ // not asked again.
750
+ if (plan.mode === 'reply') {
751
+ const correction = buildCorrection(plan, text)
752
+ let appended
753
+ try {
754
+ appended = session.append(correction.type, correction.data, { surfaceOp: 'append' })
755
+ } catch (error) {
756
+ return {
757
+ kind: 'reply',
758
+ replacementSeq: replacement.seq,
759
+ applied: false,
760
+ applyError: `the corrected reply was refused: ${String((error && error.message) || error)}`,
761
+ shadowed: plan.shadowed,
762
+ ...flush,
763
+ }
764
+ }
765
+ const corrected = await flushSession(ctx, session)
766
+ return {
767
+ kind: 'reply',
768
+ replacementSeq: replacement.seq,
769
+ appendedSeq: appended.seq,
770
+ applied: true,
771
+ shadowed: plan.shadowed,
772
+ ...corrected,
773
+ }
774
+ }
775
+
776
+ // A rewritten prompt is re-run through the only official prompt path, which
777
+ // also resumes a cold Session and starts exactly one new turn.
637
778
  const controller = ctx.get('sessionController')
638
779
  if (!controller || typeof controller.prompt !== 'function') {
639
780
  return {
781
+ kind: 'prompt',
640
782
  replacementSeq: replacement.seq,
641
783
  promptAccepted: false,
642
784
  promptError: 'sessionController.prompt unavailable',
@@ -656,6 +798,7 @@ async function applyEdit(ctx, sessionId, body, config) {
656
798
  )
657
799
  } catch (error) {
658
800
  return {
801
+ kind: 'prompt',
659
802
  replacementSeq: replacement.seq,
660
803
  promptAccepted: false,
661
804
  promptError: String((error && error.message) || error),
@@ -665,6 +808,7 @@ async function applyEdit(ctx, sessionId, body, config) {
665
808
  }
666
809
 
667
810
  return {
811
+ kind: 'prompt',
668
812
  replacementSeq: replacement.seq,
669
813
  promptAccepted: true,
670
814
  shadowed: plan.shadowed,
@@ -716,16 +860,24 @@ function registerTool(ctx) {
716
860
  if (!events) throw new Error(`no session log for ${sessionId}`)
717
861
  const nodes = surfaceOf(ctx, sessionId, events)
718
862
  const turns = editableTurns(events, nodes)
863
+ const replies = editableReplies(events, nodes)
719
864
  const limit = typeof args.limit === 'number' && args.limit > 0 ? Math.floor(args.limit) : 20
720
865
  const shown = turns.slice(-limit)
866
+ const shownReplies = replies.slice(-limit)
721
867
  const lines = [
722
- `session ${sessionId}: ${turns.length} editable turn(s), ${isBusy(events) ? 'BUSY' : 'idle'}`,
868
+ `session ${sessionId}: ${turns.length} editable turn(s), ${replies.length} editable reply/replies, ${isBusy(events) ? 'BUSY' : 'idle'}`,
723
869
  ]
724
870
  for (const turn of shown) {
725
871
  const preview = turn.text.length > 160 ? `${turn.text.slice(0, 160)}...` : turn.text
726
872
  lines.push(`- turn ${turn.turn} (seq ${turn.seq}, ${turn.attachments} attachment(s)): ${preview}`)
727
873
  }
728
874
  if (turns.length > shown.length) lines.push(`(${turns.length - shown.length} earlier turn(s) omitted)`)
875
+ for (const reply of shownReplies) {
876
+ const preview = reply.text.length > 160 ? `${reply.text.slice(0, 160)}...` : reply.text
877
+ lines.push(`- reply (seq ${reply.seq}, ${reply.attachments} non-text part(s)): ${preview}`)
878
+ }
879
+ if (replies.length > shownReplies.length) lines.push(`(${replies.length - shownReplies.length} earlier reply/replies omitted)`)
880
+ lines.push('editing a turn re-runs it; editing a reply replaces its text and discards what follows.')
729
881
  return lines.join('\n')
730
882
  },
731
883
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-edit-turn",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Edit any user turn in DeepSeek Harness and re-run it: an inline editor on the message row rolls the conversation back to just before that turn through the official surface-replace contract, then re-prompts the agent with the revised text. The append-only session log is never rewritten.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -39,6 +39,7 @@
39
39
  "verify:client": "node tools/verify-client-static.mjs",
40
40
  "verify:live": "node tools/verify-live-client.mjs",
41
41
  "verify:profile": "bash tools/verify-dsh-plugin.sh",
42
+ "probe:loaded": "node tools/probe-loaded.mjs",
42
43
  "check": "npm run test && npm run verify:contract && npm run verify:client"
43
44
  },
44
45
  "dependencies": {