diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml new file mode 100644 index 0000000000..c3f436a8db --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-13-draft-attachments-across-session-switches.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +/agent-note-draft-attachments-across-session-switches: + en: 2a1645c8c80d6dff + zh: 59277c3754231479 +/agent-note-draft-attachments-across-session-switches/problem: + en: 46a55e2fd42657ca + zh: da1033d096f2fa56 +/agent-note-draft-attachments-across-session-switches/decision: + en: 4fa08f8abfda5e6e + zh: 53775fc23322f1c0 +/agent-note-draft-attachments-across-session-switches/alternatives-considered: + en: 2c43ad479f4a3577 + zh: 07743f45870eb0fe +/agent-note-draft-attachments-across-session-switches/consequences: + en: 6ac6defa552ea040 + zh: aa64a3c3e54dbebc diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md new file mode 100644 index 0000000000..8fc611469c --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -0,0 +1,25 @@ +# Agent Note: Draft attachments across Session switches + +Status: implemented + +English | [中文](2026-11-13-draft-attachments-across-session-switches.zh.md) + +## Problem + +Switching to another Session and back emptied the composer's attachment rail while its text survived ([#5070](https://github.com/deepseek-harness/deepseek-harness/issues/5070)). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them. + +## Decision + +**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A retiring composer releases its attachments only when a send is still in flight or its Session was removed; otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. + +**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice. + +## Alternatives considered + +**Restoring attachments after a reload from durable browser references and a Host `restore` Remote.** It would bring uploaded files and images back after a page reload, but it needs a Host Remote with its Liveshare and catalog classifications, a persisted browser format, a send gate during restoration, and an image byte payload. Desktop, where most users work, gains little: its Host binds a new port on every launch, so its storage origin, and with it every saved reference, does not survive an application restart. + +**Releasing settled attachments on a switch and restoring them from the Host on return.** It would save the memory of pasted images while a Session is not shown, but every return needs a Host round trip, fails on a weak network, and allocates the same bytes again. + +## Consequences + +Switching never touches the Host, so a weak network cannot lose a draft attachment there. A reload or crash still discards attachments; a crash writes no mark and so shows no notice. diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md new file mode 100644 index 0000000000..717f12a13e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -0,0 +1,25 @@ +# Agent Note:草稿附件跨会话切换 + +Status: implemented + +[English](2026-11-13-draft-attachments-across-session-switches.md) | 中文 + +## 问题 + +切到另一个会话再切回时,输入框的附件栏被清空,文字却还在([#5070](https://github.com/deepseek-harness/deepseek-harness/issues/5070))。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 + +## 决策 + +**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。退役的输入框只在发送仍在途或其会话已被删除时释放附件;其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 + +**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。 + +## 考虑过的替代方案 + +**刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。 + +**切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。 + +## 影响 + +切换会话从不访问 Host,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。 diff --git a/apps/web/tests/draft-attachment-session-switch.e2e.ts b/apps/web/tests/draft-attachment-session-switch.e2e.ts new file mode 100644 index 0000000000..3fff0f980b --- /dev/null +++ b/apps/web/tests/draft-attachment-session-switch.e2e.ts @@ -0,0 +1,99 @@ +// Web e2e scenario: a composer draft's pasted image survives a sidebar session +// switch. The reported defect spans the whole chain — sidebar row click, Session +// scope retirement, the input shell's teardown, and the rail's rebuild — so only +// the real composition can pin it. Units cover each link separately (hub/shell/ +// service specs); this covers the assembled path and the rail the user sees. +// +// Zero model calls: a seeded session is non-blank (so the sidebar can create a +// second one instead of reusing it) and the scenario never submits. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const MODE = webSnapshotMode() +const SEED_ID = 'draft-attachment-switch-a' +const PEER_ID = 'draft-attachment-switch-b' +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url)) +const PNG = fileURLToPath(new URL('../../../snapshots/session/read-image/workspace/red.png', import.meta.url)) +const DRAFT_TEXT = 'draft text that survives the switch' + +/** The composer's pending-attachment rail, present only while it holds items. */ +const RAIL = '[role="group"][aria-label="Pending attachments"]' + +/** + * Paste one real PNG into the composer through a genuine clipboard event, the + * same intake a user's screenshot paste performs. + * @param page - page holding the composer. + * @param bytes - PNG bytes. + */ +async function pasteImage(page: Page, bytes: Uint8Array): Promise { + await page.locator('[data-composer-input]').first().evaluate((surface, data) => { + const transfer = new DataTransfer() + transfer.items.add(new File([new Uint8Array(data)], 'draft.png', { type: 'image/png' })) + surface.dispatchEvent(new ClipboardEvent('paste', { + clipboardData: transfer, bubbles: true, cancelable: true, + })) + }, [...bytes]) +} + +describe.skipIf(MODE === 'record')('web e2e: draft attachment across a session switch', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + const log = await readFile(FIXTURE, 'utf8') + await seedSession(scaffold, log, SEED_ID) + await seedSession(scaffold, log, PEER_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + // Expand the workspace group and open the seeded session. + const groupRow = page.locator('[role="treeitem"]').first() + await groupRow.waitFor({ timeout: 15_000 }) + await groupRow.click() + const sessionRow = page.locator(`[data-row-key="session:${SEED_ID}"]`) + await sessionRow.waitFor({ timeout: 15_000 }) + await sessionRow.click() + await page.locator('[data-composer-input]').first().waitFor({ timeout: 15_000 }) + }) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('keeps the pasted image and the typed draft when the sidebar leaves and returns', async () => { + onTestFailed(() => saveFailureShot(page, 'draft-attachment-session-switch')) + // (a) paste an image, then type text into the seeded session's composer. + await pasteImage(page, await readFile(PNG)) + await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1) + await page.locator('[data-composer-input]').first().click() + await page.keyboard.type(DRAFT_TEXT, { delay: 5 }) + await expect.poll(() => page.locator(RAIL).locator('img').count(), { timeout: 10_000 }).toBe(1) + + // (b) leave through the sidebar: switching to another session retires this + // one's Session scope. + await page.locator(`[data-row-key="session:${PEER_ID}"]`).click() + await expect.poll(() => page.locator(RAIL).count(), { timeout: 15_000 }).toBe(0) + + // (c) return: the rebuilt composer must show the image AND the text. + await page.locator(`[data-row-key="session:${SEED_ID}"]`).click() + await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1) + await expect.poll( + () => page.locator('[data-composer-input]').first().innerText(), + { timeout: 10_000 }, + ).toContain(DRAFT_TEXT) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4b9010be09..02033a002f 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -184,6 +184,7 @@ "tests/present-after-closing-reply.e2e.ts", "tests/autolink-cjk-punctuation.e2e.ts", "tests/composer-draft-scroll.e2e.ts", + "tests/draft-attachment-session-switch.e2e.ts", "tests/composer-focus.e2e.ts", "tests/composer-placeholder.e2e.ts", "tests/context-meter.e2e.ts", diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 83044eef74..89ea06d3e0 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: dcbdef97e4532896 - zh: 23d6840c89f66bab + en: 4919c08c24d2453b + zh: 45566252950a1ed1 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +42,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: c8323c1986c1be46 - zh: 6151492c67d4cb88 + en: c65789c64093eb47 + zh: b58cccbeea767849 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 24077e4a55..528c8e368c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. @@ -225,6 +225,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. - **Manual continuation uses a fixed product allowlist** — the supported failure codes are independent of the provider's configurable `retryableCodes`; changing automatic retry policy does not expand or reduce this action. `STREAM_CLOSED` permits an explicit new user turn even when the default policy does not retry it. That code can also identify a protocol violation, so another request is not guaranteed to recover. - **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. +- **A reload discards draft attachments** — only switching between Sessions keeps them; after a reload the reopened composer reports the loss and asks the user to add them again, and a crash leaves no notice. While a Session is not shown, a pasted image keeps its bytes in memory ([decision](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md)). - **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index a2d6b994cb..c43343c7be 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 @@ -225,6 +225,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 - **手动继续使用固定产品白名单**——支持的失败码独立于提供方可配置的 `retryableCodes`;修改自动重试策略不会扩展或缩小此操作的范围。即使默认策略不重试 `STREAM_CLOSED`,用户仍可明确发起新轮次。该错误码也可能表示协议违规,因此再次请求不保证能够恢复。 - **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 +- **刷新会丢弃草稿附件**——只有在 Session 之间切换时附件才会保留;刷新后重新打开的输入框会提示丢失并请用户重新添加,崩溃时不会有提示。Session 未显示期间,粘贴的图片会把字节保留在内存中([决策](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md))。 - **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index f6e9ce4183..32ed12258a 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -52,11 +52,41 @@ interface ConversationAttachmentFace { ): Promise serializeDraftAttachments(attachmentIds: readonly DraftAttachmentId[]): Promise releaseDraftAttachment(id: DraftAttachmentId): void + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] + draftAttachmentSessions(): readonly SessionId[] + releaseDraftSession(sessionId: SessionId): void +} + +/** Per-Session marker that a page unload discarded the draft's browser-owned attachments. */ +const UNLOAD_MARK_PREFIX = 'dsh.composer-draft-attachments-unloaded' + +/** Record that an unloading page held draft attachments for these Sessions. */ +function writeUnloadMarks(sessionIds: readonly SessionId[]): void { + try { + for (const sessionId of sessionIds) localStorage.setItem(`${UNLOAD_MARK_PREFIX}.${sessionId}`, '1') + } catch (error) { + console.error('conversation draft attachment unload marks could not be saved; a reload cannot report the loss', error) + } +} + +/** Remove one Session's unload marker. @returns whether the marker was present. */ +function takeUnloadMark(sessionId: SessionId): boolean { + try { + const key = `${UNLOAD_MARK_PREFIX}.${sessionId}` + const marked = localStorage.getItem(key) !== null + localStorage.removeItem(key) + return marked + } catch (error) { + console.error('conversation draft attachment unload mark could not be read', error) + return false + } } /** Session-addressed input facade registry (SessionInputResolver face + composer-layer extras). */ export class InputHub implements SessionInputResolver { private readonly shells = new WeakMap() + private knownSessionIds: Set | undefined + private lifecycleWatchInstalled = false /** * @param ctx - client root context (services resolved lazily per call — boot order stays free). @@ -168,10 +198,22 @@ export class InputHub implements SessionInputResolver { ] return () => { for (const off of offs) off() + // Snapshot the phase before dispose resets the machine. + const phaseAtTeardown = shell.snapshot.phase const drafts = shell.dispose() this.shells.delete(binding) const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) + if (conversation === undefined) return + if (binding.session.getSnapshot().removed) { + conversation.releaseDraftSession(binding.sessionId) + return + } + // A send caught before its echo retires cannot settle through the retirement path, + // so its attachments release here; every other draft attachment stays registered + // for the Session's next composer. + if (phaseAtTeardown !== 'plain' && phaseAtTeardown !== 'claimed') { + for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) + } } }, 'conversation.input: session shell') actx.inject(['inputTriggers'], (scope) => { @@ -181,9 +223,64 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) + this.ensureLifecycleWatch() + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const retained = conversation?.draftAttachmentIds(binding.sessionId) ?? [] + // A Session switch keeps the draft's attachments registered; this composer re-adopts them. + if (retained.length > 0) shell.addAttachments(retained) + // A reload discarded the browser-owned attachments; say so instead of dropping them silently. + if (takeUnloadMark(binding.sessionId) && retained.length === 0) shell.notify('error', this.t('attachments.unavailable')) return shell } + /** + * Install the root-lifetime watchers once: a Session removed while no composer + * is mounted releases its draft attachments, and an unloading page marks the + * Sessions whose attachments it discards. + */ + private ensureLifecycleWatch(): void { + if (this.lifecycleWatchInstalled) return + this.lifecycleWatchInstalled = true + const sessions = this.sessions() + this.knownSessionIds = new Set(sessions.list.getSnapshot().ids) + this.rootCtx.effect(() => { + const stop = sessions.list.subscribe(() => { this.cleanupRemovedSessions() }) + const conversation = (): ConversationAttachmentFace | undefined => + this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const onHide = (): void => { writeUnloadMarks(conversation()?.draftAttachmentSessions() ?? []) } + // A back-forward cache restore keeps the registry, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of conversation()?.draftAttachmentSessions() ?? []) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + stop() + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + this.knownSessionIds = undefined + this.lifecycleWatchInstalled = false + } + }, 'conversation.input: draft attachment lifecycle') + } + + /** Release draft attachments and unload marks for every Session removed from the catalog. */ + private cleanupRemovedSessions(): void { + const known = this.knownSessionIds + /* v8 ignore next -- the catalog subscription is stopped before the known set is cleared. */ + if (known === undefined) return + const liveIds = new Set(this.sessions().list.getSnapshot().ids) + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + for (const id of [...known]) { + if (liveIds.has(id)) continue + known.delete(id) + conversation?.releaseDraftSession(id) + takeUnloadMark(id) + } + for (const id of liveIds) known.add(id) + } + /** * Resident shell by session id (service-face path; the provide channel has * normally created it already — this covers direct id-addressed access). diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 192446b712..2186b0e80c 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -41,6 +41,7 @@ export const zh = { 'attachment.pathUnavailable': '无法获取文件夹路径,请重新拖入', 'attachment.pathUnsupported': '路径含有无法引用的字符,请改名后再试', 'image.pending': '待发送图片', + 'attachments.unavailable': '部分草稿附件已失效,请重新添加', 'image.openOriginal': '查看原图', 'image.openOriginalLabel': '{label},点击查看原图', 'image.remove': '移除图片 {name}', @@ -447,6 +448,7 @@ export const en = { 'attachment.pathUnavailable': 'Could not obtain the folder path; drag it in again', 'attachment.pathUnsupported': 'The path contains characters a reference cannot carry; rename it and try again', 'image.pending': 'Pending images', + 'attachments.unavailable': 'Some draft attachments are no longer available; add them again', 'image.openOriginal': 'View original', 'image.openOriginalLabel': '{label}, click to view original', 'image.remove': 'Remove image {name}', @@ -852,6 +854,7 @@ export const ja = { 'attachment.pathUnavailable': 'フォルダのパスを取得できませんでした。もう一度ドラッグしてください', 'attachment.pathUnsupported': 'パスに参照できない文字が含まれています。名前を変更して再試行してください', 'image.pending': '保留中の画像', + 'attachments.unavailable': '一部の下書き添付ファイルは利用できなくなりました。再度追加してください', 'image.openOriginal': '元の画像を表示', 'image.openOriginalLabel': '{label}、クリックで元の画像を表示', 'image.remove': '画像{name}を削除', @@ -1255,6 +1258,7 @@ export const es = { 'attachment.pathUnavailable': 'No se pudo obtener la ruta de la carpeta; arrástralo de nuevo', 'attachment.pathUnsupported': 'La ruta contiene caracteres que una referencia no puede contener; cámbiale el nombre y vuelve a intentarlo.', 'image.pending': 'Imágenes pendientes', + 'attachments.unavailable': 'Algunos adjuntos del borrador ya no están disponibles; vuelve a añadirlos', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, haga clic para ver el original', 'image.remove': 'Eliminar imagen {name}', @@ -1660,6 +1664,7 @@ export const fr = { 'attachment.pathUnavailable': "Impossible d'obtenir le chemin du dossier ; fais-le glisser à nouveau", 'attachment.pathUnsupported': "Le chemin contient des caractères qu'une référence ne peut pas transporter ; renommez-le et réessayez", 'image.pending': 'Images en attente', + 'attachments.unavailable': 'Certaines pièces jointes du brouillon ne sont plus disponibles ; ajoutez-les à nouveau', 'image.openOriginal': "Voir l'original", 'image.openOriginalLabel': "{label}, cliquez pour voir l'original", 'image.remove': "Supprimer l'image {name}", @@ -2065,6 +2070,7 @@ export const de = { 'attachment.pathUnavailable': 'Der Ordnerpfad konnte nicht abgerufen werden; Ziehen Sie es erneut hinein', 'attachment.pathUnsupported': 'Der Pfad enthält Zeichen, die eine Referenz nicht enthalten kann; Benennen Sie es um und versuchen Sie es erneut', 'image.pending': 'Ausstehende Bilder', + 'attachments.unavailable': 'Einige Entwurfsanhänge sind nicht mehr verfügbar; füge sie erneut hinzu', 'image.openOriginal': 'Original ansehen', 'image.openOriginalLabel': '{label}, klicken Sie, um das Original anzuzeigen', 'image.remove': 'Bild {name} entfernen', @@ -2470,6 +2476,7 @@ export const ru = { 'attachment.pathUnavailable': 'Не удалось получить путь к папке; перетащите это снова', 'attachment.pathUnsupported': 'Путь содержит символы, которые не может содержать ссылка; переименуй его и попробуй еще раз', 'image.pending': 'Ожидающие изображения', + 'attachments.unavailable': 'Некоторые вложения черновика больше недоступны; добавьте их снова', 'image.openOriginal': 'Посмотреть оригинал', 'image.openOriginalLabel': '{label}, нажмите, чтобы посмотреть оригинал', 'image.remove': 'Удалить изображение {name}', @@ -2875,6 +2882,7 @@ export const pt = { 'attachment.pathUnavailable': 'Não foi possível obter o caminho da pasta; arraste-o novamente', 'attachment.pathUnsupported': 'O caminho contém caracteres que uma referência não pode transportar; renomeie-o e tente novamente', 'image.pending': 'Imagens pendentes', + 'attachments.unavailable': 'Alguns anexos do rascunho não estão mais disponíveis; adicione-os novamente', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, clique para ver o original', 'image.remove': 'Remover imagem {name}', diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 27cae036db..e9030433be 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -158,6 +158,10 @@ export class ConversationController extends Service implements IConversation { /** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */ readonly fileUploads: SnapshotStore> = createSnapshotStore>({}) private readonly draftAttachments = new Map() + /** Draft attachment ids per owning Session; they outlive that Session's composer so a return re-adopts them. */ + private readonly sessionDraftIds = new Map>() + /** Reverse ownership lookup for release and Workspace rebinding. */ + private readonly draftAttachmentSession = new Map() private readonly fileUploadOperations = new Map @@ -196,6 +200,8 @@ export class ConversationController extends Service implements IConversation { if (attachment.kind === 'image') revokePreview(attachment.previewUrl) } this.draftAttachments.clear() + this.sessionDraftIds.clear() + this.draftAttachmentSession.clear() this.fileUploads.set({}) }, 'conversation draft attachments') } @@ -332,6 +338,7 @@ export class ConversationController extends Service implements IConversation { if (isImageMediaType(file.type)) { const attachment = browserDraftAttachment(file) this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) probeDimensions(attachment) if (uploadImages) this.beginFileUpload(sessionId, attachment) return attachment @@ -342,6 +349,7 @@ export class ConversationController extends Service implements IConversation { file, } this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) this.beginFileUpload(sessionId, attachment) return attachment }) @@ -369,6 +377,7 @@ export class ConversationController extends Service implements IConversation { for (const id of ids) { const attachment = this.draftAttachments.get(id) if (attachment === undefined) continue + this.ownDraftAttachment(sessionId, id) if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) else this.beginFileUpload(sessionId, attachment) } @@ -504,11 +513,59 @@ export class ConversationController extends Service implements IConversation { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return this.draftAttachments.delete(id) + this.forgetDraftAttachment(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. this.dropUpload(id) } + /** + * Draft attachment ids a Session still owns after its composer retired. + * @param sessionId - owning Session identity. + * @returns registered ids in registration order. + */ + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] { + return [...this.sessionDraftIds.get(sessionId) ?? []] + } + + /** + * Sessions that still own registered draft attachments. + * @returns Session identities with at least one registered attachment. + */ + draftAttachmentSessions(): readonly SessionId[] { + return [...this.sessionDraftIds.keys()] + } + + /** + * Release every draft attachment one removed Session owns. + * @param sessionId - removed Session identity. + */ + releaseDraftSession(sessionId: SessionId): void { + for (const id of this.draftAttachmentIds(sessionId)) this.releaseDraftAttachment(id) + } + + /** Record, or move after a Workspace rebind, one draft attachment's owning Session. */ + private ownDraftAttachment(sessionId: SessionId, id: DraftAttachmentId): void { + this.forgetDraftAttachment(id) + this.draftAttachmentSession.set(id, sessionId) + let ids = this.sessionDraftIds.get(sessionId) + if (ids === undefined) { + ids = new Set() + this.sessionDraftIds.set(sessionId, ids) + } + ids.add(id) + } + + /** Forget one draft attachment's owning Session. */ + private forgetDraftAttachment(id: DraftAttachmentId): void { + const sessionId = this.draftAttachmentSession.get(id) + if (sessionId === undefined) return + this.draftAttachmentSession.delete(id) + const ids = this.sessionDraftIds.get(sessionId) + ids?.delete(id) + if (ids?.size === 0) this.sessionDraftIds.delete(sessionId) + } + /** Abort one draft's active upload and drop its upload state. */ private dropUpload(id: DraftAttachmentId): void { const operation = this.fileUploadOperations.get(id) @@ -605,6 +662,7 @@ export class ConversationController extends Service implements IConversation { continue } this.draftAttachments.delete(attachment.id) + this.forgetDraftAttachment(attachment.id) this.forgetUpload(attachment.id) if (ref !== undefined && 'mediaType' in ref && uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts new file mode 100644 index 0000000000..787ead89af --- /dev/null +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -0,0 +1,260 @@ +// @vitest-environment jsdom +// Draft attachments outlive their Session's composer: a switch keeps them registered, +// a removed Session releases them, and a page unload reports what it discarded. +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { FileUploadValue } from '@deepseek-ai/dsh-client-file-upload/client' +import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ComposerBlockRegistry } from '../src/client/input/blocks.ts' +import { InputHub } from '../src/client/input/hub.ts' +import { ConversationController } from '../src/client/service.ts' +import { zh } from '../src/client/locales.ts' + +const SESSION = 's1' +const UNLOAD_MARK = `dsh.composer-draft-attachments-unloaded.${SESSION}` + +function sessionId(): SessionId { + return brandString(SESSION) +} + +function uploadValue(name: string): FileUploadValue { + return { + receiptId: brandString(`receipt-${name}`), + file: { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), name, bytes: 3 }, + } +} + +interface UploadBehavior { + uploadFile?: (...input: unknown[]) => Promise +} + +/** One retained Session with the production Conversation service and its input hub. */ +async function bench(prepare?: () => void) { + const runtime = await SlotTestRuntime.create() + const upload = vi.fn((id: SessionId, ...args: unknown[]) => { + const behavior = runtime.sessions.behavior(id) as UploadBehavior + if (behavior.uploadFile === undefined) throw new Error('test file upload has no Session override') + return behavior.uploadFile(...args) + }) + runtime.fileUpload.upload = upload + runtime.fileUpload.uploadImage = vi.fn(() => Promise.resolve({ ok: true as const, value: { + receiptId: brandString('receipt-image'), + image: { attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 }, + } })) + await runtime.sessions.add({ + id: SESSION, + session: { + prompt: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + updateQueue: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + cancel: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + loadOlder: vi.fn(() => Promise.resolve()), + }, + }) + prepare?.() + let reference = runtime.sessions.retain(sessionId()) + await reference.ready + const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + await runtime.ctx.plugin(ConversationController, { + input: hub, + blocks: new ComposerBlockRegistry(), + maxConcurrentFileUploads: 2, + }).await() + const root = runtime.ctx.get('conversation') as ConversationController + const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) + const shell = shellNow() + const behavior = () => runtime.sessions.behavior(SESSION) as UploadBehavior + /** Retire the Session's composer, as a switch to another Session does. */ + const switchAway = async (): Promise => { + reference.release() + await runtime.flush() + expect(runtime.sessions.binding(SESSION)).toBeUndefined() + } + /** Mount a fresh composer for the Session again. */ + const switchBack = async () => { + reference = runtime.sessions.retain(sessionId()) + await reference.ready + return shellNow() + } + return { runtime, hub, root, shell, upload, behavior, switchAway, switchBack } +} + +function draftFile(name = 'notes.txt'): File { + return new File([new Uint8Array([1, 2, 3])], name, { type: 'text/plain' }) +} + +beforeEach(() => { localStorage.clear() }) +afterEach(() => { vi.restoreAllMocks() }) + +describe('draft attachments across a Session switch', () => { + it('re-adopts settled files and images without uploading them again', async () => { + const b = await bench() + const revoked = vi.spyOn(URL, 'revokeObjectURL') + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const drafts = b.root.createDrafts(sessionId(), [draftFile(), new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + expect(b.shell.addAttachments(drafts.map(draft => draft.id))).toBe(true) + await vi.waitFor(() => { + for (const draft of drafts) expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') + }) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual(drafts.map(draft => draft.id)) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual(drafts.map(draft => draft.id)) + expect(b.root.resolveDraftAttachments(back.snapshot.attachmentIds)).toEqual(drafts) + expect(b.upload).toHaveBeenCalledOnce() + expect(revoked).not.toHaveBeenCalled() + expect(back.notices.getSnapshot()).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps an upload running while the Session is switched away', async () => { + const b = await bench() + try { + let finish!: (value: unknown) => void + b.behavior().uploadFile = vi.fn((...args: unknown[]) => new Promise((resolve) => { + finish = resolve + ;(args[2] as AbortSignal).addEventListener('abort', () => { resolve({ ok: false, error: new Error('aborted') }) }) + })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('uploading') }) + await b.switchAway() + finish({ ok: true, value: uploadValue('big.bin') }) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(b.upload).toHaveBeenCalledOnce() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps a failed upload so it can be retried in place after returning', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.reject(new Error('network lost'))) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('error') }) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('big.bin') })) + b.root.retryFileUpload(sessionId(), draft.id) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('removed Sessions', () => { + it('releases the draft attachments of a Session removed while no composer is mounted', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + localStorage.setItem(UNLOAD_MARK, '1') + await b.runtime.sessions.remove(SESSION) + await vi.waitFor(() => { expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) }) + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('releases the draft attachments when the mounted composer of a removed Session retires', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.runtime.sessions.remove(SESSION) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('page unload report', () => { + it('marks Sessions whose attachments an unload discards, and reports them on the next page', async () => { + const first = await bench() + try { + first.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = first.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + first.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + } finally { + await first.runtime.dispose() + } + // A reload starts with an empty registry; the saved mark survives in browser storage. + const second = await bench(() => { localStorage.setItem(UNLOAD_MARK, '1') }) + try { + expect(second.shell.notices.getSnapshot()).toMatchObject({ level: 'error', text: zh['attachments.unavailable'] }) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await second.runtime.dispose() + } + }) + + it('does not report attachments a switch kept, and drops marks a back-forward restore made stale', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + const restore = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(restore, 'persisted', { value: false }) + window.dispatchEvent(restore) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + const cached = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(cached, 'persisted', { value: true }) + window.dispatchEvent(cached) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + localStorage.setItem(UNLOAD_MARK, '1') + await b.switchAway() + const back = await b.switchBack() + expect(back.notices.getSnapshot()).toBeNull() + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps working when browser storage refuses the marks', async () => { + const b = await bench() + const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + window.dispatchEvent(new Event('pagehide')) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(errors).toHaveBeenCalledTimes(2) + } finally { + await b.runtime.dispose() + } + }) +}) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index e29bf0a8e0..9b93ef4240 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -138,7 +138,7 @@ describe('ConversationController', () => { await b.runtime.dispose() }) - it('releases draft previews when their session scope is disposed', async () => { + it('keeps draft previews registered when their session scope is disposed and re-adopts them on return', async () => { const b = await bench() const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:draft-1') const revoked = vi.spyOn(URL, 'revokeObjectURL').mockReturnValue(undefined) @@ -150,8 +150,11 @@ describe('ConversationController', () => { b.root.input.for(b.runtime.sessions.scope('s1')!).addAttachments([attachment.id]) b.reference.release() await b.runtime.flush() - expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([]) - expect(revoked).toHaveBeenCalledWith('blob:draft-1') + expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([attachment]) + expect(revoked).not.toHaveBeenCalled() + const again = b.runtime.sessions.retain('s1' as SessionId) + await again.ready + expect(b.hub.shellFor(b.runtime.sessions.binding('s1')!).snapshot.attachmentIds).toEqual([attachment.id]) } finally { created.mockRestore() revoked.mockRestore() diff --git a/tsconfig.host.json b/tsconfig.host.json index 7e17a942fe..7c78b91ca4 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -173,6 +173,7 @@ "apps/web/tests/present-after-closing-reply.e2e.ts", "apps/web/tests/autolink-cjk-punctuation.e2e.ts", "apps/web/tests/composer-draft-scroll.e2e.ts", + "apps/web/tests/draft-attachment-session-switch.e2e.ts", "apps/web/tests/composer-focus.e2e.ts", "apps/web/tests/composer-placeholder.e2e.ts", "apps/web/tests/context-meter.e2e.ts",