diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index cfc7291505..60b0cb137d 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -18,11 +18,11 @@ en: b149da9963eb9837 zh: 2426ea37fbd0f8b7 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: - en: e07d3a607d54cb47 - zh: 9a7342f05b64db38 + en: c9022effccebd157 + zh: 54e76ec13b5c1029 /deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation: - en: 22da59203ca974e6 - zh: f288bd6a193bccef + en: 423b66c7f36f7c40 + zh: 9b891fb7c8a8d240 /deepseek-ai-dsh-client-ui-open-in-app/further-exploration: en: 720527877e452a97 zh: b2241c7a336a3eeb @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: c2241315dc0c89c9 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work: - en: 59c434b70679fc16 - zh: 7fe9e52b0bb82df1 + en: 31af13d29ff76a1c + zh: 6a08bd80d71c6434 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work/dev-note: en: 84f92568fc74adf1 zh: 286b47e6b5b1a556 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index 9b0f75963b..5664376801 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -39,11 +39,11 @@ The **Open locally** shortcut captures the main Session’s directory and rememb File menus list the discovered associated applications without a separate “Open in default app” row. “Show file location” stays in a fixed footer separated from the scrolling applications. A successful query with only one available action renders a single button without a dropdown. Initial file-association loading uses a gray skeleton icon. When the Host identifies a default application the menu marks it “(default)” and the main button opens it; otherwise the first associated application takes that place, so the main button reveals the file only when no application is registered. Directory menus have no reveal row. Choosing a file application does not change the system default. An unpreviewable file uses the same menu in a 40px-high split button with an icon and action text; its label is “Open” or “Show file location” according to the default action. -Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. +Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A successful answer also replaces the page’s record for the file’s association class unless a later-started query has already answered it; the class is the final name extension, compared case-sensitively, or the whole path when the name has none. Mounted controls do not read that record and keep their own answer until their menu opens again, so the file header and a context menu can name different applications for one file meanwhile. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. Workspace context menus reveal the captured folder through the shared directory application catalog. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. -Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata before querying applications. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. +Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata, then name the application recorded for the file’s type without waiting for the Host. A type’s first opening on the page waits up to 300 ms for the Host’s answer; if none arrives by then, the row reads “Open in default application” and opens the file through its OS association. Each opening re-queries the Host in the background; a changed answer updates the open menu in place, and a failed query keeps the recorded answer. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. File menus copy absolute paths without line numbers; URL copying preserves query and fragment. Image files also expose image copy and original download, alongside the existing file actions. Successful downloads and saves show the shared Toast; picker cancellation is silent. @@ -59,7 +59,7 @@ A file menu offers “Open in sidebar” and “Open in floating panel”, which [`session-open-with.ts`](src/client/session-open-with.ts) shares one resolver across the shared context-menu package’s `session` and `sessionHeader` targets; other contributions do not cross between those targets. The file-tree slot uses `OpenInAppAction` with its owner’s `absolutePath`; there is no independent Session-header opener slot. A page-lifetime [`controller`](src/client/controller.ts) owns availability, persisted choice, and launch POST state. Menu observers and injected component hooks read those same sources. Document-relative routes and payload types come from the Host’s browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. Adapters resolve native and transport failures to named outcomes; skipped requests announce nothing. -The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. +The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening or plugin unload cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot; when its own file type’s answer changes, it re-resolves synchronously from the path its opening verified, so the context-menu registry keeps the other rows while the application row changes. A type without a recorded answer holds the file contribution until its refresh settles, 300 ms pass, or the menu closes; the registry opens the menu once every contribution is ready, so the whole menu waits. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. @@ -93,6 +93,9 @@ The Host verifies the path through the composed filesystem before opening or rev - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. - **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. +- **File associations are cached by type for the page.** Files sharing a final name extension share one answer; extensions that differ only in case, such as `.PNG` and `.png`, are separate types. A per-document override, such as a macOS “Open with” choice for one file, can therefore show the type’s previous answer until the background query corrects the open menu. Linux content sniffing and multi-part extensions such as `.tar.gz` have the same effect, and one file’s empty answer shows the row disabled for the type’s other files the same way. Choosing the row before the correction opens the application that answer named. Names without an extension are recorded per path. Records, with one icon per application, grow with the file types seen and end with the page. +- **A type’s first file menu can open late.** The whole menu waits up to 300 ms for that type’s first answer on the page, and a slower answer still changes the row after opening. +- **One background refresh at a time.** Opening another file menu cancels the previous menu’s unanswered query, so that type keeps its earlier answer, or none, until its next opening. - **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. - **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here remains deferred. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index 7bac1ae79f..69598cbc60 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -39,11 +39,11 @@ kind: "package-reference" 文件菜单列出已发现的关联应用,不单列“用默认应用打开”。“显示文件位置”固定在菜单底部,通过分隔线与滚动的应用列表分开。查询成功且只有一个可用操作时显示单按钮,不再显示下拉箭头。文件关联首次加载时使用灰色骨架图标。Host 识别出默认应用时,菜单将该项标注为“(默认)”,主按钮打开该应用;否则第一个关联应用占据该位置,只有在一个关联应用都没有时主按钮才执行文件定位。目录菜单不包含定位项。选择文件应用不修改系统默认应用。无法预览文件时,空态使用同一菜单,按钮增大到 40px 高并显示图标和动作文字;根据默认动作显示“打开”或“显示文件位置”。 -使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 +使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询成功后,结果还会替换本页面中该文件关联类别的记录,除非更晚发起的查询已经给出回答;类别按文件名的最后一个扩展名划分(区分大小写),没有扩展名的文件按完整路径划分。已挂载控件不读取这份记录,会保留自己的回答,直到再次打开其菜单,因此在此期间同一个文件在文件标题栏和右键菜单中可能显示不同的应用。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 工作区右键菜单通过共享的目录应用列表定位被点击的文件夹。文件树目录提供原生定位与复制文件夹路径,不提供文件预览或保存。 -右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,再查询关联应用。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 +右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,然后直接显示该文件类型已记录的应用,不等待 Host。某个类型在本页面第一次打开菜单时,最多等待 Host 回答 300 毫秒;到时仍未回答,这一项显示“使用默认应用打开”,通过系统的文件关联打开文件。每次打开菜单都会在后台重新查询 Host;回答有变化时,已打开的菜单原地更新,查询失败则保留已记录的回答。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 文件菜单复制不含行号的绝对路径;网址复制保留查询参数与锚点。图片文件在既有文件操作之外,还提供复制图片与下载原图。下载和保存成功后显示共享 Toast,取消选择器时不提示。 @@ -59,7 +59,7 @@ kind: "package-reference" [`session-open-with.ts`](src/client/session-open-with.ts) 为共享右键菜单包声明的 `session` 和 `sessionHeader` 目标共用一个解析器;其他贡献不会在这两种目标间扩散。文件树插槽通过所属组件的 `absolutePath` 使用 `OpenInAppAction`;会话头部没有独立打开按钮插槽。页面生命周期的 [`controller`](src/client/controller.ts) 持有可用性、持久化偏好与启动 POST 状态。菜单观察器和组件注入 hooks 读取同一组源。文档相对路由与载荷类型来自 Host 的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared`。适配器将原生操作及传输失败解析为具名结果;跳过的请求不播报。 -目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 +目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单或插件卸载会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照;只有本文件类型的回答变化时,才基于本次打开时验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。尚无记录的类型会让文件菜单项等到这次刷新结束、满 300 毫秒或菜单关闭;注册表在所有菜单项都就绪后才打开菜单,所以整个菜单都会等待。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 @@ -93,6 +93,9 @@ Host 在打开或定位前通过当前文件系统验证路径。没有对应 Ho - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 - **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 +- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答;只有大小写不同的扩展名(如 `.PNG` 和 `.png`)算作不同类型。因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”)可能先显示该类型之前的回答,再由后台查询更正已打开的菜单。Linux 的内容嗅探和 `.tar.gz` 这类多段扩展名也有同样的效果;某个文件的空回答也会以同样的方式,让同类型其他文件的这一项先显示为禁用。在更正之前选择这一项,会用该回答中的应用打开。没有扩展名的文件按路径记录。记录以及每个应用的一份图标随出现过的文件类型增长,并在页面关闭时释放。 +- **某个类型的第一次文件菜单可能打开得较慢。** 整个菜单最多等待该类型在本页面的第一个回答 300 毫秒;回答更慢时,菜单打开后这一项仍会原地变化。 +- **同一时间只有一次后台刷新。** 打开另一个文件的菜单会取消前一个菜单尚未返回的查询,该类型保留之前的回答(或仍没有回答),直到下次打开。 - **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 - **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上仍属延期工作。 diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 5810a3aab7..aa69108391 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -3,18 +3,44 @@ import { useState } from 'react' import { IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { ContextMenuTargetMap, MenuAction } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-api-workspace-files/remote' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppController } from './controller.ts' import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import type { OpenInAppPathController } from './open-path.ts' import type { OpenInAppKey } from './locales.ts' import type { OpenInAppToastSource } from './open-toast.tsx' +type Applications = readonly SessionWorkspacePathApplication[] +/** A file menu's verified Host path and the association answer its resolution showed. */ +interface Verification { readonly absolutePath: string; readonly shown: Applications | undefined } + +/** + * How long a file menu waits for the first association answer of its file type before opening with the + * unnamed default-application row; most first answers arrive sooner, so the row rarely changes after opening. + */ +const FIRST_ANSWER_WAIT_MS = 300 + +/** + * @param pending - settles without rejecting. + * @param ms - longest wait. + * @param signal - ends the wait early. + * @returns settles when `pending` settles, after `ms`, or on abort, whichever comes first; the timer never outlives it. + */ +function settleWithin(pending: Promise, ms: number, signal: AbortSignal): Promise { + return new Promise((settle) => { + const done = (): void => { clearTimeout(timer); signal.removeEventListener('abort', done); settle() } + const timer = setTimeout(done, ms) + signal.addEventListener('abort', done, { once: true }) + void pending.then(done) + }) +} + /** * Register native opening, original-path reveal, and URL actions. * @param ctx - declared plugin dependencies. @@ -76,40 +102,88 @@ export function registerContextMenus( ] }, }), 'open-in-app: directory context menu') + const fileMenu = (target: ContextMenuTargetMap['file'], absolutePath: string | undefined): MenuAction[] => { + const { sessionId, path, line } = target + const available = absolutePath !== undefined + const desktop = paths.desktop.getSnapshot() === true && available + // Undefined until the Host first answers for this file type; the row then opens through the association. + const apps = desktop ? paths.cachedApplications(absolutePath) : [] + const application = apps?.find(app => app.default) + const openApplication = absolutePath === undefined || !desktop ? undefined + : application !== undefined ? () => open(absolutePath, 'open', application.id) + : apps === undefined ? () => open(absolutePath, 'open') : undefined + // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. + const openIn = (destination: 'sidebar' | 'float') => () => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { + destination, ...(line === undefined ? {} : { params: { line } }), + }) + } + return [ + { id: 'sidebar', icon: { key: 'open-in-app.sidebar' }, label: t('menu.openInSidebar'), disabled: !available, run: openIn('sidebar') }, + { id: 'float', icon: { key: 'open-in-app.float' }, label: t('menu.openInFloat'), disabled: !available, run: openIn('float') }, + { id: 'reveal', icon: { key: 'open-in-app.reveal' }, label: fileManager(), disabled: !desktop, + ...absolutePath === undefined ? {} : { run: () => open(absolutePath, 'reveal') } }, + { id: 'open', label: application ? t('open.title', { app: application.name }) : t('menu.defaultApp'), + icon: { key: 'open-in-app.application', ...application?.icon ? { src: application.icon } : {} }, + disabled: openApplication === undefined, ...openApplication === undefined ? {} : { run: openApplication } }, + { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), + run: async () => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) + ctx.contextMenus.notify(t('menu.copied'), true) + } }, + ] + } + // The Host path from each file target's latest successful stat and the answer its menu showed, shared by menus open + // on one target object at once. A stat clears it while running; answers arriving meanwhile need no re-resolution, as + // that stat's resolution reads the newest answers. + const verified = new WeakMap() + // The target whose changed association answer is being applied; only that re-resolution reuses the verified path, + // so every opening runs its own stat. The in-place update relies on the registry re-resolving synchronously from + // the notification, without which the menu stats again, and on a synchronous resolution replacing rows without + // clearing them first, without which the rows flicker. + let answering: ContextMenuTargetMap['file'] | undefined ctx.effect(() => ctx.contextMenus.register({ id: 'open-in-app.file', target: 'file', order: 100, - resolve: async (target, signal) => { - const { sessionId, path, line } = target - await paths.load() - const absolutePath = await resolvePath(sessionId, path, signal) - const available = absolutePath !== undefined - const desktop = paths.desktop.getSnapshot() === true && available - const apps = desktop ? await paths.applications(absolutePath, signal) : [] - signal.throwIfAborted() - const application = apps?.find(app => app.default) - // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. - const openIn = (destination: 'sidebar' | 'float') => () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { - destination, ...(line === undefined ? {} : { params: { line } }), + observe: target => [{ + getSnapshot: paths.associations.getSnapshot.bind(paths.associations), + subscribe: (listener: () => void) => { + // The answer this subscription last applied for a verification; answers for other file types leave it unchanged. + let applied: { readonly verification: Verification; readonly applications: Applications | undefined } | undefined + return paths.associations.subscribe(() => { + const verification = verified.get(target) + if (verification === undefined) return + const applications = paths.cachedApplications(verification.absolutePath) + const current = applied?.verification === verification ? applied.applications : verification.shown + if (applications === current) return + applied = { verification, applications } + answering = target + try { listener() } finally { answering = undefined } }) - } - return [ - { id: 'sidebar', icon: { key: 'open-in-app.sidebar' }, label: t('menu.openInSidebar'), disabled: !available, run: openIn('sidebar') }, - { id: 'float', icon: { key: 'open-in-app.float' }, label: t('menu.openInFloat'), disabled: !available, run: openIn('float') }, - { id: 'reveal', icon: { key: 'open-in-app.reveal' }, label: fileManager(), disabled: !desktop, - ...absolutePath === undefined ? {} : { run: () => open(absolutePath, 'reveal') } }, - { id: 'open', label: application ? t('open.title', { app: application.name }) : t('menu.defaultApp'), - icon: { key: 'open-in-app.application', ...application?.icon ? { src: application.icon } : {} }, - disabled: application === undefined, - ...absolutePath === undefined || application === undefined ? {} : { run: () => open(absolutePath, 'open', application.id) } }, - { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), - run: async () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) - ctx.contextMenus.notify(t('menu.copied'), true) - } }, - ] + }, + }], + resolve: (target, signal) => { + const reused = answering === target ? verified.get(target) : undefined + if (reused !== undefined) return fileMenu(target, reused.absolutePath) + verified.delete(target) + return (async () => { + await paths.load() + const absolutePath = await resolvePath(target.sessionId, target.path, signal) + signal.throwIfAborted() + if (absolutePath === undefined) return fileMenu(target, undefined) + if (paths.desktop.getSnapshot() === true) { + // Every opening re-queries so a changed association reaches this menu; a type's first opening waits for it briefly. + const unanswered = paths.cachedApplications(absolutePath) === undefined + const refreshed = paths.refreshApplications(absolutePath) + if (unanswered) { + await settleWithin(refreshed, FIRST_ANSWER_WAIT_MS, signal) + signal.throwIfAborted() + } + } + verified.set(target, { absolutePath, shown: paths.cachedApplications(absolutePath) }) + return fileMenu(target, absolutePath) + })() }, }), 'open-in-app: file context menu') ctx.effect(() => ctx.contextMenus.register({ diff --git a/packages/client/ui-open-in-app/src/client/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index e706f9eb25..84bdc9168e 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -56,6 +56,7 @@ export function apply(ctx: ClientContext): void { const controller = new OpenInAppController() void controller.load() const paths = new OpenInAppPathController(ctx.remote) + ctx.effect(() => () => { paths.dispose() }, 'open-in-app: association refreshes') ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'open-in-app: dictionaries') const t = ctx.locale.bind(NS) // Keep operation feedback visible after its initiating panel closes. diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index 4484bb29b9..85ea703b5d 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -1,12 +1,38 @@ /** * Host desktop availability, file associations, and open/reveal actions over the Session Remote. - * The desktop answer is read once per page; a failed read renders no control. + * The desktop answer is read once per page; a failed read renders no control. Association answers + * are recorded per association class so menus can show them without waiting for the Host. */ -import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionOpenWorkspacePathRequest, SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppOutcome, OpenInAppPathFailure } from './outcome.ts' +type Applications = readonly SessionWorkspacePathApplication[] + +/** + * Name the association class of a Host path: desktops look handlers up by the final name extension, so + * files sharing it share one answer; a name without one (`Makefile`, `.env`) is its own class. + */ +function associationKey(path: string): string { + const name = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1) + const dot = name.lastIndexOf('.') + return dot > 0 && dot < name.length - 1 ? `extension:${name.slice(dot)}` : `path:${path}` +} + +/** The compared application fields; a field added to the type fails to compile until it is listed here. */ +const APPLICATION_FIELDS = Object.keys({ + id: true, name: true, default: true, icon: true, +} satisfies Record) as readonly (keyof SessionWorkspacePathApplication)[] + +/** Equal answers keep the published snapshot, so observers re-resolve only when an answer changes. */ +function sameApplications(left: Applications, right: Applications): boolean { + return left.length === right.length && left.every((app, index) => { + const other = right[index] + return other !== undefined && APPLICATION_FIELDS.every(field => app[field] === other[field]) + }) +} + /** What a path gesture asks of the Host desktop: the default application, or the file manager showing the file. */ export type OpenInAppPathAction = 'open' | 'reveal' @@ -24,11 +50,25 @@ export interface OpenInAppPathRemote { } } -/** Page-lifetime desktop availability and the open/reveal carrier shared by every path control. */ +/** + * Page-lifetime desktop availability, association answers, and the open/reveal carrier shared by every path control. + * Answers are kept per association class for the page's life and grow with the classes queried. + */ export class OpenInAppPathController { /** Whether the Host desktop can open paths; null until the Host answered, false also after a failed read. */ readonly desktop: SnapshotStore = createSnapshotStore(null) + private readonly answers = createSnapshotStore>(new Map()) + /** Latest successful answer per association class; the snapshot keeps its identity until an answer changes. */ + readonly associations: ObservableSnapshot> = this.answers private loading: Promise | undefined + private readonly lifetime = new AbortController() + /** The latest background refresh; a newer refresh aborts it. */ + private refresh: AbortController | undefined + /** Start order of the query whose answer each class holds; an earlier query never replaces a later one. */ + private readonly answeredBy = new Map() + /** One icon string per application id, reused by every class that lists the application so its data URL is held once. */ + private readonly icons = new Map() + private queries = 0 /** * @param remote - the Session Remote namespace answering availability and running gestures. @@ -66,20 +106,70 @@ export class OpenInAppPathController { } /** - * Refresh the file's OS associations; failures remain distinct from an empty handler list. + * Query the file's current OS associations and record a successful answer for its association class. + * Failures remain distinct from an empty handler list and leave the recorded answer in place. * @param path - file path reported by the Host. - * @param signal - lifetime of the requesting preview. + * @param signal - lifetime of the requesting control. * @returns application metadata, or null when the query fails. */ - async applications(path: string, signal: AbortSignal): Promise { - let result: RemoteResult + async applications(path: string, signal: AbortSignal): Promise { + const order = ++this.queries + let result: RemoteResult try { result = await this.remote.session.workspacePathApplications({ path }, signal) } catch (_error) { // The control reports query failure and keeps file reveal available. return null } - return result.ok ? result.value : null + if (!result.ok) return null + this.record(associationKey(path), order, result.value) + return result.value + } + + /** + * Read the recorded answer of a file's association class without querying the Host. + * @param path - absolute Host path of the file. + * @returns the latest successful answer, or undefined before a query of this class succeeded. + */ + cachedApplications(path: string): Applications | undefined { + return this.answers.getSnapshot().get(associationKey(path)) + } + + /** + * Re-query a file's associations in the background. One refresh runs at a time: it outlives the + * requesting menu and ends with its answer, the next refresh, which cancels it, or {@link dispose}. + * @param path - absolute Host path of the file. + * @returns settles without rejecting when this refresh's query settles, after any answer is recorded; + * already settled after {@link dispose}. + */ + refreshApplications(path: string): Promise { + if (this.lifetime.signal.aborted) return Promise.resolve() + this.refresh?.abort() + const refresh = new AbortController() + this.refresh = refresh + return this.applications(path, AbortSignal.any([this.lifetime.signal, refresh.signal])).then(() => {}) + } + + /** Cancel background refreshes and refuse new ones; recorded answers stay readable. */ + dispose(): void { + this.lifetime.abort() + } + + private record(key: string, order: number, applications: Applications): void { + if ((this.answeredBy.get(key) ?? 0) > order) return + this.answeredBy.set(key, order) + const answers = this.answers.getSnapshot() + const previous = answers.get(key) + if (previous !== undefined && sameApplications(previous, applications)) return + const next = new Map(answers) + next.set(key, applications.map((app) => { + if (app.icon === null) return app + const icon = this.icons.get(app.id) + if (icon === app.icon) return { ...app, icon } + this.icons.set(app.id, app.icon) + return app + })) + this.answers.set(next) } private async run(): Promise { diff --git a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts index ca27f69e50..274d379207 100644 --- a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts @@ -49,10 +49,13 @@ afterEach(() => { /** The Session Remote slice the path controls call; answers a desktop and acknowledges every gesture. */ const remote = { session: { - workspacePathApplications: vi.fn(async () => ({ ok: true as const, value: [] })), + workspacePathApplications: vi.fn(async (_request: { path: string }, _signal?: AbortSignal) => ({ ok: true as const, value: [] })), canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: { opened: true as const } })), }, + workspaceFiles: { + stat: vi.fn(async (_sessionId: SessionId, path: string) => ({ ok: true as const, value: { absolutePath: `/w/${path}` } })), + }, } /** Boot the browser half over a real slot tree that declares the header list and the document-preview seats. */ @@ -335,6 +338,24 @@ describe('open-in-app browser half', () => { expect(ctx.slots.entries('deliverables.file.actions')).toHaveLength(0) }) + it('lets a file-menu association refresh outlive the menu and cancels it with the plugin', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) + const { ctx, fiber } = await bench() + let refresh: AbortSignal | undefined + remote.session.workspacePathApplications.mockImplementationOnce((_request, signal) => { + refresh = signal + return new Promise(() => {}) + }) + const menu = ctx.contextMenus.resolve({ kind: 'file', value: { sessionId: 'files' as SessionId, path: 'notes.txt' } }) + await menu.ready + expect(remote.workspaceFiles.stat).toHaveBeenCalledWith('files', 'notes.txt', expect.any(AbortSignal)) + expect(remote.session.workspacePathApplications).toHaveBeenCalledWith({ path: '/w/notes.txt' }, refresh) + menu.dispose() + expect(refresh?.aborted).toBe(false) + await fiber.dispose() + expect(refresh?.aborted).toBe(true) + }) + it('injects the announcement seat into the delivery entries and releases every entry with the fiber', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) const { ctx, fiber } = await bench() diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index 10407f9f54..4a0e8963ae 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -7,6 +7,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { SessionId } from '@deepseek-ai/dsh-session' import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' import type { ContextMenus, ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { FileActionSource, FileSaveResult } from '@deepseek-ai/dsh-client-ui-file-actions/client' import { OpenInAppPathController } from '../src/client/open-path.ts' import { OpenInAppController } from '../src/client/controller.ts' @@ -15,6 +17,9 @@ import { registerContextMenus } from '../src/client/context-menus.tsx' import type { OpenInAppToastSource } from '../src/client/open-toast.tsx' const sessionId = SessionId('menu-actions') +type Applications = readonly SessionWorkspacePathApplication[] +/** Let settled Remote answers finish their queued continuations. */ +const settle = () => new Promise((resolve) => { setTimeout(resolve, 0) }) afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) async function boot() { @@ -27,13 +32,13 @@ async function boot() { const remote = { session: { canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), - workspacePathApplications: vi.fn(async () => ({ ok: true as const, value: [ - { id: 'preview', name: 'Preview', default: true, icon: 'data:image/png;base64,a' }, - ] })), + workspacePathApplications: vi.fn(async (_request: { path: string }, _signal?: AbortSignal): Promise> => ({ + ok: true, value: [{ id: 'preview', name: 'Preview', default: true, icon: 'data:image/png;base64,a' }], + })), openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: undefined })), }, workspaceFiles: { - stat: vi.fn(async () => ({ ok: true as const, value: { absolutePath: '/workspace/file.svg' } })), + stat: vi.fn(async (_sessionId: SessionId, path: string) => ({ ok: true as const, value: { absolutePath: path.startsWith('/') ? path : `/workspace/${path}` } })), readBytes: vi.fn(async () => ({ ok: true as const, value: { data: [...new TextEncoder().encode('')] } })), }, } @@ -82,14 +87,17 @@ it('routes file actions through an explicit host, the line, native association a const h = await boot() // A menu raised inside a floating panel names that panel; the open names a host instead, never a pane. const file = { kind: 'file', value: { sessionId, path: 'file.svg', paneId: 'float7' as never, line: 24 } } as const - const items = (await h.resolve(file)).source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) - expect(items.map(item => [item.id, item.label, item.icon?.key])).toEqual([ + const first = await h.resolve(file) + const items = () => first.source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) + await vi.waitFor(() => { expect(items().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + expect(items().map(item => [item.id, item.label, item.icon?.key])).toEqual([ ['open-in-app.file/sidebar', 'menu.openInSidebar', 'open-in-app.sidebar'], ['open-in-app.file/float', 'menu.openInFloat', 'open-in-app.float'], ['open-in-app.file/reveal', 'menu.reveal', 'open-in-app.reveal'], ['open-in-app.file/open', 'open.title', 'open-in-app.application'], ['open-in-app.file/copyPath', 'menu.copyPath', 'open-in-app.copy'], ]) + first.dispose() await h.choose(file, 'open-in-app.file/sidebar') expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(sessionId, expect.stringContaining('file.svg'), { destination: 'sidebar', params: { line: 24 } }) @@ -114,7 +122,8 @@ it('routes file actions through an explicit host, the line, native association a const simple = { kind: 'file', value: { sessionId: SessionId('absent'), path: '/file.unknown' } } as const h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const menu = await h.resolve(simple) - expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) + // The Host's empty answer arrives within the first-answer wait, so the row opens disabled. + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) }) expect(menu.source.getSnapshot().some(item => item.id.endsWith('/copyImage'))).toBe(false) expect(menu.source.getSnapshot().filter(item => item.id.startsWith('file-actions.')).map(item => item.id)) .toEqual(['file-actions.file/saveAs']) @@ -122,10 +131,153 @@ it('routes file actions through an explicit host, the line, native association a expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'sidebar' }) h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const floating = await h.resolve(simple) + expect(floating.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) floating.select('open-in-app.file/float') expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'float' }) }) +it('names the application when the first answer of a file type arrives within the wait', async () => { + const h = await boot() + // The answer arrives a macrotask later, after a resolution that did not wait would have published its rows. + h.remote.session.workspacePathApplications.mockImplementationOnce(() => new Promise((answer) => { + setTimeout(() => { answer({ ok: true, value: [{ id: 'preview', name: 'Preview', default: true, icon: null }] }) }, 10) + })) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + const labels: (string | undefined)[] = [] + const stop = menu.source.subscribe(() => { + labels.push(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label) + }) + await menu.ready + stop() + expect(labels.filter(label => label !== undefined)).toEqual(['open.title']) + menu.dispose() +}) + +it('waits for the first answer of a file type at most 300 ms, and a dismissal ends the wait', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + onTestFinished(() => { vi.useRealTimers() }) + const h = await boot() + h.remote.session.workspacePathApplications.mockImplementation(() => new Promise(() => {})) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + let ready = false + void menu.ready.then(() => { ready = true }) + await vi.advanceTimersByTimeAsync(299) + expect(ready).toBe(false) + await vi.advanceTimersByTimeAsync(1) + expect(ready).toBe(true) + expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + menu.dispose() + const dismissed = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'todo.md' } }) + await vi.advanceTimersByTimeAsync(100) + expect(vi.getTimerCount()).toBe(1) + dismissed.dispose() + await dismissed.ready + expect(vi.getTimerCount()).toBe(0) + expect(h.failure).not.toHaveBeenCalled() +}) + +it('opens file menus after the first-answer wait and changes only the application row in place', async () => { + const h = await boot() + const answers: ((answer: RemoteResult) => void)[] = [] + h.remote.session.workspacePathApplications.mockImplementation(() => new Promise((answer) => { answers.push(answer) })) + const file = { kind: 'file', value: { sessionId, path: 'notes.txt' } } as const + const menu = await h.resolve(file) + const rows = () => menu.source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) + const application = () => rows().find(item => item.id === 'open-in-app.file/open') + expect(answers).toHaveLength(1) + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + expect(application()?.icon).toEqual({ key: 'open-in-app.application' }) + const published: number[] = [] + const stop = menu.source.subscribe(() => { published.push(rows().length) }) + answers[0]!({ ok: true, value: [ + { id: '/Applications/TextEdit.app', name: 'TextEdit', default: false, icon: null }, + { id: '/Applications/Sublime Text.app', name: 'Sublime Text', default: true, icon: 'data:image/png;base64,c3Vi' }, + ] }) + await vi.waitFor(() => { expect(application()).toMatchObject({ label: 'open.title', icon: { src: 'data:image/png;base64,c3Vi' } }) }) + stop() + expect(published.length).toBeGreaterThan(0) + expect(published.every(count => count === 5)).toBe(true) + menu.select('open-in-app.file/open') + await vi.waitFor(() => { + expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.txt', application: '/Applications/Sublime Text.app' }) + }) + // Another file of the same type shows the recorded answer at once and asks the Host again. + const other = await h.resolve({ kind: 'file', value: { sessionId, path: 'todo.txt' } }) + const otherApplication = () => other.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(otherApplication()?.label).toBe('open.title') + expect(answers).toHaveLength(2) + answers[1]!({ ok: true, value: [] }) + await vi.waitFor(() => { expect(otherApplication()).toMatchObject({ label: 'menu.defaultApp', disabled: true }) }) + other.dispose() + expect(h.failure).not.toHaveBeenCalled() +}) + +it('opens through the OS association until the Host first answers, including after failed queries', async () => { + const h = await boot() + let refuse = () => {} + h.remote.session.workspacePathApplications.mockImplementationOnce(() => new Promise((answer) => { + refuse = () => { answer({ ok: false } as never) } + })) + const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.md' } }) + const application = () => menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + refuse() + await settle() + expect(h.paths.cachedApplications('/workspace/notes.md')).toBeUndefined() + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + menu.select('open-in-app.file/open') + await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.md' }) }) + await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'opened' }) }) +}) + +it('verifies a file menu once when answers for other files arrive during verification', async () => { + const h = await boot() + let release = () => {} + const verifying = new Promise((resolve) => { release = resolve }) + h.remote.workspaceFiles.stat.mockImplementation(async (_sessionId: SessionId, path: string) => { + await verifying + return { ok: true as const, value: { absolutePath: `/workspace/${path}` } } + }) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) + release() + await menu.ready + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) + menu.dispose() +}) + +it('verifies every opening of a file target, whatever order the registry observes and resolves in', async () => { + const register = vi.spyOn(MenuRegistry.prototype, 'register') + const h = await boot() + const contribution = register.mock.calls.map(([input]) => input).find(input => input.id === 'open-in-app.file')! + const target = { sessionId, path: 'notes.txt' } + // Resolving without observing first, as a registry that subscribes after its first resolution would. + await contribution.resolve(target, new AbortController().signal) + await contribution.resolve(target, new AbortController().signal) + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) +}) + +it('re-resolves an open file menu only when its own file type answers differently', async () => { + const h = await boot() + const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + const shown = menu.source.getSnapshot() + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) + expect(menu.source.getSnapshot()).toBe(shown) + h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) + await h.paths.applications('/workspace/todo.txt', new AbortController().signal) + const changed = menu.source.getSnapshot() + expect(changed.find(item => item.id === 'open-in-app.file/open')).toMatchObject({ label: 'menu.defaultApp', disabled: true }) + h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(menu.source.getSnapshot()).toBe(changed) + menu.dispose() +}) + it('keeps copy-path available on failed metadata and reports native action failures', async () => { const h = await boot() const file = { kind: 'file', value: { sessionId, path: 'file.svg' } } as const @@ -139,14 +291,25 @@ it('keeps copy-path available on failed metadata and reports native action failu h.remote.session.openWorkspacePath.mockResolvedValueOnce({ ok: false } as never) await h.choose(file, 'open-in-app.file/reveal') await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'failed', failure: 'revealError' }) }) + await vi.waitFor(() => { expect(h.paths.cachedApplications('/workspace/file.svg')).toHaveLength(1) }) + // A failed query keeps the recorded answer. h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: false } as never) - expect((await h.resolve(file)).source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) + const kept = await h.resolve(file) + await vi.waitFor(() => { + expect(h.remote.session.workspacePathApplications.mock.settledResults.every(result => result.type !== 'incomplete')).toBe(true) + }) + await settle() + expect(h.paths.cachedApplications('/workspace/file.svg')).toHaveLength(1) + expect(kept.source.getSnapshot().find(item => item.id.endsWith('/open'))).toMatchObject({ label: 'open.title', disabled: false }) + kept.dispose() h.paths.desktop.set(false) h.fileActions.canSaveAs = false + const queried = h.remote.session.workspacePathApplications.mock.calls.length const web = await h.resolve(file) expect(web.source.getSnapshot().some(item => item.id.endsWith('/saveAs'))).toBe(false) expect(web.source.getSnapshot().filter(item => ['/open', '/reveal'].some(suffix => item.id.endsWith(suffix))) .every(item => item.disabled)).toBe(true) + expect(h.remote.session.workspacePathApplications).toHaveBeenCalledTimes(queried) }) it('opens links in the registered browser, externally, and on the clipboard', async () => { diff --git a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts index e542b9164c..3222bbb738 100644 --- a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts @@ -94,3 +94,91 @@ it('distinguishes failed association queries from an empty application list', as const rejecting = new OpenInAppPathController(remoteOf({ workspacePathApplications: async () => { throw new Error('disconnected') } })) expect(await rejecting.applications('/file.mp3', new AbortController().signal)).toBeNull() }) + +describe('OpenInAppPathController association answers', () => { + type Answer = Awaited> + const app = (name: string, icon: string | null = null) => ({ id: `/Applications/${name}.app`, name, default: true, icon }) + const answered = (...apps: ReturnType[]): Answer => ({ ok: true, value: apps }) + /** A Remote whose association queries settle when the test answers them, and reject once cancelled. */ + function deferredRemote() { + const queries: { path: string; signal: AbortSignal | undefined; answer: (result: Answer) => void }[] = [] + const workspacePathApplications = vi.fn((request: { path: string }, signal?: AbortSignal) => new Promise((answer, reject) => { + queries.push({ path: request.path, signal, answer }) + signal?.addEventListener('abort', () => { reject(new Error('cancelled')) }, { once: true }) + })) + return { queries, controller: new OpenInAppPathController(remoteOf({ workspacePathApplications })) } + } + + it('shares an answer across files with the same final extension and keeps extensionless names apart', async () => { + const answers: Record = { + '/w/notes.txt': answered(app('TextEdit')), '/w/Makefile': answered(app('Xcode')), '/w/.env': answered(app('Zed')), + } + const controller = new OpenInAppPathController(remoteOf({ workspacePathApplications: async ({ path }) => answers[path]! })) + const signal = new AbortController().signal + expect(controller.cachedApplications('/w/notes.txt')).toBeUndefined() + for (const path of Object.keys(answers)) await controller.applications(path, signal) + expect(controller.cachedApplications('/elsewhere/todo.txt')).toEqual([app('TextEdit')]) + expect(controller.cachedApplications('C:\\work\\archive.tar.txt')).toEqual([app('TextEdit')]) + expect(controller.cachedApplications('/w/NOTES.TXT')).toBeUndefined() + expect(controller.cachedApplications('/w/Makefile')).toEqual([app('Xcode')]) + expect(controller.cachedApplications('/other/Makefile')).toBeUndefined() + expect(controller.cachedApplications('/w/.env')).toEqual([app('Zed')]) + expect(controller.cachedApplications('/w/draft.')).toBeUndefined() + }) + + it('publishes changed answers only, and an earlier query never replaces a later answer', async () => { + const { queries, controller } = deferredRemote() + const signal = new AbortController().signal + const earlier = controller.applications('/w/a.txt', signal) + const later = controller.applications('/w/b.txt', signal) + queries[1]!.answer(answered(app('Sublime Text', 'data:image/png;base64,c3Vi'))) + expect(await later).toEqual([app('Sublime Text', 'data:image/png;base64,c3Vi')]) + const published = controller.associations.getSnapshot() + queries[0]!.answer(answered(app('TextEdit'))) + expect(await earlier).toEqual([app('TextEdit')]) + expect(controller.associations.getSnapshot()).toBe(published) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('Sublime Text', 'data:image/png;base64,c3Vi')]) + const unchanged = controller.applications('/w/c.txt', signal) + queries[2]!.answer(answered(app('Sublime Text', 'data:image/png;base64,c3Vi'))) + await unchanged + expect(controller.associations.getSnapshot()).toBe(published) + const changed = controller.applications('/w/c.txt', signal) + queries[3]!.answer(answered(app('Sublime Text', 'data:image/png;base64,bmV3'), app('TextEdit'))) + await changed + expect(controller.associations.getSnapshot()).not.toBe(published) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('Sublime Text', 'data:image/png;base64,bmV3'), app('TextEdit')]) + const other = controller.applications('/w/d.md', signal) + queries[4]!.answer(answered(app('Sublime Text', 'data:image/png;base64,bmV3'))) + await other + expect(controller.cachedApplications('/w/e.md')).toEqual([app('Sublime Text', 'data:image/png;base64,bmV3')]) + expect(controller.cachedApplications('/w/e.txt')).toHaveLength(2) + }) + + it('keeps the recorded answer through refused and rejected queries', async () => { + const workspacePathApplications = vi.fn() + .mockResolvedValueOnce(answered(app('Preview'))) + .mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'boom', {}) }) + .mockRejectedValueOnce(new Error('down')) + const controller = new OpenInAppPathController(remoteOf({ workspacePathApplications })) + const signal = new AbortController().signal + await controller.applications('/w/a.png', signal) + expect(await controller.applications('/w/a.png', signal)).toBeNull() + expect(await controller.applications('/w/a.png', signal)).toBeNull() + expect(controller.cachedApplications('/w/b.png')).toEqual([app('Preview')]) + }) + + it('runs one background refresh at a time, cancelling the older for the newer file, and disposal cancels it', async () => { + const { queries, controller } = deferredRemote() + void controller.refreshApplications('/w/a.txt') + void controller.refreshApplications('/w/b.txt') + expect(queries.map(query => [query.path, query.signal?.aborted])).toEqual([['/w/a.txt', true], ['/w/b.txt', false]]) + queries[1]!.answer(answered(app('TextEdit'))) + await vi.waitFor(() => { expect(controller.cachedApplications('/w/c.txt')).toEqual([app('TextEdit')]) }) + void controller.refreshApplications('/w/d.md') + controller.dispose() + expect(queries[2]).toMatchObject({ path: '/w/d.md', signal: { aborted: true } }) + void controller.refreshApplications('/w/e.json') + expect(queries).toHaveLength(3) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('TextEdit')]) + }) +})