@anionex/dsh-turn-rewind 0.3.11 → 0.3.13

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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.3.13 — 2026-11-12
6
+
7
+ - Support exact DSH `0.2.2-rc.1`: the per-session chat snapshot hooks (`useChat`/`useSession`) are gone from the client slot API, so the rewind button now keys Host-provided turn anchors (`GET /turn-rewind/turns`) to rendered user rows via `data-chat-turn`. The legacy snapshot path is retained for older Hosts.
8
+ - 支持 DSH `0.2.2-rc.1`:客户端 slot API 已移除会话级 chat 快照 hooks(`useChat`/`useSession`),回退按钮改为把 Host 提供的轮次锚点(`GET /turn-rewind/turns`)按 `data-chat-turn` 映射到已渲染的用户消息行;旧 Host 的 snapshot 路径保留。
9
+ - Refresh anchors for new messages, scope buttons to their owning session, cancel stale requests, and retain missing attachment references for explicit recovery errors.
10
+ - 新消息自动刷新回退锚点,按钮限定于所属会话,取消过期请求,并保留缺失附件引用以明确提示恢复失败。
11
+ - Keep messages-only rewind available on turns recorded before this plugin created a file checkpoint.
12
+ - 对插件建立文件检查点之前的轮次,仍可使用仅回退消息。
13
+
14
+ ## 0.3.12 — 2026-11-07
15
+
16
+ - Restore message images and files into the draft when rewinding or restarting, using the public session-input API. Validate original message references before reading attachment bytes; retain empty files and explain missing or refused attachments.
17
+ - 回溯或重新开始会话时,通过公开草稿接口恢复原消息的图片和文件;读取前核对原消息引用,保留空文件,并提示无法恢复的附件。
18
+ - Finish attachment reads before opening the restored draft, preventing late uploads from entering a later message.
19
+ - 打开恢复后的草稿前完成附件读取,避免延迟返回的附件进入后续消息。
20
+ - Support exact DSH `0.2.1-rc.5`, preserving earlier supported releases. Verified with 146 tests and clean rc.5 tarball Profile installation and startup.
21
+ - 支持 DSH `0.2.1-rc.5`,保留此前支持版本;通过 146 项测试及 rc.5 压缩包干净 Profile 安装、启动验收。
22
+
3
23
  ## 0.3.11 — 2026-10-26
4
24
 
5
25
  - Support exact DSH `0.2.1-rc.3` through the settings peer and compatibility declarations; keep earlier supported versions and reject unverified future prereleases.
package/README.md CHANGED
@@ -30,6 +30,7 @@ It never commits, stashes, resets, switches branches, edits the Git index, or de
30
30
 
31
31
  Most recent work first:
32
32
 
33
+ - **Rewind button survives the 0.2.2 client slot API** — DSH `0.2.2-rc.1` no longer injects the `useChat`/`useSession` chat snapshot hooks into `conversation.session.header.actions`; the bridge now reads Host-provided turn anchors (`GET /turn-rewind/turns`) and matches rendered user rows by `data-chat-turn`. The legacy snapshot path remains for older Hosts.
33
34
  - **File rewind works in ordinary directories (0.3.0)** — when the working directory is not a Git repository it is snapshotted as an ordinary directory (`.git` and `node_modules` excluded by default, plus an optional `.dsh-rewindignore`), so messages-only rewind is no longer the only option.
34
35
  - **The fastest path is now the default (0.3.8)** — the new `auto` mode uses Git-native checkpoints in a Git worktree (reusing the repository object database, so committed content is never stored twice) and the plugin's own store for ordinary directories.
35
36
  - **Unchanged files are no longer re-read (0.3.5)** — each workspace keeps a persistent path identity cache; a measured 20 000-file / 351 MB workspace dropped from 237 s to about 7 s per capture.
@@ -124,6 +125,8 @@ Restart a running profile after changing its bundle list.
124
125
 
125
126
  The package is a DSH Profile Bundle. `package.json` declares `dsh.bundle.patch`, and `cordis.patch.yml` mounts `@anionex/dsh-turn-rewind` without a DSH core patch.
126
127
 
