@gooftoken/dsh-rewind 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,1549 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@gooftoken/dsh-rewind',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const NS = 'rewind'
7
+ const TURNS = 'turnOutline'
8
+
9
+ const zh = {
10
+ title: '回退',
11
+ intro: '把文件、对话或上下文压缩到更早的轮次。',
12
+ checkpoints: '检查点',
13
+ empty: '还没有可回退的轮次。',
14
+ listUnavailable: '暂时读不到本会话的轮次,稍后重试。',
15
+ files: '文件',
16
+ conversation: '对话',
17
+ both: '文件与对话',
18
+ compactBefore: '压缩此前',
19
+ compactAfter: '压缩此后',
20
+ modeLabel: '操作方式',
21
+ filesHint: '恢复该轮开始时的整棵 Git 工作树;此后经 shell 或手动产生的改动也会一并还原,.gitignore 忽略的文件除外。',
22
+ conversationHint: '在当前会话内收缩模型上下文;历史仍保留在日志与转录中。',
23
+ compactBeforeHint: '把该轮之前的对话压成摘要;该轮及之后的原文保留。',
24
+ compactAfterHint: '把该轮及之后的对话压成摘要;之前的原文保留。',
25
+ cacheHint: 'Prompt 缓存不受影响:既有请求前缀不会被重写;回退只追加一个不产生模型消息的切点。',
26
+ compactCacheHint: '压缩会改写被替换的那段上下文,后续请求需要重建这段缓存;后台任务不受影响。',
27
+ keepRunning: '后台任务、子代理和进程不会被取消;它们仍在原会话继续运行。',
28
+ restoreWriters: '正在运行的任务可能已在检查点之后写入文件,本次恢复会连同这些写入一起还原。',
29
+ busyRunning: '当前轮次仍在运行;请先停止它再回退,后台任务不受影响。',
30
+ cancel: '取消',
31
+ apply: '回退',
32
+ applying: '正在回退…',
33
+ undo: '撤销上次回退',
34
+ undoing: '正在撤销…',
35
+ undoHint: '撤销最近一次回退:文件和对话恢复到回退之前。回退之后如果已有新进展,则不能撤销。',
36
+ undoTitle: '已撤销上次回退',
37
+ undoBody: '文件和对话已恢复到上次回退之前。',
38
+ undoFailed: '撤销失败:{message}',
39
+ undoFailedTitle: '撤销失败',
40
+ compact: '压缩',
41
+ compacting: '正在压缩…',
42
+ notRegistered: '宿主端未注册 /rewind:请确认 rewind 插件已启用。',
43
+ requestFailed: '请求失败:{message}',
44
+ failed: '回退失败:{message}',
45
+ compactFailed: '压缩失败',
46
+ failedGeneric: '回退失败。',
47
+ filesHidden: '该轮没有可恢复的文件变更,已隐藏文件选项。',
48
+ compactedHint: '该轮已被压缩;文件可原地恢复,对话回退会在当前会话重放压缩前的历史。',
49
+ replayHint: '回退会在当前会话里重放压缩前的历史(不新建会话);后台任务不受影响。',
50
+ replayCacheHint: '重放会改写该段上下文,后续请求需要重建这段缓存。',
51
+ filesDetecting: '正在检查该轮的文件变更…',
52
+ select: '选择要回退到的轮次',
53
+ markerTitle: '已回退到第 {turn} 轮之前',
54
+ markerBody: '该轮及之后的消息已从转录和模型上下文中隐藏;后台任务仍在原会话继续运行。',
55
+ filesToastTitle: '已恢复第 {turn} 轮的文件',
56
+ filesToastBody: '工作树已恢复到该轮开始时的状态;对话未变。',
57
+ compactBeforeToast: '已压缩第 {turn} 轮之前的对话',
58
+ compactAfterToast: '已压缩第 {turn} 轮及之后的对话',
59
+ compactToastBody: '已用摘要替换 {items} 项历史(约 {tokens} tokens)。',
60
+ compactToastBodyUnknown: '已用摘要替换 {items} 项历史。',
61
+ }
62
+
63
+ const en = {
64
+ title: 'Rewind',
65
+ intro: 'Restore files, rewind the conversation, or condense context at an earlier turn.',
66
+ checkpoints: 'Checkpoints',
67
+ empty: 'No rewindable turns yet.',
68
+ listUnavailable: 'The turn list is unavailable right now. Try again in a moment.',
69
+ files: 'Files',
70
+ conversation: 'Conversation',
71
+ both: 'Files & conversation',
72
+ compactBefore: 'Compact before',
73
+ compactAfter: 'Compact after',
74
+ modeLabel: 'Action',
75
+ filesHint: 'Restores the whole Git work tree at that turn start, including later shell or manual edits; files ignored by .gitignore are not covered.',
76
+ conversationHint: 'Truncates the model context inside this session; history stays in the log and transcript.',
77
+ compactBeforeHint: 'Summarizes the conversation before this turn; the turn and everything after stay verbatim.',
78
+ compactAfterHint: 'Summarizes this turn and everything after it; the earlier conversation stays verbatim.',
79
+ cacheHint: 'The prompt cache stays valid: the existing request prefix is not rewritten; the rewind appends only an empty cut node with no model message.',
80
+ compactCacheHint: 'Compaction rewrites the replaced span, so the next request rebuilds that part of the prompt cache; background work is untouched.',
81
+ keepRunning: 'Background jobs, subagents, and processes are not cancelled; they keep running in this session.',
82
+ restoreWriters: 'Running jobs may have written files after the checkpoint; this restore reverts those writes too.',
83
+ busyRunning: 'A turn is still running. Stop it before rewinding; background jobs are not affected.',
84
+ cancel: 'Cancel',
85
+ apply: 'Rewind',
86
+ applying: 'Rewinding…',
87
+ undo: 'Undo last rewind',
88
+ undoing: 'Undoing…',
89
+ undoHint: 'Undo the last rewind: files and conversation return to their state before it. Once the session has moved on, undo is unavailable.',
90
+ undoTitle: 'Undid the last rewind',
91
+ undoBody: 'Files and conversation are back to their state before the rewind.',
92
+ undoFailed: 'Undo failed: {message}',
93
+ undoFailedTitle: 'Undo failed',
94
+ compact: 'Compact',
95
+ compacting: 'Compacting…',
96
+ notRegistered: 'The Host does not register /rewind. Make sure the rewind plugin is enabled.',
97
+ requestFailed: 'Request failed: {message}',
98
+ failed: 'Rewind failed: {message}',
99
+ compactFailed: 'Compaction failed',
100
+ failedGeneric: 'Rewind failed.',
101
+ filesHidden: 'No file changes are restorable at this turn; the file options are hidden.',
102
+ compactedHint: 'This turn was condensed by a compaction; files restore in place, and a conversation rewind replays the pre-compaction history in this session.',
103
+ replayHint: 'The rewind replays the pre-compaction history into this same session; no new session is created and background work is untouched.',
104
+ replayCacheHint: 'The replay rewrites that part of the prompt, so the next request rebuilds it in the cache.',
105
+ filesDetecting: 'Checking file changes for this turn…',
106
+ select: 'Select the turn to return to',
107
+ markerTitle: 'Rewound to before turn {turn}',
108
+ markerBody: 'That turn and later messages are hidden from this transcript and the model context; background work keeps running.',
109
+ filesToastTitle: 'Files restored to before turn {turn}',
110
+ filesToastBody: 'The work tree is back at that turn start; the conversation was not rewound.',
111
+ compactBeforeToast: 'Compacted the conversation before turn {turn}',
112
+ compactAfterToast: 'Compacted the conversation from turn {turn} onward',
113
+ compactToastBody: 'Replaced {items} history items with a summary (~{tokens} tokens).',
114
+ compactToastBodyUnknown: 'Replaced {items} history items with a summary.',
115
+ }
116
+
117
+ /** Shallow observable store for the overlay. */
118
+ function createStore() {
119
+ let state = { open: false, sessionId: null }
120
+ const listeners = new Set()
121
+ const publish = (next) => {
122
+ state = next
123
+ for (const listener of listeners) listener()
124
+ }
125
+ return {
126
+ subscribe(listener) {
127
+ listeners.add(listener)
128
+ return () => { listeners.delete(listener) }
129
+ },
130
+ getSnapshot() { return state },
131
+ open(sessionId) { publish({ open: true, sessionId }) },
132
+ close() { publish({ open: false, sessionId: null }) },
133
+ }
134
+ }
135
+
136
+ /** Human-prompt turns of one turn-outline value, newest first. */
137
+ function normalizeTurns(outline) {
138
+ if (!Array.isArray(outline)) return []
139
+ return outline
140
+ .filter(entry => entry && typeof entry.turn === 'number' && typeof entry.seq === 'number'
141
+ && typeof entry.prompt === 'string' && entry.prompt !== '')
142
+ .map(entry => ({ turn: entry.turn, seq: entry.seq, prompt: entry.prompt }))
143
+ .reverse()
144
+ }
145
+
146
+ /** Turns opened by this plugin for an internal replay or undo. */
147
+ function internalTurnNumbers(entries) {
148
+ const turns = new Set()
149
+ for (const entry of entries || []) {
150
+ const event = entry && entry.event
151
+ if (!event || event.type !== 'turn/start' || !event.data) continue
152
+ if (event.data.rewindReplay === true && typeof event.data.turn === 'number') turns.add(event.data.turn)
153
+ }
154
+ return turns
155
+ }
156
+
157
+ /** Seq of the internal turn opened immediately before a replay head. */
158
+ function replayEnvelopeStart(entries, headSeq) {
159
+ const list = entries || []
160
+ const index = list.findIndex(entry => entry && entry.event && entry.event.seq === headSeq)
161
+ if (index < 2) return undefined
162
+ const step = list[index - 1] && list[index - 1].event
163
+ const turn = list[index - 2] && list[index - 2].event
164
+ if (!step || !turn || step.type !== 'step/start' || turn.type !== 'turn/start') return undefined
165
+ if (!turn.data || turn.data.rewindReplay !== true || typeof turn.seq !== 'number') return undefined
166
+ return turn.seq
167
+ }
168
+
169
+ /** Modes the segmented bar can offer, in display order. */
170
+ const FILE_MODES = ['files+conversation', 'files']
171
+ const ALL_MODES = ['files+conversation', 'conversation', 'files', 'compact-after', 'compact-before']
172
+
173
+ /** Whether one mode condenses context instead of restoring it. */
174
+ function isCompactMode(mode) {
175
+ return mode === 'compact-before' || mode === 'compact-after'
176
+ }
177
+
178
+ /**
179
+ * Modes offered for one turn. File modes need restorable changes; the
180
+ * "compact before" mode needs an earlier turn still on the model surface.
181
+ * A compacted turn is off the surface: files restore in place, while a
182
+ * conversation rewind replays the pre-compaction prefix in this session.
183
+ */
184
+ function availableModes(fileState, oldest, compacted) {
185
+ const candidates = compacted === true
186
+ ? ['files+conversation', 'conversation', 'files']
187
+ : ALL_MODES
188
+ return candidates.filter(mode => {
189
+ if (FILE_MODES.includes(mode)) {
190
+ return fileState === undefined || fileState === 'unknown' || fileState === 'changed'
191
+ }
192
+ if (mode === 'compact-before') return !oldest
193
+ return true
194
+ })
195
+ }
196
+
197
+ /** Whether one turn is the oldest turn still on the model surface. */
198
+ function oldestSurfaceTurn(turns, compacted, turn) {
199
+ if (!Array.isArray(turns) || typeof turn !== 'number') return false
200
+ const surface = turns.filter(row => !compacted.has(row.turn))
201
+ return surface.length > 0 && surface[surface.length - 1].turn === turn
202
+ }
203
+
204
+ /** Command line the modal submits for one selection. */
205
+ function commandLine(turn, mode) {
206
+ const flag = mode === 'conversation' ? '--conversation'
207
+ : mode === 'files' ? '--files'
208
+ : mode === 'compact-before' ? '--compact-before'
209
+ : mode === 'compact-after' ? '--compact-after'
210
+ : '--files --conversation'
211
+ return '/rewind apply ' + String(turn) + ' ' + flag
212
+ }
213
+
214
+ /** Whether the primary button may run. */
215
+ function canApply(state) {
216
+ return Boolean(state) && typeof state.turn === 'number' && !state.busy && typeof state.mode === 'string'
217
+ }
218
+
219
+ /** Interpret one Remote command execution for the modal. */
220
+ function interpretExecution(execution) {
221
+ if (!execution || !execution.result) return { ok: false, message: null }
222
+ const result = execution.result
223
+ if (result.kind === 'error') return { ok: false, message: result.text || '' }
224
+ return { ok: true }
225
+ }
226
+
227
+ const DOUBLE_ESCAPE_MS = 500
228
+
229
+ /** Whether a second Escape arrived inside the double-press window. */
230
+ function isDoubleEscape(lastAt, now) {
231
+ return lastAt > 0 && now >= lastAt && now - lastAt <= DOUBLE_ESCAPE_MS
232
+ }
233
+
234
+ /** Interpolate one `{name}` placeholder for the rare message that needs it. */
235
+ function format(text, values) {
236
+ return String(text).replace(/\{([a-zA-Z]+)\}/g, (match, key) => {
237
+ const value = values[key]
238
+ return value === undefined ? match : String(value)
239
+ })
240
+ }
241
+
242
+ /** Whether one flag is present in a whitespace-separated argument list. */
243
+ function hasFlag(args, flag) {
244
+ return new RegExp('(?:^|\\s)' + flag + '(?:\\s|$)').test(args)
245
+ }
246
+
247
+ /** One settled `/rewind apply` (success or error) that was not a dry run. */
248
+ function applyCommandInfo(run, done) {
249
+ if (!run || run.type !== 'command/run' || !run.data || run.data.name !== 'rewind') return null
250
+ const args = typeof run.data.args === 'string' ? run.data.args.trim() : ''
251
+ const match = /^apply\s+(\d+)(?:\s|$)/.exec(args)
252
+ if (match === null) return null
253
+ if (hasFlag(args, '--dry-run')) return null
254
+ if (!done || done.type !== 'command/done' || !done.data) return null
255
+ const mode = hasFlag(args, '--compact-before') ? 'compact-before'
256
+ : hasFlag(args, '--compact-after') ? 'compact-after'
257
+ : hasFlag(args, '--files') && hasFlag(args, '--conversation') ? 'files+conversation'
258
+ : hasFlag(args, '--conversation') ? 'conversation'
259
+ : hasFlag(args, '--files') ? 'files'
260
+ : 'files+conversation'
261
+ return {
262
+ commandId: String(run.data.commandId),
263
+ turn: Number(match[1]),
264
+ mode,
265
+ done,
266
+ ok: done.data.kind === 'success',
267
+ text: typeof done.data.text === 'string' ? done.data.text : '',
268
+ }
269
+ }
270
+
271
+ /** One settled `/rewind undo` (success or error) that was not a dry run. */
272
+ function undoCommandInfo(run, done) {
273
+ if (!run || run.type !== 'command/run' || !run.data || run.data.name !== 'rewind') return null
274
+ const args = typeof run.data.args === 'string' ? run.data.args.trim() : ''
275
+ if (!/^undo(?:\s|$)/.test(args)) return null
276
+ if (hasFlag(args, '--dry-run')) return null
277
+ if (!done || done.type !== 'command/done' || !done.data) return null
278
+ return {
279
+ commandId: String(run.data.commandId),
280
+ done,
281
+ ok: done.data.kind === 'success',
282
+ text: typeof done.data.text === 'string' ? done.data.text : '',
283
+ }
284
+ }
285
+
286
+ function commandMaps(entries) {
287
+ const runs = new Map()
288
+ const dones = new Map()
289
+ const markers = []
290
+ for (const entry of entries || []) {
291
+ const event = entry && entry.event
292
+ if (!event || !event.data) continue
293
+ if (event.type === 'command/run') runs.set(String(event.data.commandId), event)
294
+ else if (event.type === 'command/done') dones.set(String(event.data.commandId), event)
295
+ else if (event.type === 'user/message' || event.type === 'developer/message') {
296
+ const op = event.surfaceOp
297
+ const replace = op && typeof op === 'object' && op.op === 'replace'
298
+ const source = event.type === 'user/message'
299
+ ? event.data.source
300
+ : event.data.message && event.data.message.source
301
+ const checkpoint = source && source.kind === 'rewind-checkpoint'
302
+ && (op === 'append' || replace)
303
+ const replay = source && (source.kind === 'rewind-replay' || source.kind === 'rewind-cut')
304
+ && (op === 'append' || replace)
305
+ if (checkpoint || replay) markers.push(event)
306
+ }
307
+ }
308
+ return { runs, dones, markers }
309
+ }
310
+
311
+ /** Settled apply invocations still in the loaded window, for toasts. */
312
+ function completedRewinds(entries) {
313
+ const { runs, dones, markers } = commandMaps(entries)
314
+ const summaries = (entries || []).filter(entry => entry && entry.event && entry.event.type === 'compaction/summary')
315
+ const result = []
316
+ for (const run of runs.values()) {
317
+ const done = dones.get(String(run.data.commandId))
318
+ const undo = undoCommandInfo(run, done)
319
+ if (undo !== null) {
320
+ let payload
321
+ try { payload = undo.text === '' ? undefined : JSON.parse(undo.text) } catch { payload = undefined }
322
+ result.push({
323
+ commandId: undo.commandId,
324
+ kind: 'undo',
325
+ ok: undo.ok,
326
+ text: undo.text,
327
+ turn: payload && typeof payload.turn === 'number' ? payload.turn : undefined,
328
+ files: Boolean(payload && payload.files),
329
+ conversation: Boolean(payload && payload.conversation),
330
+ })
331
+ continue
332
+ }
333
+ const info = applyCommandInfo(run, done)
334
+ if (info === null) continue
335
+ if (isCompactMode(info.mode)) {
336
+ const summary = summaries.find(entry => entry.event.seq > run.seq && entry.event.seq < done.seq)
337
+ const data = summary === undefined ? undefined : summary.event.data
338
+ result.push({
339
+ commandId: info.commandId,
340
+ turn: info.turn,
341
+ mode: info.mode,
342
+ ok: info.ok,
343
+ text: info.text,
344
+ items: data && Array.isArray(data.shadowedSeqs) ? data.shadowedSeqs.length : undefined,
345
+ tokens: data && Number.isSafeInteger(data.shadowedTokenCount) ? data.shadowedTokenCount : undefined,
346
+ })
347
+ continue
348
+ }
349
+ const marker = markers.find(event => event.seq > run.seq && event.seq < done.seq)
350
+ const source = marker === undefined ? undefined : markerSource(marker)
351
+ result.push({
352
+ commandId: info.commandId,
353
+ turn: marker === undefined || source === undefined ? info.turn : Number(source.turn),
354
+ mode: info.mode,
355
+ conversation: marker !== undefined,
356
+ ok: info.ok,
357
+ text: info.text,
358
+ })
359
+ }
360
+ return result
361
+ }
362
+
363
+ /**
364
+ * Command rows to hide: every settled `apply`/`undo` (dry runs and
365
+ * compactions included) plus internal JSON list calls. Results and raw
366
+ * JSON never belong in the transcript; compaction pastes its own summary
367
+ * marker and failures show a toast.
368
+ */
369
+ function commandRanges(entries) {
370
+ const list = entries || []
371
+ const runs = new Map()
372
+ const dones = new Map()
373
+ for (const entry of list) {
374
+ const event = entry && entry.event
375
+ if (!event || !event.data) continue
376
+ if (event.type === 'command/run') runs.set(String(event.data.commandId), event)
377
+ else if (event.type === 'command/done') dones.set(String(event.data.commandId), event)
378
+ }
379
+ const ranges = []
380
+ for (const run of runs.values()) {
381
+ const done = dones.get(String(run.data.commandId))
382
+ if (done === undefined || run.data.name !== 'rewind') continue
383
+ const args = typeof run.data.args === 'string' ? run.data.args.trim() : ''
384
+ const hidden = /^(?:apply|undo)(?:\s|$)/.test(args)
385
+ || (/^list(?:\s|$)/.test(args) && hasFlag(args, '--json'))
386
+ if (hidden) ranges.push({ start: run.seq, end: done.seq, kind: 'command' })
387
+ }
388
+ return ranges
389
+ }
390
+
391
+ /**
392
+ * Every rewind marker still loaded: the turn, its log position, and the
393
+ * target turn start when recorded. Replacement markers came from a normal
394
+ * rewind; append markers came from a pre-compaction replay.
395
+ */
396
+ function rewindMarkers(entries) {
397
+ const markers = []
398
+ for (const entry of entries || []) {
399
+ const event = entry && entry.event
400
+ if (!event || !event.data) continue
401
+ if (event.type !== 'user/message' && event.type !== 'developer/message') continue
402
+ const op = event.surfaceOp
403
+ const append = op === 'append'
404
+ const replace = op && typeof op === 'object' && op.op === 'replace'
405
+ if (!append && !replace) continue
406
+ const source = event.type === 'user/message'
407
+ ? event.data.source
408
+ : event.data.message && event.data.message.source
409
+ if (!source) continue
410
+ if (source.kind === 'rewind-undo') {
411
+ markers.pop()
412
+ continue
413
+ }
414
+ if (source.kind === 'rewind-replay' && event.type === 'user/message') {
415
+ // The first rebuilt message replaced (or appended after) the tail.
416
+ } else if (source.kind === 'rewind-cut' && event.type === 'developer/message') {
417
+ // The fallback cut node.
418
+ } else if (source.kind === 'rewind-checkpoint' && event.type === 'user/message') {
419
+ // A normal in-place rewind marker.
420
+ } else {
421
+ continue
422
+ }
423
+ const turn = Number(source.turn)
424
+ if (!Number.isSafeInteger(turn) || turn < 0) continue
425
+ const cut = Number(source.cut)
426
+ markers.push({
427
+ turn,
428
+ seq: event.seq,
429
+ ...Number.isSafeInteger(cut) && cut >= 0 ? { cut } : {},
430
+ })
431
+ }
432
+ return markers
433
+ }
434
+
435
+ /** Whether an earlier rewind already hid this turn's start. */
436
+ function hiddenByRewind(turn, seq, markers) {
437
+ if (!markers || markers.length === 0 || typeof turn !== 'number' || typeof seq !== 'number') return false
438
+ return markers.some(marker => turn >= marker.turn && seq < marker.seq)
439
+ }
440
+
441
+ /** Surface ranges a user rewind hid, extended to each hidden turn's log bounds. */
442
+ function markerRanges(entries) {
443
+ const list = entries || []
444
+ const turnStarts = []
445
+ const turnEnds = []
446
+ for (const entry of list) {
447
+ const event = entry && entry.event
448
+ if (!event || !event.data || typeof event.data.turn !== 'number') continue
449
+ if (event.type === 'turn/start') turnStarts.push({ turn: event.data.turn, seq: event.seq })
450
+ else if (event.type === 'turn/end') turnEnds.push({ turn: event.data.turn, seq: event.seq })
451
+ }
452
+ const ranges = []
453
+ const stack = []
454
+ for (const entry of list) {
455
+ const event = entry && entry.event
456
+ if (!event || !event.data) continue
457
+ if (event.type !== 'user/message' && event.type !== 'developer/message') continue
458
+ const op = event.surfaceOp
459
+ const append = op === 'append'
460
+ const replace = op && typeof op === 'object' && op.op === 'replace'
461
+ if (!append && !replace) continue
462
+ const source = event.type === 'user/message'
463
+ ? event.data.source
464
+ : event.data.message && event.data.message.source
465
+ if (!source) continue
466
+ if (source.kind === 'rewind-undo') {
467
+ // Undo unhides the tail its rewind shadowed and hides the rewind output.
468
+ const canceled = stack.pop()
469
+ if (canceled === undefined) continue
470
+ const position = ranges.lastIndexOf(canceled.range)
471
+ if (position >= 0) ranges.splice(position, 1)
472
+ const start = replayEnvelopeStart(list, canceled.seq) ?? canceled.seq
473
+ ranges.push({ start, end: event.seq, kind: 'surface' })
474
+ continue
475
+ }
476
+ if (source.kind === 'rewind-replay' && event.type === 'user/message') {
477
+ // The first rebuilt message replaced (or appended after) the old
478
+ // tail; the appended copies are hidden by their message ids.
479
+ const target = Number(source.turn)
480
+ const start = Number(source.cut)
481
+ if (!Number.isSafeInteger(target) || target < 0
482
+ || !Number.isSafeInteger(start) || start < 0) continue
483
+ const range = { start, end: event.seq, kind: 'surface' }
484
+ ranges.push(range)
485
+ stack.push({ seq: event.seq, range })
486
+ continue
487
+ }
488
+ if (source.kind === 'rewind-cut' && event.type === 'developer/message') {
489
+ // The fallback cut node; copies after it are hidden by message id.
490
+ const target = Number(source.turn)
491
+ const start = Number(source.cut)
492
+ if (!Number.isSafeInteger(target) || target < 0
493
+ || !Number.isSafeInteger(start) || start < 0) continue
494
+ const range = { start, end: event.seq, kind: 'surface' }
495
+ ranges.push(range)
496
+ stack.push({ seq: event.seq, range })
497
+ continue
498
+ }
499
+ if (event.type !== 'user/message' || source.kind !== 'rewind-checkpoint') continue
500
+ const target = Number(source.turn)
501
+ if (!Number.isSafeInteger(target) || target < 0) continue
502
+ let start = Number(source.cut)
503
+ let end = append ? event.seq : Number(op.endSeq)
504
+ if (!Number.isSafeInteger(start) || start < 0) {
505
+ start = replace ? Number(op.startSeq) : event.seq
506
+ }
507
+ if (replace) {
508
+ const opStart = Number(op.startSeq)
509
+ const opEnd = Number(op.endSeq)
510
+ if (!Number.isSafeInteger(opStart) || !Number.isSafeInteger(opEnd) || opStart < 0 || opEnd < opStart) continue
511
+ if (opStart < start) start = opStart
512
+ if (opEnd > end) end = opEnd
513
+ }
514
+ if (!Number.isSafeInteger(start) || start < 0 || !Number.isSafeInteger(end) || end < start) continue
515
+ // Turn-level nodes (process control, footer) start at turn/start, which
516
+ // sits just before the first shadowed surface node; their closing
517
+ // updates land on the turn's turn/end, just after the last one. The
518
+ // target turn's start may be outside the loaded window, so cover every
519
+ // still-loaded start of a hidden turn, not just the target's.
520
+ for (const turnStart of turnStarts) {
521
+ if (turnStart.turn >= target && turnStart.seq < event.seq && turnStart.seq < start) start = turnStart.seq
522
+ }
523
+ for (const turnEnd of turnEnds) {
524
+ if (turnEnd.turn >= target && turnEnd.seq < event.seq && turnEnd.seq > end) end = turnEnd.seq
525
+ }
526
+ ranges.push({ start, end, kind: 'surface' })
527
+ stack.push({ seq: event.seq, range: ranges[ranges.length - 1] })
528
+ }
529
+ return ranges
530
+ }
531
+
532
+ /**
533
+ * Plugin-owned compactions still loaded: the checkpoint, its summary
534
+ * facts, and the turn whose start marks the real compaction point.
535
+ * A `/rewind apply <turn> --compact-*` run owns the first summary written
536
+ * between its run and done events, so native compactions keep their own
537
+ * placement.
538
+ */
539
+ function compactionRecords(entries) {
540
+ const list = entries || []
541
+ const runs = new Map()
542
+ const dones = new Map()
543
+ const summaries = []
544
+ const checkpoints = new Map()
545
+ const turnStarts = new Map()
546
+ for (const entry of list) {
547
+ const event = entry && entry.event
548
+ if (!event || !event.data) continue
549
+ if (event.type === 'command/run') {
550
+ runs.set(String(event.data.commandId), event)
551
+ } else if (event.type === 'command/done') {
552
+ dones.set(String(event.data.commandId), event)
553
+ } else if (event.type === 'compaction/summary') {
554
+ summaries.push(event)
555
+ } else if (event.type === 'turn/start') {
556
+ if (typeof event.data.turn === 'number') turnStarts.set(event.data.turn, event.seq)
557
+ } else if (event.type === 'user/message') {
558
+ const op = event.surfaceOp
559
+ const source = event.data.source
560
+ if (!op || typeof op !== 'object' || op.op !== 'replace') continue
561
+ if (!source || source.kind !== 'compact-checkpoint') continue
562
+ checkpoints.set(String(source.compactionId), event)
563
+ }
564
+ }
565
+ const records = []
566
+ for (const run of runs.values()) {
567
+ const info = applyCommandInfo(run, dones.get(String(run.data.commandId)))
568
+ if (info === null || !isCompactMode(info.mode)) continue
569
+ const summary = summaries.find(event => event.seq > run.seq && event.seq < info.done.seq)
570
+ const checkpoint = summary === undefined
571
+ ? undefined
572
+ : checkpoints.get(String((summary.data || {}).compactionId))
573
+ if (summary === undefined || checkpoint === undefined) continue
574
+ const blocks = Array.isArray(summary.data.summary) ? summary.data.summary : []
575
+ const text = blocks.map(block => block && block.type === 'text' && typeof block.text === 'string' ? block.text : '').join('')
576
+ const shadowed = Array.isArray(summary.data.shadowedSeqs) ? summary.data.shadowedSeqs : null
577
+ const direction = info.mode === 'compact-before' ? 'before' : 'after'
578
+ const anchor = turnStarts.get(info.turn)
579
+ records.push({
580
+ compactionId: String(summary.data.compactionId),
581
+ checkpointSeq: checkpoint.seq,
582
+ time: checkpoint.time,
583
+ turn: info.turn,
584
+ direction,
585
+ anchorSeq: anchor === undefined ? checkpoint.seq : anchor,
586
+ hideFrom: direction === 'after' && anchor !== undefined ? anchor : undefined,
587
+ summary: text.trim() === '' ? null : text,
588
+ summaryEventSeq: summary.seq,
589
+ itemCount: shadowed === null ? null : shadowed.length,
590
+ tokenCount: Number.isSafeInteger(summary.data.shadowedTokenCount) && summary.data.shadowedTokenCount >= 0
591
+ ? summary.data.shadowedTokenCount
592
+ : null,
593
+ })
594
+ }
595
+ return records
596
+ }
597
+
598
+ /**
599
+ * Log ranges the transcript hides. A rewind hides its old tail; a
600
+ * "compact after" hides the summarized tail too, so the visible
601
+ * conversation ends where the model context now ends. "Compact before"
602
+ * keeps the summarized history above the native marker, as DSH does.
603
+ */
604
+ function rewindRanges(entries) {
605
+ const ranges = [...commandRanges(entries), ...markerRanges(entries)]
606
+ for (const record of compactionRecords(entries)) {
607
+ if (record.hideFrom === undefined) continue
608
+ ranges.push({ start: record.hideFrom, end: record.checkpointSeq - 1, kind: 'surface' })
609
+ }
610
+ return ranges
611
+ }
612
+
613
+ /** Whether one event is a compaction lifecycle record or its checkpoint. */
614
+ function isCompactionRecord(event) {
615
+ if (!event) return false
616
+ if (typeof event.type === 'string' && event.type.indexOf('compaction/') === 0) return true
617
+ return event.type === 'user/message' && Boolean(event.data) && Boolean(event.data.source)
618
+ && event.data.source.kind === 'compact-checkpoint'
619
+ }
620
+
621
+ /** Whether one log position falls inside a hidden range, optionally of one kind. */
622
+ function insideRanges(ranges, seq, kind) {
623
+ if (typeof seq !== 'number' || !ranges) return false
624
+ for (const range of ranges) {
625
+ if (kind !== undefined && range.kind !== kind) continue
626
+ if (seq >= range.start && seq <= range.end) return true
627
+ }
628
+ return false
629
+ }
630
+
631
+ /** The producer source of one user or developer surface message. */
632
+ function markerSource(event) {
633
+ if (!event || !event.data) return undefined
634
+ return event.type === 'developer/message'
635
+ ? event.data.message && event.data.message.source
636
+ : event.data.source
637
+ }
638
+
639
+ /** Whether one event is a message copied into the surface by a replay. */
640
+ function isReplayCopy(event) {
641
+ if (!event || !event.data) return false
642
+ const id = event.type === 'user/message'
643
+ ? event.data.id
644
+ : event.data.message && event.data.message.id
645
+ return typeof id === 'string' && id.startsWith('rewind-replay-')
646
+ }
647
+
648
+ /** Question replies are exclusively claimed by the host's questions UI. */
649
+ function isQuestionReply(event) {
650
+ if (!event || event.type !== 'user/message' || !event.data) return false
651
+ if (!event.data.source || event.data.source.kind !== 'user-question-reply') return false
652
+ // Replay copies reuse the source kind; their fresh ids distinguish them.
653
+ const id = event.data.id
654
+ return typeof id !== 'string' || !id.startsWith('rewind-replay-')
655
+ }
656
+
657
+ const CSS = `
658
+ .gtr-backdrop{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.45);background:var(--dsw-alias-bg-mask-1,rgba(0,0,0,.45))}
659
+ .gtr-dialog{width:min(560px,100%);max-height:min(80vh,720px);display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#111);border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.12));border-radius:14px;box-shadow:0 18px 48px rgba(0,0,0,.28);overflow:hidden;font:inherit;outline:none}
660
+ .gtr-head{padding:16px 18px 10px}
661
+ .gtr-title{margin:0;font-size:16px;font-weight:600;line-height:1.4}
662
+ .gtr-intro{margin:6px 0 0;font-size:12.5px;line-height:1.55;color:var(--dsw-alias-label-tertiary,#666)}
663
+ .gtr-section{padding:8px 18px 0;font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--dsw-alias-label-tertiary,#666)}
664
+ .gtr-list{flex:1;min-height:120px;overflow:auto;padding:4px 8px;border-top:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08));border-bottom:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))}
665
+ .gtr-btn:focus-visible,.gtr-row:focus-visible,.gtr-dialog:focus-visible,.gtr-list:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#1f6feb);outline-offset:2px}
666
+ .gtr-row{display:flex;gap:10px;align-items:flex-start;width:100%;padding:9px 10px;border:0;border-radius:9px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
667
+ .gtr-row:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05))}
668
+ .gtr-row[aria-selected="true"]{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05));box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l3,rgba(0,0,0,.2))}
669
+ .gtr-badge{flex:none;min-width:44px;padding:2px 8px;border-radius:999px;background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.05));color:var(--dsw-alias-label-secondary,#555);font-size:11.5px;line-height:18px;text-align:center}
670
+ .gtr-prompt{flex:1;min-width:0;font-size:13px;line-height:1.5;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;word-break:break-word}
671
+ .gtr-empty{padding:28px 16px;text-align:center;font-size:13px;color:var(--dsw-alias-label-tertiary,#666)}
672
+ .gtr-options{display:flex;flex-direction:column;gap:8px;padding:12px 18px 4px}
673
+ .gtr-modes{display:flex;flex-wrap:wrap;gap:4px;padding:4px;border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.05))}
674
+ .gtr-mode{flex:1 1 auto;padding:6px 9px;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary,#555);font:inherit;font-size:12.5px;line-height:1.4;white-space:nowrap;cursor:pointer}
675
+ .gtr-mode:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.06))}
676
+ .gtr-mode[aria-checked="true"]{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#111);box-shadow:0 1px 3px rgba(0,0,0,.16)}
677
+ .gtr-mode:disabled{opacity:.5;cursor:default}
678
+ .gtr-mode:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#1f6feb);outline-offset:1px}
679
+ .gtr-note{margin:2px 0 0;font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-tertiary,#666)}
680
+ .gtr-error{margin:6px 18px 0;font-size:12.5px;line-height:1.5;color:var(--dsw-alias-state-error-primary,#d33);white-space:pre-wrap}
681
+ .gtr-warn{margin:6px 18px 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-state-warn-label,#a15c00)}
682
+ .gtr-foot{display:flex;justify-content:flex-end;gap:8px;padding:14px 18px 16px}
683
+ .gtr-btn{padding:7px 14px;border-radius:9px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.14));background:transparent;color:inherit;font:inherit;font-size:13px;cursor:pointer}
684
+ .gtr-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.06))}
685
+ .gtr-btn:disabled{opacity:.5;cursor:default}
686
+ .gtr-primary{border-color:transparent;background:var(--dsw-alias-button-primary-fill,#1f6feb);color:var(--dsw-alias-label-primary-foreground,#fff)}
687
+ .gtr-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-fill,#1f6feb);filter:brightness(1.06)}
688
+ `
689
+
690
+ /** Parse the JSON turn list returned by the internal list call. */
691
+ function parseTurnList(result) {
692
+ if (!result || result.ok !== true || result.value === undefined) return null
693
+ const execution = result.value
694
+ if (!execution || !execution.result || execution.result.kind !== 'success') return null
695
+ const text = typeof execution.result.text === 'string' ? execution.result.text : ''
696
+ try {
697
+ const payload = JSON.parse(text)
698
+ if (!payload || !Array.isArray(payload.turns)) return null
699
+ return {
700
+ turns: payload.turns.filter(row => row && typeof row.turn === 'number'),
701
+ undo: payload.undo && typeof payload.undo === 'object' ? payload.undo : undefined,
702
+ }
703
+ } catch {
704
+ return null
705
+ }
706
+ }
707
+
708
+ /** Locale key of one mode label. */
709
+ function modeCopyKey(mode) {
710
+ return mode === 'files+conversation' ? 'both'
711
+ : mode === 'conversation' ? 'conversation'
712
+ : mode === 'files' ? 'files'
713
+ : mode === 'compact-before' ? 'compactBefore'
714
+ : 'compactAfter'
715
+ }
716
+
717
+ /** One rewind picker rendered inside the shell overlay. */
718
+ function RewindModal(props) {
719
+ const modal = React.useSyncExternalStore(props.store.subscribe, props.store.getSnapshot)
720
+ const t = props.t
721
+ const dialogRef = React.useRef(null)
722
+ const previousFocusRef = React.useRef(null)
723
+ const mountedRef = React.useRef(true)
724
+ const modesRef = React.useRef([])
725
+ const applyRef = React.useRef(null)
726
+ const [turns, setTurns] = React.useState(null)
727
+ const [turn, setTurn] = React.useState(null)
728
+ const [fileStates, setFileStates] = React.useState(new Map())
729
+ const [compactedTurns, setCompactedTurns] = React.useState(new Set())
730
+ const [listPending, setListPending] = React.useState(false)
731
+ const [mode, setMode] = React.useState('files+conversation')
732
+ const [running, setRunning] = React.useState(false)
733
+ const [busy, setBusy] = React.useState(false)
734
+ const [undoBusy, setUndoBusy] = React.useState(false)
735
+ const [undo, setUndo] = React.useState(null)
736
+ const [error, setError] = React.useState(null)
737
+
738
+ React.useEffect(() => () => {
739
+ mountedRef.current = false
740
+ }, [])
741
+
742
+ React.useEffect(() => {
743
+ if (!modal.open) return undefined
744
+ let rows = null
745
+ try { rows = props.loadTurns(modal.sessionId) } catch { rows = null }
746
+ setTurns(rows)
747
+ setTurn(rows && rows.length > 0 ? rows[0].turn : null)
748
+ setFileStates(new Map())
749
+ setCompactedTurns(new Set())
750
+ setListPending(true)
751
+ setMode('files+conversation')
752
+ setBusy(false)
753
+ setUndoBusy(false)
754
+ setUndo(null)
755
+ setError(null)
756
+ previousFocusRef.current = document.activeElement
757
+ dialogRef.current?.focus()
758
+ const frame = requestAnimationFrame(() => { dialogRef.current?.focus() })
759
+ return () => {
760
+ cancelAnimationFrame(frame)
761
+ const previous = previousFocusRef.current
762
+ if (previous && typeof previous.focus === 'function') previous.focus()
763
+ }
764
+ }, [modal.open, modal.sessionId])
765
+
766
+ // One internal list call supplies authoritative file-change state and
767
+ // compaction flags. It drops turns an earlier rewind hid; compacted
768
+ // turns stay listed because their files can still be restored. Its
769
+ // command row is suppressed in the transcript.
770
+ React.useEffect(() => {
771
+ if (!modal.open) return undefined
772
+ let active = true
773
+ const controller = new AbortController()
774
+ const load = async () => {
775
+ try {
776
+ const result = await props.execute(modal.sessionId, '/rewind list --json --brief', controller.signal)
777
+ if (!active) return
778
+ const parsed = parseTurnList(result)
779
+ if (parsed === null) return
780
+ const rows = parsed.turns
781
+ setUndo(parsed.undo || null)
782
+ const states = new Map()
783
+ const compacted = new Set()
784
+ const visible = new Set()
785
+ for (const row of rows) {
786
+ states.set(row.turn, typeof row.files === 'string' ? row.files : 'unknown')
787
+ if (row.compacted === true) compacted.add(row.turn)
788
+ if (row.hidden !== true) visible.add(row.turn)
789
+ }
790
+ setFileStates(states)
791
+ setCompactedTurns(compacted)
792
+ setTurns(current => current === null
793
+ ? current
794
+ : current.filter(row => visible.has(row.turn)))
795
+ } catch {
796
+ // Keep the projection-derived turn list; file modes stay available.
797
+ } finally {
798
+ if (active) setListPending(false)
799
+ }
800
+ }
801
+ void load()
802
+ return () => {
803
+ active = false
804
+ controller.abort()
805
+ }
806
+ }, [modal.open, modal.sessionId])
807
+
808
+ React.useEffect(() => {
809
+ if (!modal.open || turns === null) return
810
+ if (turns.length === 0) {
811
+ if (turn !== null) setTurn(null)
812
+ return
813
+ }
814
+ if (turn === null || !turns.some(row => row.turn === turn)) setTurn(turns[0].turn)
815
+ }, [modal.open, turns, turn])
816
+
817
+ const compacted = turn !== null && compactedTurns.has(turn)
818
+ const oldest = oldestSurfaceTurn(turns, compactedTurns, turn)
819
+ const fileState = turn === null ? undefined : fileStates.get(turn)
820
+ const modes = availableModes(fileState, oldest, compacted)
821
+ modesRef.current = modes
822
+
823
+ React.useEffect(() => {
824
+ if (!modal.open || turns === null || turn === null) return
825
+ const available = availableModes(
826
+ fileStates.get(turn),
827
+ oldestSurfaceTurn(turns, compactedTurns, turn),
828
+ compactedTurns.has(turn),
829
+ )
830
+ if (available.length > 0 && !available.includes(mode)) setMode(available[0])
831
+ }, [modal.open, turns, turn, fileStates, compactedTurns, mode])
832
+
833
+ React.useEffect(() => {
834
+ if (!modal.open) return undefined
835
+ const sync = () => { if (mountedRef.current) setRunning(props.isRunning(modal.sessionId)) }
836
+ sync()
837
+ return props.subscribeRunning(modal.sessionId, sync)
838
+ }, [modal.open, modal.sessionId])
839
+
840
+ React.useEffect(() => {
841
+ if (!modal.open || turn === null) return
842
+ const row = document.getElementById('gtr-turn-' + String(turn))
843
+ if (row && typeof row.scrollIntoView === 'function') row.scrollIntoView({ block: 'nearest' })
844
+ }, [modal.open, turn])
845
+
846
+ const close = () => {
847
+ // A pending request keeps running in the background; its command row
848
+ // in the transcript reports the outcome. Never abort a file restore
849
+ // halfway just because the picker was dismissed.
850
+ props.store.close()
851
+ }
852
+
853
+ const apply = async () => {
854
+ if (!canApply({ turn, mode: modes.includes(mode) ? mode : null, busy: busy || undoBusy || running })) return
855
+ if (props.isRunning(modal.sessionId)) {
856
+ setRunning(true)
857
+ return
858
+ }
859
+ const controller = new AbortController()
860
+ setBusy(true)
861
+ setError(null)
862
+ try {
863
+ const result = await props.execute(modal.sessionId, commandLine(turn, mode) + ' --json', controller.signal)
864
+ if (!mountedRef.current) return
865
+ if (!result || result.ok !== true) {
866
+ const detail = (result && result.error && result.error.message)
867
+ || (result && result.error ? String(result.error) : 'unknown')
868
+ setError(format(t('requestFailed'), { message: detail }))
869
+ return
870
+ }
871
+ if (result.value === undefined) {
872
+ setError(t('notRegistered'))
873
+ return
874
+ }
875
+ const outcome = interpretExecution(result.value)
876
+ if (!outcome.ok) {
877
+ setError(outcome.message ? format(t('failed'), { message: outcome.message }) : t('failedGeneric'))
878
+ return
879
+ }
880
+ let prompt
881
+ const value = result.value
882
+ const text = value && value.result && typeof value.result.text === 'string' ? value.result.text : ''
883
+ if (text !== '') {
884
+ try {
885
+ const payload = JSON.parse(text)
886
+ if (payload && typeof payload.prompt === 'string') prompt = payload.prompt
887
+ } catch {
888
+ // A non-JSON success result leaves the composer untouched.
889
+ }
890
+ }
891
+ props.store.close()
892
+ if (prompt) props.restorePrompt(modal.sessionId, prompt)
893
+ } catch (failure) {
894
+ if (!mountedRef.current) return
895
+ setError(format(t('requestFailed'), { message: failure && failure.message ? failure.message : String(failure) }))
896
+ } finally {
897
+ if (mountedRef.current) setBusy(false)
898
+ }
899
+ }
900
+
901
+ applyRef.current = apply
902
+
903
+ const undoLast = async () => {
904
+ if (busy || undoBusy || running || !undo || undo.available !== true) return
905
+ if (props.isRunning(modal.sessionId)) {
906
+ setRunning(true)
907
+ return
908
+ }
909
+ const controller = new AbortController()
910
+ setUndoBusy(true)
911
+ setError(null)
912
+ try {
913
+ const result = await props.execute(modal.sessionId, '/rewind undo --json', controller.signal)
914
+ if (!mountedRef.current) return
915
+ if (!result || result.ok !== true) {
916
+ const detail = (result && result.error && result.error.message)
917
+ || (result && result.error ? String(result.error) : 'unknown')
918
+ setError(format(t('requestFailed'), { message: detail }))
919
+ return
920
+ }
921
+ if (result.value === undefined) {
922
+ setError(t('notRegistered'))
923
+ return
924
+ }
925
+ const outcome = interpretExecution(result.value)
926
+ if (!outcome.ok) {
927
+ setError(outcome.message ? format(t('undoFailed'), { message: outcome.message }) : t('failedGeneric'))
928
+ return
929
+ }
930
+ props.store.close()
931
+ } catch (failure) {
932
+ if (!mountedRef.current) return
933
+ setError(format(t('requestFailed'), { message: failure && failure.message ? failure.message : String(failure) }))
934
+ } finally {
935
+ if (mountedRef.current) setUndoBusy(false)
936
+ }
937
+ }
938
+
939
+ const moveMode = (delta) => {
940
+ setMode(current => {
941
+ const list = modesRef.current
942
+ if (list.length === 0) return current
943
+ const index = Math.max(0, list.indexOf(current))
944
+ return list[(index + delta + list.length) % list.length]
945
+ })
946
+ }
947
+
948
+ const moveTurn = (delta) => {
949
+ if (!turns || turns.length === 0) return
950
+ const index = Math.max(0, turns.findIndex(row => row.turn === turn))
951
+ const next = (index + delta + turns.length) % turns.length
952
+ setTurn(turns[next].turn)
953
+ }
954
+
955
+ const handleKey = (event) => {
956
+ if (event.key === 'Escape') {
957
+ event.preventDefault()
958
+ close()
959
+ return
960
+ }
961
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
962
+ if (busy || undoBusy || running || modesRef.current.length === 0) return
963
+ event.preventDefault()
964
+ moveMode(event.key === 'ArrowLeft' ? -1 : 1)
965
+ return
966
+ }
967
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
968
+ if (!turns || turns.length === 0) return
969
+ event.preventDefault()
970
+ moveTurn(event.key === 'ArrowDown' ? 1 : -1)
971
+ return
972
+ }
973
+ if (event.key === 'Enter') {
974
+ const tag = event.target && event.target.tagName
975
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'BUTTON' || tag === 'A' || tag === 'SELECT') return
976
+ event.preventDefault()
977
+ dialogRef.current?.focus()
978
+ void applyRef.current?.()
979
+ }
980
+ }
981
+
982
+ const onKeyDown = (event) => {
983
+ if (event.key === 'Tab') {
984
+ const dialog = dialogRef.current
985
+ if (!dialog) return
986
+ const focusable = Array.from(dialog.querySelectorAll('button:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex="-1"])'))
987
+ if (focusable.length === 0) return
988
+ const first = focusable[0]
989
+ const last = focusable[focusable.length - 1]
990
+ if (event.shiftKey && (document.activeElement === dialog || document.activeElement === first)) {
991
+ event.preventDefault()
992
+ last.focus()
993
+ } else if (!event.shiftKey && document.activeElement === last) {
994
+ event.preventDefault()
995
+ first.focus()
996
+ }
997
+ return
998
+ }
999
+ handleKey(event)
1000
+ }
1001
+
1002
+ React.useEffect(() => {
1003
+ if (!modal.open) return undefined
1004
+ const handler = (event) => {
1005
+ const dialog = dialogRef.current
1006
+ if (dialog !== null && dialog.contains(event.target)) return
1007
+ handleKey(event)
1008
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight'
1009
+ || event.key === 'ArrowDown' || event.key === 'ArrowUp') dialog?.focus()
1010
+ }
1011
+ document.addEventListener('keydown', handler, true)
1012
+ return () => document.removeEventListener('keydown', handler, true)
1013
+ }, [modal.open, modal.sessionId, turns, turn, busy, undoBusy, running])
1014
+
1015
+ if (!modal.open) return null
1016
+
1017
+ const rows = (turns || []).map(row => h('button', {
1018
+ key: row.turn,
1019
+ id: 'gtr-turn-' + String(row.turn),
1020
+ type: 'button',
1021
+ role: 'option',
1022
+ tabIndex: -1,
1023
+ 'aria-selected': row.turn === turn ? 'true' : 'false',
1024
+ className: 'gtr-row',
1025
+ onClick: () => { setTurn(row.turn) },
1026
+ },
1027
+ h('span', { className: 'gtr-badge' }, '#' + String(row.turn)),
1028
+ h('span', { className: 'gtr-prompt' }, row.prompt)))
1029
+
1030
+ const listContent = turns === null
1031
+ ? h('div', { className: 'gtr-empty' }, t('listUnavailable'))
1032
+ : rows.length === 0 ? h('div', { className: 'gtr-empty' }, t('empty')) : rows
1033
+
1034
+ const modeButtons = modes.map(id => h('button', {
1035
+ key: id,
1036
+ type: 'button',
1037
+ role: 'radio',
1038
+ 'aria-checked': id === mode ? 'true' : 'false',
1039
+ className: 'gtr-mode',
1040
+ disabled: busy || running,
1041
+ onClick: () => { setMode(id) },
1042
+ }, t(modeCopyKey(id))))
1043
+
1044
+ const compact = isCompactMode(mode)
1045
+ const replay = compacted && (mode === 'conversation' || mode === 'files+conversation')
1046
+ const undoAvailable = Boolean(undo && undo.available === true)
1047
+ const notes = []
1048
+ if (compact) {
1049
+ notes.push(t(mode === 'compact-before' ? 'compactBeforeHint' : 'compactAfterHint'))
1050
+ notes.push(t('keepRunning'))
1051
+ notes.push(t('compactCacheHint'))
1052
+ } else if (replay) {
1053
+ notes.push(t('replayHint'))
1054
+ if (mode !== 'conversation') {
1055
+ notes.push(t('filesHint'))
1056
+ notes.push(t('restoreWriters'))
1057
+ }
1058
+ notes.push(t('keepRunning'))
1059
+ notes.push(t('replayCacheHint'))
1060
+ } else {
1061
+ notes.push(t(mode === 'conversation' ? 'conversationHint' : 'filesHint'))
1062
+ notes.push(t('keepRunning'))
1063
+ if (mode !== 'conversation') notes.push(t('restoreWriters'))
1064
+ notes.push(t('cacheHint'))
1065
+ }
1066
+ if (fileState === 'none' || fileState === 'missing' || fileState === 'unavailable') notes.push(t('filesHidden'))
1067
+ else if (listPending) notes.push(t('filesDetecting'))
1068
+ if (compacted && !replay) notes.push(t('compactedHint'))
1069
+ if (undoAvailable) notes.push(t('undoHint'))
1070
+
1071
+ return h('div', {
1072
+ className: 'gtr-backdrop',
1073
+ onMouseDown: event => { if (event.target === event.currentTarget) close() },
1074
+ },
1075
+ h('div', {
1076
+ ref: dialogRef,
1077
+ className: 'gtr-dialog',
1078
+ role: 'dialog',
1079
+ 'aria-modal': 'true',
1080
+ 'aria-labelledby': 'gtr-rewind-title',
1081
+ 'aria-busy': busy || undoBusy ? 'true' : undefined,
1082
+ tabIndex: -1,
1083
+ onKeyDown,
1084
+ },
1085
+ h('style', null, CSS),
1086
+ h('div', { className: 'gtr-head' },
1087
+ h('h2', { id: 'gtr-rewind-title', className: 'gtr-title' }, t('title')),
1088
+ h('p', { className: 'gtr-intro' }, t('intro'))),
1089
+ h('p', { className: 'gtr-section' }, t('checkpoints')),
1090
+ h('div', {
1091
+ className: 'gtr-list',
1092
+ role: 'listbox',
1093
+ tabIndex: 0,
1094
+ 'aria-label': t('select'),
1095
+ 'aria-activedescendant': turn === null ? undefined : 'gtr-turn-' + String(turn),
1096
+ }, listContent),
1097
+ h('div', { className: 'gtr-options' },
1098
+ h('div', { className: 'gtr-modes', role: 'radiogroup', 'aria-label': t('modeLabel') }, modeButtons),
1099
+ notes.map((note, index) => h('p', { key: index, className: 'gtr-note' }, note))),
1100
+ running ? h('p', { className: 'gtr-warn', role: 'status' }, t('busyRunning')) : null,
1101
+ error === null ? null : h('p', { className: 'gtr-error', role: 'alert' }, error),
1102
+ h('div', { className: 'gtr-foot' },
1103
+ undoAvailable ? h('button', {
1104
+ type: 'button',
1105
+ className: 'gtr-btn',
1106
+ style: { marginRight: 'auto' },
1107
+ title: t('undoHint'),
1108
+ disabled: busy || undoBusy || running,
1109
+ onClick: () => { void undoLast() },
1110
+ }, undoBusy ? t('undoing') : t('undo')) : null,
1111
+ h('button', { type: 'button', className: 'gtr-btn', onClick: close }, t('cancel')),
1112
+ h('button', {
1113
+ type: 'button',
1114
+ className: 'gtr-btn gtr-primary',
1115
+ disabled: !canApply({ turn, mode: modes.includes(mode) ? mode : null, busy: busy || undoBusy || running }),
1116
+ onClick: () => { void apply() },
1117
+ }, busy ? t(compact ? 'compacting' : 'applying') : t(compact ? 'compact' : 'apply')))))
1118
+ }
1119
+
1120
+ /**
1121
+ * Chat-target suppression Definition: it exclusively claims every log
1122
+ * position a rewind hid, so the built-in message/tool/turn Definitions
1123
+ * never render those events. Own contexts publish no view node.
1124
+ */
1125
+ function suppressionDefinitionOf(state, target = 'chat') {
1126
+ return {
1127
+ kind: 'rewind-hidden-' + target,
1128
+ target,
1129
+ match(event) {
1130
+ // Replayed copies are model-only; hide them wherever they land.
1131
+ if (isReplayCopy(event)) return { id: 'rewind-replay:' + String(event.seq), role: 'start', exclusive: true }
1132
+ const sessionId = state.eventSessions.get(event)
1133
+ if (sessionId === undefined) return null
1134
+ const ranges = state.rangesBySession.get(sessionId)
1135
+ if (!ranges || ranges.length === 0) return null
1136
+ if (!insideRanges(ranges, event.seq)) return null
1137
+ // A failed compaction's command row is hidden, but its lifecycle
1138
+ // records stay visible unless a rewind surface range replaced them.
1139
+ if (isCompactionRecord(event) && !insideRanges(ranges, event.seq, 'surface')) return null
1140
+ if (isQuestionReply(event)) return null
1141
+ return { id: 'rewind-hidden:' + String(event.seq), role: 'start', exclusive: true }
1142
+ },
1143
+ start: () => ({}),
1144
+ update: context => context.state,
1145
+ buildViewNode: () => null,
1146
+ }
1147
+ }
1148
+
1149
+ /**
1150
+ * Chat marker Definition for a plugin compaction: DSH's own "context
1151
+ * compacted" row, anchored where the summary replaced history instead of
1152
+ * at the end of the log, and carrying the same summary payload the native
1153
+ * card expands. Suppression keeps claiming the command row.
1154
+ */
1155
+ function compactionNodeDefinitionOf(state) {
1156
+ const recordOf = (event) => {
1157
+ if (!event || typeof event.seq !== 'number') return undefined
1158
+ const sessionId = state.eventSessions.get(event)
1159
+ if (sessionId === undefined) return undefined
1160
+ const records = state.compactions.get(sessionId)
1161
+ return records === undefined ? undefined : records.get(event.seq)
1162
+ }
1163
+ return {
1164
+ kind: 'rewind-compaction-marker',
1165
+ target: 'chat',
1166
+ match(event) {
1167
+ if (!event || event.type !== 'user/message' || !event.data || !event.data.source) return null
1168
+ if (event.data.source.kind !== 'compact-checkpoint') return null
1169
+ const sessionId = state.eventSessions.get(event)
1170
+ if (sessionId === undefined) return null
1171
+ const ranges = state.rangesBySession.get(sessionId)
1172
+ // A later rewind already hid this checkpoint; suppression claims it.
1173
+ if (ranges && insideRanges(ranges, event.seq, 'surface')) return null
1174
+ const record = recordOf(event)
1175
+ if (record === undefined) return null
1176
+ return { id: String(record.compactionId), role: 'start', exclusive: true }
1177
+ },
1178
+ start: (_context, match) => recordOf(match.event),
1179
+ update: context => context.state,
1180
+ buildViewNode(context) {
1181
+ const record = context.state ?? (context.start === undefined ? undefined : recordOf(context.start.event))
1182
+ if (record === undefined) return null
1183
+ return {
1184
+ key: context.key,
1185
+ kind: 'compaction',
1186
+ id: context.id,
1187
+ target: 'chat',
1188
+ anchorSeq: record.anchorSeq,
1189
+ location: { kind: 'session' },
1190
+ visibility: 'visible',
1191
+ data: {
1192
+ kind: 'compaction',
1193
+ seq: record.checkpointSeq,
1194
+ time: record.time,
1195
+ summary: record.summary,
1196
+ summaryEventSeq: record.summaryEventSeq,
1197
+ shadowedItemCount: record.itemCount,
1198
+ shadowedTokenCount: record.tokenCount,
1199
+ },
1200
+ }
1201
+ },
1202
+ }
1203
+ }
1204
+
1205
+ /** One-shot notice above the composer; auto-dismissed. */
1206
+ function createToastStore() {
1207
+ let current = null
1208
+ let seq = 0
1209
+ let timer = null
1210
+ const listeners = new Set()
1211
+ const publish = () => { for (const listener of listeners) listener() }
1212
+ return {
1213
+ subscribe(listener) {
1214
+ listeners.add(listener)
1215
+ return () => { listeners.delete(listener) }
1216
+ },
1217
+ getSnapshot: () => current,
1218
+ show(next, ms = 4500) {
1219
+ if (timer !== null) clearTimeout(timer)
1220
+ current = { ...next, id: ++seq }
1221
+ publish()
1222
+ timer = setTimeout(() => {
1223
+ timer = null
1224
+ current = null
1225
+ publish()
1226
+ }, ms)
1227
+ },
1228
+ dispose() {
1229
+ if (timer !== null) clearTimeout(timer)
1230
+ timer = null
1231
+ listeners.clear()
1232
+ },
1233
+ }
1234
+ }
1235
+
1236
+ /** Transient rewind confirmation styled like the former marker card. */
1237
+ function RewindToast(props) {
1238
+ const toast = React.useSyncExternalStore(props.toasts.subscribe, props.toasts.getSnapshot)
1239
+ if (toast === null) return null
1240
+ const t = props.t
1241
+ const error = toast.kind === 'error'
1242
+ const conversation = toast.kind === 'conversation'
1243
+ const compact = toast.kind === 'compact'
1244
+ const undoToast = toast.kind === 'undo'
1245
+ const icon = h('svg', {
1246
+ width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': true,
1247
+ style: { flex: 'none', marginTop: '1px' },
1248
+ },
1249
+ h('path', { d: 'M4 12a8 8 0 1 0 2.3-5.6', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round' }),
1250
+ h('path', { d: 'M4 4v4h4', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' }))
1251
+ const title = error
1252
+ ? t(toast.action === 'undo' ? 'undoFailedTitle' : toast.action === 'compact' ? 'compactFailed' : 'failedGeneric')
1253
+ : undoToast
1254
+ ? t('undoTitle')
1255
+ : compact
1256
+ ? format(t(toast.mode === 'compact-before' ? 'compactBeforeToast' : 'compactAfterToast'), { turn: toast.turn })
1257
+ : format(t(conversation ? 'markerTitle' : 'filesToastTitle'), { turn: toast.turn })
1258
+ const bodyText = error
1259
+ ? (toast.text || t('failedGeneric'))
1260
+ : undoToast
1261
+ ? t('undoBody')
1262
+ : compact
1263
+ ? (toast.tokens !== undefined && toast.items !== undefined
1264
+ ? format(t('compactToastBody'), { items: toast.items, tokens: toast.tokens })
1265
+ : format(t('compactToastBodyUnknown'), { items: toast.items === undefined ? '?' : toast.items }))
1266
+ : t(conversation ? 'markerBody' : 'filesToastBody')
1267
+ const body = h('div', null,
1268
+ h('div', {
1269
+ style: {
1270
+ fontWeight: 600,
1271
+ color: error ? 'var(--dsw-alias-state-error-primary, #d33)' : 'var(--dsw-alias-label-primary, #111)',
1272
+ },
1273
+ }, title),
1274
+ h('div', null, bodyText))
1275
+ return h('div', {
1276
+ style: {
1277
+ position: 'fixed', left: '50%', bottom: '96px', transform: 'translateX(-50%)', zIndex: 80,
1278
+ width: 'min(560px, calc(100vw - 32px))', pointerEvents: 'none',
1279
+ },
1280
+ },
1281
+ h('div', {
1282
+ role: 'status',
1283
+ 'aria-live': 'polite',
1284
+ style: {
1285
+ display: 'flex', gap: '10px', alignItems: 'flex-start', padding: '10px 14px',
1286
+ border: '1px dashed var(--dsw-alias-border-l3, rgba(0,0,0,.2))', borderRadius: '10px',
1287
+ background: 'var(--dsw-alias-bg-layer-1, #fff)', color: 'var(--dsw-alias-label-secondary, #555)',
1288
+ fontSize: '12.5px', lineHeight: 1.55, boxShadow: '0 8px 24px rgba(0,0,0,.14)',
1289
+ },
1290
+ }, icon, body))
1291
+ }
1292
+
1293
+ /** Service dependencies of the browser half. */
1294
+ const inject = ['slots', 'commandUi', 'remote', 'remote.commands', 'sessions', 'uiConversation', 'conversation', 'locale']
1295
+
1296
+ /** Register the locale dictionary, the `/rewind` decoration, and the modal. */
1297
+ function apply(ctx) {
1298
+ const store = createStore()
1299
+ const toasts = createToastStore()
1300
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'rewind: dictionaries')
1301
+ ctx.effect(() => ctx.commandUi.decorate({
1302
+ name: 'rewind',
1303
+ available: () => true,
1304
+ ui: {
1305
+ kind: 'action',
1306
+ run: session => { store.open(session.sessionId) },
1307
+ },
1308
+ }), 'rewind: decoration')
1309
+
1310
+ const loadTurns = (sessionId) => {
1311
+ const binding = ctx.sessions.binding(sessionId)
1312
+ if (!binding || !binding.session || !binding.session.projections) return null
1313
+ const outline = binding.session.projections.faceOf(TURNS).getSnapshot()
1314
+ const entries = binding.eventSource ? binding.eventSource.getSnapshot().entries : []
1315
+ const markers = rewindMarkers(entries)
1316
+ const internal = internalTurnNumbers(entries)
1317
+ return normalizeTurns(outline)
1318
+ .filter(row => !internal.has(row.turn))
1319
+ .filter(row => !hiddenByRewind(row.turn, row.seq, markers))
1320
+ }
1321
+
1322
+ const isRunning = (sessionId) => {
1323
+ const summary = ctx.sessions.list.getSnapshot().byId[sessionId]
1324
+ return Boolean(summary && summary.running)
1325
+ }
1326
+
1327
+ const subscribeRunning = (sessionId, listener) =>
1328
+ ctx.sessions.list.subscribe(() => { listener(isRunning(sessionId)) })
1329
+
1330
+ const execute = (sessionId, line, signal) => ctx.remote.commands.execute(sessionId, line, [], signal)
1331
+
1332
+ /** Put the target turn's original prompt back into the composer. */
1333
+ const restorePrompt = (sessionId, prompt) => {
1334
+ if (typeof prompt !== 'string' || prompt === '') return
1335
+ const binding = ctx.sessions.binding(sessionId)
1336
+ if (!binding) return
1337
+ try {
1338
+ ctx.conversation.input.requestDraftInitialization(binding, {
1339
+ prompt,
1340
+ whenDraftExists: 'replace',
1341
+ })
1342
+ } catch {
1343
+ // The composer may be unmounted; the host state is still correct.
1344
+ }
1345
+ }
1346
+
1347
+ let lastEscape = 0
1348
+ const activeSessionId = () => {
1349
+ const snapshot = ctx.sessions.list.getSnapshot()
1350
+ const session = Object.values(snapshot.byId).find(candidate => candidate
1351
+ && candidate.retainedBy && (candidate.retainedBy.mainView ?? 0) > 0
1352
+ && candidate.origin !== 'subagent')
1353
+ return session === undefined ? undefined : session.id
1354
+ }
1355
+ const onDoubleEscape = (event) => {
1356
+ if (event.key !== 'Escape' || event.repeat || event.isComposing
1357
+ || event.altKey || event.ctrlKey || event.metaKey) return
1358
+ if (store.getSnapshot().open) {
1359
+ lastEscape = 0
1360
+ return
1361
+ }
1362
+ const now = Date.now()
1363
+ if (!isDoubleEscape(lastEscape, now)) {
1364
+ lastEscape = now
1365
+ return
1366
+ }
1367
+ lastEscape = 0
1368
+ const sessionId = activeSessionId()
1369
+ if (sessionId === undefined) return
1370
+ event.preventDefault()
1371
+ event.stopPropagation()
1372
+ store.open(sessionId)
1373
+ }
1374
+ if (typeof document !== 'undefined') {
1375
+ document.addEventListener('keydown', onDoubleEscape, true)
1376
+ ctx.effect(() => () => document.removeEventListener('keydown', onDoubleEscape, true), 'rewind: double escape')
1377
+ }
1378
+
1379
+ // The host already truncated the model surface. To truncate the visible
1380
+ // transcript too, exclusive Chat claims suppress every log position a
1381
+ // rewind hid; re-registering the Definition rebuilds loaded sessions.
1382
+ const hidden = { eventSessions: new WeakMap(), rangesBySession: new Map(), compactions: new Map() }
1383
+ const suppressions = ['chat', 'trajectory'].map(target => suppressionDefinitionOf(hidden, target))
1384
+ const compactionMarker = compactionNodeDefinitionOf(hidden)
1385
+ const notifiedCommands = new Set()
1386
+ const tracked = new Map()
1387
+ const suppressionDisposes = []
1388
+ let listDispose = null
1389
+ let disposed = false
1390
+ let refreshQueued = false
1391
+
1392
+ const installSuppression = () => {
1393
+ if (disposed) return
1394
+ for (const dispose of suppressionDisposes.splice(0)) dispose()
1395
+ for (const definition of [...suppressions, compactionMarker]) {
1396
+ suppressionDisposes.push(ctx.uiConversation.events.register(definition))
1397
+ }
1398
+ }
1399
+ const scheduleRefresh = () => {
1400
+ if (refreshQueued || disposed) return
1401
+ refreshQueued = true
1402
+ Promise.resolve().then(() => {
1403
+ refreshQueued = false
1404
+ if (!disposed) installSuppression()
1405
+ })
1406
+ }
1407
+ const syncBinding = (sessionId) => {
1408
+ const binding = ctx.sessions.binding(sessionId)
1409
+ if (!binding || !binding.eventSource) {
1410
+ const stale = tracked.get(sessionId)
1411
+ if (stale !== undefined) {
1412
+ stale.unsubscribe()
1413
+ tracked.delete(sessionId)
1414
+ hidden.rangesBySession.delete(sessionId)
1415
+ hidden.compactions.delete(sessionId)
1416
+ }
1417
+ return
1418
+ }
1419
+ const existing = tracked.get(sessionId)
1420
+ if (existing !== undefined && existing.binding === binding) return
1421
+ if (existing !== undefined) existing.unsubscribe()
1422
+ const record = { binding, signal: '', initialized: false, unsubscribe: () => {} }
1423
+ tracked.set(sessionId, record)
1424
+ const applyWindow = () => {
1425
+ const window = binding.eventSource.getSnapshot()
1426
+ const entries = window.entries || []
1427
+ const change = window.change
1428
+ const initial = !record.initialized
1429
+ let fresh = entries
1430
+ if (!initial && change.kind === 'append') fresh = change.entries
1431
+ else if (!initial && change.kind === 'prepend') fresh = change.entries
1432
+ else if (!initial && change.kind === 'settle-assistant') fresh = change.entry === undefined ? [] : [change.entry]
1433
+ const structural = initial || fresh.some(entry => {
1434
+ const event = entry && entry.event
1435
+ return Boolean(event) && (event.type === 'command/run' || event.type === 'command/done'
1436
+ || event.type === 'turn/start' || (event.type === 'user/message' && event.surfaceOp))
1437
+ })
1438
+ const liveDone = !initial && change.kind === 'append'
1439
+ && fresh.some(entry => Boolean(entry && entry.event) && entry.event.type === 'command/done')
1440
+ let ranges = hidden.rangesBySession.get(sessionId) || []
1441
+ let compactions = ''
1442
+ if (structural) {
1443
+ const records = compactionRecords(entries)
1444
+ ranges = rewindRanges(entries)
1445
+ hidden.rangesBySession.set(sessionId, ranges)
1446
+ hidden.compactions.set(sessionId, new Map(records.map(record => [record.checkpointSeq, record])))
1447
+ compactions = records.map(record => String(record.checkpointSeq) + '>' + String(record.anchorSeq)).join(',')
1448
+ }
1449
+ let loadedHidden = false
1450
+ for (const entry of fresh) {
1451
+ const event = entry && entry.event
1452
+ if (!event || typeof event !== 'object') continue
1453
+ if (hidden.eventSessions.has(event)) continue
1454
+ hidden.eventSessions.set(event, sessionId)
1455
+ if (insideRanges(ranges, event.seq)) loadedHidden = true
1456
+ }
1457
+ if (structural) {
1458
+ for (const rewind of completedRewinds(entries)) {
1459
+ const key = String(sessionId) + ':' + rewind.commandId
1460
+ if (notifiedCommands.has(key)) continue
1461
+ notifiedCommands.add(key)
1462
+ if (liveDone) {
1463
+ if (rewind.ok) {
1464
+ if (rewind.kind === 'undo') {
1465
+ toasts.show({ kind: 'undo' })
1466
+ } else if (isCompactMode(rewind.mode)) {
1467
+ toasts.show({
1468
+ kind: 'compact', turn: rewind.turn, mode: rewind.mode,
1469
+ items: rewind.items, tokens: rewind.tokens,
1470
+ })
1471
+ } else {
1472
+ toasts.show({ kind: rewind.conversation ? 'conversation' : 'files', turn: rewind.turn })
1473
+ }
1474
+ } else {
1475
+ toasts.show({
1476
+ kind: 'error', text: rewind.text,
1477
+ action: rewind.kind === 'undo' ? 'undo' : isCompactMode(rewind.mode) ? 'compact' : 'rewind',
1478
+ }, 7000)
1479
+ }
1480
+ }
1481
+ }
1482
+ }
1483
+ record.initialized = true
1484
+ const signal = ranges.map(range => String(range.start) + ':' + String(range.end)).join(',') + '|' + compactions
1485
+ const changed = signal !== record.signal
1486
+ record.signal = signal
1487
+ if (changed || loadedHidden) scheduleRefresh()
1488
+ }
1489
+ record.unsubscribe = binding.eventSource.subscribe(applyWindow)
1490
+ applyWindow()
1491
+ }
1492
+ let retryTimer = null
1493
+ let retries = 0
1494
+ const syncAll = () => {
1495
+ const snapshot = ctx.sessions.list.getSnapshot()
1496
+ let missing = false
1497
+ for (const sessionId of Object.keys(snapshot.byId)) {
1498
+ const summary = snapshot.byId[sessionId]
1499
+ const retained = Boolean(summary && summary.retainedBy
1500
+ && Object.values(summary.retainedBy).some(count => count > 0))
1501
+ syncBinding(sessionId)
1502
+ if (retained && !tracked.has(sessionId)) missing = true
1503
+ }
1504
+ if (!missing) { retries = 0; return }
1505
+ if (retryTimer !== null || disposed || retries >= 20) return
1506
+ retries += 1
1507
+ retryTimer = setTimeout(() => { retryTimer = null; syncAll() }, 300)
1508
+ }
1509
+ installSuppression()
1510
+ listDispose = ctx.sessions.list.subscribe(syncAll)
1511
+ syncAll()
1512
+ ctx.effect(() => () => {
1513
+ disposed = true
1514
+ if (retryTimer !== null) clearTimeout(retryTimer)
1515
+ for (const dispose of suppressionDisposes.splice(0)) dispose()
1516
+ if (listDispose !== null) listDispose()
1517
+ for (const record of tracked.values()) record.unsubscribe()
1518
+ tracked.clear()
1519
+ toasts.dispose()
1520
+ }, 'rewind: transcript')
1521
+
1522
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1523
+ name: 'shell.overlay',
1524
+ id: 'rewind.toast',
1525
+ locale: NS,
1526
+ inject: () => ({ toasts }),
1527
+ }, RewindToast))
1528
+
1529
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1530
+ name: 'shell.overlay',
1531
+ id: 'rewind.modal',
1532
+ locale: NS,
1533
+ inject: () => ({ store, loadTurns, isRunning, subscribeRunning, execute, restorePrompt }),
1534
+ }, RewindModal))
1535
+ }
1536
+
1537
+ return {
1538
+ inject,
1539
+ apply,
1540
+ __test: {
1541
+ createStore, normalizeTurns, commandLine, canApply, interpretExecution, format,
1542
+ rewindRanges, markerRanges, rewindMarkers, hiddenByRewind, insideRanges, isQuestionReply,
1543
+ suppressionDefinitionOf, completedRewinds, isDoubleEscape, availableModes, oldestSurfaceTurn,
1544
+ isCompactMode, isCompactionRecord, isReplayCopy, parseTurnList, hasFlag, modeCopyKey,
1545
+ undoCommandInfo, internalTurnNumbers, replayEnvelopeStart, compactionRecords, compactionNodeDefinitionOf,
1546
+ },
1547
+ }
1548
+ },
1549
+ })