From dc3b8aba33141c0216ff00513d8e68ed4b2f8b77 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Sun, 15 Nov 2026 00:15:44 +0800 Subject: [PATCH] feat(clues): refine resizable workbench and resource previews --- CHANGELOG.md | 7 +- CHANGELOG_EN.md | 7 +- docs/external-plugin-guide.md | 6 + src/client/clues/resource-summary.module.css | 138 ++++++++++++ src/client/clues/resource-summary.tsx | 206 ++++++++++++++---- src/client/clues/selection-actions.tsx | 54 +++-- .../clues/sources/feishu/docs-preview.tsx | 152 +++++++------ .../clues/sources/feishu/feishu.module.css | 75 ++++--- .../clues/sources/feishu/task-editor.tsx | 9 + src/client/clues/sources/github/editor.tsx | 9 +- src/client/clues/sources/github/images.ts | 16 ++ src/client/clues/tab/CluesTab.tsx | 142 ++++++------ src/client/clues/tab/SectionStack.tsx | 123 +++++++++++ src/client/clues/tab/clues-tab.module.css | 25 ++- src/client/clues/windows/comments.tsx | 12 +- src/client/clues/windows/detail.tsx | 71 ++++-- src/client/clues/windows/pack.tsx | 12 +- src/client/locales-de.ts | 15 ++ src/client/locales-es.ts | 15 ++ src/client/locales-fr.ts | 15 ++ src/client/locales-ja.ts | 15 ++ src/client/locales-pt.ts | 15 ++ src/client/locales-ru.ts | 15 ++ src/client/locales.ts | 30 +++ src/client/markdown-images.ts | 8 +- src/client/windows/format-content.tsx | 31 ++- src/client/windows/types.ts | 3 + src/client/windows/windows.module.css | 19 ++ src/clues/actions.ts | 27 ++- src/clues/discussion.ts | 2 + src/clues/local-files.ts | 8 +- src/clues/resource-info.ts | 26 ++- src/clues/session-delivery.ts | 13 +- src/clues/sources/github/comments.ts | 4 +- src/clues/sources/github/gh.ts | 78 +++++-- src/clues/sources/github/sources.ts | 11 + src/clues/types.ts | 13 +- src/index.ts | 4 +- tests/clues-actions.spec.ts | 43 ++++ tests/clues-github-gh.spec.ts | 19 +- tests/clues-github-source.spec.ts | 4 +- tests/clues-local-files.spec.ts | 13 ++ tests/clues-section-stack.spec.tsx | 43 ++++ tests/clues-tab-main.spec.tsx | 13 +- tests/e2e/clues-resource-ux.e2e.ts | 121 +++++++++- tests/e2e/clues-ui19.e2e.ts | 33 ++- tests/e2e/clues-uiux.e2e.ts | 20 +- tests/fixtures/clues-github/pull-read.json | 6 +- tests/theme.spec.ts | 2 + 49 files changed, 1393 insertions(+), 355 deletions(-) create mode 100644 src/client/clues/sources/github/images.ts create mode 100644 src/client/clues/tab/SectionStack.tsx create mode 100644 tests/clues-actions.spec.ts create mode 100644 tests/clues-section-stack.spec.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index fe0eebb5..72740fc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,19 +70,20 @@ - 🧭 **新增「线索收集」Tab:把文件、飞书任务/文档、GitHub issue 与 PR 收进一处,用统一浮窗预览与编辑**:右侧栏多出一个 tab,顶部一条来源分段(本地文件 / GitHub Issues / GitHub Pull requests / 飞书文档 / 飞书任务,最后选中的来源会记住),其下是范围栏(当前仓库或工作区,可切换)与共享 `SearchField`;列表行 30px,行内动作只在悬停或键盘聚焦时出现(触控恒显且 44px)。 - - **资料 / 资料包是一条 VSCode 式手风琴**:两个区块各自展开收起、同时展开也合法,状态写入插件设置,切换工作区或重开页签时恢复;收起时内容保持挂载,草稿、分页与滚动位置不丢。来源选择在 ≥520px 时是 5 等分分段(图标 + 文字、方向键 / Home / End),更窄时降级为宿主 `SelectMenu`。 + - **资料与资料包采用 VS Code 式可调分区**:多个区块可各自展开、同时显示;用鼠标、触控或键盘上下调整分隔柄。布局写入插件设置,折叠不丢失搜索、列表位置和草稿。 - **统一浮窗**:详情、包管理、添加成员、来源配置、新建包与分享都由同一个 `windows` 宿主承载(`FloatingWindow` 记忆位置与尺寸、支持最大化)。详情里预览与编辑是两个页签,读取与写入分两条路径:打开只读预览,`clues.loadEdit` 只在点「编辑」时发生,保存永远基于编辑文档自己的基线。 - **稳定引用**:tab 内与输入框里的 @ 都只落 `[[dsh-clue:…]]` / `[[dsh-cluepack:…]]` / `[[dsh-clue-snapshot:…]]` 这类稳定 token,跨会话、跨工作区都能解析回同一条线索。 - **`.cluepack` 分享**:按包或单条线索导出 / 导入,`references` 保留原引用;导入前给出可解析 / 不可解析的预览,未落地的行不写入。 - **来源运行面**:共享来源 runtime 负责依赖安装与连接授权(GitHub 走 `gh`,飞书走 lark-cli 设备码),表里逐来源显示就绪 / 缺依赖 / 未授权;状态只在显式读取时刷新,不轮询、不自动登录。新增依赖 `uqr` 0.1.3,把授权提示里的 `prompt.qr.uri` 渲染成可扫的二维码。 - **公共扩展面**:宿主 Cordis 服务 `betterSidebarClues` 与浮窗能力一起开放(`features` 新增 `clues` / `windowHost`),外部插件用同一套 API 注册线索来源与浮窗,见 `docs/external-plugin-guide.md` §7.1。 - - **PR 头部按宿主的阅读顺序重做**:详情两行——第一行 `#1130 · 作者 · +353 −2`,第二行 `● 通过 · 冲突 · feat/x → dev`。颜色只用宿主的状态点(完成 / 失败 / 运行中 / 空闲),不再有填色胶囊;`进行中`、`可合并`、`待评审` 与 GitHub 边算边报的 `未知` 都是默认态,一律不写,只有 `已批准`、`冲突`、CI 失败才出现。列表行收成 `#1130 · 作者 · ●`:状态点只在偏离常态时(已合并 / 已关闭 / 草稿 / 已完成)出现,CI 通过只留一个点、不重复「通过」二字。 + - **GitHub 预览显示头像、名称、分支与红绿变更量**;PR 概览分开显示合并、检查、评审与评论。没有数据时不显示虚假的就绪或审批数量。 - **少一条栏带**:详情原来在标题栏下还有一整行「本地缓存 · 刷新 · 打开原始来源」。缓存时间收进刷新按钮的 tooltip,刷新与「打开原始来源」并入头部右侧的动作位,正文上方的 chrome 从 5 条压到 3 条。 - **格式与渲染**:为 Markdown、HTML、JSONL 与代码提供只读预览器;写盘前按磁盘现状还原编码与行尾,客户端只发送 LF。 - 🧪 测试:新增 `clues-resource-summary`(两行头部、状态点词汇、默认态静默、动作位独立渲染)、`clues-resource-info`(白名单保留 / 拒绝)、`clues-settings-*`(六组导航、来源开关与批次、深链)、`clues-cache-ux`、`clues-pack-windows` 等用例;`tests/side-card-section.spec.tsx` 覆盖开始页接管与线索来源组共存;挂载 lane 在真实宿主 + Chromium 下覆盖线索 tab、浮窗与设置。 - 🪟 **线索窗口默认停靠在右侧栏**:有会话时,详情、包管理、添加成员、来源配置、新建包与分享直接以右侧栏 tab 打开,不再先弹浮窗;浮窗按钮仍可随时弹出同一个实例(草稿、滚动与导航栈都不重挂),没有会话时保持浮窗。 - 🔄 **设备码授权自动复查**:点「开始授权」拿到验证码后,设置页按 CLI 自己建议的间隔重发同一次显式轮询——页面隐藏即暂停,完成 / 过期 / 取消即停,连续失败 3 次退回手动;「我已完成,检查状态」按钮保留。runtime 本身仍然不排任何定时器。 - - ✅ **PR 详情可以展开逐项 CI 检查**:一次详情读取顺带取回最多 20 条 check(check run 与旧式 status context),头部多一行「失败 2 · 8 项检查」,展开后失败与错误优先、名称可点跳转 provider 详情;列表行与搜索行仍只带聚合状态,不会为每一行多请求一次。 + - ✅ **CI 概览可展开且能识别部分结果**:在一次详情读取内显示最多 20 项检查,区分排队、运行、失败、跳过和取消;超出时标明已显示数量并跳转到 GitHub 完整检查。 + - 🖼️ **预览修复**:本地 PNG/SVG 和 Markdown 相对图片可内联显示;飞书文档保留列表和表格。预览选区动作绑定打开它的会话,明确未准入时可以安全重试,不重复产生草稿或消息。 - 🌐 **i18n 只维护宿主官方语言**:zh / en 内置,ja / de / es / fr / pt / ru 懒加载,跟随宿主当前语言(先精确匹配、再基础语言、最后 en);此前自带的 14 种第三语言词典与 better-locale 覆盖层一并删除。 - 🧪 测试:新增共享模式层(`ui-patterns`)与窗口默认停靠、设备码自动复查(含隐藏暂停 / 失败退回)与逐项 check 的读-白名单-渲染三段用例;`window-surfaces` 钉住「默认停靠且重开不改面」。**测试面按「删了再重写」收敛**:线索套件从约 5.0 万行压到约 1.8 万行(63 个冗余 spec 删除,其余保留契约、合并重复变体为表驱动),全仓用例 4432 项通过。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 9dd37f41..c1b61297 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -72,18 +72,19 @@ - 🧭 **New Clues tab: local files, Feishu tasks/docs and GitHub issues/PRs in one place, previewed and edited in one host window**: the right column gains a tab whose top row is a source segment (local files / GitHub issues / GitHub pull requests / Feishu docs / Feishu tasks, remembering the last choice), followed by a scope row (the current repository or workspace) and the shared `SearchField`. Rows are 30px, with row actions only on hover or keyboard focus (always visible at 44px on touch). - - **Resources and collections form one VSCode-style accordion**: each section opens and closes independently, both open is valid, the state is persisted in plugin settings and restored when switching workspaces or reopening the tab; a collapsed section keeps its body mounted, so drafts, paging and scroll survive. The source strip is a five-way segmented control at 520px and above (icon + label, arrow keys / Home / End) and degrades to the host `SelectMenu` below that. + - **Resources and Collections use resizable VS Code-style sections**: expand several together and drag the horizontal dividers, or resize with the keyboard. The layout is remembered, and collapsing a section preserves its search, scroll position, and drafts. - **One window host**: detail, pack management, add-member, source configuration, new pack and sharing all go through the same `windows` host (`FloatingWindow` remembers position and size and supports maximize). A detail's preview and edit are two tabs over two separate paths: opening reads a preview only, `clues.loadEdit` runs only when Edit is chosen, and a save always uses the edit document's own baseline. - **Stable references**: an @ pick inside the tab or in the composer only ever produces `[[dsh-clue:…]]` / `[[dsh-cluepack:…]]` / `[[dsh-clue-snapshot:…]]` tokens, so a reference resolves back to the same clue across sessions and workspaces. - **`.cluepack` sharing**: export and import by pack or single clue with `references` preserved; the import preview says what resolves and what does not, and unresolved rows are never written. - **Source runtime**: one shared source runtime owns dependency installation and connection authorization (GitHub through `gh`, Feishu through the lark-cli device code). The table shows ready / missing dependency / not authorized per source, refreshes only on an explicit read, and never polls or auto-logs-in. New dependency `uqr` 0.1.3 renders the authorization prompt's `prompt.qr.uri` as a scannable code. - **Public extension surface**: the host Cordis service `betterSidebarClues` and the window capability are exposed together (`features` gains `clues` / `windowHost`), so another plugin registers sources and windows through the same API; see `docs/external-plugin-guide.md` §7.1. - - **The PR header now follows the host's reading order**: two lines — `#1130 · author · +353 −2`, then `● Passed · Conflicts · feat/x → dev`. Colour appears only on the host's state dot (done / error / ongoing / idle); there is no filled capsule. Defaults stay silent — `in progress`, `mergeable`, `review required` and GitHub's transient `unknown` are not printed — and only `approved`, a conflict or a failing rollup speak. A list row shrinks to `#1130 · author · ●`: the state dot appears only when it deviates (merged / closed / draft / completed), and a passing rollup keeps a dot without repeating the word. + - **GitHub previews show avatars, names, branches, and colored line changes**. A PR overview separates merge readiness, checks, review, and comments without inventing results or counts. - **One band fewer**: the detail used to open a full row of "local cache · Refresh · Open original" under the title bar. The cache age now rides the Refresh tooltip and both actions sit in the header's own action seat, taking the chrome above the body from five rows to three. - 🧪 Tests: new `clues-resource-summary` (two-line header, state-dot vocabulary, silent defaults, standalone action seat), `clues-resource-info` (whitelist keep / reject), `clues-settings-*` (six-group navigation, source switches and batches, deep links), `clues-cache-ux` and `clues-pack-windows` cases; `tests/side-card-section.spec.tsx` covers the start-page takeover and the clue sources group coexisting; the mount lane exercises the clues tab, windows and settings against a real host in Chromium. - 🪟 **Clue windows dock to the right column by default**: with a session at hand, detail, pack management, add-member, source configuration, new pack and sharing open as right-column tabs instead of floating first; the float button still pops the SAME instance out (draft, scroll and navigation stack are never remounted), and a session-less window stays floating. - 🔄 **Device-code authorization checks itself**: after "Authorize" hands out a code, the settings page re-sends the same explicit poll at the CLI's own suggested cadence — paused while the page is hidden, stopped on completion, expiry or cancel, and falling back to the button after three consecutive failures. The runtime itself still schedules nothing. - - ✅ **A pull request's checks expand from its detail**: one read also returns up to 20 checks (check runs and legacy status contexts), the header gains a "Failing 2 · 8 checks" line, and expanding ranks failures and errors first with each name linking to the provider. List and search rows keep the aggregate state only, so no row pays for a second request. + - ✅ **CI details distinguish queued, running, failed, skipped, and canceled checks**. Up to 20 rows come from the same read; a partial result shows the number loaded and links to GitHub for the complete list. + - 🖼️ **Preview fixes**: local PNG/SVG and relative Markdown images render inline; Feishu documents retain lists and tables. Selection actions stay bound to their opening conversation and can be retried when admission was explicitly refused, without duplicating a draft or message. - 🌐 **i18n only maintains the host's official languages**: zh / en built in, ja / de / es / fr / pt / ru lazy-loaded, following the host's active locale (exact, then base language, then en); the 14 bundled third-party dictionaries and the better-locale override are gone. - 🧪 Tests: new cases for the shared page-pattern layer (`ui-patterns`), the docked window default, the device-code auto-check (hidden pause, failure fallback) and the check read→whitelist→render chain; `window-surfaces` pins "docks by default and a re-open never changes the surface". **The clue suite was rebuilt rather than patched**: roughly 50k lines down to 18k (63 redundant specs deleted, the rest keeping their contracts and folding duplicate variants into tables), with 4,432 cases green across the repo. diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 65245a1a..7c6c929c 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -1045,6 +1045,12 @@ ctx.effect(() => --- +### 线索文档预览:可选展示元数据 + +线索详情的身份与 CI 概览只读:来源可提供 `CluePerson.avatarUrl`、`ClueResourceInfo.checkCount` 和 `mergeStatus`。`checks` 是整体结论,`checkRuns` 最多 20 项,可以额外区分跳过、中性、取消和未知;当检查总数多于明细条数时,详情会标注部分结果,不从样本重算整体结论。缺失字段不妨碍旧来源渲染。 + +结构化文档可通过 `WindowDocumentContent.pathImages` 提供宿主 Markdown 的图片解析器;内置本地 Markdown 仅在已取得真实文件基址时解析相对图片,第三方来源不共享本地文件基址。PNG、SVG 等本地图片使用宿主认证文件路由,以普通图片上下文渲染;不会把 SVG 作为 HTML 或可执行文档插入。 + ### 7.1 侧边对话渲染适配器(新增提案,尚未发布) 这是 v0.29.0 新增、配合 GenUI 0.15.0 的窄范围接入能力,关联 [dsh-genui #354](https://github.com/omdsh-dev/dsh-genui/issues/354)。消费方必须先探测方法存在;未安装、旧版本或未注册适配器时,侧边对话继续使用原有 `MarkdownText` 和 `markdownTextProps()`,不改变普通 Markdown 与代码围栏。 diff --git a/src/client/clues/resource-summary.module.css b/src/client/clues/resource-summary.module.css index e029f321..a7aee063 100644 --- a/src/client/clues/resource-summary.module.css +++ b/src/client/clues/resource-summary.module.css @@ -250,3 +250,141 @@ } a.checkName:hover { text-decoration: underline; } + +.resourceTitle { + margin: 0 0 5px; + color: var(--dsw-alias-label-primary); + font-size: 17px; + line-height: 1.3; + font-weight: 600; + overflow-wrap: anywhere; +} +.summary[data-clue-resource-github] { flex-wrap: wrap; align-items: flex-start; } +.summary[data-clue-resource-github] .body { flex: 1 1 250px; gap: 3px; } +.author, .person { min-width: 0; } +.person { + display: inline-flex; + align-items: center; + gap: 6px; + max-width: 100%; + vertical-align: middle; + text-decoration: none; + color: var(--dsw-alias-label-primary); + font-weight: 600; +} +a.person:hover .personName { text-decoration: underline; } +.personName { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.avatar { + display: grid; + flex: none; + place-items: center; + width: 20px; + height: 20px; + overflow: hidden; + border-radius: 50%; + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); + font-size: 10px; +} +.avatar img { width: 100%; height: 100%; object-fit: cover; } +.inline .avatar { width: 14px; height: 14px; } +.githubState { + display: inline-flex; + padding: 1px 6px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: var(--ds-sidebar-radius); +} +.githubState[data-clue-resource-state-chip='open'] .state { color: var(--dsw-alias-state-success-primary); } +.branch code { font: inherit; color: var(--dsw-alias-label-secondary); } +.changes { display: inline-flex; gap: 5px; font-weight: 600; white-space: nowrap; } + +[data-check-tone='pass'], [data-check-tone='merged'] { color: var(--dsw-alias-state-success-primary); } +[data-check-tone='fail'] { color: var(--dsw-alias-state-error-primary); } +[data-check-tone='wait'] { color: var(--dsw-alias-state-warn-primary); } +[data-check-tone='other'], [data-check-tone='closed'] { color: var(--dsw-alias-label-tertiary); } +.quietMark { display: inline-grid; width: 12px; height: 12px; place-items: center; font-weight: 600; line-height: 1; } + +.gate { + min-width: 0; + margin: var(--ds-sidebar-gutter) var(--ds-sidebar-gutter) 0; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: var(--ds-sidebar-radius); + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-base); + font-size: 12px; + line-height: 17px; + font-variant-numeric: tabular-nums; +} +.gateHeadline { + display: flex; + align-items: center; + gap: 9px; + padding: 8px 10px; +} +.gateHeadline strong { display: block; font-size: 13px; font-weight: 600; } +.gateIcon { + display: grid; + flex: none; + place-items: center; + width: 28px; + height: 28px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 50%; +} +.gateCaption { color: var(--dsw-alias-label-tertiary); font-size: 11px; } +.gateFacts { + display: grid; + grid-template-columns: minmax(0, 1.25fr) repeat(2, minmax(0, 1fr)); + gap: 1px; + border-top: 1px solid var(--dsw-alias-border-l1); + background: var(--dsw-alias-border-l1); +} +.gateCell { + display: flex; + min-width: 0; + flex-direction: column; + gap: 2px; + align-items: stretch; + padding: 6px 8px; + border: 0; + border-radius: 0; + background: var(--dsw-alias-bg-base); + color: inherit; + font: inherit; + text-align: start; +} +button.gateCell { cursor: pointer; } +button.gateCell:hover { background: var(--dsw-alias-interactive-bg-hover); } +button.gateCell:focus-visible { outline: 1px solid var(--ds-sidebar-accent); outline-offset: -2px; } +.gateLabel { display: flex; align-items: center; justify-content: space-between; gap: 2px; font-weight: 600; overflow-wrap: anywhere; } +.gateLabel svg { flex: none; color: var(--dsw-alias-label-tertiary); } +.gateCell[aria-expanded='true'] .gateLabel svg { transform: rotate(90deg); } +.gateCell .checks { white-space: normal; overflow-wrap: anywhere; } +.gateValue:not([data-check-tone]) { color: var(--dsw-alias-label-secondary); } +.gateValue { min-width: 0; overflow-wrap: anywhere; } +.checkMeter { display: flex; gap: 2px; min-height: 3px; margin: 3px 0 2px; } +.checkMeter > span { flex: 1 1 0; border-radius: 2px; background: currentColor; } +.checkMeter > [data-check-tone='other'] { background: var(--dsw-alias-border-l2); } +.gateChecks { border-top: 1px solid var(--dsw-alias-border-l1); } +.checkListHead { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 4px 10px; + padding: 6px 10px; + color: var(--dsw-alias-label-secondary); + font-size: 11px; +} +.checkListHead a { display: inline-flex; align-items: center; gap: 3px; color: var(--ds-sidebar-accent); } +.checkRows { list-style: none; margin: 0; padding: 0; } +.checkRows > li { gap: 7px; padding: 6px 10px; border-top: 1px solid var(--dsw-alias-border-l1); } +.checkRows .checkName { flex: 1 1 auto; white-space: normal; overflow-wrap: anywhere; color: var(--dsw-alias-label-primary); } +.checkRowState { flex: none; font-variant-numeric: tabular-nums; } +@container (max-width: 360px) { + .summary[data-clue-resource-github] { gap: 4px; } + .summary[data-clue-resource-github] .body { flex-basis: 100%; } + .resourceTitle { font-size: 15px; } + .gateFacts { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } + .gateCell[data-clue-change-request-fact='checks'] { grid-column: 1 / -1; } +} diff --git a/src/client/clues/resource-summary.tsx b/src/client/clues/resource-summary.tsx index 0862f1b0..cf5a9de2 100644 --- a/src/client/clues/resource-summary.tsx +++ b/src/client/clues/resource-summary.tsx @@ -29,7 +29,7 @@ * The vocabulary comes from the public clue contract (the host half and the * browser bundle share it); this module only renders it. */ -import type { ReactNode } from 'react' +import { useId, useState, type ReactNode } from 'react' import type { ClueCheckState, CluePerson, @@ -40,7 +40,7 @@ import type { ClueResourceState, ClueResourceTime, } from '../../clues/types.ts' -import { IconChevronRightOutlineRegular, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconClockOutlineRegular, IconCloseOutlineRegular, IconRightUpOutlineRegular, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' import { t } from '../locales.ts' import css from './resource-summary.module.css' @@ -68,6 +68,24 @@ export function personLabel(person: CluePerson | undefined): string | undefined return id } +/** Provider identity with a visible initial even when the avatar cannot load. */ +export function ResourcePerson({ person, linked = false }: { person: CluePerson; linked?: boolean }): ReactNode { + const [failedSrc, setFailedSrc] = useState() + const label = personLabel(person) ?? t('clueResourceUnknownPerson') + const avatar = person.avatarUrl?.startsWith('https://') === true ? person.avatarUrl : undefined + const content = <> + + {label} + + return linked && person.url !== undefined && person.url.startsWith('https://') + ? {content} + : {content} +} + /** Localized lifecycle label of one normalized state. */ export function stateLabel(state: ClueResourceState): string { switch (state) { @@ -161,6 +179,7 @@ function stateIsInformative(state: ClueResourceState): boolean { /** The host `StateDot` semantic of one state; never `ongoing` (see module note). */ function stateDot(state: ClueResourceState): 'done' | 'warning' | 'error' | 'idle' { switch (state) { + case 'open': case 'merged': case 'completed': return 'done' @@ -172,13 +191,17 @@ function stateDot(state: ClueResourceState): 'done' | 'warning' | 'error' | 'idl } /** Localized CI value; the one mapping shared by the verdict and the list row. */ -function checksValueOf(checks: NonNullable): string { +function checksValueOf(checks: ClueResourceCheck['state']): string { switch (checks) { case 'success': return t('cluePrChecksSuccess') case 'failure': return t('cluePrChecksFailure') case 'pending': return t('cluePrChecksPending') case 'expected': return t('cluePrChecksExpected') case 'error': return t('cluePrChecksError') + case 'skipped': return t('cluePrChecksSkipped') + case 'neutral': return t('cluePrChecksNeutral') + case 'cancelled': return t('cluePrChecksCancelled') + case 'unknown': return t('cluePrMergeUnknown') } } @@ -195,13 +218,14 @@ function checksInk(checks: NonNullable): 'error' | u * `idle` for a queued rollup. Only a rollup that is genuinely running spins; * it is the one fact here that is in flight. */ -function checksGlyph(checks: NonNullable): ReactNode { +function checksGlyph(checks: ClueResourceCheck['state']): ReactNode { switch (checks) { - case 'success': return + case 'success': return case 'failure': - case 'error': return + case 'error': return case 'pending': return - case 'expected': return + case 'expected': return + default: return − } } @@ -229,7 +253,7 @@ function ChecksVerdict(props: { {...(ink === undefined ? {} : { 'data-ink': ink })} data-checks={props.checks} > - {checksGlyph(props.checks)} + {checksGlyph(props.checks)} {props.word === false ? null : {value}} ) @@ -240,12 +264,8 @@ function ChecksVerdict(props: { * before "what ran?", so failures and errors come first and a green wall never * buries the one red job. */ -const CHECK_RANK: Readonly> = { - failure: 0, - error: 1, - pending: 2, - expected: 3, - success: 4, +const CHECK_RANK: Readonly> = { + failure: 0, error: 1, cancelled: 2, pending: 3, expected: 4, unknown: 5, success: 6, skipped: 7, neutral: 8, } /** The ranked copy of one check list (stable: equal ranks keep provider order). */ @@ -254,7 +274,7 @@ function rankedChecks(checks: readonly ClueResourceCheck[]): readonly ClueResour } /** Whether one check is a verdict a reader must not miss. */ -function checkFailed(state: ClueCheckState): boolean { +function checkFailed(state: ClueResourceCheck['state']): boolean { return state === 'failure' || state === 'error' } @@ -283,13 +303,27 @@ function CheckList(props: { readonly checks: readonly ClueResourceCheck[] }): Re {failing > 0 ? ' · ' : null} {t('cluePrChecksCount', { count: ranked.length })} -
    - {ranked.map((check, index) => { + + + ) +} + +function checkTone(state: ClueResourceCheck['state']): 'pass' | 'fail' | 'wait' | 'other' { + if (state === 'success') return 'pass' + if (checkFailed(state)) return 'fail' + if (state === 'pending' || state === 'expected') return 'wait' + return 'other' +} + +function CheckRows({ checks, detailed = false }: { checks: readonly ClueResourceCheck[]; detailed?: boolean }): ReactNode { + return
      + {checks.map((check, index) => { const state = checksValueOf(check.state) const label = `${check.name} · ${state}` return (
    • - + {checksGlyph(check.state)} {check.url === undefined ? ( @@ -305,12 +339,11 @@ function CheckList(props: { readonly checks: readonly ClueResourceCheck[] }): Re {check.name} )} + {detailed && {state}}
    • ) })}
    - - ) } /** One plain fact of the second line (review / mergeability). */ @@ -345,12 +378,12 @@ function inkFacts(info: ClueResourceInfo): InkFact[] { } /** Additions/deletions only; the other counts are list-row detail. */ -function changeCounts(info: ClueResourceInfo): string | undefined { - const counts = info.counts - const additions = counts?.additions === undefined ? '' : '+' + counts.additions - const deletions = counts?.deletions === undefined ? '' : '−' + counts.deletions - const value = [additions, deletions].filter(part => part !== '').join(' ') - return value === '' ? undefined : value +function ChangeCounts({ counts }: { counts: ClueResourceCounts }): ReactNode { + if (counts.additions === undefined && counts.deletions === undefined) return null + return + {counts.additions !== undefined && +{counts.additions.toLocaleString()}} + {counts.deletions !== undefined && −{counts.deletions.toLocaleString()}} + } /** One dot plus its word, shared by the header and the list row. */ @@ -383,6 +416,9 @@ interface ResourceSummaryProps { */ readonly actions?: ReactNode readonly className?: string + readonly github?: boolean + readonly title?: string + readonly separateChecks?: boolean } /** @@ -393,42 +429,47 @@ interface ResourceSummaryProps { * two carries the facts a reader acts on. A window title or a body heading * already states the subject, so neither line repeats it. */ -export function ResourceSummary({ info, actions, className }: ResourceSummaryProps): ReactNode { +export function ResourceSummary({ info, actions, className, github, title, separateChecks }: ResourceSummaryProps): ReactNode { const number = info === undefined ? undefined : numberLabel(info) const author = personLabel(info?.author) const branches = branchesLabel(info?.branches) - const counts = info === undefined ? undefined : changeCounts(info) + const counts = info?.counts const due = info?.due === undefined ? undefined : formatResourceTime(info.due.at, info.due.allDay) - const facts = info === undefined ? [] : inkFacts(info) - const state = info?.state !== undefined && stateIsInformative(info.state) ? info.state : undefined + const facts = info === undefined || separateChecks === true ? [] : inkFacts(info) + const state = info?.state !== undefined && (github === true || stateIsInformative(info.state)) ? info.state : undefined const hasIdentity = info !== undefined && (state !== undefined || number !== undefined - || author !== undefined || counts !== undefined || due !== undefined + || author !== undefined || counts?.additions !== undefined || counts?.deletions !== undefined || due !== undefined || info.path !== undefined || info.sizeBytes !== undefined) const hasFacts = info !== undefined - && (info.checks !== undefined || facts.length > 0 || branches !== undefined) - const checkRuns = info?.checkRuns !== undefined && info.checkRuns.length > 0 ? info.checkRuns : undefined + && ((separateChecks !== true && info.checks !== undefined) || facts.length > 0 || branches !== undefined) + const checkRuns = separateChecks !== true && info?.checkRuns !== undefined && info.checkRuns.length > 0 ? info.checkRuns : undefined // The action seat is itself something to show: a window whose source reports // no metadata still keeps Refresh and the original-source link here. - if (!hasIdentity && !hasFacts && checkRuns === undefined && actions === undefined) return null + if (!hasIdentity && !hasFacts && checkRuns === undefined && actions === undefined && title === undefined) return null return (
    + {title !== undefined &&

    {title}

    } {hasIdentity && info !== undefined && (
    {state !== undefined && ( - + )} {number !== undefined && {number}} - {author !== undefined && {author}} - {counts !== undefined && {counts}} + {author !== undefined && + {github === true && info.author !== undefined ? : author} + } + {github === true && info.createdAt !== undefined && } + {counts !== undefined && } {due !== undefined && {t('clueResourceDue')} {due}} {info.path !== undefined && ( {info.path} @@ -440,7 +481,7 @@ export function ResourceSummary({ info, actions, className }: ResourceSummaryPro )} {hasFacts && info !== undefined && (
    - {info.checks !== undefined && ( + {separateChecks !== true && info.checks !== undefined && ( @@ -456,7 +497,9 @@ export function ResourceSummary({ info, actions, className }: ResourceSummaryPro ))} {branches !== undefined && ( - {branches} + + {github === true ? <>{info.branches?.head}{info.branches?.base !== undefined && <> → {info.branches.base}} : branches} + )}
    )} @@ -467,6 +510,88 @@ export function ResourceSummary({ info, actions, className }: ResourceSummaryPro ) } +function mergeGate(info: ClueResourceInfo) { + if (info.state === 'merged' || info.state === 'closed') return { key: info.state, label: stateLabel(info.state) } as const + if (info.state === 'draft') return { key: 'wait', label: stateLabel('draft') } as const + if (info.mergeable === 'conflicting') return { key: 'fail', label: t('cluePrConflict') } as const + if (info.mergeStatus === 'behind') return { key: 'wait', label: t('cluePrMergeBehind') } as const + if (info.review === 'changes-requested' || info.mergeStatus === 'blocked' || (info.checks !== undefined && checksInk(info.checks) === 'error')) { + return { key: 'fail', label: t('cluePrMergeBlocked') } as const + } + if (info.review === 'review-required' || info.checks === 'pending' || info.checks === 'expected') return { key: 'wait', label: t('cluePrMergeWaiting') } as const + if (info.state === 'open' && info.mergeStatus === 'ready' && info.mergeable === 'mergeable') return { key: 'pass', label: t('cluePrMergeReady') } as const + return { key: 'other', label: t('cluePrMergeUnknown') } as const +} + +/** One read-only PR overview. The rollup always outranks a bounded sample of runs. */ +export function PullRequestStatus({ info, sourceUrl, onDiscussion }: { + info: ClueResourceInfo + sourceUrl?: string + onDiscussion?: () => void +}): ReactNode { + const [expanded, setExpanded] = useState(false) + const listId = useId() + const runs = info.checkRuns ?? [] + const sample = info.checkCount !== undefined && info.checkCount > runs.length + const tones = { fail: 0, wait: 0, pass: 0, other: 0 } + for (const check of runs) tones[checkTone(check.state)]++ + const checkLink = sourceUrl === undefined ? undefined : sourceUrl.replace(/\/$/, '') + '/checks' + const checkToggle = runs.length > 0 + const gate = mergeGate(info) + const review = info.review === 'approved' ? t('cluePrReviewApproved') + : info.review === 'changes-requested' ? t('cluePrReviewChanges') + : info.review === 'review-required' ? t('cluePrReviewRequired') : '—' + const checksContent = <> + {t('cluePrChecks')}{checkToggle && } + {info.checks !== undefined ? + : {info.checkCount === 0 ? t('cluePrChecksNone') : t('cluePrMergeUnknown')}} +
    ) : ( - +
    + {xmlBlocks.length === 0 ?

    {t('cluePreviewBlockUnavailable')}

    : xmlBlocks} +
    )}
    {content !== '' && ( diff --git a/src/client/clues/sources/feishu/feishu.module.css b/src/client/clues/sources/feishu/feishu.module.css index 005c35a6..f15b018b 100644 --- a/src/client/clues/sources/feishu/feishu.module.css +++ b/src/client/clues/sources/feishu/feishu.module.css @@ -142,57 +142,60 @@ .docBlocks { display: flex; flex-direction: column; - gap: 6px; + gap: 8px; min-width: 0; -} - -.docParagraph, -.docHeading, -.docListItem, -.docQuote, -.docCode { - margin: 0; - min-width: 0; - color: var(--dsw-alias-label-primary); font-size: 13px; - line-height: 1.55; + line-height: 1.6; overflow-wrap: anywhere; } - -.docHeading { - font-size: 14px; - font-weight: 600; -} - -.docListItem { - padding-inline-start: 12px; - position: relative; -} - -.docListItem::before { - content: '•'; - position: absolute; - inset-inline-start: 0; - color: var(--dsw-alias-label-tertiary); -} - +.docBlocks :where(p, ul, ol, pre, blockquote, figure, hr) { margin-block: 0; } +.docBlocks :where(ul, ol) { padding-inline-start: 22px; } +.docBlocks a { color: var(--ds-sidebar-accent); } +.docBlocks [data-clue-image-preview] { margin-inline: 0; } +.docBlocks hr { border: 0; border-top: 1px solid var(--dsw-alias-border-l2); } +.docHeading { margin: 8px 0 0; font-size: 14px; font-weight: 600; } .docQuote { - padding-inline-start: 10px; + padding: 6px 8px; border-inline-start: 1px solid var(--dsw-alias-border-l2); color: var(--dsw-alias-label-secondary); } - .docCode { - padding: 6px 8px; + padding: 8px; border: 1px solid var(--dsw-alias-border-l1); - border-radius: 6px; + border-radius: var(--ds-sidebar-radius); background: var(--dsw-alias-bg-base); font-family: var(--ds-font-family-code, monospace); font-size: 12px; - line-height: 1.5; white-space: pre-wrap; - overflow: auto; } +.docTable { overflow-x: auto; } +.docTable table { width: 100%; border-collapse: collapse; font-size: 12px; } +.docTable :where(td, th) { padding: 5px 8px; border: 1px solid var(--dsw-alias-border-l2); text-align: start; } +.docTable th { background: var(--dsw-alias-interactive-bg-hover); } +.docTodo { color: var(--dsw-alias-label-secondary); } +.blockFallback { + display: flex; + flex-wrap: wrap; + gap: 4px 8px; + padding: 6px 8px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: var(--ds-sidebar-radius); + color: var(--dsw-alias-label-secondary); + font-size: 12px; +} +.taskFacts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 110px), 1fr)); + gap: 6px 12px; + margin: 0; + padding-block-end: 8px; + border-bottom: 1px solid var(--dsw-alias-border-l2); + font-size: 12px; + font-variant-numeric: tabular-nums; +} +.taskFacts dt { color: var(--dsw-alias-label-tertiary); font-size: 11px; } +.taskFacts dd { margin: 0; overflow-wrap: anywhere; } +.taskFacts dd[data-feishu-task-completed='true'] { color: var(--dsw-alias-state-success-primary); } .rawDetails { margin-top: 4px; diff --git a/src/client/clues/sources/feishu/task-editor.tsx b/src/client/clues/sources/feishu/task-editor.tsx index 72de9e07..9c14ebf1 100644 --- a/src/client/clues/sources/feishu/task-editor.tsx +++ b/src/client/clues/sources/feishu/task-editor.tsx @@ -33,6 +33,7 @@ import css from './feishu.module.css' import type { FeishuClientLabels } from './labels.ts' import { appDate, appDateTime } from './time.ts' import { t } from '../../../locales.ts' +import { personLabel } from '../../resource-summary.tsx' import { ActionButton, ActionFooter, Checkbox, Field, TextArea, TextInput } from '../../../ui/index.ts' /** Props of {@link FeishuTaskEditor}. */ @@ -99,6 +100,7 @@ function displayTime( /** The static read-only task view (a preview read is read-only by definition). */ function TaskReadOnly(props: { readonly task: FeishuTaskDocumentData + readonly assignees?: readonly string[] readonly labels: FeishuClientLabels readonly formatDateTime?: (value: string) => string readonly embedded?: boolean @@ -116,6 +118,12 @@ function TaskReadOnly(props: { } {embedded !== true &&

    {task.title}

    } + {embedded === true &&
    +
    {t('cluePreviewStatus')}
    {task.completed ? labels.completed : labels.open}
    + {props.assignees?.length ?
    {t('clueResourceAssignees')}
    {props.assignees.join(', ')}
    : null} + {task.start !== null &&
    {labels.start}
    {displayTime(task.start, labels, formatDateTime)}
    } + {task.due !== null &&
    {labels.due}
    {displayTime(task.due, labels, formatDateTime)}
    } +
    }
    {embedded !== true && ( <> @@ -273,6 +281,7 @@ export function FeishuTaskEditor(props: FeishuTaskEditorProps): ReactNode { return ( label !== undefined)} labels={labels} {...(props.formatDateTime === undefined ? {} : { formatDateTime: props.formatDateTime })} {...(props.embedded === undefined ? {} : { embedded: props.embedded })} diff --git a/src/client/clues/sources/github/editor.tsx b/src/client/clues/sources/github/editor.tsx index 58f67407..e9b187e7 100644 --- a/src/client/clues/sources/github/editor.tsx +++ b/src/client/clues/sources/github/editor.tsx @@ -30,6 +30,7 @@ * Ctrl/Cmd+Enter and remains the caller's source-owned write path). */ import { createElement, type KeyboardEvent, type ReactNode } from 'react' +import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' import type { ClueFormatRenderer, ClueFormatRendererProps, @@ -107,6 +108,7 @@ function readOnlySurface( reason: string | undefined, hostReadOnly: boolean, embedded: boolean, + pathImages?: MarkdownPathImages, ): ReactNode { return (
    {readOnlyReasonLabel(reason)}
    } {!embedded &&
    {title}
    }
    - {}} /> + {}} />
    ) @@ -175,7 +177,7 @@ function editableSurface( */ export const githubMarkdownRenderer: ClueFormatRenderer = (props: ClueFormatRendererProps): ReactNode => { const { sourceId, format, document, readOnly, saving, onChange, onSave } = props - const embedded = (props as ClueFormatRendererProps & { readonly embedded?: boolean }).embedded === true + const { embedded = false, pathImages } = props as ClueFormatRendererProps & { readonly embedded?: boolean; readonly pathImages?: MarkdownPathImages } const data = document.data if (!isGithubSource(sourceId)) { return ( @@ -184,6 +186,7 @@ export const githubMarkdownRenderer: ClueFormatRenderer = (props: ClueFormatRend text: textOf(data) ?? '', readOnly, markdown: format === 'text/markdown', + pathImages, saving, onChange: (next: string) => { onChange(withText(data, next)) }, })} @@ -202,7 +205,7 @@ export const githubMarkdownRenderer: ClueFormatRenderer = (props: ClueFormatRend } const locked = sourceReadOnly(data) if (readOnly || locked !== undefined) { - return readOnlySurface(fields.title, fields.body, locked?.reason, readOnly, embedded) + return readOnlySurface(fields.title, fields.body, locked?.reason, readOnly, embedded, pathImages) } return editableSurface(fields.title, fields.body, onChange, data, saving, onSave) } diff --git a/src/client/clues/sources/github/images.ts b/src/client/clues/sources/github/images.ts new file mode 100644 index 00000000..74a802ed --- /dev/null +++ b/src/client/clues/sources/github/images.ts @@ -0,0 +1,16 @@ +import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' +import type { JsonValue } from '../../../../clues/types.ts' + +/** Only a provider-supplied repo and immutable ref may resolve GitHub-relative media. */ +export function githubPathImages(data: JsonValue): MarkdownPathImages | undefined { + if (data === null || typeof data !== 'object' || Array.isArray(data)) return undefined + const { imageRepository: repo, imageRef: ref } = data as Record + if (typeof repo !== 'string' || !/^[\w.-]+\/[\w.-]+$/.test(repo) + || typeof ref !== 'string' || !/^[a-f0-9]{40}$/i.test(ref)) return undefined + const base = new URL('https://raw.githubusercontent.com/' + repo + '/' + ref + '/') + return { resolve(destination) { + if (!destination || /^[\s\\#]|^[a-z][a-z\d+.-]*:|^\/\//i.test(destination)) return undefined + const url = new URL(destination.replace(/^\//, ''), base) + return url.origin === base.origin && url.pathname.startsWith(base.pathname) ? url.href : undefined + } } +} diff --git a/src/client/clues/tab/CluesTab.tsx b/src/client/clues/tab/CluesTab.tsx index decb6875..89b68c02 100644 --- a/src/client/clues/tab/CluesTab.tsx +++ b/src/client/clues/tab/CluesTab.tsx @@ -41,6 +41,7 @@ import { LoadingIndicator } from '../../ui/LoadingIndicator.tsx' import { SelectMenu } from '../../ui/SelectMenu.tsx' import design from '../../ui/design.module.css' import css from './clues-tab.module.css' +import { SectionStack } from './SectionStack.tsx' /** The plugin-settings key of the clue tab (one sparse blob). */ const CLUE_TAB_SETTINGS_KEY = 'clues' @@ -49,12 +50,19 @@ const CLUE_TAB_SETTINGS_KEY = 'clues' type CluesTabProps = Pick /** The persisted section state, with the explorer defaults applied. */ -function sectionLayoutOf(blob: Record): { browse: boolean; packs: boolean } { +function sectionLayoutOf(blob: Record): { browse: boolean; packs: boolean; weights?: Record } { const raw = blob.layout const layout = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record : {} - return { browse: layout.browse !== false, packs: layout.packs === true } + const weights = layout.weights + return { + browse: layout.browse !== false, + packs: layout.packs !== false, + ...(weights !== null && typeof weights === 'object' && !Array.isArray(weights) + ? { weights: weights as Record } + : {}), + } } /** Read the sparse settings blob out of the live preferences. */ @@ -172,12 +180,17 @@ export function CluesTab({ ctx, store, scope, visible }: CluesTabProps): ReactNo /** Flip one explorer section from the rendered state, then persist it. */ const toggleSection = useCallback((key: 'browse' | 'packs', open: boolean): void => { - const next = { ...sections, [key]: open } - setSections(next) const current = blobOf(store.getPrefs()) + const next = { ...sections, weights: sectionLayoutOf(current).weights, [key]: open } + setSections(next) persistSettings({ ...current, layout: next }, true) }, [sections, persistSettings, store]) + const persistWeights = (weights: Record): void => { + const current = blobOf(store.getPrefs()) + persistSettings({ ...current, layout: { ...sections, weights } }, true) + } + /** Remember the source the reader chose (restored on the next open). */ const rememberSource = useCallback((sourceId: string): void => { const current = blobOf(store.getPrefs()) @@ -284,6 +297,7 @@ export function CluesTab({ ctx, store, scope, visible }: CluesTabProps): ReactNo face, workspaces: listClueWorkspaces(ctx), pack, + sessionId: scope.sessionId, onInsertClue: insertClue, onInsertPack: insertPack, onNotice: notifyClue, @@ -291,7 +305,7 @@ export function CluesTab({ ctx, store, scope, visible }: CluesTabProps): ReactNo scopes, onScopeChange, }) - }, [service, face, browseWorkspaceId, ctx, insertClue, insertPack, openAddToPack, scopes, onScopeChange]) + }, [service, face, browseWorkspaceId, ctx, scope.sessionId, insertClue, insertPack, openAddToPack, scopes, onScopeChange]) const openImport = useCallback((): void => { if (service === undefined || browseWorkspaceId === undefined) return @@ -364,65 +378,65 @@ export function CluesTab({ ctx, store, scope, visible }: CluesTabProps): ReactNo )} {ready && browseWorkspaceId !== undefined && ( -
    - } - open={sections.browse} - onOpenChange={open => { toggleSection('browse', open) }} - actions={utilityButtons} - className={css.browseSection} - bodyClassName={css.browseBody} - > -
    - -
    -
    - } - open={sections.packs} - onOpenChange={open => { toggleSection('packs', open) }} - // Cap the shelf only while resources also has the floor; alone, it fills. - size={sections.browse ? 'compact' : 'fill'} - className={css.packSection} - bodyClassName={css.packBody} - > -
    - -
    -
    -
    + } + open={sections.browse} + onOpenChange={open => { toggleSection('browse', open) }} + actions={utilityButtons} + className={css.browseSection} + > +
    + +
    + + ) }, + { id: 'packs', title: t('clueViewPacks'), open: sections.packs, weight: 2, content: ( + } + open={sections.packs} + onOpenChange={open => { toggleSection('packs', open) }} + > +
    + +
    +
    + ) }, + ]} /> )} diff --git a/src/client/clues/tab/SectionStack.tsx b/src/client/clues/tab/SectionStack.tsx new file mode 100644 index 00000000..68382c7d --- /dev/null +++ b/src/client/clues/tab/SectionStack.tsx @@ -0,0 +1,123 @@ +/** A vertical workbench stack. A sash redistributes only the two nearest open sections. */ +import { Fragment, useEffect, useId, useRef, useState, type ReactNode } from 'react' +import { createFrameBatcher } from '../../frame-batcher.ts' +import css from './clues-tab.module.css' + +interface Section { + id: string + title: string + open: boolean + weight: number + content: ReactNode +} + +interface Drag { + pointerId: number + y: number + room: number + start: number + next: number +} + +// A sub-pixel reserve keeps each pair adjustable after other panes collapse. +const limit = (value: number): number => Math.min(0.999, Math.max(0.001, value)) + +function Sash({ top, bottom, ratio, onPreview, onCommit }: { + top: { id: string; title: string } + bottom: { id: string; title: string } + ratio: number + onPreview(ratio: number): void + onCommit(ratio: number): void +}): ReactNode { + const drag = useRef(null) + const [batch] = useState(createFrameBatcher) + useEffect(() => () => batch.dispose(), [batch]) + + return
    { + if (event.button !== 0 || drag.current !== null) return + const document = event.currentTarget.ownerDocument + const upper = document.getElementById(top.id) + const lower = document.getElementById(bottom.id) + if (upper === null || lower === null) return + const room = [upper, lower].reduce((sum, pane) => sum + + pane.getBoundingClientRect().height - parseFloat(getComputedStyle(pane).minHeight), 0) + if (room <= 0) return + event.preventDefault() + event.currentTarget.focus({ preventScroll: true }) + event.currentTarget.setPointerCapture(event.pointerId) + drag.current = { pointerId: event.pointerId, y: event.clientY, room, start: ratio, next: ratio } + }} + onPointerMove={event => { + const current = drag.current + if (current?.pointerId !== event.pointerId) return + current.next = limit(current.start + (event.clientY - current.y) / current.room) + batch.schedule(() => { onPreview(current.next) }) + }} + onPointerUp={event => { + const current = drag.current + if (current?.pointerId !== event.pointerId) return + batch.dispose() + drag.current = null + const next = limit(current.start + (event.clientY - current.y) / current.room) + if (next !== current.start) onCommit(next) + else onPreview(next) + }} + onLostPointerCapture={event => { + const current = drag.current + if (current?.pointerId !== event.pointerId) return + batch.dispose() + drag.current = null + onPreview(current.start) + }} + onKeyDown={event => { + if (drag.current !== null) return + const next = event.key === 'Home' ? 0 : event.key === 'End' ? 1 + : event.key === 'ArrowUp' ? ratio - 0.05 : event.key === 'ArrowDown' ? ratio + 0.05 : undefined + if (next === undefined) return + event.preventDefault() + if (limit(next) !== ratio) onCommit(limit(next)) + }} /> +} + +export function SectionStack({ sections, initialWeights, onResize }: { + sections: readonly Section[] + initialWeights?: Record + onResize(weights: Record): void +}): ReactNode { + const prefix = useId() + const [weights, setWeights] = useState(() => Object.fromEntries(sections.map(({ id, weight }) => { + const saved = initialWeights?.[id] + return [id, typeof saved === 'number' && Number.isFinite(saved) && saved > 0 ? saved : weight] + }))) + const opened = sections.filter(section => section.open) + const openWeight = opened.reduce((sum, section) => sum + (weights[section.id] ?? section.weight), 0) + let previous: Section | undefined + return
    + {sections.map(section => { + const top = section.open ? previous : undefined + if (section.open) previous = section + const topWeight = top === undefined ? 0 : weights[top.id] ?? top.weight + const weight = weights[section.id] ?? section.weight + const total = topWeight + weight + const resize = (ratio: number, commit: boolean): void => { + if (top === undefined || total === 0) return + const next = { ...weights, [top.id]: total * ratio, [section.id]: total * (1 - ratio) } + setWeights(next) + if (commit) onResize(next) + } + const id = prefix + section.id + return + {top !== undefined && total > 0 && { resize(ratio, false) }} onCommit={ratio => { resize(ratio, true) }} />} +
    + {section.content} +
    +
    + })} +
    +} diff --git a/src/client/clues/tab/clues-tab.module.css b/src/client/clues/tab/clues-tab.module.css index 1690b9f7..0707cd30 100644 --- a/src/client/clues/tab/clues-tab.module.css +++ b/src/client/clues/tab/clues-tab.module.css @@ -42,12 +42,33 @@ font-size: 12px; line-height: 16px; } -.regions { +.stack { display: flex; flex: 1; flex-direction: column; - min-width: 0; min-height: 0; + min-width: 0; + overflow-y: auto; +} +.stackPane { display: flex; flex: none; min-width: 0; } +.stackPane[data-expanded='true'] { flex: 1 0 112px; min-height: 112px; } +.sash { + position: relative; + flex: 0 0 7px; + cursor: row-resize; + touch-action: none; + outline: none; + box-sizing: border-box; + padding-block: 3px; + background: var(--dsw-alias-border-l2) content-box; +} +.sash + .stackPane > div > div:first-child { border-top: 0; } +.sash:hover, .sash:focus-visible, .sash:active { + background-color: var(--ds-sidebar-accent); +} +@media (pointer: coarse) { + .stackPane[data-expanded='true'] { flex-basis: 156px; min-height: 156px; } + .sash { flex-basis: 14px; padding-block: 6px 7px; } } /* The very first workbench section at the top of the tab needs no double top rule. */ .browseSection > div:first-child { diff --git a/src/client/clues/windows/comments.tsx b/src/client/clues/windows/comments.tsx index fc826dd3..d22fb996 100644 --- a/src/client/clues/windows/comments.tsx +++ b/src/client/clues/windows/comments.tsx @@ -1,13 +1,13 @@ /** Whole-resource discussion. Source replies/reviews stay separate from the body. */ import { useId, useMemo, useRef, useState, type ReactNode } from 'react' -import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' +import { MarkdownText, type MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' import type { ClueComment, ClueCommentCapabilities, ClueDiscussionPage } from '../../../clues/types.ts' import { markdownTextProps } from '../../markdown-labels.tsx' import { t, type CopyKey } from '../../locales.ts' import { LoadingIndicator } from '../../ui/LoadingIndicator.tsx' import { ActionButton, ErrorBlock, Notice, TextArea } from '../../ui/index.ts' import { clueErrorMessage } from '../copy.ts' -import { personLabel, formatResourceTime } from '../resource-summary.tsx' +import { ResourcePerson, personLabel, formatResourceTime } from '../resource-summary.tsx' import { ResourceSelectionActions, type ClueSelectionActionTarget } from '../selection-actions.tsx' import css from './comments.module.css' @@ -19,6 +19,8 @@ export interface ResourceDiscussionProps { readonly loading: boolean readonly error?: string readonly readOnly?: boolean + readonly pathImages?: MarkdownPathImages + readonly showAvatars?: boolean /** Captured resource ownership; only each comment's body enters this surface. */ readonly selectionTarget?: Pick onLoad(cursor?: string, parentId?: string): void @@ -106,11 +108,13 @@ export function ResourceDiscussion(props: ResourceDiscussionProps): ReactNode { {comments.map(comment => { const url = commentUrl(comment.url) const body = comment.format === 'text/markdown' - ?
    + ?
    :
    {comment.body}
    return
    - {personLabel(comment.author) ?? t('clueResourceUnknownPerson')} + {props.showAvatars && comment.author !== undefined + ? + : personLabel(comment.author) ?? t('clueResourceUnknownPerson')} {comment.createdAt !== undefined && } {comment.reviewState !== undefined && {reviewStateLabel(comment.reviewState)}} {comment.resolved === true && {copy('clueCommentResolved')}} diff --git a/src/client/clues/windows/detail.tsx b/src/client/clues/windows/detail.tsx index 34ac8188..ce24cbba 100644 --- a/src/client/clues/windows/detail.tsx +++ b/src/client/clues/windows/detail.tsx @@ -33,7 +33,7 @@ * candidate uses a deterministic hash of source/type/locator, so clicking the * same row twice focuses the same window instead of stacking previews. */ -import { createElement, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' +import { Fragment, createElement, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' import type { ReactNode } from 'react' import { IconRefreshOutlineRegular, IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { ActionButton, IconButton } from '../../ui/kit.tsx' @@ -63,10 +63,14 @@ import type { BetterSidebarCluesClientFace } from '../registry.ts' import { categoryOf, clueErrorMessage, clueErrorHint } from '../copy.ts' import { preferredClueWindowSurface, type ClueWindowSurface } from '../../prefs.ts' import { t } from '../../locales.ts' +import { isAbsolutePath, resolveSidebarPath } from '../../paths.ts' +import { createMarkdownPathImages } from '../../markdown-images.ts' +import { githubPathImages } from '../sources/github/images.ts' import { supportsWindowEditing } from '../../windows/format-content.tsx' import { SelectMenu } from '../../ui/SelectMenu.tsx' import { LoadingIndicator } from '../../ui/LoadingIndicator.tsx' import { + PullRequestStatus, ResourceSummary, formatResourceTime, mergeResourceInfo, @@ -595,6 +599,10 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl const { face, workspaceId, target } = options const readCache = options.readCache ?? (face.api === cluesApi ? defaultReadCache : noReadCache) const resource = resourceOf(options) + const github = target.sourceId === BUILTIN_SOURCE_IDS.githubIssues || target.sourceId === BUILTIN_SOURCE_IDS.githubPulls + const pull = target.sourceId === BUILTIN_SOURCE_IDS.githubPulls + const discussionId = 'clue-discussion-' + locatorHash([workspaceId, clueDetailWindowId(target), options.sessionId ?? '']) + const workspaceRoot = options.workspaces?.find(workspace => workspace.workspaceId === workspaceId)?.title const bodyResource = { ...resource, includeDiscussion: false as const } // A window keeps the session captured when it opened; never borrow the // active composer/session later when the reader selects its retained body. @@ -643,12 +651,7 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl mode: 'preview', read: initialRead ?? null, edit: null, - info: infoOf( - initialRead?.format ?? '', - initialRead?.data ?? null, - target.info, - initialRead === undefined ? undefined : attachedInfo(initialRead), - ), + info: initialRead === undefined ? target.info : readInfoOf(initialRead, target.info), editable: undefined, readLoading: initialRead === undefined, refreshing: false, @@ -718,10 +721,37 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl ) } + let imageRead: ClueReadResult | null = null + let pathImages: WindowDocumentContent['pathImages'] + function previewImages(): WindowDocumentContent['pathImages'] { + if (imageRead === state.read) return pathImages + imageRead = state.read + pathImages = undefined + if (imageRead?.format !== 'text/markdown') return undefined + if (github) pathImages = githubPathImages(imageRead.data) + else if (target.sourceId === BUILTIN_SOURCE_IDS.files && imageRead.freshness !== 'snapshot') { + const path = imageRead.info?.path + if (path !== undefined && (isAbsolutePath(path) || workspaceRoot !== undefined)) { + pathImages = createMarkdownPathImages(undefined, resolveSidebarPath(workspaceRoot, path)) + } + } + return pathImages + } + + function readInfoOf(read: ClueReadResult, base: ClueResourceInfo | undefined): ClueResourceInfo | undefined { + // A pull read is authoritative for its volatile checks. Missing after a + // refresh means unavailable now, not the old head's successful status. + const { checks: _checks, checkRuns: _runs, checkCount: _count, + review: _review, mergeStatus: _status, mergeable: _mergeable, ...stable } = base ?? {} + return infoOf(read.format, read.data, pull ? stable : base, attachedInfo(read)) + } + function headerNode(): ReactNode { // Always render the seat: a source that reports no metadata still keeps // Refresh and the original-source link inside the header. - return createElement(ResourceSummary, { info: state.info, actions: headerActions() }) + const info = target.sourceId === BUILTIN_SOURCE_IDS.feishuTasks && state.read !== null + ? { ...state.info, due: undefined } : state.info + return createElement(ResourceSummary, { info, actions: headerActions(), github, title: github ? currentTitle : undefined, separateChecks: pull }) } function failureContent(): ReactNode { @@ -768,8 +798,18 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl embedded: true, header: headerNode(), afterBody: afterBody(), - ...(selectionTarget === undefined ? {} : { - bodyWrapper: (body: ReactNode) => createElement(ResourceSelectionActions, selectionTarget, body), + pathImages: previewImages(), + ...(selectionTarget === undefined && !pull ? {} : { + bodyWrapper: (body: ReactNode) => createElement(Fragment, null, + pull && state.info !== undefined ? createElement(PullRequestStatus, { + info: state.info, sourceUrl: sourceUrl?.startsWith('https://github.com/') ? sourceUrl : undefined, + ...(commentsCapabilities?.read === true ? { onDiscussion: () => { + const node = document.getElementById(discussionId) + node?.scrollIntoView({ block: 'start' }) + node?.focus({ preventScroll: true }) + } } : {}), + }) : null, + selectionTarget === undefined ? body : createElement(ResourceSelectionActions, selectionTarget, body)), }), ...(offerEdit ? { @@ -801,8 +841,10 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl : null, commentsCapabilities?.read !== true || discussionApi.commentsList === undefined ? null - : createElement(ResourceDiscussion, { + : createElement('div', { id: discussionId, tabIndex: -1 }, createElement(ResourceDiscussion, { key: `discussion:${authGeneration}`, + pathImages: github ? previewImages() : undefined, + showAvatars: github, page: discussion, capabilities: { ...commentsCapabilities, create: commentsCapabilities.create && discussionApi.commentsCreate !== undefined }, loading: commentsLoading, ...(commentsError === undefined ? {} : { error: commentsError }), readOnly: state.read?.freshness === 'snapshot', @@ -812,7 +854,7 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl void loadComments(next.cursor, next.parentId) }, onCreate: createComment, - })) + }))) } async function loadComments(cursor?: string, parentId?: string): Promise { @@ -1134,7 +1176,7 @@ function createDetailController(options: ClueDetailWindowOptions): DetailControl state = { ...state, read: result, - info: infoOf(result.format, result.data, state.info, attachedInfo(result)), + info: readInfoOf(result, state.info), readLoading: false, refreshing: false, readStale: false, @@ -1625,7 +1667,8 @@ function resourceOf(options: ClueDetailWindowOptions): ClueClientResourceInput { */ export function openClueDetailWindow(options: ClueDetailWindowOptions): WindowHandle { const { windows, target } = options - const id = clueDetailWindowId(target) + const resourceId = clueDetailWindowId(target) + const id = options.sessionId === undefined ? resourceId : resourceId + ':session:' + options.sessionId const guard: DetailGuard = { dirty: false, saving: false } const previous = loadedDetailWindows.get(id) const controller = createDetailController(options) diff --git a/src/client/clues/windows/pack.tsx b/src/client/clues/windows/pack.tsx index 6e047fb5..6b89e716 100644 --- a/src/client/clues/windows/pack.tsx +++ b/src/client/clues/windows/pack.tsx @@ -104,6 +104,7 @@ interface PackManagementOptions { readonly face: BetterSidebarCluesClientFace readonly workspaces: readonly PackWorkspaceChoice[] readonly pack: CluePack + readonly sessionId?: string onInsertClue(clueId: string, title: string): boolean onInsertPack(pack: CluePack): boolean onNotice(message: string): void @@ -203,7 +204,8 @@ export function openPackManagementWindow(options: PackManagementOptions): Window const titleFor = (dirty: boolean): string => dirty ? `${options.pack.name} · ${t('cluePackUnsaved')}` : options.pack.name const handle: WindowHandle = options.windows.open({ - id: packWindowId(options.pack.id), + id: packWindowId(options.pack.id) + (options.sessionId === undefined ? '' : ':session:' + options.sessionId), + sessionId: options.sessionId, surface: options.surface ?? preferredClueWindowSurface(), title: titleFor(false), size: 'collection', @@ -848,10 +850,10 @@ export function PackManagementPage( openClueDetailWindow({ windows: props.windows, face, workspaceId, target: { sourceId: row.clue.sourceId, typeId: row.clue.typeId, clueId: row.clue.id, title: row.clue.title, info: row.clue.info, subtitle: row.clue.subtitle }, - workspaces, onInsertClue: props.onInsertClue, + workspaces, onInsertClue: props.onInsertClue, sessionId: props.sessionId, ...(props.onAddToPack === undefined ? {} : { onAddToPack: props.onAddToPack }), }) - }, [face, props.onAddToPack, props.onInsertClue, props.windows, workspaceId, workspaces]) + }, [face, props.onAddToPack, props.onInsertClue, props.sessionId, props.windows, workspaceId, workspaces]) const openCandidateDetail = useCallback((candidate: ClueCandidate): void => { openClueDetailWindow({ @@ -864,10 +866,10 @@ export function PackManagementPage( title: candidate.title, info: candidate.info, subtitle: candidate.subtitle, }, - workspaces, onInsertClue: props.onInsertClue, + workspaces, onInsertClue: props.onInsertClue, sessionId: props.sessionId, ...(props.onAddToPack === undefined ? {} : { onAddToPack: props.onAddToPack }), }) - }, [face, props.onAddToPack, props.onInsertClue, props.windows, workspaceId, workspaces]) + }, [face, props.onAddToPack, props.onInsertClue, props.sessionId, props.windows, workspaceId, workspaces]) const onRowMenuSelect = useCallback((id: string): void => { const menu = rowMenu diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index 4e18d978..f5fcb846 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -49,6 +49,21 @@ export const de: Record = { clueSelectionExpand: "Erweitern", clueSelectionExplain: "Erklären", clueSelectionFailed: "Die Aktion konnte nicht gestartet werden.", + clueSelectionWriterHeld: "Eine andere DSH-Instanz verwendet diese Unterhaltung. Versuche es erneut, sobald sie frei ist.", + clueSelectionSessionUnavailable: "Diese Unterhaltung kann die Aktion nicht empfangen. Öffne die Vorschau in einer verfügbaren Hauptunterhaltung.", + clueSelectionReceiptUnknown: "Die Zustellung wurde nicht bestätigt. Prüfe die Unterhaltung vor einem erneuten Versuch.", + cluePreviewImageUnavailable: "Dieses Bild kann nicht angezeigt werden.", + cluePreviewBlockUnavailable: "Dieser Block kann hier nicht angezeigt werden.", + cluePreviewStatus: "Status", + cluePrChecksSkipped: "Übersprungen", + cluePrChecksNeutral: "Neutral", + cluePrChecksCancelled: "Abgebrochen", + cluePrChecksNone: "Keine Prüfungen", + cluePrChecksPartial: "{shown} von {total} Prüfungen angezeigt", + cluePrMergeBehind: "Branch muss aktualisiert werden", + cluePrMergeBlocked: "Merge blockiert", + cluePrMergeWaiting: "Wartet auf Prüfungen oder Review", + cluePrMergeReady: "Bereit zum Mergen", clueSelectionInsert: "Auswahl einfügen", clueSelectionMenu: "Auswahlaktionen", clueSelectionRewrite: "Umschreiben", diff --git a/src/client/locales-es.ts b/src/client/locales-es.ts index 98558226..645670b6 100644 --- a/src/client/locales-es.ts +++ b/src/client/locales-es.ts @@ -23,6 +23,21 @@ export const es: Record = { clueSelectionShorten: "Acortar", clueSelectionTranslate: "Traducir", clueSelectionFailed: "No se pudo iniciar la acción.", + clueSelectionWriterHeld: "Otra instancia de DSH usa esta conversación. Reintenta cuando quede libre.", + clueSelectionSessionUnavailable: "Esta conversación no puede recibir la acción. Abre la vista previa en una conversación principal disponible.", + clueSelectionReceiptUnknown: "No se confirmó la entrega. Revisa la conversación antes de volver a iniciar la acción.", + cluePreviewImageUnavailable: "No se puede previsualizar esta imagen.", + cluePreviewBlockUnavailable: "No se puede previsualizar este bloque aquí.", + cluePreviewStatus: "Estado", + cluePrChecksSkipped: "Omitida", + cluePrChecksNeutral: "Neutra", + cluePrChecksCancelled: "Cancelada", + cluePrChecksNone: "Sin comprobaciones", + cluePrChecksPartial: "Se muestran {shown} de {total} comprobaciones", + cluePrMergeBehind: "Hay que actualizar la rama", + cluePrMergeBlocked: "Fusión bloqueada", + cluePrMergeWaiting: "En espera de comprobaciones o revisión", + cluePrMergeReady: "Lista para fusionar", clueAuthPermissionDocsCommentsRead: "Leer comentarios de documentos", clueAuthPermissionDocsCommentsWrite: "Publicar comentarios en documentos", clueAuthPermissionTasksCommentsRead: "Leer comentarios de tareas", diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index 3a0154e5..9970916d 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -55,6 +55,21 @@ export const fr: Record = { clueSelectionExpand: "Développer", clueSelectionExplain: "Expliquer", clueSelectionFailed: "Impossible de démarrer l’action.", + clueSelectionWriterHeld: "Une autre instance de DSH utilise cette conversation. Réessayez lorsqu’elle la libère.", + clueSelectionSessionUnavailable: "Cette conversation ne peut pas recevoir l’action. Rouvrez l’aperçu dans une conversation principale disponible.", + clueSelectionReceiptUnknown: "L’envoi n’a pas été confirmé. Vérifiez la conversation avant de relancer l’action.", + cluePreviewImageUnavailable: "Impossible d’afficher l’aperçu de cette image.", + cluePreviewBlockUnavailable: "Impossible d’afficher ce bloc ici.", + cluePreviewStatus: "État", + cluePrChecksSkipped: "Ignorée", + cluePrChecksNeutral: "Neutre", + cluePrChecksCancelled: "Annulée", + cluePrChecksNone: "Aucune vérification", + cluePrChecksPartial: "{shown} vérifications sur {total} affichées", + cluePrMergeBehind: "Branche à mettre à jour", + cluePrMergeBlocked: "Fusion bloquée", + cluePrMergeWaiting: "En attente des vérifications ou de la revue", + cluePrMergeReady: "Prête à fusionner", clueSelectionInsert: "Insérer la sélection", clueSelectionMenu: "Actions sur la sélection", clueSelectionRewrite: "Réécrire", diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index 6fa40e3d..78003527 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -36,6 +36,21 @@ export const ja: Record = { clueSelectionShorten: "短縮", clueSelectionTranslate: "翻訳", clueSelectionFailed: "操作を開始できませんでした。", + clueSelectionWriterHeld: "別の DSH インスタンスがこの会話を使用中です。解放されたら再試行してください。", + clueSelectionSessionUnavailable: "この会話では操作を受信できません。利用可能なメイン会話でプレビューを開き直してください。", + clueSelectionReceiptUnknown: "送信を確認できませんでした。再度開始する前に会話を確認してください。", + cluePreviewImageUnavailable: "この画像はプレビューできません。", + cluePreviewBlockUnavailable: "このブロックはここではプレビューできません。", + cluePreviewStatus: "状態", + cluePrChecksSkipped: "スキップ", + cluePrChecksNeutral: "中立", + cluePrChecksCancelled: "キャンセル済み", + cluePrChecksNone: "チェックなし", + cluePrChecksPartial: "{total} 件中 {shown} 件のチェックを表示", + cluePrMergeBehind: "ブランチの更新が必要", + cluePrMergeBlocked: "マージがブロックされました", + cluePrMergeWaiting: "チェックまたはレビュー待ち", + cluePrMergeReady: "マージ可能", clueAuthPermissionDocsCommentsRead: "ドキュメントのコメントを読む", clueAuthPermissionDocsCommentsWrite: "ドキュメントにコメントを投稿", clueAuthPermissionTasksCommentsRead: "タスクのコメントを読む", diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index 55351b29..9409fb19 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -46,6 +46,21 @@ export const pt: Record = { clueSelectionExpand: "Expandir", clueSelectionExplain: "Explicar", clueSelectionFailed: "Não foi possível iniciar a ação.", + clueSelectionWriterHeld: "Outra instância do DSH está usando esta conversa. Tente novamente quando ela for liberada.", + clueSelectionSessionUnavailable: "Esta conversa não pode receber a ação. Reabra a prévia em uma conversa principal disponível.", + clueSelectionReceiptUnknown: "A entrega não foi confirmada. Verifique a conversa antes de iniciar novamente.", + cluePreviewImageUnavailable: "Não é possível visualizar esta imagem.", + cluePreviewBlockUnavailable: "Não é possível visualizar este bloco aqui.", + cluePreviewStatus: "Estado", + cluePrChecksSkipped: "Ignorada", + cluePrChecksNeutral: "Neutra", + cluePrChecksCancelled: "Cancelada", + cluePrChecksNone: "Sem verificações", + cluePrChecksPartial: "Exibindo {shown} de {total} verificações", + cluePrMergeBehind: "A branch precisa ser atualizada", + cluePrMergeBlocked: "Mesclagem bloqueada", + cluePrMergeWaiting: "Aguardando verificações ou revisão", + cluePrMergeReady: "Pronto para mesclar", clueSelectionInsert: "Inserir seleção", clueSelectionMenu: "Ações da seleção", clueSelectionRewrite: "Reescrever", diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 303a460e..c80066ae 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -59,6 +59,21 @@ export const ru: Record = { clueSelectionExpand: "Расширить", clueSelectionExplain: "Объяснить", clueSelectionFailed: "Не удалось запустить действие.", + clueSelectionWriterHeld: "Этот диалог занят другим экземпляром DSH. Повторите попытку, когда он освободится.", + clueSelectionSessionUnavailable: "Этот диалог не может принять действие. Откройте предпросмотр в доступном основном диалоге.", + clueSelectionReceiptUnknown: "Доставка не подтверждена. Проверьте диалог перед повторным запуском.", + cluePreviewImageUnavailable: "Не удалось показать изображение.", + cluePreviewBlockUnavailable: "Этот блок нельзя просмотреть здесь.", + cluePreviewStatus: "Состояние", + cluePrChecksSkipped: "Пропущена", + cluePrChecksNeutral: "Нейтрально", + cluePrChecksCancelled: "Отменена", + cluePrChecksNone: "Нет проверок", + cluePrChecksPartial: "Показано проверок: {shown} из {total}", + cluePrMergeBehind: "Ветку нужно обновить", + cluePrMergeBlocked: "Слияние заблокировано", + cluePrMergeWaiting: "Ожидание проверок или ревью", + cluePrMergeReady: "Готово к слиянию", clueSelectionInsert: "Вставить выделенное", clueSelectionMenu: "Действия с выделенным", clueSelectionRewrite: "Переписать", diff --git a/src/client/locales.ts b/src/client/locales.ts index 887d3fec..884042b7 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -29,6 +29,21 @@ export const zh = { clueSelectionShorten: "缩短", clueSelectionTranslate: "翻译", clueSelectionFailed: "无法启动该操作。", + clueSelectionWriterHeld: "此会话正由另一个 DSH 实例使用。释放后可重试。", + clueSelectionSessionUnavailable: "无法向此会话投递。请在可用的主会话中重新打开预览。", + clueSelectionReceiptUnknown: "操作未确认送达。再次发起前请先查看会话。", + cluePreviewImageUnavailable: "图片无法预览。", + cluePreviewBlockUnavailable: "此内容块无法在这里预览。", + cluePreviewStatus: "状态", + cluePrChecksSkipped: "已跳过", + cluePrChecksNeutral: "中性", + cluePrChecksCancelled: "已取消", + cluePrChecksNone: "无检查", + cluePrChecksPartial: "已显示 {shown} / {total} 项检查", + cluePrMergeBehind: "分支需要更新", + cluePrMergeBlocked: "合并受阻", + cluePrMergeWaiting: "等待检查或评审", + cluePrMergeReady: "可以合并", clueAuthPermissionDocsCommentsRead: "读取文档评论", clueAuthPermissionDocsCommentsWrite: "发表文档评论", clueAuthPermissionTasksCommentsRead: "读取任务评论", @@ -1264,6 +1279,21 @@ export const en: Record = { clueSelectionShorten: "Shorten", clueSelectionTranslate: "Translate", clueSelectionFailed: "Could not start the action.", + clueSelectionWriterHeld: "Another DSH instance is using this conversation. Retry after it releases it.", + clueSelectionSessionUnavailable: "This conversation cannot receive the action. Reopen the preview in an available main conversation.", + clueSelectionReceiptUnknown: "Delivery was not confirmed. Check the conversation before starting again.", + cluePreviewImageUnavailable: "This image cannot be previewed.", + cluePreviewBlockUnavailable: "This block cannot be previewed here.", + cluePreviewStatus: "Status", + cluePrChecksSkipped: "Skipped", + cluePrChecksNeutral: "Neutral", + cluePrChecksCancelled: "Cancelled", + cluePrChecksNone: "No checks", + cluePrChecksPartial: "Showing {shown} of {total} checks", + cluePrMergeBehind: "Branch needs updating", + cluePrMergeBlocked: "Merge blocked", + cluePrMergeWaiting: "Waiting for checks or review", + cluePrMergeReady: "Ready to merge", clueAuthPermissionDocsCommentsRead: "Read document comments", clueAuthPermissionDocsCommentsWrite: "Post document comments", clueAuthPermissionTasksCommentsRead: "Read task comments", diff --git a/src/client/markdown-images.ts b/src/client/markdown-images.ts index 78637daa..dc76d632 100644 --- a/src/client/markdown-images.ts +++ b/src/client/markdown-images.ts @@ -224,7 +224,7 @@ export function desktopFileUrl(target: string, baseUrl: string): string { * @returns The owner's local-path image vocabulary. */ export function createMarkdownPathImages( - scope: SessionScope, + scope: SessionScope | undefined, filePath: string, baseUrl: string = hostHttpBase(), ): MarkdownPathImages { @@ -244,18 +244,18 @@ export function createMarkdownPathImages( // load it). The path goes through the same media route as a relative one. const filePathFromUrl = fileUrlToLocalPath(destination) if (filePathFromUrl !== undefined) { - if (!desktop) return markdownMediaUrl(filePathFromUrl, scope, baseUrl) + if (!desktop && scope !== undefined) return markdownMediaUrl(filePathFromUrl, scope, baseUrl) return desktopFileUrl(filePathFromUrl, baseUrl) } const decoded = decodeDestination(destination) if (decoded === undefined) return undefined const target = markdownImageTarget(decoded, filePath) if (target === undefined) return undefined - if (!desktop) return markdownMediaUrl(target, scope, baseUrl) + if (!desktop && scope !== undefined) return markdownMediaUrl(target, scope, baseUrl) // The host file route requires an ABSOLUTE path (a relative one answers // 400 "absolute path required"); a relative tab path is the common case // for files opened from chat, so join the workspace root explicitly. - const absolute = absoluteTarget(target, scope.cwd) + const absolute = absoluteTarget(target, scope?.cwd) return absolute === undefined ? undefined : desktopFileUrl(absolute, baseUrl) }, } diff --git a/src/client/windows/format-content.tsx b/src/client/windows/format-content.tsx index 064048e5..ec5e8f17 100644 --- a/src/client/windows/format-content.tsx +++ b/src/client/windows/format-content.tsx @@ -5,7 +5,10 @@ * Unknown formats stay read-only and never acquire a generic save path. */ import { createElement, useCallback, useId, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react' -import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' +import { MarkdownText, type MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' +import { BUILTIN_SOURCE_IDS } from '../../clues/types.ts' +import { hostHttpBase } from '../desktop-env.ts' +import { desktopFileUrl } from '../markdown-images.ts' import type { ClueFormatRenderer, ClueFormatRendererProps, JsonValue } from '../../clues/types.ts' import type { WindowDocumentContent } from './types.ts' import { markdownTextProps } from '../markdown-labels.tsx' @@ -63,6 +66,7 @@ export interface TextDocumentContentProps { readonly text: string readonly readOnly: boolean readonly markdown?: boolean + readonly pathImages?: MarkdownPathImages readonly saving?: boolean onChange(text: string): void } @@ -76,7 +80,7 @@ export function TextDocumentContent(props: TextDocumentContentProps): ReactNode + }, props.pathImages)} />
    } return
    {text}
    @@ -94,10 +98,20 @@ export function TextDocumentContent(props: TextDocumentContentProps): ReactNode ) } +/** Keep SVG and remote diagrams in image context, never an inline document. */ +export function DocumentImage({ url, alt, original }: { url?: string; alt: string; original?: string }): ReactNode { + const [failed, setFailed] = useState(false) + return
    + {url !== undefined && !failed + ? {alt} { setFailed(true) }} /> + :
    {t('cluePreviewImageUnavailable')}{original !== undefined && {t('clueDetailOpenSource')}}
    } +
    +} + export function ClueFormatHost(props: ClueFormatHostProps): ReactNode { const { registry, sourceId, typeId, format, document, readOnly, saving, saved, loading, error, onChange, onSave, - presentation, mode: controlledMode, onModeChange, editLoading, header, embedded, afterBody, bodyWrapper, + presentation, mode: controlledMode, onModeChange, editLoading, header, embedded, afterBody, bodyWrapper, pathImages, } = props const renderer = useFormatRenderer(registry, format) const text = renderer === undefined ? textOf(document.data) : undefined @@ -132,7 +146,7 @@ export function ClueFormatHost(props: ClueFormatHostProps): ReactNode { const body = (preview: boolean): ReactNode => { if (renderer !== undefined) { - const rendererProps: ClueFormatRendererProps & { readonly embedded?: boolean } = { + const rendererProps: ClueFormatRendererProps & { readonly embedded?: boolean; readonly pathImages?: MarkdownPathImages } = { sourceId, typeId, format, document, readOnly: preview, saving: saving === true, @@ -142,6 +156,7 @@ export function ClueFormatHost(props: ClueFormatHostProps): ReactNode { // mounts keep the source renderer's own save affordance. ...(preview || onSave === undefined || embedded === true ? {} : { onSave }), ...(embedded === undefined ? {} : { embedded }), + ...(pathImages === undefined ? {} : { pathImages }), } return createElement(renderer, rendererProps) } @@ -151,11 +166,19 @@ export function ClueFormatHost(props: ClueFormatHostProps): ReactNode { text={text} readOnly={preview} markdown={format === 'text/markdown'} + pathImages={pathImages} saving={saving === true} onChange={(next) => { onChange?.(dataWithText(document.data, next)) }} />
    } + if (sourceId === BUILTIN_SOURCE_IDS.files && 'assets' in document && document.freshness !== 'snapshot') { + const image = document.assets?.find(asset => asset.mime?.startsWith('image/') === true && asset.path !== undefined) + if (image?.path !== undefined) { + const url = desktopFileUrl(image.path, hostHttpBase()) + return + } + } return
    {t('windowReadOnly')} diff --git a/src/client/windows/types.ts b/src/client/windows/types.ts index c806f5ac..e055b0ae 100644 --- a/src/client/windows/types.ts +++ b/src/client/windows/types.ts @@ -14,6 +14,7 @@ * conversion by the host. */ import type { ReactNode } from 'react' +import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives' import type { ClueEditDocument, ClueReadResult, JsonValue } from '../../clues/types.ts' import type { ViewportSize, WindowBox, WindowSize, WindowSizePreset } from './geometry.ts' @@ -69,6 +70,8 @@ export interface WindowDocumentContent { readonly afterBody?: ReactNode /** Wrap only the rendered preview body, e.g. body-scoped TOC / selection actions. */ readonly bodyWrapper?: (body: ReactNode) => ReactNode + /** Image vocabulary scoped to this document's actual origin. */ + readonly pathImages?: MarkdownPathImages /** * The document is embedded in a larger detail surface (window chrome already * shows the title, toolbar already shows the source link). Source renderers diff --git a/src/client/windows/windows.module.css b/src/client/windows/windows.module.css index 1bd89972..735f3b71 100644 --- a/src/client/windows/windows.module.css +++ b/src/client/windows/windows.module.css @@ -56,6 +56,7 @@ } .document { + container-type: inline-size; background: var(--dsw-alias-bg-base); display: flex; flex-direction: column; @@ -79,6 +80,8 @@ overscroll-behavior: contain; } +.documentHeader:has([data-clue-resource-github]) { max-height: min(55%, 160px); } + .modeBar { display: flex; align-items: center; @@ -183,6 +186,22 @@ color: var(--dsw-alias-label-secondary); } +.documentImage { + display: grid; + place-items: center; + min-width: 0; + min-height: 120px; + margin: var(--ds-sidebar-gutter); + padding: var(--ds-sidebar-gutter); + border: 1px solid var(--dsw-alias-border-l1); + border-radius: var(--ds-sidebar-radius); + background: var(--dsw-alias-bg-base); +} +.documentImage[data-image-unavailable] { min-height: 0; } +.documentImage img { display: block; max-width: 100%; max-height: 65vh; object-fit: contain; } +.documentImage figcaption { display: grid; gap: 6px; text-align: center; color: var(--dsw-alias-label-secondary); } +.documentImage a { color: var(--ds-sidebar-accent); } + .markdownPreview { box-sizing: border-box; flex: 1; diff --git a/src/clues/actions.ts b/src/clues/actions.ts index f0496395..5ff5cf25 100644 --- a/src/clues/actions.ts +++ b/src/clues/actions.ts @@ -2,6 +2,7 @@ import { existsSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { ClueError } from './error.ts' +import { ClueWriterHeldError } from './session-delivery.ts' import type { ClueDraft, ClueDraftManager } from './drafts.ts' import type { ClueApiContext, CluesReadParams, Locator } from './types.ts' @@ -29,6 +30,7 @@ export interface ClueActionDelivery { readonly skillPath: string readonly scriptPath?: string readonly draft?: ClueDraft + readonly signal?: AbortSignal } export interface ClueActionStartResult { readonly action: ClueSelectionAction @@ -79,7 +81,7 @@ const instructions: Record, string> = { } /** Public handler for `clues.actions.start` (registered by the host entry). */ export function createClueActionStartHandler(deps: ClueActionStartDeps): (payload: unknown, context: ClueApiContext) => Promise { - const starts = new Map }>() + const starts = new Map }>() return async (payload, context) => { if (context.caller !== 'ui') throw new ClueError('permission-denied', 'only an explicit interactive action can start a clue action') const input = record(payload) @@ -100,15 +102,15 @@ export function createClueActionStartHandler(deps: ClueActionStartDeps): (payloa const previous = starts.get(key) if (previous !== undefined) { if (previous.signature !== signature) throw new ClueError('conflict', 'the action identity was already used for another operation') - return previous.result + if (!previous.retryable) return previous.result } - if (starts.size >= 128) { + if (previous === undefined && starts.size >= 128) { const oldest = [...starts].find(([, entry]) => !entry.pending)?.[0] if (oldest === undefined) throw new ClueError('rate-limited', 'too many clue operations are pending') starts.delete(oldest) } - const entry = { signature, pending: true, result: Promise.resolve().then(async (): Promise => { - let draft: ClueDraft | undefined + let draft = previous?.draft + const entry = { signature, pending: true, retryable: false, draft, result: Promise.resolve().then(async (): Promise => { let scriptPath: string | undefined let commitUrl: string | undefined const skillPath = assetPath(action === 'explain' ? 'clue-selection-explain/SKILL.md' : 'clue-selection-edit/SKILL.md') @@ -116,7 +118,8 @@ export function createClueActionStartHandler(deps: ClueActionStartDeps): (payloa commitUrl = deps.getCommitUrl() if (commitUrl === undefined) throw new ClueError('failed', 'the local draft commit endpoint is unavailable') scriptPath = assetPath('clue-selection-edit/scripts/commit-draft.mjs') - draft = await deps.drafts.prepare(resource, { caller: context.caller, signal: context.signal, sessionId }) + draft ??= await deps.drafts.prepare(resource, { caller: context.caller, signal: context.signal, sessionId }) + entry.draft = draft } const prompt = action === 'explain' ? [ @@ -135,10 +138,16 @@ export function createClueActionStartHandler(deps: ClueActionStartDeps): (payloa ].join('\n') if (context.signal?.aborted) throw new ClueError('cancelled', 'the clue action was cancelled; its prepared draft was preserved') try { - const delivery = await deps.deliver({ workspaceId, sessionId, target, requestId, action, resource, selection, prompt, skillPath, ...(scriptPath === undefined ? {} : { scriptPath }), ...(draft === undefined ? {} : { draft }) }) + const delivery = await deps.deliver({ workspaceId, sessionId, target, requestId, action, resource, selection, prompt, skillPath, signal: context.signal, ...(scriptPath === undefined ? {} : { scriptPath }), ...(draft === undefined ? {} : { draft }) }) return { action, target, ...(draft === undefined ? {} : { draft }), ...(delivery?.deliveryId === undefined ? {} : { deliveryId: delivery.deliveryId }) } - } catch { - throw new ClueError('failed', 'the action could not be delivered; any prepared draft was preserved', draft === undefined ? undefined : { draftId: draft.draftId }) + } catch (error) { + const meta = draft === undefined ? undefined : { draftId: draft.draftId } + if (error instanceof ClueWriterHeldError) { + entry.retryable = true + throw new ClueWriterHeldError(meta) + } + if (error instanceof ClueError) throw new ClueError(error.category, error.message, meta) + throw new ClueError('failed', 'The conversation did not confirm receipt of the action.', meta) } }).finally(() => { entry.pending = false }) } starts.set(key, entry) diff --git a/src/clues/discussion.ts b/src/clues/discussion.ts index efec9f4f..6c4eade8 100644 --- a/src/clues/discussion.ts +++ b/src/clues/discussion.ts @@ -172,11 +172,13 @@ export function parseClueDiscussion(value: unknown, source = 'discussion'): Clue const name = optionalString(record, 'name', what) const handle = optionalString(record, 'handle', what) const url = optionalString(record, 'url', what) + const avatarUrl = optionalString(record, 'avatarUrl', what) return { ...(id === undefined ? {} : { id }), ...(name === undefined ? {} : { name }), ...(handle === undefined ? {} : { handle }), ...(url === undefined ? {} : { url }), + ...(avatarUrl === undefined ? {} : { avatarUrl }), } } const anchorOf = (raw: unknown, what: string): ClueCommentAnchor => { diff --git a/src/clues/local-files.ts b/src/clues/local-files.ts index 9b540308..b44b107f 100644 --- a/src/clues/local-files.ts +++ b/src/clues/local-files.ts @@ -141,7 +141,7 @@ const MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown']) * only keeps browsing/resolution from having to open every file. */ const BINARY_EXTENSIONS = new Set([ - '.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.ico', '.avif', '.tif', '.tiff', '.heic', '.psd', + '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp', '.ico', '.avif', '.tif', '.tiff', '.heic', '.psd', '.pdf', '.zip', '.gz', '.tgz', '.tar', '.bz2', '.xz', '.7z', '.rar', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods', '.odp', '.mp3', '.wav', '.flac', '.ogg', '.m4a', '.mp4', '.mov', '.webm', '.mkv', '.avi', @@ -792,7 +792,7 @@ async function readFileContent( // `stat` succeeds on an unreadable entry; `readText` would report the // resulting EACCES as a generic fs-error, so probe first. await requireAccess(absolute, FILE_ACCESS) - if (typeId === LOCAL_FILE_TYPE_IDS.binary) { + if (typeId === LOCAL_FILE_TYPE_IDS.binary || localFileTypeOf(locator.path, locator.dialect) === LOCAL_FILE_TYPE_IDS.binary) { return binaryReadResult(locator, absolute, info, new Date().toISOString()) } const result = await readText(absolute).catch((error: unknown) => { @@ -838,7 +838,7 @@ async function loadEditDocument( ): Promise { throwIfAborted(context) const format = formatOf(typeId) - if (typeId === LOCAL_FILE_TYPE_IDS.binary) { + if (typeId === LOCAL_FILE_TYPE_IDS.binary || localFileTypeOf(locator.path, locator.dialect) === LOCAL_FILE_TYPE_IDS.binary) { throw new ClueError('unsupported', 'a binary local file is read-only') } const absolute = absolutePathOf(locator, context) @@ -873,7 +873,7 @@ async function saveEditDocument( ): Promise { throwIfAborted(context) const expectedFormat = formatOf(typeId) - if (typeId === LOCAL_FILE_TYPE_IDS.binary) { + if (typeId === LOCAL_FILE_TYPE_IDS.binary || localFileTypeOf(locator.path, locator.dialect) === LOCAL_FILE_TYPE_IDS.binary) { throw new ClueError('unsupported', 'a binary local file is read-only') } if (document.format !== expectedFormat) { diff --git a/src/clues/resource-info.ts b/src/clues/resource-info.ts index 3cf12328..20b55145 100644 --- a/src/clues/resource-info.ts +++ b/src/clues/resource-info.ts @@ -16,6 +16,8 @@ */ import { CLUE_CHECK_STATES, + CLUE_CHECK_RUN_STATES, + CLUE_MERGE_STATES, CLUE_MAX_CHECK_RUNS, CLUE_RESOURCE_STATES, ClueError, @@ -23,6 +25,8 @@ import { type CluePerson, type ClueResourceBranches, type ClueResourceCheck, + type ClueCheckRunState, + type ClueMergeState, type ClueResourceCounts, type ClueResourceInfo, type ClueResourceState, @@ -173,7 +177,7 @@ function personOf(value: unknown, what: string): CluePerson | undefined { if (!isRecord(value)) { throw new ClueError('invalid-request', `${what} must be a JSON object`) } - const person: { id?: string; name?: string; handle?: string; url?: string } = {} + const person: { id?: string; name?: string; handle?: string; url?: string; avatarUrl?: string } = {} if (value.id !== undefined) person.id = displayText(value.id, `${what}.id`, MAX_CLUE_PERSON_TEXT) if (value.name !== undefined) person.name = displayText(value.name, `${what}.name`, MAX_CLUE_PERSON_TEXT) if (value.handle !== undefined) person.handle = displayText(value.handle, `${what}.handle`, MAX_CLUE_PERSON_TEXT) @@ -181,6 +185,7 @@ function personOf(value: unknown, what: string): CluePerson | undefined { if (Object.keys(person).length === 0) { throw new ClueError('invalid-request', `${what} must name at least one id, name, handle or url`) } + if (value.avatarUrl !== undefined) person.avatarUrl = displayUrl(value.avatarUrl, what + '.avatarUrl') return person } @@ -310,7 +315,10 @@ function checkRunsOf(value: unknown): ClueResourceCheck[] | undefined { const what = `clue resource info checkRuns[${index}]` if (!isRecord(entry)) throw new ClueError('invalid-request', `${what} must be a JSON object`) const name = displayText(entry.name, `${what}.name`, MAX_CLUE_CHECK_NAME) - const state = checkStateOf(entry.state, `${what}.state`) + if (typeof entry.state !== 'string' || !(CLUE_CHECK_RUN_STATES as readonly string[]).includes(entry.state)) { + throw new ClueError('invalid-request', what + '.state is not a check run state') + } + const state = entry.state as ClueCheckRunState const url = entry.url === undefined ? undefined : displayUrl(entry.url, `${what}.url`) return { name, state, ...(url === undefined ? {} : { url }) } }) @@ -365,6 +373,8 @@ export function normalizeClueResourceInfo( mergeable?: 'mergeable' | 'conflicting' | 'unknown' checks?: ClueCheckState checkRuns?: readonly ClueResourceCheck[] + checkCount?: number + mergeStatus?: ClueMergeState } = {} const state = stateOf(value.state) @@ -440,6 +450,18 @@ export function normalizeClueResourceInfo( if (value.checks !== undefined) info.checks = checkStateOf(value.checks, what + '.checks') const checkRuns = checkRunsOf(value.checkRuns) if (checkRuns !== undefined) info.checkRuns = checkRuns + if (value.checkCount !== undefined) { + if (typeof value.checkCount !== 'number' || !Number.isSafeInteger(value.checkCount) || value.checkCount < 0) { + throw new ClueError('invalid-request', what + '.checkCount must be a non-negative integer') + } + info.checkCount = value.checkCount + } + if (value.mergeStatus !== undefined) { + if (typeof value.mergeStatus !== 'string' || !(CLUE_MERGE_STATES as readonly string[]).includes(value.mergeStatus)) { + throw new ClueError('invalid-request', what + '.mergeStatus is not a merge state') + } + info.mergeStatus = value.mergeStatus as ClueMergeState + } return info } diff --git a/src/clues/session-delivery.ts b/src/clues/session-delivery.ts index ac1f9e3f..828330a4 100644 --- a/src/clues/session-delivery.ts +++ b/src/clues/session-delivery.ts @@ -14,6 +14,13 @@ interface SessionPromptFace { } export interface ClueSessionReceipt { readonly sessionId: string; readonly accepted: true } +/** The host explicitly rejected admission before sending; this intent can be retried. */ +export class ClueWriterHeldError extends ClueError { + constructor(meta?: Record) { + super('conflict', 'The conversation is in use by another DSH instance.', meta) + } +} + /** The side start callback is the already mounted sidechat.start handler. */ export function createClueSessionDelivery(ctx: Context, startSide: (payload: { sessionId: string; question: string }) => Promise<{ childId: string }>) { const deliveries = new Map }>() @@ -53,7 +60,11 @@ export function createClueSessionDelivery(ctx: Context, startSide: (payload: { s if (signal?.aborted || (error instanceof Error && error.name === 'AbortError')) throw new ClueError('cancelled', 'the operation was cancelled') const code = error !== null && typeof error === 'object' ? (error as { code?: unknown }).code : undefined if (code === 'session/not-found') throw new ClueError('not-found', 'the target conversation is unavailable') - if (code === 'session/writer-held' || code === 'session/agent-busy') throw new ClueError('conflict', 'the target conversation could not admit the operation') + if (code === 'session/writer-held') { + deliveries.delete(key) + throw new ClueWriterHeldError() + } + if (code === 'session/agent-busy') throw new ClueError('conflict', 'the target conversation could not admit the operation') throw new ClueError('failed', 'the conversation operation could not be admitted') } }).finally(() => { entry.pending = false }) } diff --git a/src/clues/sources/github/comments.ts b/src/clues/sources/github/comments.ts index 6d7502b0..84b62f9b 100644 --- a/src/clues/sources/github/comments.ts +++ b/src/clues/sources/github/comments.ts @@ -2,7 +2,7 @@ import { ClueError, type ClueComment } from '../../types.ts' import type { GithubResource } from './ids.ts' -const AUTHOR = 'author{login url ... on User{name} ... on Organization{name}}' +const AUTHOR = 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}}' const COMMENT_FIELDS = `id body createdAt updatedAt url ${AUTHOR}` const REVIEW_FIELDS = `id body createdAt submittedAt updatedAt url state ${AUTHOR}` @@ -53,6 +53,7 @@ export function githubCommentOf(value: unknown, rest = false): ClueComment { const handle = text(author?.login) const name = text(author?.name) const authorUrl = text(rest ? author?.html_url : author?.url) + const avatarUrl = text(rest ? author?.avatar_url : author?.avatarUrl) const review = node.__typename === 'PullRequestReview' const createdAt = text(rest ? node.created_at : review ? node.submittedAt ?? node.createdAt : node.createdAt) const updatedAt = text(rest ? node.updated_at : node.updatedAt) @@ -62,6 +63,7 @@ export function githubCommentOf(value: unknown, rest = false): ClueComment { ...(handle === undefined && name === undefined ? {} : { author: { ...(handle === undefined ? {} : { handle }), ...(name === undefined ? {} : { name }), ...(authorUrl === undefined ? {} : { url: authorUrl }), + ...(avatarUrl === undefined ? {} : { avatarUrl }), } }), ...(createdAt === undefined ? {} : { createdAt }), ...(updatedAt === undefined ? {} : { updatedAt }), ...(url === undefined ? {} : { url }), diff --git a/src/clues/sources/github/gh.ts b/src/clues/sources/github/gh.ts index b1294782..de6ea8b6 100644 --- a/src/clues/sources/github/gh.ts +++ b/src/clues/sources/github/gh.ts @@ -63,7 +63,7 @@ const ISSUE_LIST_QUERY = 'query($owner:String!,$repo:String!,$first:Int!,$after: + '{repository(owner:$owner,name:$repo){issues(first:$first,after:$after,states:$states,' + 'orderBy:{field:UPDATED_AT,direction:DESC}){totalCount pageInfo{hasNextPage endCursor} ' + 'nodes{number title state createdAt updatedAt closedAt url ' - + 'author{login url ... on User{name} ... on Organization{name}} ' + + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}} ' + 'assignees(first:10){nodes{login name url}} labels(first:20){nodes{name}}}}}}' /** One pull request browse page. */ @@ -72,14 +72,14 @@ const PULL_LIST_QUERY = 'query($owner:String!,$repo:String!,$first:Int!,$after:S + 'orderBy:{field:UPDATED_AT,direction:DESC}){totalCount pageInfo{hasNextPage endCursor} ' + 'nodes{number title state isDraft mergedAt headRefName baseRefName headRepository{nameWithOwner} ' + 'createdAt updatedAt closedAt url reviewDecision mergeable statusCheckRollup{state} ' - + 'author{login url ... on User{name} ... on Organization{name}} ' + + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}} ' + 'assignees(first:10){nodes{login name url}} labels(first:20){nodes{name}}}}}}' /** One issue read (live; also the repository's archived/permission state). */ const ISSUE_READ_QUERY = 'query($owner:String!,$repo:String!,$number:Int!)' - + '{repository(owner:$owner,name:$repo){isArchived viewerPermission ' + + '{repository(owner:$owner,name:$repo){isArchived viewerPermission defaultBranchRef{target{oid}} ' + 'issue(number:$number){number title body state stateReason createdAt updatedAt closedAt url ' - + 'author{login url ... on User{name} ... on Organization{name}} ' + + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}} ' + 'assignees(first:10){nodes{login name url}} labels(first:20){nodes{name}} ' + 'comments(first:1){totalCount}}}}' @@ -93,12 +93,12 @@ const ISSUE_READ_QUERY = 'query($owner:String!,$repo:String!,$number:Int!)' const PULL_READ_QUERY = 'query($owner:String!,$repo:String!,$number:Int!)' + '{repository(owner:$owner,name:$repo){isArchived viewerPermission ' + 'pullRequest(number:$number){number title body state isDraft merged mergedAt createdAt updatedAt closedAt url ' - + 'author{login url ... on User{name} ... on Organization{name}} ' + + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}} ' + 'assignees(first:10){nodes{login name url}} labels(first:20){nodes{name}} ' + 'comments(first:1){totalCount} commits(first:1){totalCount} ' - + 'changedFiles additions deletions headRefName baseRefName headRepository{nameWithOwner} ' - + 'reviewDecision mergeable statusCheckRollup{state ' - + `contexts(first:${CLUE_MAX_CHECK_RUNS}){nodes{__typename ` + + 'changedFiles additions deletions headRefName headRefOid baseRefName headRepository{nameWithOwner} ' + + 'reviewDecision mergeable mergeStateStatus statusCheckRollup{state ' + + `contexts(first:${CLUE_MAX_CHECK_RUNS}){totalCount nodes{__typename ` + '... on CheckRun{name status conclusion detailsUrl} ' + '... on StatusContext{context state targetUrl}}}}}}}' @@ -106,7 +106,7 @@ const PULL_READ_QUERY = 'query($owner:String!,$repo:String!,$number:Int!)' const SEARCH_ISSUE_QUERY = 'query($q:String!,$first:Int!,$after:String)' + '{search(query:$q,type:ISSUE,first:$first,after:$after){issueCount pageInfo{hasNextPage endCursor} ' + 'nodes{... on Issue{number title state createdAt updatedAt closedAt url ' - + 'author{login url ... on User{name} ... on Organization{name}} ' + + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}} ' + 'assignees(first:10){nodes{login name url}} labels(first:20){nodes{name}}}}}}' /** Same-repository pull request search. */ @@ -114,7 +114,7 @@ const SEARCH_PULL_QUERY = 'query($q:String!,$first:Int!,$after:String)' + '{search(query:$q,type:ISSUE,first:$first,after:$after){issueCount pageInfo{hasNextPage endCursor} ' + 'nodes{... on PullRequest{number title state isDraft mergedAt ' + 'headRefName baseRefName headRepository{nameWithOwner} createdAt updatedAt closedAt url ' - + 'author{login url ... on User{name} ... on Organization{name}} ' + + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}} ' + 'assignees(first:10){nodes{login name url}} labels(first:20){nodes{name}}}}}}' /** The state filter's GraphQL enum, or undefined for "all". */ @@ -350,6 +350,7 @@ export interface GithubListItem { readonly author?: string readonly authorName?: string readonly authorUrl?: string + readonly authorAvatarUrl?: string readonly assignees?: readonly GithubPerson[] readonly labels?: readonly string[] readonly isDraft?: boolean @@ -384,6 +385,7 @@ export interface GithubResourceSnapshot { readonly author?: string readonly authorName?: string readonly authorUrl?: string + readonly authorAvatarUrl?: string readonly assignees: readonly GithubPerson[] readonly url: string readonly createdAt: string @@ -409,6 +411,9 @@ export interface GithubResourceSnapshot { readonly checks?: ClueCheckState /** Individual checks of this read (check runs + legacy status contexts). */ readonly checkRuns?: readonly ClueResourceCheck[] + readonly checkCount?: number + readonly mergeStatus?: 'ready' | 'blocked' | 'behind' | 'unknown' + readonly imageRef?: string readonly isArchived: boolean readonly viewerPermission?: string /** Opaque check-before-save baseline (updatedAt + content fingerprint). */ @@ -532,6 +537,7 @@ function listItemOf(value: unknown, kind: GithubKind): GithubListItem { const authorRecord = isRecord(value.author) ? value.author : undefined const authorName = stringField(authorRecord?.name) const authorUrl = stringField(authorRecord?.url) + const authorAvatarUrl = stringField(authorRecord?.avatarUrl) const createdAt = stringField(value.createdAt) const closedAt = stringField(value.closedAt) const assignees = peopleOf(value.assignees) @@ -554,6 +560,7 @@ function listItemOf(value: unknown, kind: GithubKind): GithubListItem { ...(author === undefined ? {} : { author }), ...(authorName === undefined ? {} : { authorName }), ...(authorUrl === undefined ? {} : { authorUrl }), + ...(authorAvatarUrl === undefined ? {} : { authorAvatarUrl }), ...(assignees.length === 0 ? {} : { assignees }), ...(isRecord(value.labels) ? { labels: labelsOf(value.labels) } : {}), ...(kind === 'pull' && typeof value.isDraft === 'boolean' ? { isDraft: value.isDraft } : {}), @@ -624,6 +631,21 @@ function mergeableOf(raw: unknown): 'mergeable' | 'conflicting' | 'unknown' | un return undefined } +/** CLEAN means GitHub reports the merge checks are satisfied, not just a conflict-free tree. */ +function mergeStatusOf(raw: unknown): GithubResourceSnapshot['mergeStatus'] { + switch (raw) { + case 'CLEAN': return 'ready' + case 'BLOCKED': + case 'DIRTY': return 'blocked' + case 'BEHIND': return 'behind' + case 'DRAFT': + case 'HAS_HOOKS': + case 'UNSTABLE': + case 'UNKNOWN': return 'unknown' + default: return undefined + } +} + /** Normalize the status-check rollup state; an empty rollup stays absent. */ function checksOf(raw: unknown): ClueCheckState | undefined { if (!isRecord(raw)) return undefined @@ -645,23 +667,23 @@ function checksOf(raw: unknown): ClueCheckState | undefined { * neutral/skipped/stale never blocked a merge, timeout/action-required did, and * a cancelled run is reported as an error rather than silently passing. */ -function checkRunStateOf(status: string | undefined, conclusion: string | undefined): ClueCheckState | undefined { - if (conclusion === undefined) return status === undefined ? undefined : 'pending' +function checkRunStateOf(status: string | undefined, conclusion: string | undefined): ClueResourceCheck['state'] { + if (conclusion === undefined) { + if (status === 'QUEUED' || status === 'WAITING' || status === 'REQUESTED' || status === 'PENDING') return 'expected' + return status === 'IN_PROGRESS' ? 'pending' : 'unknown' + } switch (conclusion) { - case 'SUCCESS': - case 'NEUTRAL': - case 'SKIPPED': - case 'STALE': - return 'success' + case 'SUCCESS': return 'success' + case 'NEUTRAL': return 'neutral' + case 'SKIPPED': return 'skipped' + case 'STALE': return 'unknown' case 'FAILURE': case 'TIMED_OUT': case 'ACTION_REQUIRED': case 'STARTUP_FAILURE': return 'failure' - case 'CANCELLED': - return 'error' - default: - return undefined + case 'CANCELLED': return 'cancelled' + default: return 'unknown' } } @@ -696,12 +718,11 @@ function checkRunsOf(raw: unknown): readonly ClueResourceCheck[] | undefined { const state = statusContext ? statusContextStateOf(stringField(node.state)) : checkRunStateOf(stringField(node.status), stringField(node.conclusion)) - if (state === undefined) continue const url = stringField(statusContext ? node.targetUrl : node.detailsUrl) runs.push({ // The provider owns the name; clip rather than drop a long matrix leg. name: name.length > GITHUB_CHECK_NAME_MAX ? name.slice(0, GITHUB_CHECK_NAME_MAX - 1) + '…' : name, - state, + state: state ?? 'unknown', ...(url === undefined ? {} : { url }), }) if (runs.length >= CLUE_MAX_CHECK_RUNS) break @@ -729,6 +750,7 @@ function snapshotOf( const authorRecord = isRecord(node.author) ? node.author : undefined const authorName = stringField(authorRecord?.name) const authorUrl = stringField(authorRecord?.url) + const authorAvatarUrl = stringField(authorRecord?.avatarUrl) const assignees = peopleOf(node.assignees) const url = requireString(node.url, 'read response') const createdAt = requireString(node.createdAt, 'read response') @@ -773,6 +795,12 @@ function snapshotOf( checks = checksOf(node.statusCheckRollup) checkRuns = checkRunsOf(node.statusCheckRollup) } + const rollup = isRecord(node.statusCheckRollup) ? node.statusCheckRollup : undefined + const checkCount = resource.kind === 'pull' ? countOf(rollup?.contexts) : undefined + const mergeStatus = resource.kind === 'pull' ? mergeStatusOf(node.mergeStateStatus) : undefined + const branch = isRecord(repository.defaultBranchRef) ? repository.defaultBranchRef : undefined + const imageRef = resource.kind === 'pull' ? stringField(node.headRefOid) + : isRecord(branch?.target) ? stringField(branch.target.oid) : undefined const revision = githubRevisionOf({ updatedAt, title, @@ -791,6 +819,7 @@ function snapshotOf( ...(author === undefined ? {} : { author }), ...(authorName === undefined ? {} : { authorName }), ...(authorUrl === undefined ? {} : { authorUrl }), + ...(authorAvatarUrl === undefined ? {} : { authorAvatarUrl }), assignees, url, createdAt, @@ -812,6 +841,9 @@ function snapshotOf( ...(mergeable === undefined ? {} : { mergeable }), ...(checks === undefined ? {} : { checks }), ...(checkRuns === undefined ? {} : { checkRuns }), + ...(checkCount === undefined ? {} : { checkCount }), + ...(mergeStatus === undefined ? {} : { mergeStatus }), + ...(imageRef === undefined ? {} : { imageRef }), isArchived, ...(viewerPermission === undefined ? {} : { viewerPermission }), revision, diff --git a/src/clues/sources/github/sources.ts b/src/clues/sources/github/sources.ts index 8db6ad5f..c1238b90 100644 --- a/src/clues/sources/github/sources.ts +++ b/src/clues/sources/github/sources.ts @@ -296,6 +296,11 @@ function dataOf(kind: GithubKind, snapshot: GithubResourceSnapshot): JsonObject } if (snapshot.stateReason !== undefined) data.stateReason = snapshot.stateReason if (snapshot.author !== undefined) data.author = snapshot.author + const imageRepository = kind === 'pull' ? snapshot.headRepository : snapshot.resource.owner + '/' + snapshot.resource.repo + if (snapshot.imageRef !== undefined && imageRepository !== undefined) { + data.imageRepository = imageRepository + data.imageRef = snapshot.imageRef + } if (snapshot.viewerPermission !== undefined) data.viewerPermission = snapshot.viewerPermission if (snapshot.isDraft !== undefined) data.isDraft = snapshot.isDraft if (snapshot.merged !== undefined) data.merged = snapshot.merged @@ -372,6 +377,7 @@ interface GithubInfoFields { readonly author?: string readonly authorName?: string readonly authorUrl?: string + readonly authorAvatarUrl?: string readonly assignees?: readonly GithubPerson[] readonly labels?: readonly string[] readonly createdAt?: string @@ -392,6 +398,8 @@ interface GithubInfoFields { readonly mergeable?: 'mergeable' | 'conflicting' | 'unknown' readonly checks?: ClueResourceInfo['checks'] readonly checkRuns?: readonly ClueResourceCheck[] + readonly checkCount?: number + readonly mergeStatus?: ClueResourceInfo['mergeStatus'] } /** Map one provider person to the public display person (login -> handle). */ @@ -430,6 +438,7 @@ function githubInfoOf( handle: fields.author, ...(fields.authorName === undefined ? {} : { name: fields.authorName }), ...(fields.authorUrl === undefined ? {} : { url: fields.authorUrl }), + ...(fields.authorAvatarUrl === undefined ? {} : { avatarUrl: fields.authorAvatarUrl }), } const assignees = (fields.assignees ?? []).map(githubPersonOf) const createdAt = isoInstantOf(fields.createdAt) @@ -475,6 +484,8 @@ function githubInfoOf( ...(fields.mergeable === undefined ? {} : { mergeable: fields.mergeable }), ...(fields.checks === undefined ? {} : { checks: fields.checks }), ...(fields.checkRuns === undefined ? {} : { checkRuns: fields.checkRuns }), + ...(fields.checkCount === undefined ? {} : { checkCount: fields.checkCount }), + ...(fields.mergeStatus === undefined ? {} : { mergeStatus: fields.mergeStatus }), } } diff --git a/src/clues/types.ts b/src/clues/types.ts index f3370af6..93e83d0b 100644 --- a/src/clues/types.ts +++ b/src/clues/types.ts @@ -69,6 +69,12 @@ export const CLUE_CHECK_STATES = ['success', 'failure', 'pending', 'expected', ' /** One normalized CI state (rollup or a single check). */ export type ClueCheckState = (typeof CLUE_CHECK_STATES)[number] +export const CLUE_CHECK_RUN_STATES = [...CLUE_CHECK_STATES, 'skipped', 'neutral', 'cancelled', 'unknown'] as const +export type ClueCheckRunState = (typeof CLUE_CHECK_RUN_STATES)[number] + +export const CLUE_MERGE_STATES = ['ready', 'blocked', 'behind', 'unknown'] as const +export type ClueMergeState = (typeof CLUE_MERGE_STATES)[number] + /** * Most individual checks one detail read carries. The provider query asks for * exactly this many, so the bound is a request budget, not a truncation of a @@ -80,7 +86,7 @@ export const CLUE_MAX_CHECK_RUNS = 20 export interface ClueResourceCheck { /** The provider's check name/job (bounded display text, never a raw log). */ readonly name: string - readonly state: ClueCheckState + readonly state: ClueCheckRunState /** Provider link to the full check; absent when the provider reported none. */ readonly url?: string } @@ -95,6 +101,7 @@ export interface CluePerson { readonly name?: string readonly handle?: string readonly url?: string + readonly avatarUrl?: string } /** One display instant; `allDay` keeps the provider's own semantics. */ @@ -157,6 +164,10 @@ export interface ClueResourceInfo { * browsing row never pays for them. */ readonly checkRuns?: readonly ClueResourceCheck[] + /** Provider's total, independent of the bounded list of check runs. */ + readonly checkCount?: number + /** Provider-reported merge gate, distinct from content conflicts. */ + readonly mergeStatus?: ClueMergeState } // ── Resource discussion ─────────────────────────────────────────────────── diff --git a/src/index.ts b/src/index.ts index c68b088f..1d3b550d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1501,7 +1501,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void { } | undefined if (controller?.resolveAgent === undefined) throw new ClueError('unsupported', 'the parent conversation cannot be resumed') const restored = await controller.resolveAgent(payload.sessionId) - if ('error' in restored) throw new ClueError('conflict', 'the parent conversation could not be resumed') + if ('error' in restored) throw restored.error } return await api['sidechat.start']!(payload) as { childId: string } }) @@ -1510,7 +1510,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void { runtime: clueStack.runtime, deliver: async operation => { const receipt = await deliverClueOperation({ sessionId: operation.sessionId, target: operation.target, - requestId: operation.requestId, prompt: operation.prompt }) + requestId: operation.requestId, prompt: operation.prompt, signal: operation.signal }) return { deliveryId: receipt.sessionId } }, }) diff --git a/tests/clues-actions.spec.ts b/tests/clues-actions.spec.ts new file mode 100644 index 00000000..8b08b390 --- /dev/null +++ b/tests/clues-actions.spec.ts @@ -0,0 +1,43 @@ +/** A refused admission can be retried without preparing or delivering an accepted intent twice. */ +import { describe, expect, it, vi } from 'vitest' +import { createClueActionStartHandler } from '../src/clues/actions.ts' +import { createClueSessionDelivery } from '../src/clues/session-delivery.ts' +import type { ClueDraftManager } from '../src/clues/drafts.ts' +import type { Context } from '../src/context-types.ts' + +const request = { workspaceId: 'ws', sessionId: 'session', resource: { clueId: 'clue' }, target: 'main', action: 'rewrite', requestId: 'intent', selection: 'chosen line' } + +function fixture(prompt: ReturnType) { + const ctx = { get: () => ({ prompt }) } as unknown as Context + const send = createClueSessionDelivery(ctx, vi.fn()) + const prepare = vi.fn().mockResolvedValue({ draftId: 'draft', status: 'prepared', bodyPath: '/draft.md', format: 'text/markdown', createdAt: '2026-01-01T00:00:00Z' }) + const handler = createClueActionStartHandler({ + drafts: { prepare, commit: vi.fn(), discard: vi.fn(), list: vi.fn() }, + getCommitUrl: () => 'http://127.0.0.1:12345/sidebar/agent/clues/commit', + deliver: async operation => ({ deliveryId: (await send(operation)).sessionId }), + }) + return { start: () => handler(request, { caller: 'ui' }), prepare } +} + +describe('selection action admission', () => { + it('retries a writer refusal with the same request and draft, then reuses the receipt', async () => { + const prompt = vi.fn().mockRejectedValueOnce({ code: 'session/writer-held' }).mockResolvedValue({ accepted: true }) + const { start, prepare } = fixture(prompt) + await expect(start()).rejects.toMatchObject({ category: 'conflict', meta: { draftId: 'draft' } }) + const [receipt, joined] = await Promise.all([start(), start()]) + expect(joined).toEqual(receipt) + await expect(start()).resolves.toEqual(receipt) + expect(prepare).toHaveBeenCalledTimes(1) + expect(prompt).toHaveBeenCalledTimes(2) + expect(prompt.mock.calls[1]?.[0]).toEqual(prompt.mock.calls[0]?.[0]) + }) + + it('does not retry an admission whose outcome is uncertain', async () => { + const prompt = vi.fn().mockRejectedValue(new Error('connection interrupted')) + const { start, prepare } = fixture(prompt) + await expect(start()).rejects.toMatchObject({ category: 'failed' }) + await expect(start()).rejects.toMatchObject({ category: 'failed' }) + expect(prepare).toHaveBeenCalledTimes(1) + expect(prompt).toHaveBeenCalledTimes(1) + }) +}) diff --git a/tests/clues-github-gh.spec.ts b/tests/clues-github-gh.spec.ts index ab010972..025c769e 100644 --- a/tests/clues-github-gh.spec.ts +++ b/tests/clues-github-gh.spec.ts @@ -97,7 +97,7 @@ describe('browse and search argv', () => { expect(['owner', 'repo', 'first', 'states[]'].map(key => argValue(request.args, key))) .toEqual(['cli', 'cli', '30', 'OPEN']) for (const fragment of ['issues(first:$first', '$states:[IssueState!]', 'createdAt updatedAt closedAt', - 'author{login url ... on User{name} ... on Organization{name}}', + 'author{login url avatarUrl(size:48) ... on User{name} ... on Organization{name}}', 'assignees(first:10){nodes{login name url}}', 'labels(first:20){nodes{name}}']) expect(query).toContain(fragment) expect(request.args.join(' ')).not.toContain('--paginate') expect(page.items).toHaveLength(2) @@ -189,15 +189,17 @@ describe('read', () => { const snapshot = await clientOf(fake).readResource(PULL) const query = argValue(fake.runs[0]!.args, 'query')! for (const fragment of ['pullRequest(number:$number)', 'commits(first:1){totalCount}', 'changedFiles additions deletions', - 'headRefName baseRefName headRepository{nameWithOwner}', 'reviewDecision mergeable statusCheckRollup{state contexts(first:20)', - 'contexts(first:20){nodes{__typename', '... on CheckRun{name status conclusion detailsUrl}', + 'headRefName headRefOid baseRefName headRepository{nameWithOwner}', 'reviewDecision mergeable mergeStateStatus statusCheckRollup{state contexts(first:20)', + 'contexts(first:20){totalCount nodes{__typename', '... on CheckRun{name status conclusion detailsUrl}', '... on StatusContext{context state targetUrl}']) expect(query).toContain(fragment) // Read-only review/CI/mergeability facts are normalized, never invented. expect(snapshot).toMatchObject({ isDraft: false, merged: false, viewerPermission: 'TRIAGE', labels: ['bug'], commentsCount: 5, headRefName: 'fix/type-resolution', baseRefName: 'trunk', headRepository: 'umairnaeem0309/cli', review: 'approved', mergeable: 'mergeable', checks: 'success', commitsCount: 12, changedFiles: 3, - additions: 42, deletions: 7, + additions: 42, deletions: 7, checkCount: 28, mergeStatus: 'ready', + imageRef: '2345678abc012345678abc012345678abc0123456', + authorAvatarUrl: 'https://avatars.githubusercontent.com/u/1234?v=4', // Individual checks ride the SAME read (one request); an inconclusive run is pending. checkRuns: [ { name: 'build (macos)', state: 'success', url: 'https://github.com/cli/cli/runs/1' }, @@ -210,14 +212,19 @@ describe('read', () => { }) it('normalizes check runs: drops unusable nodes, stays absent when empty, bounds and clips', async () => { const read = (rollup: unknown) => clientOf(fakeRuntime(() => cliResult({ stdout: pullRead({ statusCheckRollup: rollup }) }))).readResource(PULL) - // Unknown conclusions are not guessed at; a nameless node cannot be rendered. + // Known names are retained even for new GitHub conclusions; a nameless node cannot render. const nodes = [ { __typename: 'CheckRun', name: 'novel', status: 'COMPLETED', conclusion: 'SOMETHING_NEW' }, { __typename: 'CheckRun', conclusion: 'SUCCESS', detailsUrl: 'https://ci.example/1' }, { __typename: 'StatusContext', context: 'ci/legacy', state: 'EXPECTED' }, + { __typename: 'CheckRun', name: 'docs', status: 'COMPLETED', conclusion: 'SKIPPED' }, + { __typename: 'CheckRun', name: 'nightly', status: 'COMPLETED', conclusion: 'CANCELLED' }, ] const snapshot = await read({ state: 'PENDING', contexts: { nodes } }) - expect([snapshot.checks, snapshot.checkRuns]).toEqual(['pending', [{ name: 'ci/legacy', state: 'expected' }]]) + expect([snapshot.checks, snapshot.checkRuns]).toEqual(['pending', [ + { name: 'novel', state: 'unknown' }, { name: 'ci/legacy', state: 'expected' }, + { name: 'docs', state: 'skipped' }, { name: 'nightly', state: 'cancelled' }, + ]]) // No rollup contexts at all (or an empty node list) stays absent. for (const rollup of [{ state: 'PENDING' }, { state: 'PENDING', contexts: { nodes: [] } }]) expect((await read(rollup)).checkRuns).toBeUndefined() // Bounded to 20 in provider order, with a name clipped to the display limit. diff --git a/tests/clues-github-source.spec.ts b/tests/clues-github-source.spec.ts index d5e6c0ca..0c3f67b1 100644 --- a/tests/clues-github-source.spec.ts +++ b/tests/clues-github-source.spec.ts @@ -256,12 +256,12 @@ describe('read and loadEdit', () => { expect(result.data).toMatchObject({ kind: 'pull', isDraft: false, merged: false, checkRuns }) expect(result.info).toEqual({ state: 'open', number: 14727, repository: 'cli/cli', - author: { handle: 'umairnaeem0309', name: 'Umair Naeem', url: 'https://github.com/umairnaeem0309' }, + author: { handle: 'umairnaeem0309', name: 'Umair Naeem', url: 'https://github.com/umairnaeem0309', avatarUrl: 'https://avatars.githubusercontent.com/u/1234?v=4' }, assignees: [{ handle: 'cli-triage', name: 'CLI Triage', url: 'https://github.com/apps/cli-triage' }], labels: ['bug'], createdAt: '2026-10-17T12:00:00.000Z', updatedAt: '2026-10-17T15:26:56.000Z', branches: { head: 'fix/type-resolution', base: 'trunk', headRepository: 'umairnaeem0309/cli', baseRepository: 'cli/cli' }, counts: { comments: 5, commits: 12, changedFiles: 3, additions: 42, deletions: 7 }, - review: 'approved', mergeable: 'mergeable', checks: 'success', checkRuns, + review: 'approved', mergeable: 'mergeable', checks: 'success', checkRuns, checkCount: 28, mergeStatus: 'ready', }) }) diff --git a/tests/clues-local-files.spec.ts b/tests/clues-local-files.spec.ts index 4ec75ee6..2aa3afe0 100644 --- a/tests/clues-local-files.spec.ts +++ b/tests/clues-local-files.spec.ts @@ -184,6 +184,19 @@ describe('builtin.files read', () => { await expect(service.saveEdit({ workspaceId: WORKSPACE_ID, clueId: clue.clue.id, document: { format: 'application/octet-stream', data: { text: 'x' }, baseRevision: 'r' } })).rejects.toMatchObject({ category: 'unsupported' }) }) + it('serves SVG as a read-only image asset, including an already saved text-typed clue', async () => { + const { workspace, service } = fixture() + const path = join(workspace, 'diagram.svg') + writeFileSync(path, '') + const { clue } = await service.ensure({ workspaceId: WORKSPACE_ID, sourceId: 'builtin.files', + typeId: LOCAL_FILE_TYPE_IDS.text, locator: workspaceLocator('diagram.svg'), title: 'diagram.svg' }) + const resource = { workspaceId: WORKSPACE_ID, clueId: clue.id } + const read = await service.read(resource) + expect(read).toMatchObject({ format: 'application/octet-stream', assets: [{ path, mime: 'image/svg+xml' }] }) + expect(read.text).toBeUndefined() + await expect(service.loadEdit(resource)).rejects.toMatchObject({ category: 'unsupported' }) + }) + it('pages an explicitly requested large read without silent truncation', async () => { const { workspace, service } = fixture() const content = `${Array.from({ length: 4000 }, () => 'x'.repeat(63)).join('\n')}\n` diff --git a/tests/clues-section-stack.spec.tsx b/tests/clues-section-stack.spec.tsx new file mode 100644 index 00000000..c7cacc02 --- /dev/null +++ b/tests/clues-section-stack.spec.tsx @@ -0,0 +1,43 @@ +/** Three sections resize adjacent open neighbors, even across a collapsed pane. */ +// @vitest-environment jsdom +import { createElement } from 'react' +import { act } from 'react-dom/test-utils' +import { expect, it, vi } from 'vitest' +import { SectionStack } from '../src/client/clues/tab/SectionStack.tsx' +import { renderRoot, setupReactAct } from './test-utils.ts' + +setupReactAct() + +it('resizes a pair without moving the third or unmounting it when collapsed', () => { + const commit = vi.fn() + const sections = ['first', 'second', 'third'].map(id => ({ id, title: id, open: true, weight: 1, + content: createElement('input', { 'aria-label': id, defaultValue: id }) })) + const view = renderRoot(createElement(SectionStack, { sections, onResize: commit })) + try { + const separators = () => Array.from(view.container.querySelectorAll('[role="separator"]')) + const press = (node: HTMLElement, key: string) => { + act(() => { node.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })) }) + } + expect(separators()).toHaveLength(2) + press(separators()[0]!, 'End') + const firstResize = commit.mock.calls.at(-1)?.[0] + expect(firstResize.first).toBeCloseTo(2) + expect(firstResize.second).toBeCloseTo(0) + expect(firstResize.third).toBe(1) + const input = view.container.querySelector('[aria-label="second"]')! + input.value = 'retained draft' + view.rerender(createElement(SectionStack, { sections: sections.map(section => section.id === 'second' + ? { ...section, open: false } : section), onResize: commit })) + expect(separators()).toHaveLength(1) + expect(separators()[0]!.getAttribute('aria-label')).toBe('first / third') + press(separators()[0]!, 'Home') + const secondResize = commit.mock.calls.at(-1)?.[0] + expect(secondResize.first).toBeCloseTo(0) + expect(secondResize.second).toBe(firstResize.second) + expect(secondResize.third).toBeCloseTo(3) + view.rerender(createElement(SectionStack, { sections, onResize: commit })) + expect(view.container.querySelector('[aria-label="second"]')).toBe(input) + expect(input.value).toBe('retained draft') + expect(separators()).toHaveLength(2) + } finally { view.unmount() } +}) diff --git a/tests/clues-tab-main.spec.tsx b/tests/clues-tab-main.spec.tsx index 7294464e..a047db62 100644 --- a/tests/clues-tab-main.spec.tsx +++ b/tests/clues-tab-main.spec.tsx @@ -636,8 +636,14 @@ describe('clue tab main page', () => { expect(nav.textContent).not.toContain('Local files') expect(trigger.querySelector('svg')).not.toBeNull() }) - it('defaults to resources and reads only the visible mounted view', async () => { + it('defaults to both sections open', async () => { const { fx, view } = await mountTab() + expect(sectionOf(view.container, t('clueViewPacks'))?.getAttribute('data-open')).toBe('true') + expect(view.container.querySelector('[role="separator"]')).not.toBeNull() + expect(fx.calls).toMatchObject({ packsList: 1, list: 1 }) + }) + it('restores a collapsed section without reading it until expanded', async () => { + const { fx, view } = await mountTab({ clueSettings: { layout: { packs: false } } }) const query = browserQueryInput(view.container) expect(sectionOf(view.container, t('clueViewPacks'))?.getAttribute('data-open')).toBe('false') expect(sectionOf(view.container, t('clueViewBrowse'))?.getAttribute('data-open')).toBe('true') @@ -1127,7 +1133,7 @@ describe('clue selection confirmation', () => { const unresolved: ClueCandidate = { sourceId: FILES.sourceId, typeId: 'file', title: 'Unregistered note', locator: { path: 'new.md' }, } - const { fx, view } = await mountTab({ listItems: [selectionFiles[0]!, unresolved] }) + const { fx, view } = await mountTab({ listItems: [selectionFiles[0]!, unresolved], clueSettings: { layout: { packs: false } } }) const collection = await selectionWindow(view) const name = startNewPack(collection) typeInto(name, ' Investigation ') @@ -1515,6 +1521,7 @@ describe('clue workbench UX regressions', () => { it('reveals the whole pack library progressively without paging controls', async () => { installIntersectionObserver() const { fx, view } = await mountTab({ + clueSettings: { layout: { packs: false } }, enabled: [FILES.sourceId], listItems: [{ sourceId: FILES.sourceId, typeId: 'file', title: 'A note', locator: { path: 'a.md' } }], }) @@ -1667,7 +1674,7 @@ describe('clue browser trailing query and row menu', () => { expect(checkbox.checked).toBe(false) click(first, 'First note') await flush() - expect(fx.opened.at(-1)).toMatchObject({ id: 'clue:c-a', title: 'First note' }) + expect(fx.opened.at(-1)).toMatchObject({ id: 'clue:c-a:session:s1', sessionId: 's1', title: 'First note' }) expect(checkbox.checked).toBe(false) click(first, 'Insert First note') await flush() diff --git a/tests/e2e/clues-resource-ux.e2e.ts b/tests/e2e/clues-resource-ux.e2e.ts index 389ede94..ca3d8b62 100644 --- a/tests/e2e/clues-resource-ux.e2e.ts +++ b/tests/e2e/clues-resource-ux.e2e.ts @@ -6,8 +6,8 @@ import { mkdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { test, expect } from '@playwright/test' -import { clueWindowFrame, floatClueWindow, selectClueSource, setTheme } from './ui-helpers' -import { createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage } from './host' +import { clueView, clueWindowFrame, floatClueWindow, selectClueSource, setTheme } from './ui-helpers' +import { createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host' const now = '2026-10-23T03:00:00.000Z' const tasks = [ @@ -15,14 +15,81 @@ const tasks = [ { sourceId: 'builtin.feishu.tasks', typeId: 'builtin.feishu.task', title: 'Confirm design review', locator: { kind: 'task', guid: 'fixture-task-2' }, info: { state: 'completed', author: { name: 'Ada' }, assignees: [{ name: 'Grace' }], completedAt: now, updatedAt: now } }, ] const pull = { sourceId: 'builtin.github.pulls', typeId: 'builtin.github.pull', title: 'Improve the resource workbench', locator: { kind: 'pull', owner: 'acme', repo: 'demo', number: 42, url: 'https://github.com/acme/demo/pull/42' }, info: { state: 'open', repository: 'acme/demo', number: 42, author: { handle: 'grace', name: 'Grace' }, assignees: [{ name: 'Ada' }], branches: { head: 'feat/resource-ui', base: 'main' }, counts: { comments: 3, commits: 2, changedFiles: 4, additions: 88, deletions: 20 }, labels: ['ux', 'review'], checks: 'success', review: 'approved', mergeable: 'mergeable', createdAt: now, updatedAt: now } } +const icon = '' +const avatarUrl = 'https://avatars.githubusercontent.com/u/424242?v=4' +const pullDetails = { ...pull.info, author: { ...pull.info.author, url: 'https://github.com/grace', avatarUrl }, + mergeStatus: 'blocked', checks: 'failure', checkCount: 24, checkRuns: [ + { name: 'Unit tests', state: 'success' }, { name: 'Documentation', state: 'skipped' }, + { name: 'Lint', state: 'failure', url: 'https://github.com/acme/demo/actions/runs/42' }, + { name: 'Integration', state: 'pending' }, + ] } const issue = { ...pull, sourceId: 'builtin.github.issues', typeId: 'builtin.github.issue', title: 'Keep resource details readable', locator: { ...pull.locator, kind: 'issue', url: 'https://github.com/acme/demo/issues/42' }, info: { ...pull.info, branches: undefined, counts: { comments: 5 } } } const doc = { sourceId: 'builtin.feishu.docs', typeId: 'builtin.feishu.docx', title: 'Launch notes', locator: { kind: 'docx', token: 'doc-fixture' }, info: { updatedAt: now } } +test('Clues previews decode local PNG, SVG and relative Markdown media', async ({ page }) => { + const api = await createHostApi() + const root = join(process.env.DSH_E2E_WORKSPACE ?? tmpdir(), 'resources-images-' + Date.now()) + mkdirSync(join(root, 'notes'), { recursive: true }) + writeFileSync(join(root, 'notes', 'diagram.svg'), icon) + writeFileSync(join(root, 'notes', 'sample.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+l9wAAAABJRU5ErkJggg==', 'base64')) + writeFileSync(join(root, 'notes', 'broken.svg'), 'not a picture') + writeFileSync(join(root, 'notes', 'readme.md'), '# Image reference\n\n![Diagram from Markdown](./diagram.svg)\n') + try { + const workspace = await hostRpc<{ workspace: { workspaceId: string } }>(api, 'workspace.create', { path: root }) + const session = await hostRpc<{ sessionId: string }>(api, 'session.create', { workspaceId: workspace.value.workspace.workspaceId }) + await gotoPage(page, { sessionId: session.value.sessionId }) + await dismissOnboarding(page) + await sendFirstMessage(page) + await page.locator('[data-sidebar-right-expand]:visible').first().click() + await page.locator('[data-sidebar-right-guide-entry="clues"]').click() + const tab = page.locator('[data-clue-tab]:visible') + await clueView(tab, 'browse') + const browse = tab.locator('[data-clue-browse-region]') + await selectClueSource(browse, 'builtin.files') + await browse.getByRole('button', { name: /^notes$/ }).dblclick() + for (const [name, alt, width] of [['diagram.svg', 'diagram.svg', 48], ['sample.png', 'sample.png', 1], ['readme.md', 'Diagram from Markdown', 48]] as const) { + await browse.getByRole('button', { name: new RegExp('^' + name) }).click() + const frame = await floatClueWindow(page, page.locator('[data-window-document-preview]')) + const preview = frame.locator('[data-window-document-preview]') + await expect(preview.getByRole('img', { name: alt, exact: true })).toHaveJSProperty('naturalWidth', width) + await expect(preview.locator('[data-window-unknown-format]')).toHaveCount(0) + if (name !== 'readme.md') await expect(frame.getByRole('tab', { name: 'Edit', exact: true })).toHaveCount(0) + await frame.getByRole('button', { name: 'Close', exact: true }).click() + } + await browse.getByRole('button', { name: /^broken.svg/ }).click() + const frame = await floatClueWindow(page, page.locator('[data-window-document-preview]')) + await expect(frame.locator('[data-clue-image-preview]')).toContainText('This image cannot be previewed.') + await expect(frame.locator('[data-clue-image-preview]').getByRole('link')).toBeVisible() + } finally { await api.dispose() } +}) + +test('scratch host admits a Clues explanation to main and side without a composer draft', async () => { + const api = await createHostApi() + const root = join(process.env.DSH_E2E_WORKSPACE ?? tmpdir(), 'action-admission-' + Date.now()) + mkdirSync(root, { recursive: true }) + try { + const workspace = await hostRpc<{ workspace: { workspaceId: string } }>(api, 'workspace.create', { path: root }) + const workspaceId = workspace.value.workspace.workspaceId + const { value: { sessionId } } = await hostRpc<{ sessionId: string }>(api, 'session.create', { workspaceId }) + const resource = { sourceId: 'builtin.files', typeId: 'builtin.files.markdown', locator: { path: 'readme.md' } } + for (const target of ['main', 'side'] as const) { + const request = { workspaceId, sessionId, resource, target, requestId: 'clues-smoke-' + target, action: 'explain', selection: 'fixture content' } + const response = await api.post(sidebarApi('clues.actions.start'), { data: request }) + const body = await response.json() + expect(body, JSON.stringify(body)).toMatchObject({ ok: true, value: { target, deliveryId: target === 'main' ? sessionId : expect.any(String) } }) + const retry = await api.post(sidebarApi('clues.actions.start'), { data: request }) + expect(await retry.json()).toEqual(body) + } + } finally { await api.dispose() } +}) + test('clues cache revisits and expose source status, author and branches in one compact detail', async ({ page }, testInfo) => { const api = await createHostApi() const errors: string[] = [] page.on('pageerror', error => errors.push(error.message)) const requests: string[] = [] + let clearedChecks = false + await page.route('https://avatars.githubusercontent.com/u/424242?*', async route => route.fulfill({ contentType: 'image/svg+xml', body: icon })) const root = join(process.env.DSH_E2E_WORKSPACE ?? tmpdir(), `resources-ux-${Date.now()}`) mkdirSync(root, { recursive: true }) writeFileSync(join(root, 'context.md'), '# Local context\n') @@ -42,6 +109,13 @@ test('clues cache revisits and expose source status, author and branches in one : body.sourceId === pull.sourceId ? [pull] : body.sourceId === issue.sourceId ? [issue] : [doc] await route.fulfill({ json: { ok: true, value: { items } } }) }) + await page.route('**/sidebar/api/clues.comments.list', async route => { + const { sourceId } = route.request().postDataJSON() as { sourceId: string } + const items = sourceId === pull.sourceId ? [{ id: 'pr-comment', kind: 'review', format: 'text/markdown', + body: 'Looks good. Please check the lint step.', author: { name: 'Grace', avatarUrl }, + reviewState: 'APPROVED', createdAt: now }] : [] + await route.fulfill({ json: { ok: true, value: { status: 'ok', coverage: 'document', fetchedAt: now, complete: true, items } } }) + }) await page.route('**/sidebar/api/clues.read', async route => { const body = route.request().postDataJSON() as { sourceId: string; locator: { guid?: string } } requests.push(`read:${body.sourceId}:${body.locator?.guid ?? ''}`) @@ -50,8 +124,9 @@ test('clues cache revisits and expose source status, author and branches in one const value = body.sourceId === 'builtin.feishu.tasks' ? { format: 'feishu.task.document', data: { kind: 'task', guid: task.locator.guid, title: task.title, description: '## Checklist\n\n- Check release notes\n- Confirm ownership', completed: task.info.state === 'completed', start: null, due: null }, info: task.info } : body.sourceId === 'builtin.feishu.docs' - ? { format: 'feishu.docs.xml', data: { kind: 'docx', docToken: 'doc-fixture', title: doc.title, projection: 'xml', content: 'Launch notes

    Release plan

    Readable document content.

    ' }, info: doc.info } - : { format: 'text/markdown', data: { title: body.sourceId === pull.sourceId ? pull.title : issue.title, body: '## Context\n\nA readable change description.', text: '## Context\n\nA readable change description.' }, info: body.sourceId === pull.sourceId ? pull.info : issue.info } + ? { format: 'feishu.docs.xml', data: { kind: 'docx', docToken: 'doc-fixture', title: doc.title, projection: 'xml', content: 'Launch notes

    Release plan

    Readable document content.

    1. First step
    2. Second step
    BudgetApproved
    Missing source image' }, info: doc.info } + : { format: 'text/markdown', data: { title: body.sourceId === pull.sourceId ? pull.title : issue.title, body: '## Context\n\nA readable change description.', text: '## Context\n\nA readable change description.' }, info: body.sourceId === pull.sourceId ? (clearedChecks + ? { state: 'open', number: 42, mergeable: 'unknown' } : pullDetails) : issue.info } await route.fulfill({ json: { ok: true, value: { ...value, fetchedAt: now, freshness: 'live' } } }) }) await gotoPage(page, {}, { firstCluesVisit: true }) @@ -115,15 +190,29 @@ test('clues cache revisits and expose source status, author and branches in one await expect(rowChecks).toHaveText('') await openDetail(/^Improve the resource workbench/) await expect(summary).toContainText('Grace') - await expect(summary.locator('[data-clue-change-request-fact="checks"]')).toContainText('Passed') - await expect(summary.locator('[data-clue-change-request-fact="checks"]').getByRole('img')) - .toHaveAttribute('aria-label', 'CI: Passed') - await expect(summary.locator('[data-clue-change-request-fact="review"]')).toContainText('Approved') - // Mergeable is the resting case and stays silent; only a conflict is a fact. - await expect(summary.locator('[data-clue-change-request-fact="merge"]')).toHaveCount(0) + const overview = frame.locator('[data-clue-pr-status]') + await expect(overview).toContainText('Merge blocked') + await expect(summary.getByRole('link', { name: 'Grace' }).locator('img')).toHaveJSProperty('complete', true) + const checks = overview.locator('[data-clue-change-request-fact="checks"]') + await expect(checks.getByRole('img')).toHaveAttribute('aria-label', 'CI: Failing') + await expect(overview.locator('[data-clue-change-request-fact="review"]')).toContainText('Approved') + await checks.click() + const details = overview.locator('[data-clue-check-list]') + await expect(details).toContainText('Showing 4 of 24 checks') + await expect(details.locator('li').first()).toContainText('Lint') + await expect(details.getByRole('link', { name: 'GitHub' })).toHaveAttribute('href', 'https://github.com/acme/demo/pull/42/checks') + await expect(details).toContainText('Skipped') + await setTheme(page, 'dark') + await page.mouse.move(0, 0) + await frame.screenshot({ animations: 'disabled', path: testInfo.outputPath('pull-checks-dark.png') }) + await checks.click() + await page.mouse.move(0, 0) await expect(summary).toContainText('feat/resource-ui') await expect(summary).toContainText('main') - await expect(summary).toContainText('88') + const changes = summary.locator('[data-clue-resource-item="changes"]') + await expect(changes.getByText('+88', { exact: true })).toHaveAttribute('data-check-tone', 'pass') + await expect(changes.getByText('−20', { exact: true })).toHaveAttribute('data-check-tone', 'fail') + expect(await changes.locator('span').evaluateAll(nodes => new Set(nodes.map(node => getComputedStyle(node).color)).size)).toBe(2) for (const theme of ['light', 'dark'] as const) { await setTheme(page, theme) await frame.screenshot({ animations: 'disabled', path: testInfo.outputPath(`pull-${theme}.png`) }) @@ -134,6 +223,10 @@ test('clues cache revisits and expose source status, author and branches in one expect(footer.x).toBeGreaterThanOrEqual(bounds.x) expect(footer.x + footer.width).toBeLessThanOrEqual(bounds.x + bounds.width + 1) await frame.screenshot({ animations: 'disabled', path: testInfo.outputPath('pull-compact.png') }) + clearedChecks = true + await frame.getByRole('button', { name: 'Refresh', exact: true }).click() + await expect(overview.locator('[data-clue-pr-merge]')).toHaveAttribute('data-clue-pr-merge', 'other') + await expect(overview.locator('[data-clue-check-list]')).toHaveCount(0) await frame.getByRole('button', { name: 'Close', exact: true }).click() await selectClueSource(browse, 'builtin.github.issues') await openDetail(/^Keep resource details readable/) @@ -141,7 +234,11 @@ test('clues cache revisits and expose source status, author and branches in one await frame.getByRole('button', { name: 'Close', exact: true }).click() await selectClueSource(browse, 'builtin.feishu.docs') await openDetail(/^Launch notes/) - await expect(frame.locator('[data-window-document-preview]')).toContainText('Readable document content.') + const preview = frame.locator('[data-window-document-preview]') + await expect(preview).toContainText('Readable document content.') + await expect(preview.getByRole('listitem').first()).toHaveText('First step') + await expect(preview.getByRole('cell', { name: 'Budget', exact: true })).toBeVisible() + await expect(preview.locator('[data-clue-image-preview]')).toContainText('This image cannot be previewed.') await expect(frame.locator('[data-window-document-preview] details summary')).toHaveText('Details') await frame.screenshot({ animations: 'disabled', path: testInfo.outputPath('document-readable.png') }) await frame.getByRole('button', { name: 'Close', exact: true }).click() diff --git a/tests/e2e/clues-ui19.e2e.ts b/tests/e2e/clues-ui19.e2e.ts index 28dae1cb..bf49363a 100644 --- a/tests/e2e/clues-ui19.e2e.ts +++ b/tests/e2e/clues-ui19.e2e.ts @@ -40,6 +40,7 @@ interface ActionRequest { interface FixtureState { workspaceId?: string actions: ActionRequest[] + rejectNext?: boolean reads: number comments: number blocked: string[] @@ -85,6 +86,11 @@ async function interceptFixture(page: Page): Promise { case 'clues.snapshots.list': await ok(route, { snapshots: [] }); return case 'clues.actions.start': state.actions.push(route.request().postDataJSON() as ActionRequest) + if (state.rejectNext === true) { + state.rejectNext = false + await route.fulfill({ status: 409, json: { ok: false, error: { code: 'conflict', + message: 'The conversation is in use by another DSH instance.' } } }); return + } // No deliveryId: the client must not reopen/start a sidechat either. await ok(route, { accepted: true }); return default: @@ -157,10 +163,10 @@ async function openFixture(page: Page): Promise<{ state: FixtureState; surface: } /** Set a real DOM Selection, then let the rendered surface handle mouseup. */ -async function selectText(page: Page, scope: Locator, text: string): Promise { +async function selectText(page: Page, scope: Locator, text: string, right = false): Promise { const paragraph = scope.getByText(text, { exact: true }) await paragraph.scrollIntoViewIfNeeded() - await paragraph.evaluate((node, selected) => { + const handled = await paragraph.evaluate((node, { selected, right }) => { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT) let textNode: Node | null while ((textNode = walker.nextNode()) !== null) { @@ -172,11 +178,14 @@ async function selectText(page: Page, scope: Locator, text: string): Promise { const { state, surface, sessionId } = await openFixture(page) const body = surface.locator('[data-window-document-body]') - let menu = await selectText(page, body, BODY_SELECTION) + let menu = await selectText(page, body, BODY_SELECTION, true) expect(await menu.locator('[data-clue-selection-action]').evaluateAll(nodes => nodes.map(node => node.getAttribute('data-clue-selection-action')))) .toEqual(['insert', 'explain', 'rewrite', 'expand', 'continue', 'shorten', 'translate']) await expect(menu.getByRole('menuitemradio', { name: 'Main conversation', exact: true })).toHaveAttribute('aria-checked', 'true') await expect(menu.getByRole('menuitemradio', { name: 'Side conversation', exact: true })).toBeVisible() + state.rejectNext = true await menu.locator('[data-clue-selection-action="explain"]').click() + await expect(menu.getByRole('alert')).toContainText('Another DSH instance is using this conversation.') + await menu.getByRole('menuitem', { name: 'Retry', exact: true }).click() await expect(menu).toHaveCount(0) - await expect.poll(() => state.actions.length).toBe(1) + await expect.poll(() => state.actions.length).toBe(2) + expect(state.actions[1]).toEqual(state.actions[0]) expect(state.actions[0]).toMatchObject({ workspaceId: state.workspaceId, sessionId, action: 'explain', target: 'main', selection: BODY_SELECTION, resource: { sourceId: SOURCE, typeId: TYPE, locator: candidate.locator } }) expect(state.actions[0]!.requestId).toBeTruthy() expect(state.actions[0]!.comment).toBeUndefined() @@ -233,13 +246,13 @@ test('UI19 selects body and comment actions with readable main/side targets with await side.click() await expect(side).toHaveAttribute('aria-checked', 'true') await menu.locator('[data-clue-selection-action="explain"]').click() - await expect.poll(() => state.actions.length).toBe(2) - expect(state.actions[1]).toMatchObject({ workspaceId: state.workspaceId, sessionId, action: 'explain', target: 'side', selection: COMMENT_SELECTION, comment: true, resource: { sourceId: SOURCE, typeId: TYPE, locator: candidate.locator } }) + await expect.poll(() => state.actions.length).toBe(3) + expect(state.actions[2]).toMatchObject({ workspaceId: state.workspaceId, sessionId, action: 'explain', target: 'side', selection: COMMENT_SELECTION, comment: true, resource: { sourceId: SOURCE, typeId: TYPE, locator: candidate.locator } }) menu = await selectText(page, surface.locator('[data-clue-comment="ui19-comment"] [data-clue-selection-surface]'), COMMENT_SELECTION) await menu.locator('[data-clue-selection-action="insert"]').click() const composer = page.getByRole('textbox', { name: /^(Describe what you want to build|Message or run a task|描述你想要构建)/ }) await expect(composer).toContainText(COMMENT_SELECTION) - expect(state.actions).toHaveLength(2) + expect(state.actions).toHaveLength(3) expectQuiet(state) }) diff --git a/tests/e2e/clues-uiux.e2e.ts b/tests/e2e/clues-uiux.e2e.ts index 90c2fdeb..9d77da5f 100644 --- a/tests/e2e/clues-uiux.e2e.ts +++ b/tests/e2e/clues-uiux.e2e.ts @@ -163,8 +163,26 @@ test('clues workbench stays usable across column widths and host themes', async const layoutMetrics: ClueLayoutMetric[] = [] const colorMetrics: Record[] = [] await expect(tab.getByRole('button', { name: 'Resources', exact: true })).toHaveAttribute('aria-expanded', 'true') - await expect(packs).toBeHidden() + const packHeading = tab.getByRole('button', { name: 'Collections', exact: true }) + if (await packHeading.getAttribute('aria-expanded') === 'false') await packHeading.click() + await expect(packs).toBeVisible() await expect(browser.getByRole('region', { name: 'Resources', exact: true })).toBeVisible() + const sash = tab.getByRole('separator', { name: 'Resources / Collections', exact: true }) + const topHeight = (await browser.boundingBox())!.height + const handle = (await sash.boundingBox())! + const x = handle.x + handle.width / 2 + const y = handle.y + handle.height / 2 + await page.mouse.move(x, y) + await page.mouse.down() + await page.mouse.move(x, y - 36, { steps: 6 }) + await page.mouse.up() + await expect.poll(async () => (await browser.boundingBox())!.height).toBeLessThan(topHeight - 20) + const afterDrag = (await browser.boundingBox())!.height + await sash.press('ArrowDown') + await expect.poll(async () => (await browser.boundingBox())!.height).toBeGreaterThan(afterDrag) + await packHeading.click() + await expect(sash).toHaveCount(0) + await expect(packs).toBeHidden() await clueView(tab, 'packs') await expect(packs.getByRole('region', { name: 'Collections', exact: true })).toBeVisible() await clueView(tab, 'browse') diff --git a/tests/fixtures/clues-github/pull-read.json b/tests/fixtures/clues-github/pull-read.json index 35fd8557..8acbbc29 100644 --- a/tests/fixtures/clues-github/pull-read.json +++ b/tests/fixtures/clues-github/pull-read.json @@ -18,7 +18,8 @@ "author": { "login": "umairnaeem0309", "name": "Umair Naeem", - "url": "https://github.com/umairnaeem0309" + "url": "https://github.com/umairnaeem0309", + "avatarUrl": "https://avatars.githubusercontent.com/u/1234?v=4" }, "assignees": { "nodes": [ @@ -32,13 +33,16 @@ "additions": 42, "deletions": 7, "headRefName": "fix/type-resolution", + "headRefOid": "2345678abc012345678abc012345678abc0123456", "baseRefName": "trunk", "headRepository": { "nameWithOwner": "umairnaeem0309/cli" }, "reviewDecision": "APPROVED", "mergeable": "MERGEABLE", + "mergeStateStatus": "CLEAN", "statusCheckRollup": { "state": "SUCCESS", "contexts": { + "totalCount": 28, "nodes": [ { "__typename": "CheckRun", diff --git a/tests/theme.spec.ts b/tests/theme.spec.ts index 294e7db2..5e8eb78a 100644 --- a/tests/theme.spec.ts +++ b/tests/theme.spec.ts @@ -151,6 +151,8 @@ describe('skin contract: the plugin owns no color of its own', () => { it('clue surfaces keep every paint themed and pair primary foreground with fill', () => { for (const file of [ 'src/client/clues/tab/clues-tab.module.css', + 'src/client/clues/resource-summary.module.css', + 'src/client/clues/sources/feishu/feishu.module.css', 'src/client/clues/windows/pack.module.css', 'src/client/clues/windows/share.module.css', 'src/client/clues/windows/detail.module.css',