128
+ Compatibility is declared and exercised against DSH `0.2.2-rc.1` (previous releases stay supported). On `0.2.2` the `conversation.session.header.actions` slot no longer carries a per-session chat snapshot, so the Web bridge resolves turn anchors from the Host (`GET /turn-rewind/turns`) instead of the removed snapshot hooks.
129
+
127
130
  When the profile also provides the DSH Agent service, the plugin captures a hidden checkpoint in the first `agent/pre-step` waterfall before the Agent processes the opening user message. Capture failures are reported but do not reject the user's turn; the corresponding message simply has no usable rewind point. In Web profiles, the same-origin `/turn-rewind` endpoint resolves the selected `user/message` sequence, exposes a paged file preview, mints a short-lived session-bound restore plan, and delegates child creation to DSH's official Host create/fork lifecycle. It never restores files automatically.
128
131
 
129
132
  ## User flow
@@ -132,9 +135,11 @@ In the Web profile, each direct user message gains a compact, icon-only **Rewind
132
135
 
133
136
  | Mode | Code | Conversation |
134
137
  | --- | --- | --- |
135
- | **Restore files and restart** (default when files changed) | Restores the project files after automatically backing up their current state. | Creates and opens a Session ending before the selected message, then puts that message's text back in the composer. |
138
+ | **Restore files and restart** (default when files changed) | Restores the project files after automatically backing up their current state. | Creates and opens a Session ending before the selected message, then puts that message's text and attachments back in the composer. |
136
139
  | **Restore files only** | Restores the project files after automatically backing up their current state. | Leaves the current Session open and unchanged. |
137
- | **Rewind messages only** (default when no checkpoint or no file changes) | Leaves the project files exactly as they are. | Creates and opens a Session ending before the selected message, then puts that message's text back in the composer. |
140
+ | **Rewind messages only** (default when no checkpoint or no file changes) | Leaves the project files exactly as they are. | Creates and opens a Session ending before the selected message, then puts that message's text and attachments back in the composer. |
141
+
142
+ Unavailable attachments are reported by name so you can add them again; restored text and available attachments remain in the draft.
138
143
 
139
144
  The dialog itself is the confirmation: there is no duplicate checkbox. It describes each file as restoring an earlier version, finding a deleted file, removing a later-added file, or restoring permissions/type. **Rewind messages only** is always available — including when the checkpoint for that message is missing, was skipped (for example after disabling automatic checkpoints), or the project files already match the saved state — because it never touches the worktree. It is not blocked by other running Agents in the same worktree.
140
145
 
package/README.zh.md CHANGED
@@ -30,6 +30,7 @@ Agent / 用户 / 外部程序修改工作树
30
30
 
31
31
  按版本倒序,最近几轮集中解决的几件事:
32
32
 
33
+ - **回退按钮适配 0.2.2 客户端 slot API** —— DSH `0.2.2-rc.1` 不再向 `conversation.session.header.actions` 注入 `useChat`/`useSession` 会话快照钩子;客户端改为读取 Host 提供的轮次锚点(`GET /turn-rewind/turns`),按 `data-chat-turn` 匹配已渲染的用户消息行,旧 Host 的 snapshot 路径保留。
33
34
  - **普通目录也能回退文件(0.3.0)** —— 工作目录不是 Git 仓库时,插件会把它当成普通目录快照(默认排除 `.git`、`node_modules`,可用 `.dsh-rewindignore` 追加规则),不再只能「只回溯消息」。
34
35
  - **默认走最快的路径(0.3.8)** —— 新增「自动(推荐)」模式:Git 工作区用 Git 原生检查点(复用仓库对象库,**首次检查点不再重存已提交内容**),普通目录用插件自己的存储。
35
36
  - **未改动的文件不再重读(0.3.5)** —— 每个工作区持久化路径身份缓存,身份没变就直接复用;实测 20 000 文件 / 351 MB 的工作区,每轮捕获从 237 秒降到 7 秒出头。
@@ -122,6 +123,8 @@ dsh --profile web --dump-config | grep turn-rewind
122
123
 
123
124
  本仓库是标准 DSH Profile Bundle:`package.json` 声明 `dsh.bundle.patch`,`cordis.patch.yml` 直接挂载 `@anionex/dsh-turn-rewind`,不修改 DSH 主仓库。
124
125
 
126
+ 兼容性已覆盖到 DSH `0.2.2-rc.1`(此前版本继续支持)。`0.2.2` 的 `conversation.session.header.actions` slot 不再附带会话级 chat 快照,Web 桥改为从 Host 的 `GET /turn-rewind/turns` 读取轮次锚点。
127
+
125
128
  当 Profile 同时提供 DSH Agent 服务时,插件会在每轮第一次 `agent/pre-step`、Agent 开始处理用户消息之前保存隐藏文件状态。保存失败只会让该消息无法回退,不会拦住用户这一轮。Web Profile 还会提供同源 `/turn-rewind` 接口:根据所选 `user/message` 序号找到对应状态,分页返回文件预览,生成短期、会话绑定的恢复授权,并把新对话创建交给 DSH 官方 Host create/fork 生命周期。插件绝不会自动恢复文件。
