fix(web): render @ mentions as chips only for existing paths
Sent file and folder mentions now render as reference chips only after the Session's filesystem confirms the path through the existing workspaceFiles.stat Remote; a missing path such as a hand-typed @ceshi stays original text. ui-reference owns a per-plugin presence cache keyed by Session and path, exposes it to the chips through a keyed hook, treats a settled pick as confirmed, and aborts outstanding stats on disposal.
This commit is contained in:
1 parent
1a33461f2b
commit
f7b4dbd752
18 files changed
+544
-33
No files matched your search
@@ -0,0 +1,80 @@
|
||||
/** Typed `@` mentions render as file and folder chips only when the Session's filesystem has the path. */
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { chromium, type Browser, type Page } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import {
|
||||
captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, readPersistedEvents, recordFixture,
|
||||
watchConsole, webSnapshotMode, type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
|
||||
|
||||
const DIR = fileURLToPath(new URL('../../../snapshots/web/mention-path-presence', import.meta.url))
|
||||
const FIXTURE = join(DIR, 'session.v4.jsonl')
|
||||
const MODE = webSnapshotMode()
|
||||
const PROMPT = '@ceshi @随便写点文字 @LICENSE @docs/ mail@host'
|
||||
|
||||
describe.skipIf(MODE === 'record')('web e2e: mention path presence', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let page: Page
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
|
||||
beforeAll(async () => {
|
||||
scaffold = await launchWebScaffold({
|
||||
replayFixture: FIXTURE,
|
||||
compareReplaySession: true,
|
||||
paceMs: 10,
|
||||
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
|
||||
})
|
||||
await mkdir(join(scaffold.workspaceCwd, 'workspace', 'docs'), { recursive: true })
|
||||
await writeFile(join(scaffold.workspaceCwd, 'workspace', 'LICENSE'), 'Reference fixture license.\n')
|
||||
browser = await chromium.launch()
|
||||
page = await newEnglishPage(browser)
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]')
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await browser?.close()
|
||||
} finally {
|
||||
await scaffold?.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('decorates typed mentions of existing paths and keeps other @ text verbatim across reload', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'mention-path-presence'))
|
||||
const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
|
||||
await writeComposerDraft(page, composer, PROMPT)
|
||||
// The trailing token is not a mention, so no completion is open to take the Enter.
|
||||
await page.getByRole('listbox', { name: 'Trigger suggestions' }).waitFor({ state: 'hidden' })
|
||||
expect(await composer.locator('[data-composer-chip]').count()).toBe(0)
|
||||
|
||||
const settled = scaffold.whenTurnSettled()
|
||||
await composer.press('Enter')
|
||||
const sessionId = await settled
|
||||
const persisted = (await readPersistedEvents(scaffold, sessionId))
|
||||
.find(event => event.type === 'user/message' && event.data.source.kind === 'user')
|
||||
expect(persisted).toMatchObject({ data: { content: [{ type: 'text', text: PROMPT }] } })
|
||||
if (MODE === 'refresh') await recordFixture(scaffold, sessionId, FIXTURE)
|
||||
expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
|
||||
|
||||
for (const reload of [false, true]) {
|
||||
if (reload) await page.reload({ waitUntil: 'load' })
|
||||
const bubble = page.locator('[data-chat-flow-kind="user"]')
|
||||
await expect.poll(() => bubble.locator('[data-ref-chip]').allTextContents()).toEqual(['LICENSE', 'docs'])
|
||||
expect(await bubble.textContent()).toContain('@ceshi @随便写点文字 ')
|
||||
expect(await bubble.textContent()).toContain(' mail@host')
|
||||
await bubble.getByRole('button', { name: 'LICENSE', exact: true }).click()
|
||||
await page.getByText('Reference fixture license.', { exact: true }).waitFor()
|
||||
}
|
||||
await compareOrRefreshGolden(join(DIR, 'ui.expected.md'),
|
||||
await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -157,6 +157,7 @@
|
||||
"tests/markdown-file-links.e2e.ts",
|
||||
"tests/user-text-secret-mask.e2e.ts",
|
||||
"tests/reference-composer.e2e.ts",
|
||||
"tests/mention-path-presence.e2e.ts",
|
||||
"tests/markdown-wide-table.e2e.ts",
|
||||
"tests/thinking-markdown.e2e.ts",
|
||||
"tests/math-rendering.e2e.ts",
|
||||
|
||||
@@ -74,9 +74,11 @@ async function bench() {
|
||||
}, UserText)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'text' }, PlainUserText)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'session' }, SessionReference)
|
||||
// Every path mention in these units is Host-confirmed; ui-reference owns presence coverage.
|
||||
const keyedHooks = { pathPresence: () => ({ getSnapshot: () => 'present' as const, subscribe: () => () => {} }) }
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', locale: 'reference',
|
||||
inject: () => ({ openFile }) }, FileReference)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder' }, FolderReference)
|
||||
inject: () => ({ openFile, keyedHooks }) }, FileReference)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', inject: () => ({ keyedHooks }) }, FolderReference)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'skill', inject: () => ({ openSkill }) }, SkillReference)
|
||||
ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ name: 'conversation.chat.user.images' }, function ImageProbe(props) {
|
||||
imageCalls.push(props)
|
||||
|
||||
@@ -49,6 +49,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in
|
||||
const openFile = actions.openFile ?? (() => { throw new Error('This fixture has no file navigation action') })
|
||||
const openSkill = actions.openSkill ?? (() => { throw new Error('This fixture has no skill navigation action') })
|
||||
const t = makeTranslate(referenceZh, commonZh)
|
||||
// Composition units treat every path mention as Host-confirmed; ui-reference owns presence coverage.
|
||||
const usePathPresence = () => 'present' as const
|
||||
const renderSlot: UserTextProps['renderSlot'] = (name: string, input: object, options?: { fallback?: ReactNode }) => {
|
||||
if (name !== 'conversation.user.text.node') throw new Error(`Unexpected UserText Slot: ${name}`)
|
||||
const owner = input as UserTextNodeOwnerProps & { node: UserTextNode }
|
||||
@@ -56,8 +58,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in
|
||||
// The production components only read these owner, action and locale seats in these units.
|
||||
case 'text': return createElement(PlainUserText, owner as ComponentProps<typeof PlainUserText>)
|
||||
case 'session': return createElement(SessionReference, owner as ComponentProps<typeof SessionReference>)
|
||||
case 'file': return createElement(FileReference, { ...owner, openFile, t } as ComponentProps<typeof FileReference>)
|
||||
case 'folder': return createElement(FolderReference, owner as ComponentProps<typeof FolderReference>)
|
||||
case 'file': return createElement(FileReference, { ...owner, openFile, usePathPresence, t } as ComponentProps<typeof FileReference>)
|
||||
case 'folder': return createElement(FolderReference, { ...owner, usePathPresence } as ComponentProps<typeof FolderReference>)
|
||||
case 'skill': return createElement(SkillReference, { ...owner, openSkill } as ComponentProps<typeof SkillReference>)
|
||||
case 'command': return createElement(GoalCommandReference, owner as ComponentProps<typeof GoalCommandReference>)
|
||||
default: return options?.fallback ?? null
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts:
|
||||
en: 0b41c33743e5b422
|
||||
zh: 551896094c03f57e
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/sent-file-and-folder-mentions:
|
||||
en: 6f276d2ef3135c8e
|
||||
zh: f4aaadb82a828af9
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior:
|
||||
en: 228ee6f4b81d96a7
|
||||
zh: e1c960c3f5b25317
|
||||
@@ -30,8 +33,8 @@
|
||||
en: 6c77da1e946f72e1
|
||||
zh: b7b8e1e1d4f5a102
|
||||
/deepseek-ai-dsh-client-ui-reference/understand-the-implementation/serialization:
|
||||
en: c3fe8963ed80e403
|
||||
zh: ba3e057cd63e9189
|
||||
en: 9138c6d815be54db
|
||||
zh: 5c3075c07e35c783
|
||||
/deepseek-ai-dsh-client-ui-reference/further-exploration:
|
||||
en: 157b1bcf84b5c11b
|
||||
zh: 6b7e4f3326b19036
|
||||
@@ -42,8 +45,8 @@
|
||||
en: ff23f8026f7c6050
|
||||
zh: 6b0841800076bcd2
|
||||
/deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work:
|
||||
en: e79991a25b11e342
|
||||
zh: 15064e8374c8e63d
|
||||
en: f51b285964650dd2
|
||||
zh: 5a237964dff7f98a
|
||||
/deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -33,6 +33,10 @@ A file closes completion as an atomic inline reference displayed with a file gly
|
||||
|
||||
A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`.
|
||||
|
||||
### Sent file and folder mentions
|
||||
|
||||
In sent messages, queued rows, and local echoes, an `@path` or `@"path"` token renders as a file or folder reference only after the Session's filesystem confirms the path exists. Until then, and for a path that does not exist, such as a hand-typed `@notes`, the original text stays verbatim; email addresses never match. A picked candidate counts as confirmed, so its echo shows the reference immediately. Each Session and path is checked once per page load.
|
||||
|
||||
### Failure behavior
|
||||
|
||||
One unavailable or failed candidate domain yields no rows for that domain while the other still lists. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn.
|
||||
@@ -59,7 +63,7 @@ Candidate requests require an existing retained Client Session and share one tem
|
||||
|
||||
File picks preserve the natural text defined by the shared `@path` grammar as the hidden serialized and clipboard form. Session picks use the canonical `@[label](dsh-session:…)` mention; serialization never reconstructs identity from the visible title.
|
||||
|
||||
The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Interactive file nodes receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels.
|
||||
The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete candidate reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Both node renderers subscribe to a Session-bound `pathPresence` keyed Hook backed by `workspaceFiles/stat`: a stat result or a `workspace-file/not-regular-file` failure confirms the path, `workspace-file/not-found` rejects it, and any other failure leaves it unconfirmed for the next subscriber to retry. The plugin owns these answers, keeps one per Session and path, and aborts outstanding stats on disposal; a settling pick records its path as confirmed. Interactive file nodes also receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -95,6 +99,7 @@ These limits define when the reference source cannot help; they are current pack
|
||||
|
||||
- **Candidate failure is intentionally quiet** — one unavailable or failed Remote discovery call yields no rows for that domain. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn.
|
||||
- **No browser-side file scan** — Web completion requires a mounted Host `ctx.fileReferences` provider; the browser cannot fall back to its own filesystem.
|
||||
- **Sent references do not follow file changes** — a path's confirmed or missing answer lasts for the page load; creating or removing the path later changes how its mentions render only after reload.
|
||||
- **Session search remains metadata-only** — discovery filters session id, cwd, and the latest log-backed title through `ctx.sessionReferenceResolver`; message bodies and full transcripts are not searched.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -33,6 +33,10 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。
|
||||
|
||||
### 已发送的文件与目录引用
|
||||
|
||||
在已发送消息、排队行和本地回显中,`@path` 或 `@"path"` token 只有在 Session 的文件系统确认该路径存在后才渲染为文件或目录引用。确认之前,以及路径不存在时(例如手写的 `@notes`),原文保持不变;邮箱地址永远不会匹配。从候选中选择的路径视为已确认,因此其回显会立即显示引用。每个 Session 与路径在一次页面加载中只检查一次。
|
||||
|
||||
### 失败行为
|
||||
|
||||
某个候选领域不可用或失败时,该领域不产生任何行,另一领域仍正常列出。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。
|
||||
@@ -59,7 +63,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
文件选择把共享 `@path` 语法所定义的自然文本保留为隐藏的序列化与剪贴板形式。会话选择使用规范的 `@[label](dsh-session:…)` mention;序列化永远不会根据可见标题重建身份。
|
||||
|
||||
插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整引用,不执行文件发现;共享计算器按原文位置裁定重叠。可交互的文件节点通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。
|
||||
插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整候选引用,不执行文件发现;共享计算器按原文位置裁定重叠。两个节点 renderer 都订阅绑定 Session 的 `pathPresence` 键控 Hook,其背后是 `workspaceFiles/stat`:stat 成功或 `workspace-file/not-regular-file` 失败即确认路径存在,`workspace-file/not-found` 判定不存在,其他失败则保持未确认,由下一个订阅者重试。插件持有这些结果,每个 Session 与路径保留一份,并在卸载时中止未完成的 stat;选定 pick 会把其路径记为已确认。可交互的文件节点还通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -95,6 +99,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
- **候选失败有意保持静默**:Remote 发现调用不可用或失败时,该领域不产生候选行。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。
|
||||
- **浏览器侧不扫描文件**:Web 补全需要挂载宿主 `ctx.fileReferences` 提供方;浏览器无法回退到自身文件系统。
|
||||
- **已发送引用不跟随文件变化**:路径的确认或不存在结果在一次页面加载内保持不变;之后创建或删除该路径,只有刷新页面后才会改变其引用的渲染。
|
||||
- **会话搜索仍仅使用元数据**:发现流程通过 `ctx.sessionReferenceResolver` 筛选 session id、cwd 与以日志为依据的最新标题;不搜索消息主体或完整 transcript。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
/** File navigation feedback belongs to the individual inline reference that requested it. */
|
||||
import { useState } from 'react'
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { Button, Modal, ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { Button, Modal, ReferenceChip, UserTextRun } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { NS } from './locales.ts'
|
||||
import type { PathPresence } from './path-presence.ts'
|
||||
import type {} from './user-text-rules.ts'
|
||||
|
||||
/** Host-confirmed presence of mention paths in the rendering Session. */
|
||||
export interface PathPresenceInjected {
|
||||
readonly keyedHooks: {
|
||||
/** Presence of one decoded mention path; subscribing starts its Host stat. */
|
||||
readonly pathPresence: (path: string) => HostObservable<PathPresence | undefined>
|
||||
}
|
||||
}
|
||||
|
||||
/** Session-authorized synchronous navigation; document reading belongs to the preview host. */
|
||||
export interface FileReferenceInjected {
|
||||
export interface FileReferenceInjected extends PathPresenceInjected {
|
||||
/**
|
||||
* Open or reveal a file in the current Sidebar using the originating Session's authority.
|
||||
* @param path - decoded path from the reference.
|
||||
@@ -18,14 +27,18 @@ export interface FileReferenceInjected {
|
||||
|
||||
type FileReferenceProps = UserTextNodeProps<'file'> & InjectFace<FileReferenceInjected> & PropsLocale<typeof NS>
|
||||
|
||||
type FolderReferenceProps = UserTextNodeProps<'folder'> & InjectFace<PathPresenceInjected>
|
||||
|
||||
/**
|
||||
* Render a file chip and contain synchronous navigation failures without hiding the reference.
|
||||
* @param props - JSON node, interaction policy, Session-authorized navigation, and locale seat.
|
||||
* @returns an inline chip and, after a navigation failure, its body-portaled dialog.
|
||||
* Render a file chip once the Host confirms its path exists, and contain synchronous navigation failures without hiding the reference.
|
||||
* @param props - JSON node, interaction policy, Session-authorized navigation and presence, and locale seat.
|
||||
* @returns the original spelling until confirmation; afterwards an inline chip and, after a navigation failure, its body-portaled dialog.
|
||||
*/
|
||||
export function FileReference({ node, raw, interactive, openFile, t }: FileReferenceProps) {
|
||||
export function FileReference({ node, raw, interactive, openFile, usePathPresence, t }: FileReferenceProps) {
|
||||
const [failedPath, setFailedPath] = useState<string | null>(null)
|
||||
const { path, label } = node.data
|
||||
const presence = usePathPresence(path)
|
||||
if (presence !== 'present') return <UserTextRun text={raw} />
|
||||
const close = () => { setFailedPath(null) }
|
||||
const open = () => {
|
||||
try {
|
||||
@@ -53,10 +66,12 @@ export function FileReference({ node, raw, interactive, openFile, t }: FileRefer
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a directory as a label, even when the containing text permits file navigation.
|
||||
* @param props - resolved directory data and the original reference spelling.
|
||||
* @returns an inline non-interactive chip.
|
||||
* Render a directory as a label once the Host confirms its path exists, even when the containing text permits file navigation.
|
||||
* @param props - directory data, the original reference spelling, and Session-scoped presence.
|
||||
* @returns the original spelling until confirmation, then an inline non-interactive chip.
|
||||
*/
|
||||
export function FolderReference({ node, raw }: UserTextNodeProps<'folder'>) {
|
||||
return <ReferenceChip appearance="folder" label={node.data.label} title={raw} />
|
||||
export function FolderReference({ node, raw, usePathPresence }: FolderReferenceProps) {
|
||||
return usePathPresence(node.data.path) === 'present'
|
||||
? <ReferenceChip appearance="folder" label={node.data.label} title={raw} />
|
||||
: <UserTextRun text={raw} />
|
||||
}
|
||||
@@ -11,6 +11,11 @@
|
||||
* workspace is not the current one. A session is dated from the Host session
|
||||
* list, so the `@` menu and the session list never disagree about its age.
|
||||
*
|
||||
* A file or folder mention in sent text renders as a chip only after the
|
||||
* Session's filesystem confirms the path exists; picking a listed candidate
|
||||
* confirms it, and any other mention stays original text until a Host stat
|
||||
* answers.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-client-ui-reference/client
|
||||
*/
|
||||
// Type-only: pulls the generated Remote API and ctx.remote merge through the Client assembly boundary.
|
||||
@@ -23,8 +28,11 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis'
|
||||
import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { FileReference, FolderReference, type FileReferenceInjected } from './FileReference.tsx'
|
||||
import { fileReferenceRule, folderReferenceRule } from './user-text-rules.ts'
|
||||
import {
|
||||
FileReference, FolderReference, type FileReferenceInjected, type PathPresenceInjected,
|
||||
} from './FileReference.tsx'
|
||||
import { createPathPresence } from './path-presence.ts'
|
||||
import { fileReferenceRule, folderReferenceRule, mentionPath } from './user-text-rules.ts'
|
||||
export type {} from './user-text-rules.ts'
|
||||
import type {
|
||||
ClientSessionContext, InputTriggerCrumb, InputTriggerServiceContract, InputTriggerSource,
|
||||
@@ -45,7 +53,7 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' {
|
||||
/** Required services: the trigger registry, the Remote namespaces, and the copy. */
|
||||
export const inject = [
|
||||
'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences',
|
||||
'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation',
|
||||
'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation',
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -56,19 +64,27 @@ export function apply(ctx: ClientContext): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-reference: dictionaries')
|
||||
const t = ctx.locale.bind(NS)
|
||||
const sessions = ctx.get('sessions') as ISessions
|
||||
const presence = createPathPresence((sessionId, path, signal) => ctx.remote.workspaceFiles.stat(sessionId, path, signal))
|
||||
ctx.effect(() => () => { presence.dispose() }, 'ui-reference: mention path stats')
|
||||
const presenceFor = (sessionId: UserTextNodeProps<'file'>['sessionId']): PathPresenceInjected => ({
|
||||
keyedHooks: { pathPresence: path => presence.source(sessionId, path) },
|
||||
})
|
||||
ctx.uiConversation.userText.register(fileReferenceRule)
|
||||
ctx.uiConversation.userText.register(folderReferenceRule)
|
||||
ctx.slots.inject('conversation.user.text.node', function* () {
|
||||
yield ctx.slots.register({
|
||||
name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS,
|
||||
inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({
|
||||
...presenceFor(sessionId),
|
||||
openFile: (path) => {
|
||||
const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd
|
||||
ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))
|
||||
},
|
||||
}),
|
||||
}, FileReference)
|
||||
yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', priority: 100 }, FolderReference)
|
||||
yield ctx.slots.register({
|
||||
name: 'conversation.user.text.node', key: 'folder', priority: 100, inject: presenceFor,
|
||||
}, FolderReference)
|
||||
})
|
||||
const source: InputTriggerSource = {
|
||||
trigger: '@',
|
||||
@@ -128,7 +144,7 @@ export function apply(ctx: ClientContext): void {
|
||||
header(_session: ClientSessionContext, req) {
|
||||
return crumbsFor(req.query, req.quoted === true, req.drilled, t)
|
||||
},
|
||||
onPick({ candidate, action }) {
|
||||
onPick({ candidate, session, action }) {
|
||||
const value = parseCandidate(candidate.value)
|
||||
if (value?.kind === 'file') {
|
||||
// A directory row carries two verbs: the settling pick resolves the
|
||||
@@ -138,6 +154,8 @@ export function apply(ctx: ClientContext): void {
|
||||
if (value.fileKind === 'directory' && action === 'drill') {
|
||||
return { text: value.mention, continue: true }
|
||||
}
|
||||
// The Host has just listed this path, so its sent echo renders as a chip without a stat.
|
||||
presence.confirm(session.sessionId, mentionPath(value.mention))
|
||||
return {
|
||||
insert: {
|
||||
source: 'reference',
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Session-scoped Host confirmation that a mentioned path exists.
|
||||
*
|
||||
* Each Session and path pair is stat'ed at most once while the owning plugin
|
||||
* is live. Only a definitive Host answer is retained; any other failure leaves
|
||||
* the pair unconfirmed, and the next subscriber asks again. Retained answers
|
||||
* are not refreshed when the path is created or removed later. Entries live as
|
||||
* long as the plugin, one per distinct mention the client has rendered.
|
||||
*/
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
|
||||
/** Session whose filesystem resolves a mention. */
|
||||
export type MentionSessionId = UserTextNodeProps<'file'>['sessionId']
|
||||
|
||||
/** Host answer for one mentioned path; `undefined` means unconfirmed. */
|
||||
export type PathPresence = 'present' | 'absent'
|
||||
|
||||
/**
|
||||
* Session-authorized stat of one path, absolute or relative to the Session's workspace root.
|
||||
* @param sessionId - Session whose filesystem resolves the path.
|
||||
* @param path - path as the mention spells it.
|
||||
* @param signal - cancellation owned by the presence sources.
|
||||
* @returns the regular file's metadata, or the Host's typed failure.
|
||||
*/
|
||||
export type PathStat = (
|
||||
sessionId: MentionSessionId,
|
||||
path: string,
|
||||
signal: AbortSignal,
|
||||
) => Promise<RemoteResult<WorkspaceFileStat>>
|
||||
|
||||
/** Presence sources shared by every mention one plugin instance renders. */
|
||||
export interface PathPresenceSources {
|
||||
/**
|
||||
* Observe one path; the first subscription to an unconfirmed path starts its Host stat.
|
||||
* @param sessionId - Session whose filesystem resolves the path.
|
||||
* @param path - decoded mention path.
|
||||
* @returns the same source for the same pair until disposal.
|
||||
*/
|
||||
source(sessionId: MentionSessionId, path: string): HostObservable<PathPresence | undefined>
|
||||
/**
|
||||
* Record a path the Host has just listed, such as a picked completion candidate.
|
||||
* @param sessionId - Session whose filesystem listed the path.
|
||||
* @param path - decoded mention path.
|
||||
*/
|
||||
confirm(sessionId: MentionSessionId, path: string): void
|
||||
/** Abort outstanding stats; later subscriptions start none. */
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
presence: PathPresence | undefined
|
||||
probing: boolean
|
||||
readonly listeners: Set<() => void>
|
||||
readonly source: HostObservable<PathPresence | undefined>
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify one stat. A directory or other non-regular entry still exists;
|
||||
* failures that do not describe the path leave it unconfirmed.
|
||||
* @param result - Host stat result.
|
||||
* @returns the definitive presence, or undefined.
|
||||
*/
|
||||
function presenceOf(result: RemoteResult<WorkspaceFileStat>): PathPresence | undefined {
|
||||
if (result.ok) return 'present'
|
||||
switch (result.error.code) {
|
||||
case 'workspace-file/not-regular-file':
|
||||
return 'present'
|
||||
case 'workspace-file/not-found':
|
||||
return 'absent'
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create presence sources over one stat function.
|
||||
* @param stat - Session-authorized Host stat.
|
||||
* @returns sources the caller disposes with its plugin.
|
||||
*/
|
||||
export function createPathPresence(stat: PathStat): PathPresenceSources {
|
||||
const lifetime = new AbortController()
|
||||
const entries = new Map<string, Entry>()
|
||||
|
||||
const publish = (entry: Entry, presence: PathPresence) => {
|
||||
entry.presence = presence
|
||||
for (const listener of [...entry.listeners]) listener()
|
||||
}
|
||||
|
||||
const probe = (entry: Entry, sessionId: MentionSessionId, path: string) => {
|
||||
if (entry.probing || entry.presence !== undefined || lifetime.signal.aborted) return
|
||||
entry.probing = true
|
||||
// Cancellation and carrier faults resolve as failures; only a Remote
|
||||
// assembly fault rejects, and it surfaces as an unhandled rejection.
|
||||
void stat(sessionId, path, lifetime.signal).then((result) => {
|
||||
entry.probing = false
|
||||
const presence = presenceOf(result)
|
||||
// A confirmation recorded while this stat was outstanding is newer.
|
||||
if (presence === undefined || entry.presence !== undefined || lifetime.signal.aborted) return
|
||||
publish(entry, presence)
|
||||
})
|
||||
}
|
||||
|
||||
const entryFor = (sessionId: MentionSessionId, path: string): Entry => {
|
||||
const key = JSON.stringify([sessionId, path])
|
||||
const existing = entries.get(key)
|
||||
if (existing !== undefined) return existing
|
||||
const entry: Entry = {
|
||||
presence: undefined,
|
||||
probing: false,
|
||||
listeners: new Set(),
|
||||
source: {
|
||||
getSnapshot: () => entry.presence,
|
||||
subscribe: (listener) => {
|
||||
entry.listeners.add(listener)
|
||||
probe(entry, sessionId, path)
|
||||
return () => { entry.listeners.delete(listener) }
|
||||
},
|
||||
},
|
||||
}
|
||||
entries.set(key, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
return {
|
||||
source: (sessionId, path) => entryFor(sessionId, path).source,
|
||||
confirm(sessionId, path) {
|
||||
const entry = entryFor(sessionId, path)
|
||||
if (entry.presence !== 'present') publish(entry, 'present')
|
||||
},
|
||||
dispose() {
|
||||
lifetime.abort()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
/** Forward file and folder recognition in original text, without Facts or discovery. */
|
||||
/**
|
||||
* Forward file and folder mention candidates in original text, without Facts or discovery.
|
||||
* The node components decide whether a candidate names an existing path.
|
||||
*/
|
||||
import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
interface PathReferenceData {
|
||||
@@ -13,6 +16,15 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the path a complete `@path` or `@"quoted path"` mention names.
|
||||
* @param mention - mention spelling starting with `@`, without trailing sentence punctuation.
|
||||
* @returns the path that file and folder nodes carry.
|
||||
*/
|
||||
export function mentionPath(mention: string): string {
|
||||
return mention.slice(1).replace(/^"|"$/gu, '')
|
||||
}
|
||||
|
||||
function nextPath(text: string, from: number, folder: boolean) {
|
||||
const tokens = /(?<!\S)(@"[^"\n]+"|@[^\s]+)/gu
|
||||
tokens.lastIndex = from
|
||||
@@ -20,7 +32,7 @@ function nextPath(text: string, from: number, folder: boolean) {
|
||||
const token = match[0]
|
||||
const raw = token.startsWith('@"') ? token : token.replace(/[.,;:!?,。;:!?]+$/u, '')
|
||||
if (raw.length <= 1) continue
|
||||
const path = raw.slice(1).replace(/^"|"$/gu, '')
|
||||
const path = mentionPath(raw)
|
||||
if (path.endsWith('/') !== folder) continue
|
||||
const label = path.split(/[\\/]/u).filter(Boolean).at(-1) ?? raw.slice(1)
|
||||
return { start: match.index, end: match.index + raw.length, data: { path, label } }
|
||||
|
||||
@@ -9,7 +9,10 @@ import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts'
|
||||
import { FileReference, FolderReference, type FileReferenceInjected } from '../src/client/FileReference.tsx'
|
||||
import {
|
||||
FileReference, FolderReference, type FileReferenceInjected, type PathPresenceInjected,
|
||||
} from '../src/client/FileReference.tsx'
|
||||
import type { PathStat } from '../src/client/path-presence.ts'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { RemoteError, TestSessions } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { SessionFixture } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
@@ -99,6 +102,7 @@ async function bench(
|
||||
projectionValues?: { title?: string | null }
|
||||
}> = {},
|
||||
opening: Pick<SessionFixture, 'initialOpen' | 'snapshot'> = {},
|
||||
stat: PathStat = vi.fn<PathStat>(() => new Promise(() => {})),
|
||||
) {
|
||||
const ctx = new Context()
|
||||
ctx.provide('sidebarRight', { openResource: vi.fn() })
|
||||
@@ -119,6 +123,7 @@ async function bench(
|
||||
new RemoteService(ctx)
|
||||
ctx.provide('remote.fileReferences', { list: files })
|
||||
ctx.provide('remote.sessionReferenceResolver', { candidates: sessions })
|
||||
ctx.provide('remote.workspaceFiles', { stat })
|
||||
ctx.provide('locale', new LocaleRuntime(ctx))
|
||||
const sessionStore = new TestSessions(async (action) => { await action() }, ctx)
|
||||
onTestFinished(async () => {
|
||||
@@ -139,11 +144,17 @@ async function bench(
|
||||
return { ctx, fiber, source, sessions: sessionStore, owner }
|
||||
}
|
||||
|
||||
/** The Session-bound presence face a file or folder text node entry injects. */
|
||||
function injectedPresence(ctx: Context, key: 'file' | 'folder'): (id: SessionId) => PathPresenceInjected {
|
||||
const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === key)!
|
||||
return entry.inject as NonNullable<typeof entry.inject> & ((id: SessionId) => PathPresenceInjected)
|
||||
}
|
||||
|
||||
describe('apply', () => {
|
||||
it('declares its services and releases the @ reference registration on disposal', async () => {
|
||||
expect(inject).toEqual([
|
||||
'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences',
|
||||
'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation',
|
||||
'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation',
|
||||
])
|
||||
const { fiber } = await bench()
|
||||
let registered: InputTriggerSource | undefined
|
||||
@@ -166,6 +177,7 @@ describe('apply', () => {
|
||||
new RemoteService(ctx)
|
||||
ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) })
|
||||
ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) })
|
||||
ctx.provide('remote.workspaceFiles', { stat: vi.fn() })
|
||||
ctx.provide('locale', new LocaleRuntime(ctx))
|
||||
const sessions = new TestSessions(async (action) => { await action() }, ctx)
|
||||
onTestFinished(() => sessions.disposeScopes())
|
||||
@@ -671,6 +683,23 @@ describe('pick and codec', () => {
|
||||
await expect(source.codec?.serialize(mention, new AbortController().signal)).resolves.toBe(mention)
|
||||
})
|
||||
|
||||
it('confirms settled file and folder picks for the picking Session; a drill confirms nothing', async () => {
|
||||
const stat = vi.fn<PathStat>(() => new Promise(() => {}))
|
||||
const { ctx, source } = await bench(undefined, undefined, {}, {}, stat)
|
||||
const [directory, file] = await source.candidates(session, request(''))
|
||||
const folderFace = injectedPresence(ctx, 'folder')
|
||||
const fileFace = injectedPresence(ctx, 'file')
|
||||
drill(source, directory!)
|
||||
expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined()
|
||||
pick(source, directory!)
|
||||
pick(source, file!)
|
||||
expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBe('present')
|
||||
expect(fileFace(session.sessionId).keyedHooks.pathPresence('docs/a b.md').getSnapshot()).toBe('present')
|
||||
expect(folderFace(sid('other')).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined()
|
||||
folderFace(session.sessionId).keyedHooks.pathPresence('src/').subscribe(vi.fn())
|
||||
expect(stat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores candidates that do not carry a source-owned value', async () => {
|
||||
const { source } = await bench()
|
||||
expect(pick(source, { name: 'foreign candidate' })).toBeUndefined()
|
||||
@@ -678,6 +707,17 @@ describe('pick and codec', () => {
|
||||
})
|
||||
|
||||
describe('reference preview', () => {
|
||||
it('stats each mention through its rendering Session and aborts outstanding stats on disposal', async () => {
|
||||
const stat = vi.fn<PathStat>(() => new Promise(() => {}))
|
||||
const { ctx, fiber } = await bench(undefined, undefined, {}, {}, stat)
|
||||
injectedPresence(ctx, 'file')(session.sessionId).keyedHooks.pathPresence('LICENSE').subscribe(vi.fn())
|
||||
injectedPresence(ctx, 'folder')(sid('other')).keyedHooks.pathPresence('docs/').subscribe(vi.fn())
|
||||
expect(stat.mock.calls.map(([id, path]) => [id, path])).toEqual([['target', 'LICENSE'], ['other', 'docs/']])
|
||||
expect(stat.mock.calls.some(([, , signal]) => signal.aborted)).toBe(false)
|
||||
await fiber.dispose()
|
||||
expect(stat.mock.calls.every(([, , signal]) => signal.aborted)).toBe(true)
|
||||
})
|
||||
|
||||
it('binds each inline file action to its originating Session', async () => {
|
||||
const { ctx } = await bench()
|
||||
const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === 'file')!
|
||||
|
||||
@@ -9,15 +9,39 @@ import { en } from '../src/client/locales.ts'
|
||||
afterEach(cleanup)
|
||||
|
||||
type Props = ComponentProps<typeof FileReference>
|
||||
type Presence = ReturnType<Props['usePathPresence']>
|
||||
|
||||
function props(openFile: Props['openFile']): Props {
|
||||
function presenceHook(presence: Record<string, Presence>): Props['usePathPresence'] {
|
||||
const hook = (path: string) => presence[path]
|
||||
return hook as Props['usePathPresence']
|
||||
}
|
||||
|
||||
const PRESENT = presenceHook({ 'docs/a b.md': 'present', 'docs/': 'present' })
|
||||
|
||||
function props(openFile: Props['openFile'], usePathPresence = PRESENT): Props {
|
||||
return {
|
||||
node: { id: 'file', start: 0, end: 14, data: { path: 'docs/a b.md', label: 'a b.md' } },
|
||||
raw: '@"docs/a b.md"', interactive: true, openFile, t: makeTranslate(en),
|
||||
raw: '@"docs/a b.md"', interactive: true, openFile, usePathPresence, t: makeTranslate(en),
|
||||
} as Props
|
||||
}
|
||||
|
||||
describe('FileReference', () => {
|
||||
it('keeps the original spelling until the Host confirms the path exists', () => {
|
||||
const openFile = vi.fn()
|
||||
const folder = { id: 'folder', start: 0, end: 6, data: { path: 'docs/', label: 'docs' } } as const
|
||||
for (const presence of [undefined, 'absent'] as const) {
|
||||
const usePathPresence = presenceHook({ 'docs/a b.md': presence, 'docs/': presence })
|
||||
const view = render(<>
|
||||
<FileReference {...props(openFile, usePathPresence)} />
|
||||
<FolderReference {...props(openFile, usePathPresence)} node={folder} raw="@docs/" />
|
||||
</>)
|
||||
expect(view.container.textContent).toBe('@"docs/a b.md"@docs/')
|
||||
expect(view.container.querySelector('[data-ref-chip]')).toBeNull()
|
||||
view.unmount()
|
||||
}
|
||||
expect(openFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the decoded path and leaves summaries and folders non-interactive', () => {
|
||||
const openFile = vi.fn()
|
||||
const input = props(openFile)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { createPathPresence, type MentionSessionId, type PathStat } from '../src/client/path-presence.ts'
|
||||
|
||||
const sid = (value: string): MentionSessionId => value as MentionSessionId
|
||||
const STAT: WorkspaceFileStat = { absolutePath: '/w/LICENSE', version: 'v1' }
|
||||
|
||||
interface StatCall {
|
||||
readonly sessionId: MentionSessionId
|
||||
readonly path: string
|
||||
readonly signal: AbortSignal
|
||||
readonly resolve: (result: RemoteResult<WorkspaceFileStat>) => void
|
||||
}
|
||||
|
||||
function deferredStat() {
|
||||
const calls: StatCall[] = []
|
||||
const stat = vi.fn<PathStat>((sessionId, path, signal) => new Promise((resolve) => {
|
||||
calls.push({ sessionId, path, signal, resolve })
|
||||
}))
|
||||
return { stat, calls }
|
||||
}
|
||||
|
||||
const failure = (error: RemoteFailure): RemoteResult<WorkspaceFileStat> => ({ ok: false, error })
|
||||
|
||||
describe('createPathPresence', () => {
|
||||
it('shares one stat per Session and path and publishes the Host answer to every subscriber', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'LICENSE')
|
||||
expect(presence.source(sid('a'), 'LICENSE')).toBe(source)
|
||||
expect(presence.source(sid('b'), 'LICENSE')).not.toBe(source)
|
||||
expect(source.getSnapshot()).toBeUndefined()
|
||||
expect(stat).not.toHaveBeenCalled()
|
||||
const first = vi.fn()
|
||||
const second = vi.fn()
|
||||
const unsubscribe = source.subscribe(first)
|
||||
source.subscribe(second)
|
||||
expect(calls.map(call => [call.sessionId, call.path])).toEqual([['a', 'LICENSE']])
|
||||
unsubscribe()
|
||||
calls[0]!.resolve({ ok: true, value: STAT })
|
||||
await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') })
|
||||
expect(first).not.toHaveBeenCalled()
|
||||
expect(second).toHaveBeenCalledOnce()
|
||||
source.subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('treats a non-regular entry as present, a missing entry as absent, and retries any other failure', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const folder = presence.source(sid('a'), 'docs/')
|
||||
const missing = presence.source(sid('a'), 'ceshi')
|
||||
const offline = presence.source(sid('a'), 'notes.md')
|
||||
folder.subscribe(vi.fn())
|
||||
missing.subscribe(vi.fn())
|
||||
offline.subscribe(vi.fn())
|
||||
calls[0]!.resolve(failure(new RemoteError('workspace-file/not-regular-file', 'directory', { path: 'docs/', kind: 'directory' })))
|
||||
calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'ceshi' })))
|
||||
calls[2]!.resolve(failure(new RemoteError('gateway/internal', 'offline', {})))
|
||||
await vi.waitFor(() => { expect(missing.getSnapshot()).toBe('absent') })
|
||||
expect(folder.getSnapshot()).toBe('present')
|
||||
expect(offline.getSnapshot()).toBeUndefined()
|
||||
offline.subscribe(vi.fn())
|
||||
expect(calls.map(call => call.path)).toEqual(['docs/', 'ceshi', 'notes.md', 'notes.md'])
|
||||
calls[3]!.resolve({ ok: true, value: STAT })
|
||||
await vi.waitFor(() => { expect(offline.getSnapshot()).toBe('present') })
|
||||
})
|
||||
|
||||
it('lets a picked confirmation stand over an older outstanding stat and over an earlier absence', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'new.md')
|
||||
const listener = vi.fn()
|
||||
source.subscribe(listener)
|
||||
presence.confirm(sid('a'), 'new.md')
|
||||
presence.confirm(sid('a'), 'new.md')
|
||||
expect(source.getSnapshot()).toBe('present')
|
||||
expect(listener).toHaveBeenCalledOnce()
|
||||
calls[0]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'new.md' })))
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(source.getSnapshot()).toBe('present')
|
||||
|
||||
const created = presence.source(sid('a'), 'later.md')
|
||||
created.subscribe(vi.fn())
|
||||
calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'later.md' })))
|
||||
await vi.waitFor(() => { expect(created.getSnapshot()).toBe('absent') })
|
||||
presence.confirm(sid('a'), 'later.md')
|
||||
expect(created.getSnapshot()).toBe('present')
|
||||
const picked = presence.source(sid('a'), 'picked.md')
|
||||
presence.confirm(sid('a'), 'picked.md')
|
||||
picked.subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('aborts outstanding stats on disposal, drops their answers, and starts no further stats', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'LICENSE')
|
||||
const listener = vi.fn()
|
||||
source.subscribe(listener)
|
||||
presence.dispose()
|
||||
expect(calls[0]!.signal.aborted).toBe(true)
|
||||
calls[0]!.resolve({ ok: true, value: STAT })
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(source.getSnapshot()).toBeUndefined()
|
||||
expect(listener).not.toHaveBeenCalled()
|
||||
presence.source(sid('a'), 'other.md').subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
{"type":"session","version":4,"id":"{{session:1}}","createdAt":1792123530041,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"}
|
||||
{"type":"permission/preset","data":{"preset":"workspace-write"}}
|
||||
{"type":"sandbox/mode","data":{"mode":"workspace-write"}}
|
||||
{"type":"approval/policy","data":{"policy":"ask"}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"@ceshi @随便写点文字 @LICENSE @docs/ mail@host"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"@ceshi @随便写点文字 @LICENSE @docs/ mail@host"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}}
|
||||
{"type":"session/title","data":{"title":"@ceshi @随便写点文字 @LICENSE @doc","messageSeqs":[8],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"Reference display checked."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":256,"outputTokens":5},"stream":[{"type":"chunk","time":1792123531296,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792123531307,"index":0,"dt":[],"texts":["Reference display checked."]},{"type":"chunk","time":1792123531318,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Reference display checked."}}},{"type":"chunk","time":1792123531330,"chunk":{"type":"usage","usage":{"inputTokens":256,"outputTokens":5}}},{"type":"chunk","time":1792123531340,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
@@ -0,0 +1,7 @@
|
||||
version: 1
|
||||
scenario: mention-path-presence
|
||||
profile: web
|
||||
composition: web-default
|
||||
recording: authored
|
||||
header:
|
||||
class: web-default
|
||||
@@ -0,0 +1,27 @@
|
||||
- banner:
|
||||
- navigation "Session hierarchy": "@ceshi @随便写点文字 @LICENSE @doc"
|
||||
- text: Standard mode
|
||||
- button "More actions"
|
||||
- tablist:
|
||||
- tab "Chat" [selected]
|
||||
- tab "Trajectory"
|
||||
- text: "@ceshi @随便写点文字"
|
||||
- button "LICENSE"
|
||||
- text: docs mail@host {{clock}}
|
||||
- button "Copy"
|
||||
- status: Completed
|
||||
- button "Completed in {{duration}}" [disabled]
|
||||
- paragraph: Reference display checked.
|
||||
- button "Copy"
|
||||
- button "Good response"
|
||||
- button "Bad response"
|
||||
- button "Branch into a new conversation"
|
||||
- text: {{clock}}
|
||||
- textbox "Message or run a task, / commands, @ files or sessions"
|
||||
- button "Add files or run commands"
|
||||
- 'button "Access mode, current: Workspace Write"': Workspace Write
|
||||
- button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash
|
||||
- button "Send message" [disabled]
|
||||
- button "1 turns 1 steps · {{throughput}} tok/s": 1 turns 1 steps{{throughput}} tok/s
|
||||
- button "261 tok · Cache hit 0%": 261 tokCache hit 0%
|
||||
- button "0% of context used": 0%
|
||||
@@ -150,6 +150,7 @@
|
||||
"apps/web/tests/markdown-file-links.e2e.ts",
|
||||
"apps/web/tests/user-text-secret-mask.e2e.ts",
|
||||
"apps/web/tests/reference-composer.e2e.ts",
|
||||
"apps/web/tests/mention-path-presence.e2e.ts",
|
||||
"apps/web/tests/markdown-wide-table.e2e.ts",
|
||||
"apps/web/tests/thinking-markdown.e2e.ts",
|
||||
"apps/web/tests/math-rendering.e2e.ts",
|
||||
|
||||
Reference in new issue
Block a user