126
129
 
127
130
  ## 使用流程
@@ -132,7 +135,9 @@ dsh --profile web --dump-config | grep turn-rewind
132
135
  | --- | --- | --- |
133
136
  | **恢复文件并从这里继续**(文件有变化时的默认) | 自动备份当前状态后恢复项目文件。 | 创建一个从这里开始的新会话(当前对话会保留)。 |
134
137
  | **只恢复文件** | 自动备份当前状态后恢复项目文件。 | 当前 Session 保持原位且内容不变。 |
135
- | **只回溯消息(不动文件)**(无检查点或文件无变化时的默认) | 项目文件保持当前状态,不做任何修改。 | 创建一个从这里开始的新会话,并把原消息文字填入输入框。 |
138
+ | **只回溯消息(不动文件)**(无检查点或文件无变化时的默认) | 项目文件保持当前状态,不做任何修改。 | 创建一个从这里开始的新会话,并把原消息的文字与附件(图片/文件)填回输入框。 |
139
+
140
+ 无法恢复的附件会显示名称,供你重新添加;已恢复的文字和可用附件会保留在草稿中。
136
141
 
137
142
  弹窗和最终主按钮就是确认流程,不再要求重复勾选。文件会按实际结果显示为“恢复之前的版本”“找回文件”“移除后来新增的文件”“恢复文件权限”或“恢复之前的文件类型”。**只回溯消息**始终可用——即使该消息没有保存检查点、检查点被跳过(例如在设置里关闭了自动检查点),或项目文件已经与保存状态一致——因为它完全不触碰工作区,也不会被同一工作区中其他运行中的 Agent 阻止。
138
143
 
package/lib/client.js CHANGED
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.inject = void 0;
6
6
  exports.resolveUiLocale = resolveUiLocale;
7
7
  exports.selectRewindMessage = selectRewindMessage;
8
+ exports.selectRewindAttachments = selectRewindAttachments;
8
9
  exports.apply = apply;
9
10
  exports.collectChatNodes = collectChatNodes;
10
11
  exports.RewindMessagePortals = RewindMessagePortals;
@@ -12,6 +13,9 @@ exports.RewindMessageAction = RewindMessageAction;
12
13
  exports.TurnRewindSettingsCard = TurnRewindSettingsCard;
13
14
  exports.formatBytes = formatBytes;
14
15
  exports.selectRewindMessageTarget = selectRewindMessageTarget;
16
+ exports.collectPortalTargets = collectPortalTargets;
17
+ exports.readAttachmentFile = readAttachmentFile;
18
+ exports.restoreComposerAttachments = restoreComposerAttachments;
15
19
  exports.openSessionWithDraft = openSessionWithDraft;
16
20
  exports.responseJson = responseJson;
17
21
  exports.fileRecoveryLabel = fileRecoveryLabel;
@@ -24,6 +28,10 @@ const react_dom_1 = require("react-dom");
24
28
  const dsh_client_ui_primitives_1 = require("@deepseek-ai/dsh-client-ui-primitives");
25
29
  const PATH = '/turn-rewind';
26
30
  const MANAGE_PATH = '/turn-rewind/manage';
31
+ /** Same-origin route mapping each rendered turn number to its Session user-message seq. */
32
+ const TURNS_PATH = '/turn-rewind/turns';
33
+ /** Same-origin route that replays one stored attachment's bytes. */
34
+ const ATTACHMENT_BYTES_PATH = '/turn-rewind/attachment-bytes';
27
35
  const STYLE_ID = '@anionex/dsh-turn-rewind';
28
36
  const styles = `
29
37
  .dcl-rewind-tail{display:inline-flex;align-items:center;align-self:center;order:0;height:24px;margin-left:2px}
@@ -241,6 +249,7 @@ const ZH = {
241
249
  invalidObject: '服务器返回了无效对象',
242
250
  unknownStatus: status => `未知回退状态:${status}`,
243
251
  sessionNotReady: '新对话还没有准备好',
252
+ attachmentsFailed: names => `文字已恢复,但以下附件未恢复,请重新添加:${names}`,
244
253
  unparsableResponse: status => `回退服务返回了无法解析的内容(HTTP ${status})。`,
245
254
  requestFailed: status => `请求失败:${status}`,
246
255
  emptyResponse: '回退服务返回了空响应。',
@@ -406,6 +415,7 @@ const EN = {
406
415
  invalidObject: 'The server returned an invalid object',
407
416
  unknownStatus: status => `Unknown rewind status: ${status}`,
408
417
  sessionNotReady: 'The new conversation is not ready yet',
418
+ attachmentsFailed: names => `The text was restored, but these attachments need to be added again: ${names}`,
409
419
  unparsableResponse: status => `The rewind service returned content that could not be parsed (HTTP ${status}).`,
410
420
  requestFailed: status => `Request failed: ${status}`,
411
421
  emptyResponse: 'The rewind service returned an empty response.',
@@ -525,7 +535,7 @@ function hostLocale(ctx) {
525
535
  return undefined;
526
536
  }
527
537
  }
528
- /** Return the rewind anchor and editable text owned by one direct user message. */
538
+ /** Return the rewind anchor, editable text, and durable attachments owned by one direct user message. */
529
539
  function selectRewindMessage(node) {
530
540
  if (node.kind !== 'user' || !Number.isSafeInteger(node.seq) || node.seq < 0)
531
541
  return null;
@@ -533,7 +543,36 @@ function selectRewindMessage(node) {
533
543
  .filter((block) => block.type === 'text' && typeof block.text === 'string')
534
544
  .map(block => block.text)
535
545
  .join('\n');
536
- return { messageSeq: node.seq, promptText };
546
+ const attachments = selectRewindAttachments(node);
547
+ return attachments.length === 0
548
+ ? { messageSeq: node.seq, promptText }
549
+ : { messageSeq: node.seq, promptText, attachments };
550
+ }
551
+ /**
552
+ * Collect the durable `image` / `file` references carried by one user message.
553
+ *
554
+ * Keep missing references so restoration can report unavailable attachments.
555
+ * @param node - the direct user-message node the rewind anchors on.
556
+ * @returns attachments in message order; empty when the message has none.
557
+ */
558
+ function selectRewindAttachments(node) {
559
+ const attachments = [];
560
+ for (const block of node.content ?? []) {
561
+ if (block.type !== 'image' && block.type !== 'file')
562
+ continue;
563
+ const attachment = block.attachment;
564
+ const fallbackName = block.type === 'image' ? 'image' : 'file';
565
+ const mediaType = typeof attachment?.mediaType === 'string' && attachment.mediaType !== ''
566
+ ? attachment.mediaType
567
+ : 'application/octet-stream';
568
+ attachments.push({
569
+ kind: block.type,
570
+ attachmentId: typeof attachment?.attachmentId === 'string' ? attachment.attachmentId : '',
571
+ name: typeof attachment?.name === 'string' && attachment.name !== '' ? attachment.name : fallbackName,
572
+ mediaType,
573
+ });
574
+ }
575
+ return attachments;
537
576
  }
538
577
  /**
539
578
  * Browser plugin entry: bridge every direct user-message action row to the rewind UI.
@@ -561,8 +600,8 @@ function apply(ctx) {
561
600
  id: 'turn-rewind-portals',
562
601
  order: 100,
563
602
  inject: () => ({
564
- openRestoredSession: async (sessionId, promptText) => {
565
- await openSessionWithDraft(ctx, sessionId, promptText);
603
+ openRestoredSession: async (sessionId, promptText, attachments) => {
604
+ await openSessionWithDraft(ctx, sessionId, promptText, attachments);
566
605
  },
567
606
  }),
568
607
  }, RewindMessagePortals));
@@ -621,11 +660,169 @@ function collectChatNodes(order, store) {
621
660
  }
622
661
  return typeof store.values === 'function' ? Array.from(store.values()) : [];
623
662
  }
624
- /** Session-scoped bridge that portals rewind controls into direct user-message action rows. */
625
- function RewindMessagePortals({ sessionId, openRestoredSession, useSession, useChat }) {
626
- // DSH 0.1.2+ moved the Chat projection out of the Session snapshot into its own
627
- // session-scoped `useChat` hook; `snapshot.chat` remains the 0.1.1 shape.
628
- const readSnapshot = useChat ?? useSession;
663
+ /** Read the Host turn anchors that map a rendered `data-chat-turn` row to an event seq. */
664
+ async function fetchTurnAnchors(sessionId, signal) {
665
+ const query = new URLSearchParams({ sessionId });
666
+ const response = await fetch(`${TURNS_PATH}?${query.toString()}`, {
667
+ headers: { accept: 'application/json' },
668
+ cache: 'no-store',
669
+ signal,
670
+ });
671
+ if (!response.ok)
672
+ return new Map();
673
+ return parseTurnAnchors(await response.json());
674
+ }
675
+ /** Narrow the turn-anchor payload into per-turn {@link RewindMatch} entries. */
676
+ function parseTurnAnchors(body) {
677
+ const anchors = new Map();
678
+ if (body === null || typeof body !== 'object')
679
+ return anchors;
680
+ const turns = body.turns;
681
+ if (!Array.isArray(turns))
682
+ return anchors;
683
+ for (const value of turns) {
684
+ if (value === null || typeof value !== 'object')
685
+ continue;
686
+ const record = value;
687
+ const turn = record.turn;
688
+ const userSeq = record.userSeq;
689
+ if (!Number.isSafeInteger(turn) || !Number.isSafeInteger(userSeq))
690
+ continue;
691
+ const promptText = typeof record.promptText === 'string' ? record.promptText : '';
692
+ const attachments = parseTurnAttachments(record.attachments);
693
+ anchors.set(turn, {
694
+ messageSeq: userSeq,
695
+ promptText,
696
+ ...(attachments.length === 0 ? {} : { attachments }),
697
+ });
698
+ }
699
+ return anchors;
700
+ }
701
+ /** Narrow one Host attachment reference; malformed entries are dropped. */
702
+ function parseTurnAttachments(value) {
703
+ if (!Array.isArray(value))
704
+ return [];
705
+ const attachments = [];
706
+ for (const item of value) {
707
+ if (item === null || typeof item !== 'object')
708
+ continue;
709
+ const record = item;
710
+ if (record.kind !== 'image' && record.kind !== 'file')
711
+ continue;
712
+ const kind = record.kind;
713
+ attachments.push({
714
+ kind,
715
+ attachmentId: typeof record.attachmentId === 'string' ? record.attachmentId : '',
716
+ name: typeof record.name === 'string' && record.name !== '' ? record.name : kind,
717
+ mediaType: typeof record.mediaType === 'string' && record.mediaType !== '' ? record.mediaType : 'application/octet-stream',
718
+ });
719
+ }
720
+ return attachments;
721
+ }
722
+ /**
723
+ * Map every rendered user-message row onto its Host turn anchor.
724
+ *
725
+ * DSH 0.2.x flow rows carry `data-chat-flow-kind="user"` and `data-chat-turn` but
726
+ * no event seq; the Host endpoint supplies the seq and the message text the
727
+ * restart dialog needs. Duplicate grouped rows keep the first portal target.
728
+ * @param anchors - per-turn rewind matches loaded from the Host.
729
+ * @returns one portal target per direct user message, in document order.
730
+ */
731
+ function sessionRows(sessionId) {
732
+ return Array.from(document.querySelectorAll('[data-conversation-session]'))
733
+ .filter(root => root.dataset.conversationSession === sessionId)
734
+ .flatMap(root => Array.from(root.querySelectorAll('[data-chat-flow-kind="user"][data-chat-turn]')));
735
+ }
736
+ function collectDomPortalTargets(anchors, sessionId) {
737
+ if (anchors.size === 0)
738
+ return [];
739
+ const targets = [];
740
+ const seen = new Set();
741
+ for (const row of sessionRows(sessionId)) {
742
+ const turn = Number(row.dataset.chatTurn);
743
+ if (!Number.isSafeInteger(turn))
744
+ continue;
745
+ const matched = anchors.get(turn);
746
+ if (matched === undefined || seen.has(matched.messageSeq))
747
+ continue;
748
+ const actions = findActionsContainer(row);
749
+ if (!(actions instanceof HTMLElement))
750
+ continue;
751
+ seen.add(matched.messageSeq);
752
+ targets.push({ container: actions, matched });
753
+ }
754
+ return targets;
755
+ }
756
+ /** 0.2.x bridge: rendered DOM rows matched through Host-provided turn anchors. */
757
+ function DomRewindMessagePortals({ sessionId, openRestoredSession }) {
758
+ const [targets, setTargets] = (0, react_1.useState)([]);
759
+ const anchors = (0, react_1.useRef)(new Map());
760
+ (0, react_1.useLayoutEffect)(() => {
761
+ let active = true;
762
+ let queued = false;
763
+ let loading = false;
764
+ let retry;
765
+ const controller = new AbortController();
766
+ anchors.current = new Map();
767
+ const refresh = () => {
768
+ if (!active)
769
+ return;
770
+ const next = collectDomPortalTargets(anchors.current, sessionId);
771
+ setTargets(current => samePortalTargets(current, next) ? current : next);
772
+ const missing = sessionRows(sessionId).some(row => Number.isSafeInteger(Number(row.dataset.chatTurn)) && !anchors.current.has(Number(row.dataset.chatTurn)));
773
+ if (missing && !loading && retry === undefined)
774
+ void load();
775
+ };
776
+ const queueRefresh = () => {
777
+ if (queued || !active)
778
+ return;
779
+ queued = true;
780
+ queueMicrotask(() => {
781
+ queued = false;
782
+ refresh();
783
+ });
784
+ };
785
+ const load = async () => {
786
+ if (!active || loading)
787
+ return;
788
+ loading = true;
789
+ try {
790
+ const loaded = await fetchTurnAnchors(sessionId, controller.signal);
791
+ if (!active)
792
+ return;
793
+ anchors.current = loaded;
794
+ }
795
+ catch {
796
+ // A transient failure is retried only while a rendered turn lacks an anchor.
797
+ }
798
+ finally {
799
+ loading = false;
800
+ if (active) {
801
+ // Bound retries when the DOM precedes persistence, and avoid fetching
802
+ // again for every streamed token or portal insertion.
803
+ retry = setTimeout(() => {
804
+ retry = undefined;
805
+ queueRefresh();
806
+ }, 1000);
807
+ queueRefresh();
808
+ }
809
+ }
810
+ };
811
+ void load();
812
+ refresh();
813
+ const observer = new MutationObserver(queueRefresh);
814
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-chat-turn'] });
815
+ return () => {
816
+ active = false;
817
+ controller.abort();
818
+ clearTimeout(retry);
819
+ observer.disconnect();
820
+ };
821
+ }, [sessionId]);
822
+ return targets.map(target => (0, react_dom_1.createPortal)((0, jsx_runtime_1.jsx)(RewindMessageAction, { matched: target.matched, sessionId: sessionId, openRestoredSession: openRestoredSession }), target.container, `${sessionId}:${String(target.matched.messageSeq)}`));
823
+ }
824
+ /** Legacy bridge for 0.1.x hosts that still inject a chat snapshot hook. */
825
+ function LegacyRewindMessagePortals({ sessionId, openRestoredSession, readSnapshot }) {
629
826
  const chatOf = (snapshot) => snapshot.chat ?? snapshot;
630
827
  const chatOrder = readSnapshot(snapshot => chatOf(snapshot).order ?? null);
631
828
  const chatStore = readSnapshot(snapshot => chatOf(snapshot).nodes ?? null);
@@ -659,6 +856,19 @@ function RewindMessagePortals({ sessionId, openRestoredSession, useSession, useC
659
856
  }, [nodes]);
660
857
  return targets.map(target => (0, react_dom_1.createPortal)((0, jsx_runtime_1.jsx)(RewindMessageAction, { matched: target.matched, sessionId: sessionId, openRestoredSession: openRestoredSession }), target.container, `${sessionId}:${String(target.matched.messageSeq)}`));
661
858
  }
859
+ /**
860
+ * Session-scoped bridge that portals rewind controls into direct user-message action rows.
861
+ *
862
+ * DSH 0.1.x passes chat snapshot hooks; DSH 0.2.0 stopped injecting them, so the
863
+ * bridge falls back to DOM rows plus the Host turn-anchor endpoint.
864
+ */
865
+ function RewindMessagePortals(props) {
866
+ const readSnapshot = props.useChat ?? props.useSession;
867
+ if (readSnapshot === undefined) {
868
+ return (0, jsx_runtime_1.jsx)(DomRewindMessagePortals, { sessionId: props.sessionId, openRestoredSession: props.openRestoredSession }, props.sessionId);
869
+ }
870
+ return (0, jsx_runtime_1.jsx)(LegacyRewindMessagePortals, { ...props, readSnapshot: readSnapshot });
871
+ }
662
872
  /** User-message action and its review-first file/conversation restore dialog. */
663
873
  function RewindMessageAction({ matched, sessionId, openRestoredSession }) {
664
874
  const t = useText();
@@ -819,7 +1029,7 @@ function RewindMessageAction({ matched, sessionId, openRestoredSession }) {
819
1029
  const childSessionId = requiredString(result.sessionId, 'sessionId');
820
1030
  setCompleted(t.completedMessages);
821
1031
  try {
822
- await openRestoredSession(childSessionId, matched.promptText);
1032
+ await openRestoredSession(childSessionId, matched.promptText, matched.attachments?.map(attachment => ({ ...attachment, sourceSessionId: sessionId, messageSeq: matched.messageSeq })));
823
1033
  setOpen(false);
824
1034
  }
825
1035
  catch (navigationError) {
@@ -836,7 +1046,7 @@ function RewindMessageAction({ matched, sessionId, openRestoredSession }) {
836
1046
  requiredString(result.rescuePointId, 'rescuePointId');
837
1047
  setCompleted(t.completedBoth);
838
1048
  try {
839
- await openRestoredSession(childSessionId, matched.promptText);
1049
+ await openRestoredSession(childSessionId, matched.promptText, matched.attachments?.map(attachment => ({ ...attachment, sourceSessionId: sessionId, messageSeq: matched.messageSeq })));
840
1050
  setOpen(false);
841
1051
  }
842
1052
  catch (navigationError) {
@@ -1155,6 +1365,10 @@ function findActionsContainer(row) {
1155
1365
  return null;
1156
1366
  return queryInside(legacy, ACTIONS_SELECTOR) ?? legacy.lastElementChild;
1157
1367
  }
1368
+ /**
1369
+ * Legacy chat-snapshot bridge kept for 0.1.x hosts and test doubles.
1370
+ * DSH 0.2.0 uses {@link collectDomPortalTargets} instead.
1371
+ */
1158
1372
  function collectPortalTargets(nodes) {
1159
1373
  const rows = new Map();
1160
1374
  for (const element of Array.from(document.querySelectorAll('[data-chat-flow-kind="user"][data-chat-anchor-key]'))) {
@@ -1175,16 +1389,128 @@ function collectPortalTargets(nodes) {
1175
1389
  }
1176
1390
  return targets;
1177
1391
  }
1392
+ /** Compare two attachment lists by identity: order and durable id both matter. */
1393
+ function sameAttachments(left, right) {
1394
+ const leftList = left ?? [];
1395
+ const rightList = right ?? [];
1396
+ return leftList.length === rightList.length && leftList.every((attachment, index) => {
1397
+ const other = rightList[index];
1398
+ return other !== undefined
1399
+ && attachment.kind === other.kind
1400
+ && attachment.attachmentId === other.attachmentId
1401
+ && attachment.name === other.name
1402
+ && attachment.mediaType === other.mediaType;
1403
+ });
1404
+ }
1178
1405
  function samePortalTargets(left, right) {
1179
1406
  return left.length === right.length && left.every((target, index) => {
1180
1407
  const other = right[index];
1181
1408
  return other !== undefined
1182
1409
  && target.container === other.container
1183
1410
  && target.matched.messageSeq === other.matched.messageSeq
1184
- && target.matched.promptText === other.matched.promptText;
1411
+ && target.matched.promptText === other.matched.promptText
1412
+ && sameAttachments(target.matched.attachments, other.matched.attachments);
1185
1413
  });
1186
1414
  }
1187
- async function openSessionWithDraft(ctx, sessionId, promptText) {
1415
+ /**
1416
+ * Re-upload one durable attachment as a fresh draft attachment.
1417
+ *
1418
+ * The stored bytes are read back from the Host, wrapped in a `File`, and handed
1419
+ * to the composer bridge, because the composer only understands browser files.
1420
+ * @param attachment - durable reference taken from the rewound message.
1421
+ * @returns the rebuilt file, or `undefined` when the Host cannot serve it.
1422
+ */
1423
+ async function readAttachmentFile(attachment) {
1424
+ const query = new URLSearchParams({
1425
+ attachmentId: attachment.attachmentId,
1426
+ kind: attachment.kind,
1427
+ mediaType: attachment.mediaType,
1428
+ sessionId: attachment.sourceSessionId ?? '',
1429
+ messageSeq: String(attachment.messageSeq ?? ''),
1430
+ });
1431
+ const response = await fetch(`${ATTACHMENT_BYTES_PATH}?${query.toString()}`, {
1432
+ headers: { accept: 'application/json' },
1433
+ signal: AbortSignal.timeout(30_000),
1434
+ });
1435
+ const value = await responseJson(response);
1436
+ if (typeof value.data !== 'string')
1437
+ throw new Error(uiText().attachmentsFailed(attachment.name));
1438
+ const binary = atob(value.data);
1439
+ const bytes = new Uint8Array(binary.length);
1440
+ for (let index = 0; index < binary.length; index += 1)
1441
+ bytes[index] = binary.charCodeAt(index);
1442
+ return new File([bytes], attachment.name, { type: attachment.mediaType });
1443
+ }
1444
+ /**
1445
+ * Hand a rewound message's attachments back to the composer.
1446
+ *
1447
+ * Draft attachments are browser-owned `File`s with upload receipts, so the
1448
+ * durable references are read back from the Host and registered exactly the way
1449
+ * the composer's own picker does it: `createDrafts` allocates the drafts,
1450
+ * `input.for(scope).addAttachments` adopts their draft IDs.
1451
+ *
1452
+ * Use the public session input facade, which exists before the visual editor
1453
+ * mounts. Failures are surfaced to the rewind dialog and refused drafts are released.
1454
+ * @param ctx - client context carrying the conversation service.
1455
+ * @param sessionId - Session whose composer receives the files.
1456
+ * @param attachments - durable references carried by the rewound message.
1457
+ * @returns number of attachments actually restored.
1458
+ */
1459
+ async function restoreComposerAttachments(ctx, sessionId, attachments, prepared) {
1460
+ if (attachments.length === 0)
1461
+ return 0;
1462
+ const conversation = ctx.conversation;
1463
+ const scope = ctx.sessions.scope(sessionId);
1464
+ const input = scope === undefined ? undefined : ctx.conversation.input.for(scope);
1465
+ const failed = (items) => {
1466
+ const error = new Error(uiText().attachmentsFailed(items.map(item => item.name).join(', ')));
1467
+ // Navigation can unmount the originating dialog; retain the warning in the
1468
+ // destination session's composer instead of relying on that dialog alone.
1469
+ input?.notify?.('error', error.message);
1470
+ return error;
1471
+ };
1472
+ if (typeof input?.addAttachments !== 'function' || typeof conversation.createDrafts !== 'function')
1473
+ throw failed(attachments);
1474
+ const results = prepared ?? await Promise.allSettled(attachments.map(readAttachmentFile));
1475
+ const files = results.flatMap(result => result.status === 'fulfilled' ? [result.value] : []);
1476
+ const missing = attachments.filter((_attachment, index) => results[index]?.status !== 'fulfilled');
1477
+ if (files.length === 0)
1478
+ throw failed(attachments);
1479
+ let drafts;
1480
+ try {
1481
+ drafts = conversation.createDrafts(sessionId, files);
1482
+ }
1483
+ catch {
1484
+ throw failed(attachments);
1485
+ }
1486
+ let adopted = false;
1487
+ try {
1488
+ adopted = drafts.length === files.length && input.addAttachments(drafts.map(draft => draft.id));
1489
+ }
1490
+ catch {
1491
+ adopted = false;
1492
+ }
1493
+ if (!adopted) {
1494
+ // The composer refused the insertion (busy or locked); release the uploads
1495
+ // instead of leaving orphaned drafts behind.
1496
+ conversation.releaseDraftAttachments?.(drafts);
1497
+ throw failed(attachments);
1498
+ }
1499
+ if (missing.length !== 0)
1500
+ throw failed(missing);
1501
+ return drafts.length;
1502
+ }
1503
+ /**
1504
+ * Open the rewound Session and put the message back into its composer.
1505
+ * @param ctx - client context carrying the Session navigation service.
1506
+ * @param sessionId - target Session.
1507
+ * @param promptText - message text to restore.
1508
+ * @param attachments - attachments carried by that message.
1509
+ */
1510
+ async function openSessionWithDraft(ctx, sessionId, promptText, attachments = []) {
1511
+ // Read before navigation so the new draft is not submitted while bytes are
1512
+ // still in flight, and never append attachments to a later user message.
1513
+ const prepared = await Promise.allSettled(attachments.map(readAttachmentFile));
1188
1514
  if (typeof ctx.sessions.open === 'function')
1189
1515
  ctx.sessions.open(sessionId);
1190
1516
  else {
@@ -1199,11 +1525,14 @@ async function openSessionWithDraft(ctx, sessionId, promptText) {
1199
1525
  const scope = ctx.sessions.scope(sessionId);
1200
1526
  if (scope !== undefined) {
1201
1527
  ctx.conversation.input.for(scope).setDraft(promptText);
1528
+ await restoreComposerAttachments(ctx, sessionId, attachments, prepared);
1202
1529
  return;
1203
1530
  }
1204
1531
  lastError = new Error(uiText().sessionNotReady);
1205
1532
  }
1206
1533
  catch (error) {
1534
+ if (prepared.length !== 0 && ctx.sessions.scope(sessionId) !== undefined)
1535
+ throw error;
1207
1536
  lastError = error;
1208
1537
  }
1209
1538
  await new Promise(resolve => { setTimeout(resolve, 50); });