fix(ui-chat): 按消息当时的工作目录解析相对图片与链接
working-directory 新增 workingDirectoryHistory 投影:header 目录(seq 0)与每次 working-directory/change 的 seq 和目录,不进会话摘要。ui-primitives 新增 MarkdownPathScope,在本地目标交给委托前先解析;助手节点按自身 anchorSeq 取当时目录,cd 前后的消息各自解析到正确文件,重开会话后依旧成立。 Refs #8267
This commit is contained in:
1 parent
5d42b877c1
commit
d7ecf4b9ea
31 files changed
+243
-81
No files matched your search
@@ -5008,7 +5008,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-working-directory`
|
||||
|
||||
- `inject`: `fs` · `sessionProjections` · `systemPrompt`
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:64`](../packages/session/working-directory/src/index.ts)
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:65`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment default for Sessions without an original project directory. */
|
||||
|
||||
@@ -5010,7 +5010,7 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-working-directory`
|
||||
|
||||
- `inject`: `fs` · `sessionProjections` · `systemPrompt`
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:64`](../packages/session/working-directory/src/index.ts)
|
||||
- `source`: [`packages/session/working-directory/src/index.ts:65`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment default for Sessions without an original project directory. */
|
||||
|
||||
@@ -98,7 +98,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:33`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:34`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` |
|
||||
| `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` |
|
||||
| `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
|
||||
@@ -100,7 +100,7 @@
|
||||
| `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) |
|
||||
| `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:33`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` |
|
||||
| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:34`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` |
|
||||
| `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
| `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` |
|
||||
| `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) |
|
||||
|
||||
@@ -300,8 +300,8 @@
|
||||
en: e8dd0cebbb930eb7
|
||||
zh: e8dd0cebbb930eb7
|
||||
/session-persistence-event-catalog/events/working-directory/working-directory-change-log-only:
|
||||
en: bf12683fa0fe3dfa
|
||||
zh: 79a678a53cee33b9
|
||||
en: fbdf3777f155f458
|
||||
zh: 98dc9a9351c07415
|
||||
/session-persistence-event-catalog/events/workspace:
|
||||
en: 63ee1a85e4b59ae3
|
||||
zh: 63ee1a85e4b59ae3
|
||||
@@ -1494,8 +1494,8 @@
|
||||
en: bef51e0442ebb903
|
||||
zh: 240ebeb160533d8c
|
||||
/session-persistence-event-catalog/resolved-persistence-types/cwd:
|
||||
en: 166c1be5f6237f1b
|
||||
zh: 5002d35a2ec5fb1e
|
||||
en: 6a6f06c1421739c3
|
||||
zh: 0e28ae71c2e84a1d
|
||||
/session-persistence-event-catalog/resolved-persistence-types/decision-durationms-exitcode-handlerid:
|
||||
en: a99ac57bbec0370f
|
||||
zh: 9073329e324a66e0
|
||||
@@ -1929,8 +1929,8 @@
|
||||
en: 0b74295f7c5c8f11
|
||||
zh: 5f1213cec87f6be0
|
||||
/session-persistence-event-catalog/resolved-persistence-types/kind-working-directory:
|
||||
en: a36b909ecbd38156
|
||||
zh: b02edb123e72fbb1
|
||||
en: f688f9a75f549c23
|
||||
zh: 03ccb103398fc27b
|
||||
/session-persistence-event-catalog/resolved-persistence-types/max-tokens-messages-model-thinking:
|
||||
en: 3216b23c131d0070
|
||||
zh: 73ca171c6014f16e
|
||||
|
||||
@@ -1329,7 +1329,7 @@ Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/
|
||||
}
|
||||
```
|
||||
|
||||
Source: [`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts)
|
||||
Source: [`packages/session/working-directory/src/index.ts:57`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
### `workspace/*`
|
||||
|
||||
@@ -6209,7 +6209,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:24`](../packages/compacti
|
||||
|
||||
SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582`
|
||||
|
||||
Sources: [`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts)
|
||||
Sources: [`packages/session/working-directory/src/index.ts:57`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
@@ -7949,7 +7949,7 @@ Sources: [`packages/experimental/webhook/src/types.ts:74`](../packages/experimen
|
||||
|
||||
SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5`
|
||||
|
||||
Sources: [`packages/session/working-directory/src/index.ts:49`](../packages/session/working-directory/src/index.ts)
|
||||
Sources: [`packages/session/working-directory/src/index.ts:50`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
|
||||
@@ -1331,7 +1331,7 @@ export type SessionEvent<T extends SessionEventType = SessionEventType> = {
|
||||
}
|
||||
```
|
||||
|
||||
来源:[`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts)
|
||||
来源:[`packages/session/working-directory/src/index.ts:57`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
### `workspace/*`
|
||||
|
||||
@@ -6211,7 +6211,7 @@ SHA-256: `3e4e7683b0192c9f0e6a75c59076108f017892cdb302a98032c2632fd79c356f`
|
||||
|
||||
SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582`
|
||||
|
||||
来源:[`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts)
|
||||
来源:[`packages/session/working-directory/src/index.ts:57`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
@@ -7951,7 +7951,7 @@ SHA-256: `9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94`
|
||||
|
||||
SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5`
|
||||
|
||||
来源:[`packages/session/working-directory/src/index.ts:49`](../packages/session/working-directory/src/index.ts)
|
||||
来源:[`packages/session/working-directory/src/index.ts:50`](../packages/session/working-directory/src/index.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
|
||||
Generated
+2
-2
@@ -159,7 +159,7 @@
|
||||
{"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]},
|
||||
{"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:121"]},
|
||||
{"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]},
|
||||
{"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:49"]},
|
||||
{"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:50"]},
|
||||
{"digest":"224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc","names":[],"sources":[]},
|
||||
{"digest":"234142ee4f996f38cc9fa3b8b3e3de29b03c9aefe5ebf6c224eddd564505aa85","names":[],"sources":[]},
|
||||
{"digest":"237c004c73b6b288246816e0d7fde16e09c63a47aa3b1227383d7afe58666163","names":[],"sources":[]},
|
||||
@@ -607,7 +607,7 @@
|
||||
{"digest":"d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241","names":[],"sources":[]},
|
||||
{"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:29"]},
|
||||
{"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]},
|
||||
{"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:56"]},
|
||||
{"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:57"]},
|
||||
{"digest":"dacf3d5f3e4ff619c1320e64a48dec5e7ecd7870bece65fbd449a0e63adfa521","names":[],"sources":[]},
|
||||
{"digest":"db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c","names":[],"sources":[]},
|
||||
{"digest":"db6c5246911d47a7969f6b4cb47c7d0dbbde75c402710b22ace3672fa97bebe0","names":[],"sources":[]},
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 41cd21266011d571
|
||||
zh: 3172d1a2acbb27b7
|
||||
/deepseek-ai-dsh-client-ui-chat/reference-previews:
|
||||
en: 5d88ffc61638ee14
|
||||
zh: 32265e3d953c9389
|
||||
en: 90e75f3a18a86854
|
||||
zh: bb7b0a10050de9aa
|
||||
/deepseek-ai-dsh-client-ui-chat/hidden-chat-rows:
|
||||
en: 8ca277dc7fed699f
|
||||
zh: 167478dba50f3904
|
||||
|
||||
@@ -37,7 +37,7 @@ Image drag actions arrive through the image entry’s inject face from [ui-file-
|
||||
|
||||
Sent generic-file attachments retain the draft's [file-card radius](../../../docs/ui-radius.md#radius-scale).
|
||||
|
||||
`ChatView` supplies file and HTTP(S) navigation through the existing `MarkdownDelegateProvider` around its node list, passing `requestOpenFile`, `openExternalLink`, and `fileImages` directly. Its file opener retains Chat's failure feedback and retry handling. Assistant Markdown file links open in the right Sidebar after the message settles, including references to unmodified files. Relative link and image paths resolve from the viewed Session's current working directory, or its workspace root when none is recorded; absolute paths retain the same Session's filesystem access. [Supported Markdown line references](../ui-primitives/README.md#rendering-agent-output) navigate to the first specified line and reuse an existing file tab. Missing files show the preview's error state.
|
||||
`ChatView` supplies file and HTTP(S) navigation through the existing `MarkdownDelegateProvider` around its node list, passing `requestOpenFile`, `openExternalLink`, and `fileImages` directly. Its file opener retains Chat's failure feedback and retry handling. Assistant Markdown file links open in the right Sidebar after the message settles, including references to unmodified files. Relative link and image paths in an Assistant message resolve from the directory that was current when the message was written, using the `workingDirectoryHistory` projection; without that history they resolve from the Session's current working directory, or its workspace root when none is recorded; absolute paths retain the same Session's filesystem access. [Supported Markdown line references](../ui-primitives/README.md#rendering-agent-output) navigate to the first specified line and reuse an existing file tab. Missing files show the preview's error state.
|
||||
|
||||
`ChatView` also passes `renderCode`, so each Markdown fence in the Chat flow that has a language and content renders through the session-scoped `conversation.chat.markdown.fence` hoc slot. Its `entryKey` is the lowercased fence language, and its owner props carry that `lang`, the fence `code`, the `streaming` state, and `meta`, the rest of the info string when present. The slot content is a plain code block without unified-diff rows, so a language without a layer renders as code. Chat registers layers for `math`, which shows the source while the message streams and display TeX after it settles, and for `diff` and `patch`, which render unified-diff rows in place of the content. Other plugins add a language by registering a layer whose `key` is the lowercased language: a layer that omits `children` replaces the code block, a layer that renders `children` decorates it, and either may parse its own parameters from `meta`.
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ kind: "package-reference"
|
||||
|
||||
已发送的普通文件附件保留草稿中的[文件卡片圆角](../../../docs/ui-radius.zh.md#radius-scale)。
|
||||
|
||||
`ChatView` 通过节点列表外围既有的 `MarkdownDelegateProvider` 提供文件及 HTTP(S) 导航,直接传入 `requestOpenFile`、`openExternalLink` 和 `fileImages`。文件打开动作保留 Chat 的失败反馈与重试处理。Assistant Markdown 文件链接在消息落定后可于右侧栏打开,包括未修改文件的引用。相对链接与图片路径基于当前查看的 Session 的当前工作目录解析,未记录时回落到其工作区根目录;绝对路径仍使用同一 Session 的文件系统访问。[支持的 Markdown 行号引用](../ui-primitives/README.zh.md#rendering-agent-output)定位到指定起始行,并复用现有文件标签。文件缺失时显示预览错误状态。
|
||||
`ChatView` 通过节点列表外围既有的 `MarkdownDelegateProvider` 提供文件及 HTTP(S) 导航,直接传入 `requestOpenFile`、`openExternalLink` 和 `fileImages`。文件打开动作保留 Chat 的失败反馈与重试处理。Assistant Markdown 文件链接在消息落定后可于右侧栏打开,包括未修改文件的引用。Assistant 消息中的相对链接与图片路径按该消息写下时的当前目录解析(取自 `workingDirectoryHistory` 投影);没有该历史时按 Session 的当前工作目录解析,未记录时回落到其工作区根目录;绝对路径仍使用同一 Session 的文件系统访问。[支持的 Markdown 行号引用](../ui-primitives/README.zh.md#rendering-agent-output)定位到指定起始行,并复用现有文件标签。文件缺失时显示预览错误状态。
|
||||
|
||||
`ChatView` 还传入 `renderCode`,因此 Chat 消息流中带语言且有内容的每个 Markdown 围栏都经由 session 作用域的 `conversation.chat.markdown.fence` hoc slot 渲染。其 `entryKey` 为小写的围栏语言,owner props 携带该 `lang`、围栏 `code`、`streaming` 状态,以及存在时为 info string 其余部分的 `meta`。slot 内容是不带统一 diff 行的普通代码块,因此没有对应层的语言按代码渲染。Chat 自带 `math` 层,消息流式输出时显示源码,落定后显示行间 TeX;还自带 `diff` 与 `patch` 层,以统一 diff 行代替内容渲染。其他插件注册 `key` 为小写语言的层即可接入该语言:不渲染 `children` 的层替换代码块,渲染 `children` 的层装饰代码块,两者都可以自行从 `meta` 解析参数。
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { memo, useCallback, useMemo } from 'react'
|
||||
import { MarkdownPathScope } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory/client'
|
||||
import type { ChatFileMentions, ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from '../contract/slots.ts'
|
||||
import { AssistantMarkdown } from './AssistantMarkdown.tsx'
|
||||
import { directoryAt } from './directory-at.ts'
|
||||
|
||||
/** Business readers owned by the assistant renderer's existing Slot registration. */
|
||||
export interface AssistantNodeInjected extends PresentationInjected {
|
||||
@@ -17,7 +21,7 @@ type AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace<A
|
||||
/** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */
|
||||
export const AssistantNodeView = memo(function AssistantNodeView({
|
||||
node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, loadImage, fileMentions,
|
||||
usePresentation, renderSlot, t, sessionId, useContextMenu, resolveFilePath,
|
||||
usePresentation, renderSlot, t, sessionId, useContextMenu, resolveFilePath, useProjection,
|
||||
}: AssistantNodeViewProps) {
|
||||
const { getTriggerProps } = useContextMenu()
|
||||
const getFileTriggerProps = useCallback((path: string) => getTriggerProps(() => ({
|
||||
@@ -46,22 +50,30 @@ export const AssistantNodeView = memo(function AssistantNodeView({
|
||||
: turnProcess.spec.answerStep === data.step && turnProcess.spec.inlineReasoning)
|
||||
&& !turnProcess.open
|
||||
const revealProcess = useCallback(() => { turnProcess?.setOpen(true) }, [turnProcess])
|
||||
// Relative destinations name files in the directory that was current when this message was written.
|
||||
const directory = useProjection('workingDirectoryHistory', history => directoryAt(history, node.anchorSeq))
|
||||
const resolvePath = useCallback(
|
||||
(path: string) => directory === undefined ? path : resolveWorkspacePath(directory, path),
|
||||
[directory],
|
||||
)
|
||||
return (
|
||||
<AssistantMarkdown
|
||||
blocks={data.blocks}
|
||||
groupPart={groupPart}
|
||||
useDisclosure={useDisclosure}
|
||||
streaming={data.status === 'running'}
|
||||
textInteractionSource={data.status === 'settled' && data.finalNode?.messageId !== undefined}
|
||||
interrupted={data.status === 'interrupted'}
|
||||
loadImage={loadImage}
|
||||
reasoningHidden={reasoningHidden}
|
||||
useGroupAction={useGroupAction}
|
||||
usePresentation={usePresentation}
|
||||
renderSlot={renderSlot}
|
||||
revealProcess={revealProcess}
|
||||
mentions={mentions}
|
||||
t={t}
|
||||
/>
|
||||
<MarkdownPathScope resolvePath={resolvePath}>
|
||||
<AssistantMarkdown
|
||||
blocks={data.blocks}
|
||||
groupPart={groupPart}
|
||||
useDisclosure={useDisclosure}
|
||||
streaming={data.status === 'running'}
|
||||
textInteractionSource={data.status === 'settled' && data.finalNode?.messageId !== undefined}
|
||||
interrupted={data.status === 'interrupted'}
|
||||
loadImage={loadImage}
|
||||
reasoningHidden={reasoningHidden}
|
||||
useGroupAction={useGroupAction}
|
||||
usePresentation={usePresentation}
|
||||
renderSlot={renderSlot}
|
||||
revealProcess={revealProcess}
|
||||
mentions={mentions}
|
||||
t={t}
|
||||
/>
|
||||
</MarkdownPathScope>
|
||||
)
|
||||
})
|
||||
@@ -100,7 +100,7 @@ export function ChatView({
|
||||
const inbox = useProjection('inbox') as InboxState | undefined
|
||||
// Workspace root off the session list row: path summaries display relative to it.
|
||||
const rootCwd = useSessions(s => s.byId[sessionId]?.cwd)
|
||||
// Relative images resolve like file links: from the current directory, else that root.
|
||||
// Images outside a message's path scope resolve like file links: from the current directory, else that root.
|
||||
const imageCwd = useProjection('workingDirectory') ?? rootCwd
|
||||
const fileImages = useMemo(() => ({
|
||||
fileDrag,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Select the working directory that applied at one Session log position. */
|
||||
import type { WorkingDirectoryHistoryEntry } from '@deepseek-ai/dsh-working-directory/client'
|
||||
|
||||
/**
|
||||
* Find the directory in effect for an event: the last history entry whose seq
|
||||
* precedes the event's seq.
|
||||
* @param history - Ascending directory history, or undefined while it is unavailable.
|
||||
* @param seq - Seq of the event whose recorded paths are being resolved.
|
||||
* @returns the absolute directory, or undefined when no entry precedes `seq`.
|
||||
*/
|
||||
export function directoryAt(history: readonly WorkingDirectoryHistoryEntry[] | undefined, seq: number): string | undefined {
|
||||
let found: string | undefined
|
||||
for (const entry of history ?? []) {
|
||||
if (entry.seq >= seq) break
|
||||
found = entry.cwd
|
||||
}
|
||||
return found
|
||||
}
|
||||
@@ -789,29 +789,42 @@ describe('Chat node rendering', () => {
|
||||
expect(h.openFile).toHaveBeenCalledWith('src/index.ts', { line: 24 })
|
||||
})
|
||||
|
||||
it('resolves relative Markdown images from the Session\'s current working directory', () => {
|
||||
it('resolves each message\'s relative images and links from the directory current when it was written', () => {
|
||||
const h = makeHarness({
|
||||
nodes: [user(1, 'draw'), assistant(2, '', 1)],
|
||||
turnEnds: new Map([[1, 2]]),
|
||||
nodes: [
|
||||
user(1, 'draw'), assistant(2, ' [notes](notes.md)', 1),
|
||||
user(6, 'again'), assistant(7, ' [notes again](notes.md)', 2),
|
||||
],
|
||||
turnEnds: new Map([[1, 2], [2, 7]]),
|
||||
})
|
||||
const sessions = createSnapshotStore<SessionListState>({
|
||||
ids: [SID], phase: 'ready', projectionsBySession: {},
|
||||
byId: { [SID]: { id: SID, displayTitle: 'proj', cwd: '/proj', running: false, blank: false, updatedAt: 1, retainedBy: {} } },
|
||||
})
|
||||
h.props.useSessions = bindSnapshotSelector(sessions)
|
||||
const directory = createSnapshotStore<string | null>('/proj/.agents/worktrees/w')
|
||||
const useDirectory = bindSnapshotSelector(directory)
|
||||
const projections = createSnapshotStore<Record<string, unknown>>({
|
||||
workingDirectory: '/proj/w',
|
||||
workingDirectoryHistory: [{ seq: 0, cwd: '/proj' }, { seq: 4, cwd: '/proj/w' }],
|
||||
})
|
||||
const useProjections = bindSnapshotSelector(projections)
|
||||
const useOther = h.props.useProjection
|
||||
h.props.useProjection = (key: 'inbox' | 'workingDirectory') => {
|
||||
const current = useDirectory(value => value)
|
||||
h.props.useProjection = (key: 'inbox', selector?: (value: never) => unknown) => {
|
||||
const value: unknown = useProjections(values => values[key])
|
||||
const other: unknown = useOther(key)
|
||||
return key === 'workingDirectory' ? current : other
|
||||
const picked = key in projections.getSnapshot() ? value : other
|
||||
return selector === undefined ? picked : selector(picked as never)
|
||||
}
|
||||
const view = render(<h.ChatView {...h.props} />)
|
||||
const source = () => new URL(view.getByRole('img', { name: 'chart' }).getAttribute('src')!, document.baseURI).searchParams.get('path')
|
||||
expect(source()).toBe('/proj/.agents/worktrees/w/tmp/a.png')
|
||||
act(() => { directory.set(null) })
|
||||
expect(source()).toBe('/proj/tmp/a.png')
|
||||
const source = (name: string) => new URL(view.getByRole('img', { name }).getAttribute('src')!, document.baseURI).searchParams.get('path')
|
||||
expect(source('before')).toBe('/proj/tmp/a.png')
|
||||
expect(source('after')).toBe('/proj/w/tmp/a.png')
|
||||
fireEvent.click(view.getByRole('button', { name: 'notes' }))
|
||||
expect(h.openFile).toHaveBeenLastCalledWith('/proj/notes.md')
|
||||
fireEvent.click(view.getByRole('button', { name: 'notes again' }))
|
||||
expect(h.openFile).toHaveBeenLastCalledWith('/proj/w/notes.md')
|
||||
// Without a history, relative destinations fall back to the current directory.
|
||||
act(() => { projections.set({ workingDirectory: '/proj/w', workingDirectoryHistory: undefined }) })
|
||||
expect(source('before')).toBe('/proj/w/tmp/a.png')
|
||||
})
|
||||
|
||||
it('threads the injected file-mention vocabulary into the closing prose only', () => {
|
||||
|
||||
@@ -24,8 +24,8 @@
|
||||
en: 8265fa792c6fd9ec
|
||||
zh: 600d2af4d5a3d183
|
||||
/deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output:
|
||||
en: e2649937f077d4e0
|
||||
zh: 6ad604cb5adfc16b
|
||||
en: 67e5b615e786f933
|
||||
zh: ae8ef437861393b7
|
||||
/deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy:
|
||||
en: 3fd7072b662eed0a
|
||||
zh: 88c6c299c0a6f8cd
|
||||
|
||||
@@ -125,7 +125,7 @@ Explicit `./`, `../`, slash/backslash-rooted paths (including UNC), and Windows
|
||||
|
||||
`JsonTree` clamps collapsed strings to `collapsedStringLines` (three by default). Expanded strings show raw text, retain sibling commas, and fit within the window and outer scrolling containers. Resize and ancestor-scroll events update that limit. Row copy feedback updates independently of JSON value rendering; pending clipboard writes cannot update a different row or an unmounted tree.
|
||||
|
||||
`ImageLightbox` is the shared original-image modal with focus restoration and Escape dismissal. Like `Modal`, its mask leaves the Windows caption unpainted, and its close control sits 20px below the caption. The internal thumbnail renderer receives loading/failure labels from its owner. `HoverCard.inline` keeps a file link in the text flow and uses the shared menu material, keyboard-visible focus, and placement above or below the anchor without covering it. Its transparent hover region connects the anchor to the panel across the visual gap, so crossing the gap does not activate content beneath it. Escape closes an open thumbnail even when focus is elsewhere; subsequent Escape presses reach the owner. `MarkdownDelegateProvider.fileImages` supplies a decoded-path resolver and complete image labels: settled image links gain hover previews, and standalone images gain lightbox activation. Image-only anchors retain their single navigation target. The parser recovers only complete, unescaped, standalone local image references with bare spaces and an unambiguous supported image suffix; code and ambiguous destinations remain literal.
|
||||
`ImageLightbox` is the shared original-image modal with focus restoration and Escape dismissal. Like `Modal`, its mask leaves the Windows caption unpainted, and its close control sits 20px below the caption. The internal thumbnail renderer receives loading/failure labels from its owner. `HoverCard.inline` keeps a file link in the text flow and uses the shared menu material, keyboard-visible focus, and placement above or below the anchor without covering it. Its transparent hover region connects the anchor to the panel across the visual gap, so crossing the gap does not activate content beneath it. Escape closes an open thumbnail even when focus is elsewhere; subsequent Escape presses reach the owner. `MarkdownDelegateProvider.fileImages` supplies a decoded-path resolver and complete image labels: settled image links gain hover previews, and standalone images gain lightbox activation. `MarkdownPathScope` maps each decoded local destination of the enclosed Markdown before it reaches the delegate's file opener, image resolver, drag address, and object menus; rendered labels and alt text keep the authored path, the nearest scope wins, and destinations outside a scope pass unchanged. Image-only anchors retain their single navigation target. The parser recovers only complete, unescaped, standalone local image references with bare spaces and an unambiguous supported image suffix; code and ambiguous destinations remain literal.
|
||||
|
||||
`DraggableImage` receives explicit `fileDrag: FileDragActions`, also supplied through `MarkdownDelegateProvider.fileImages.fileDrag`. The [file-drag plugin](../ui-file-drag/README.md) owns preparation, transfer, and localized failure feedback; the image primitive manages gestures and cancellation. Resource-backed images prepare on primary pointer down; other sources also prepare on hover. Releasing inside the image preserves preparation for the next gesture; pointer leave releases unused preparation. Markdown export names use the decoded path basename. Panning images skip preparation. Starting before preparation finishes cancels that gesture quietly; an actual preparation failure reports a retry message. Managed Web transfers carry an application-local token and a `DownloadURL` pointing to a plugin-owned Blob URL, with no `text/plain` payload.
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ kind: "package-library"
|
||||
|
||||
`JsonTree` 把折叠字符串限制为 `collapsedStringLines` 行(默认三行)。展开后显示原始文本、保留同级逗号,并限制在窗口与外层滚动容器内;尺寸变化和祖先滚动事件会更新此限制。行复制反馈独立于 JSON 值渲染更新;尚未完成的剪贴板写入不会更新另一行或已卸载的树。
|
||||
|
||||
`ImageLightbox` 是共享原图浮层,支持焦点恢复与 Esc 关闭。与 `Modal` 相同,其遮罩不覆盖 Windows 顶栏,关闭按钮位于顶栏下方 20px。包内缩略图渲染器由调用方提供加载及失败文案。`HoverCard.inline` 使文件链接保持在文本流内,并使用共享菜单材质、键盘可见焦点,并在锚点上方或下方定位而不遮挡锚点。即使焦点位于其他位置,Esc 也会关闭已打开的缩略图;后续 Esc 按键继续传给 owner。`MarkdownDelegateProvider.fileImages` 提供已解码路径解析器与完整图片文案:消息落定后的图片链接支持悬停预览,独立图片支持点击放大。仅包含图片的链接保留单一导航目标。解析器仅恢复完整、未转义、独立成段且带明确图片扩展名的含裸空格本地图片引用;代码与有歧义的目标保持原文。 透明悬停区域连接锚点与弹层之间的视觉空隙,鼠标经过时不会激活下方内容。
|
||||
`ImageLightbox` 是共享原图浮层,支持焦点恢复与 Esc 关闭。与 `Modal` 相同,其遮罩不覆盖 Windows 顶栏,关闭按钮位于顶栏下方 20px。包内缩略图渲染器由调用方提供加载及失败文案。`HoverCard.inline` 使文件链接保持在文本流内,并使用共享菜单材质、键盘可见焦点,并在锚点上方或下方定位而不遮挡锚点。即使焦点位于其他位置,Esc 也会关闭已打开的缩略图;后续 Esc 按键继续传给 owner。`MarkdownDelegateProvider.fileImages` 提供已解码路径解析器与完整图片文案:消息落定后的图片链接支持悬停预览,独立图片支持点击放大。`MarkdownPathScope` 会在所包含 Markdown 的每个已解码本地目标到达委托的文件打开、图片解析、拖放地址与对象菜单之前先做映射;显示的文字与 alt 仍保留原文路径,最近的作用域生效,作用域之外的目标原样传递。仅包含图片的链接保留单一导航目标。解析器仅恢复完整、未转义、独立成段且带明确图片扩展名的含裸空格本地图片引用;代码与有歧义的目标保持原文。 透明悬停区域连接锚点与弹层之间的视觉空隙,鼠标经过时不会激活下方内容。
|
||||
|
||||
`DraggableImage` 接收显式的 `fileDrag: FileDragActions`,受管理的 Markdown 图片通过 `MarkdownDelegateProvider.fileImages.fileDrag` 接收同一组回调。[文件拖放插件](../ui-file-drag/README.zh.md) 负责准备、传递与本地化失败提示;图片原语负责手势和取消。带资源引用的图片仅在主指针按下时准备,其他来源也可在悬停时准备。在图片内松开保留准备供下一次手势使用;指针移开释放未使用的准备,平移模式跳过准备。Markdown 导出名取已解码路径的文件名。在准备完成前起拖会静默取消本次手势;实际准备失败才显示重试提示。受管理的 Web 拖放携带应用内令牌和指向插件所持 Blob URL 的 `DownloadURL`,不设置 `text/plain`。
|
||||
|
||||
|
||||
@@ -119,8 +119,8 @@ export type { CodeBlockProps } from './markdown/CodeBlock.tsx'
|
||||
export { FenceCodeBlock, FenceMathBlock } from './markdown/FenceBlocks.tsx'
|
||||
export type { FenceCodeBlockProps } from './markdown/FenceBlocks.tsx'
|
||||
export { JsonBlock } from './markdown/JsonBlock.tsx'
|
||||
export { MarkdownDelegateProvider, useMarkdownDelegate } from './markdown/MarkdownDelegate.tsx'
|
||||
export type { MarkdownDelegate, MarkdownDelegateProviderProps, MarkdownExternalLinkHandler, MarkdownDelegateFenceInfo } from './markdown/MarkdownDelegate.tsx'
|
||||
export { MarkdownDelegateProvider, MarkdownPathScope, useMarkdownDelegate } from './markdown/MarkdownDelegate.tsx'
|
||||
export type { MarkdownDelegate, MarkdownDelegateProviderProps, MarkdownExternalLinkHandler, MarkdownDelegateFenceInfo, MarkdownPathResolver, MarkdownPathScopeProps } from './markdown/MarkdownDelegate.tsx'
|
||||
export { DetailDocument, detailDocumentState, useDetailDocumentLabels } from './DetailDocument.tsx'
|
||||
export type { DetailDocumentCopy, DetailDocumentLabels, DetailDocumentRead, DetailDocumentState } from './DetailDocument.tsx'
|
||||
export { MarkdownText } from './markdown/MarkdownText.tsx'
|
||||
|
||||
@@ -93,6 +93,43 @@ export function MarkdownDelegateProvider({
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Map one decoded local Markdown destination to the path the delegate receives.
|
||||
* @param path - Destination as the document authored it.
|
||||
* @returns Path passed to file links, image previews, and object menus.
|
||||
*/
|
||||
export type MarkdownPathResolver = (path: string) => string
|
||||
|
||||
const identityPath: MarkdownPathResolver = path => path
|
||||
const MarkdownPathContext = createContext<MarkdownPathResolver>(identityPath)
|
||||
|
||||
/** Props for one local-destination resolution scope. */
|
||||
export interface MarkdownPathScopeProps {
|
||||
/** Resolver for destinations rendered inside this scope; the nearest scope wins. */
|
||||
readonly resolvePath: MarkdownPathResolver
|
||||
readonly children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve local destinations of the enclosed Markdown before they reach the
|
||||
* enclosing {@link MarkdownDelegate}, for example against the directory that
|
||||
* was current when one message was written. Rendered labels, titles, and alt
|
||||
* text keep the authored path. Outside a scope, destinations pass unchanged.
|
||||
* @param props - Resolver and child tree.
|
||||
* @returns the scoped child tree.
|
||||
*/
|
||||
export function MarkdownPathScope({ resolvePath, children }: MarkdownPathScopeProps): ReactNode {
|
||||
return <MarkdownPathContext.Provider value={resolvePath}>{children}</MarkdownPathContext.Provider>
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the nearest local-destination resolver.
|
||||
* @returns the scope's resolver, or identity outside a scope.
|
||||
*/
|
||||
export function useMarkdownPathResolver(): MarkdownPathResolver {
|
||||
return useContext(MarkdownPathContext)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the nearest Markdown navigation capabilities.
|
||||
* @returns Owner callbacks, or an empty delegate outside a provider.
|
||||
|
||||
@@ -28,7 +28,7 @@ import { FenceCodeBlock, FenceMathBlock } from './FenceBlocks.tsx'
|
||||
import { isExplicitFilePath, parseFileLink } from './file-link.ts'
|
||||
import { renderTexToReact } from './katex.tsx'
|
||||
import { LinkIconMedium, classifyLinkPath } from '../LinkIcon.tsx'
|
||||
import { useMarkdownDelegate } from './MarkdownDelegate.tsx'
|
||||
import { useMarkdownDelegate, useMarkdownPathResolver } from './MarkdownDelegate.tsx'
|
||||
import { HoverCard } from '../HoverCard.tsx'
|
||||
import { DraggableImage } from '../DraggableImage.tsx'
|
||||
import { ImageLightbox } from '../ImageLightbox.tsx'
|
||||
@@ -640,19 +640,21 @@ function MarkdownFileLink({ file, glyph, children }: {
|
||||
readonly children: ReactNode[]
|
||||
}): ReactNode {
|
||||
const { openFile, fileImages, getTriggerProps } = useMarkdownDelegate()
|
||||
const resolvePath = useMarkdownPathResolver()
|
||||
const [load] = useState(nextImageLoad)
|
||||
if (openFile === undefined) return <>{children}</>
|
||||
const target = { ...file, path: resolvePath(file.path) }
|
||||
// Pure-image anchors already contain their preview and keep one navigation target.
|
||||
const preview = glyph && classifyLinkPath(file.path) === 'image' ? fileImages : undefined
|
||||
const resolved = preview?.resolve(file.path)
|
||||
const resolved = preview?.resolve(target.path)
|
||||
const src = resolved === undefined ? undefined : freshImageUrl(resolved, load)
|
||||
const anchor = (
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(css.fileMention, css.fileLink)}
|
||||
title={src === undefined ? file.path : undefined}
|
||||
{...getTriggerProps?.({ kind: 'file', ...file })}
|
||||
onClick={() => { openFile(file.path, file.line === undefined ? undefined : { line: file.line }) }}
|
||||
{...getTriggerProps?.({ kind: 'file', ...target })}
|
||||
onClick={() => { openFile(target.path, target.line === undefined ? undefined : { line: target.line }) }}
|
||||
>
|
||||
{glyph && <LinkIconMedium kind={classifyLinkPath(file.path)} className={css.linkIcon} />}
|
||||
{children}
|
||||
@@ -694,9 +696,10 @@ function MarkdownImage({ destination, alt, pathImages, streaming, inLink }: {
|
||||
inLink: boolean
|
||||
}): ReactNode {
|
||||
const { fileImages } = useMarkdownDelegate()
|
||||
const resolvePath = useMarkdownPathResolver()
|
||||
const [load] = useState(nextImageLoad)
|
||||
const file = streaming ? undefined : parseFileLink(destination)
|
||||
const resolved = file === undefined ? undefined : fileImages?.resolve(file.path)
|
||||
const resolved = file === undefined ? undefined : fileImages?.resolve(resolvePath(file.path))
|
||||
const src = resolved === undefined ? imageSource(destination, pathImages, load) : freshImageUrl(resolved, load)
|
||||
if (src === undefined) return <span className={css.imageAlt}>{alt}</span>
|
||||
return <LoadedMarkdownImage key={src} src={src} alt={alt} destination={destination} preview={inLink ? undefined : fileImages} />
|
||||
@@ -709,12 +712,14 @@ function LoadedMarkdownImage({ src, alt, destination, preview }: {
|
||||
preview: ReturnType<typeof useMarkdownDelegate>['fileImages']
|
||||
}): ReactNode {
|
||||
const { getTriggerProps } = useMarkdownDelegate()
|
||||
const resolvePath = useMarkdownPathResolver()
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [open, setOpen] = useState(false)
|
||||
const close = useCallback(() => { setOpen(false) }, [])
|
||||
if (failed) return <span className={css.imageAlt}>{preview === undefined ? '' : `${preview.labels.failed} · `}{alt || destination}</span>
|
||||
const file = parseFileLink(destination)
|
||||
const contextMenuProps = getTriggerProps?.({ kind: 'image', url: src, ...(file === undefined ? {} : { path: file.path }) })
|
||||
const targetPath = file === undefined ? undefined : resolvePath(file.path)
|
||||
const contextMenuProps = getTriggerProps?.({ kind: 'image', url: src, ...(targetPath === undefined ? {} : { path: targetPath }) })
|
||||
const imageProps = { className: css.image, src, alt, onError: () => { setFailed(true) },
|
||||
loading: 'lazy' as const, decoding: 'async' as const, referrerPolicy: 'no-referrer' as const }
|
||||
if (preview === undefined) return <img {...imageProps} {...contextMenuProps} />
|
||||
@@ -724,7 +729,7 @@ function LoadedMarkdownImage({ src, alt, destination, preview }: {
|
||||
const img = <DraggableImage
|
||||
fileDrag={preview.fileDrag}
|
||||
{...imageProps}
|
||||
resourceAddress={file === undefined ? undefined : preview.resourceAddress?.(file.path)}
|
||||
resourceAddress={targetPath === undefined ? undefined : preview.resourceAddress?.(targetPath)}
|
||||
name={exportName}
|
||||
/>
|
||||
return <>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { fileMediaUrl } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import { MarkdownDelegateProvider } from '../src/markdown/MarkdownDelegate.tsx'
|
||||
import { MarkdownDelegateProvider, MarkdownPathScope } from '../src/markdown/MarkdownDelegate.tsx'
|
||||
import { MarkdownText } from './markdown-test-components.tsx'
|
||||
import { parseGfm, parseGfmWithMath } from '../src/markdown/parse.ts'
|
||||
|
||||
@@ -172,3 +172,25 @@ it('uses the fallback filename for an external image URL without a path', () =>
|
||||
mount('')
|
||||
expect(screen.getByRole('img').getAttribute('src')).toBe('https://example.com/')
|
||||
})
|
||||
|
||||
it('resolves scoped local destinations before every delegate call while showing the authored path', () => {
|
||||
const resolve = vi.fn((path: string) => `https://example.com/api/file?path=${encodeURIComponent(path)}`)
|
||||
const resourceAddress = vi.fn((path: string) => `dsh-resource://file/${path}`)
|
||||
const getTriggerProps = vi.fn(() => ({}))
|
||||
const openFile = vi.fn()
|
||||
render(<MarkdownDelegateProvider openFile={openFile} getTriggerProps={getTriggerProps}
|
||||
fileImages={{ fileDrag, resolve, resourceAddress, labels }}>
|
||||
<MarkdownPathScope resolvePath={path => `/then/${path}`}>
|
||||
<MarkdownText text={'\n\n[Notes](notes.md#L3) and [Shot](tmp/b.png)'} />
|
||||
</MarkdownPathScope>
|
||||
</MarkdownDelegateProvider>)
|
||||
expect(new URL(screen.getByRole('img', { name: 'Chart' }).getAttribute('src')!).searchParams.get('path')).toBe('/then/tmp/a.png')
|
||||
expect(resolve).toHaveBeenCalledWith('/then/tmp/b.png')
|
||||
expect(resolve).not.toHaveBeenCalledWith('tmp/a.png')
|
||||
expect(resourceAddress).toHaveBeenCalledWith('/then/tmp/a.png')
|
||||
expect(getTriggerProps).toHaveBeenCalledWith(expect.objectContaining({ kind: 'image', path: '/then/tmp/a.png' }))
|
||||
expect(getTriggerProps).toHaveBeenCalledWith({ kind: 'file', path: '/then/notes.md', line: 3 })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Notes' }))
|
||||
expect(openFile).toHaveBeenCalledWith('/then/notes.md', { line: 3 })
|
||||
expect(screen.getByRole('img', { name: 'Chart' }).getAttribute('alt')).toBe('Chart')
|
||||
})
|
||||
@@ -36,8 +36,8 @@
|
||||
en: b8196b8cfcacefac
|
||||
zh: 4dd8e04fca04a580
|
||||
/deepseek-ai-dsh-session-projection/use-this-package/session-summaries:
|
||||
en: ee868b44413a126f
|
||||
zh: f98c66d8e4da9a72
|
||||
en: a48a323a812f9828
|
||||
zh: 04bcda3dc370ba75
|
||||
/deepseek-ai-dsh-session-projection/understand-the-implementation:
|
||||
en: 3397f58d6f49bfda
|
||||
zh: efb85d382e25574d
|
||||
|
||||
@@ -103,7 +103,7 @@ Every unit's state is checkpointed — client-visible and host-only alike — th
|
||||
|
||||
A Session summary is every registered client view except the keys whose non-nullish `SessionProjectionMap` entry carries the `SessionProjectionSummaryExcluded<T>` mark. `summaryKeys()` returns that set, derived from the live registrations and stable — the same instance — until a registration or its disposal changes the key table. A summary consumer passes it to the existing key-taking reads — `snapshot(session, keys)` for live Sessions, `viewCheckpoint(rows, keys)` for checkpoint rows, and `cachedSnapshot(header, keys)` through the persisted cache — which treat a set as already selected, so there is no summary-specific read face, no copy per read, and no second definition of the set. Because the registry derives it, a summary consumer cannot request an excluded key through the derived set; a complete face still serves an explicitly named key, which is how an opened Session keeps every value. A list row carries the summary projection and never the full projection.
|
||||
|
||||
The mark decides the client view type; `wire.summary` decides the runtime key set, and omitting it means `true`. Declare `wire.summary: false` on a key whose map entry carries the mark so the two agree; the field is a plain boolean, not a type-level interlock. A nullable entry keeps `null` outside the wrapper (`SessionProjectionSummaryExcluded<TodoItem[]> | null`) so the pre-first-write value stays expressible. The keys currently marked are `turnOutline`, `sessionStats`, `todos`, `imageLimits`, `contextPressure`, and `contextBreakdown`: an outline grows with the whole log, no list row renders the stats, todo list, or context meter, and the image limits are one host-wide boot constant every Session shares.
|
||||
The mark decides the client view type; `wire.summary` decides the runtime key set, and omitting it means `true`. Declare `wire.summary: false` on a key whose map entry carries the mark so the two agree; the field is a plain boolean, not a type-level interlock. A nullable entry keeps `null` outside the wrapper (`SessionProjectionSummaryExcluded<TodoItem[]> | null`) so the pre-first-write value stays expressible. The keys currently marked are `turnOutline`, `sessionStats`, `todos`, `imageLimits`, `contextPressure`, `contextBreakdown`, and `workingDirectoryHistory`: an outline and a directory history grow with the log, no list row renders the stats, todo list, or context meter, and the image limits are one host-wide boot constant every Session shares.
|
||||
|
||||
Summaries serve the Session list rows, which list Sessions without opening them. The `@` reference lists Sessions the same way but reads only its `title` and `subagent` label keys through the key-taking `snapshot(session, keys)` and `cachedSnapshot(header, keys)` faces. `snapshot(session, keys)` computes only the units it returns; without a key subset it computes every client-visible unit and no Host-only unit, so an opened Session receives every projected value, and `viewCheckpoint` likewise serves every wire key without a key subset.
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ const todo = projections.todo()
|
||||
|
||||
Session 摘要包含每个已注册客户端视图,但排除 `SessionProjectionMap` 条目(非空值)带 `SessionProjectionSummaryExcluded<T>` 标记的 key。`summaryKeys()` 返回该集合,从实时注册派生;在注册或注销改变 key 表之前,它保持同一实例。摘要消费方把它传给既有的带 key 读取面 —— 实时 Session 用 `snapshot(session, keys)`,checkpoint 行用 `viewCheckpoint(rows, keys)`,持久化缓存用 `cachedSnapshot(header, keys)` —— 这些读取面把 Set 视为已选好的集合,因此不存在摘要专用读取面、每次读取无需复制,集合也只有一处定义。由于集合由注册表派生,摘要消费方无法通过该集合请求被排除的 key;完整读取面仍会按显式命名的 key 提供值,打开的 Session 因此保留全部取值。列表行携带的是摘要投影,绝不是全量投影。
|
||||
|
||||
标记决定客户端视图类型,`wire.summary` 决定运行时键集合,省略即 `true`。map 条目带标记的 key 应声明 `wire.summary: false` 以保持一致;该字段就是普通布尔值,而不是类型层的互锁。可空条目把 `null` 放在包装之外(`SessionProjectionSummaryExcluded<TodoItem[]> | null`),以便首次写入前的值仍可表达。当前被标记的 key 是 `turnOutline`、`sessionStats`、`todos`、`imageLimits`、`contextPressure` 和 `contextBreakdown`:outline 随整份日志增长,列表行不渲染统计、todo 清单或上下文用量,而图片上限是每个 Session 共享的同一个宿主级启动常量。
|
||||
标记决定客户端视图类型,`wire.summary` 决定运行时键集合,省略即 `true`。map 条目带标记的 key 应声明 `wire.summary: false` 以保持一致;该字段就是普通布尔值,而不是类型层的互锁。可空条目把 `null` 放在包装之外(`SessionProjectionSummaryExcluded<TodoItem[]> | null`),以便首次写入前的值仍可表达。当前被标记的 key 是 `turnOutline`、`sessionStats`、`todos`、`imageLimits`、`contextPressure`、`contextBreakdown` 和 `workingDirectoryHistory`:outline 与目录历史随日志增长,列表行不渲染统计、todo 清单或上下文用量,而图片上限是每个 Session 共享的同一个宿主级启动常量。
|
||||
|
||||
摘要服务于 Session 列表行,列表无需打开 Session。`@` 引用同样以列表方式枚举 Session,但只通过带 key 的 `snapshot(session, keys)` 与 `cachedSnapshot(header, keys)` 读取其 `title` 和 `subagent` 标签 key。`snapshot(session, keys)` 只计算它返回的单元;不传 key 子集时计算每个客户端可见单元、不计算 Host 专用单元,因此打开的 Session 仍会收到全部投影值,`viewCheckpoint` 不传 key 子集时同样返回每个 wire key。
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: e65405026debde7c
|
||||
zh: e12a648eb10ed16b
|
||||
/deepseek-ai-dsh-working-directory/understand-the-implementation:
|
||||
en: c786142184efa897
|
||||
zh: e2d45e821eabfc89
|
||||
en: f955368274f92559
|
||||
zh: ab2b661b27c30f07
|
||||
/deepseek-ai-dsh-working-directory/further-exploration:
|
||||
en: eabff683146786c8
|
||||
zh: 7997dec17802ef64
|
||||
|
||||
@@ -41,7 +41,7 @@ Directory validation and publication delegate through `working-directory/access`
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Clients read the `workingDirectory` projection key through the type-only `./client` export, which carries no host-side values. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. Failures are `WorkingDirectoryError` instances: `WORKING_DIRECTORY_INVALID` for an empty or malformed path, `WORKING_DIRECTORY_NOT_FOUND` when a requested change names no existing directory, and `WORKING_DIRECTORY_UNAVAILABLE` when neither the current directory nor the original project exists or the service has been disposed.
|
||||
The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. The `workingDirectoryHistory` projection lists every effective directory with the seq it applies from — the header directory at seq 0, then one entry per change — so a reader resolves a path recorded by an event against the directory current at that event. It is excluded from Session summaries. Clients read both projection keys through the type-only `./client` export, which carries no host-side values. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. Failures are `WorkingDirectoryError` instances: `WORKING_DIRECTORY_INVALID` for an empty or malformed path, `WORKING_DIRECTORY_NOT_FOUND` when a requested change names no existing directory, and `WORKING_DIRECTORY_UNAVAILABLE` when neither the current directory nor the original project exists or the service has been disposed.
|
||||
|
||||
No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use.
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ kind: "package-reference"
|
||||
<details>
|
||||
<summary>实现细节 — 点击展开</summary>
|
||||
|
||||
Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。客户端通过仅含类型的 `./client` 导出读取 `workingDirectory` 投影键,该导出不携带宿主端运行时值。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。失败均为 `WorkingDirectoryError`:路径为空或格式错误时为 `WORKING_DIRECTORY_INVALID`,请求切换到不存在的目录时为 `WORKING_DIRECTORY_NOT_FOUND`,当前目录与原始项目都不存在或服务已释放时为 `WORKING_DIRECTORY_UNAVAILABLE`。
|
||||
Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。`workingDirectoryHistory` 投影按 seq 列出每个生效目录:seq 0 为 header 目录,之后每次变更一项;读取方据此按事件当时的目录解析该事件记录的路径。它不进入 Session 摘要。客户端通过仅含类型的 `./client` 导出读取这两个投影键,该导出不携带宿主端运行时值。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。失败均为 `WorkingDirectoryError`:路径为空或格式错误时为 `WORKING_DIRECTORY_INVALID`,请求切换到不存在的目录时为 `WORKING_DIRECTORY_NOT_FOUND`,当前目录与原始项目都不存在或服务已释放时为 `WORKING_DIRECTORY_UNAVAILABLE`。
|
||||
|
||||
不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。
|
||||
|
||||
|
||||
@@ -6,14 +6,15 @@
|
||||
import { isAbsolute } from 'node:path'
|
||||
import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { z as zod } from 'zod'
|
||||
import { z as zod, type ZodType } from 'zod'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type {} from '@deepseek-ai/dsh-fs'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import { SessionSeq, type Session } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
import { WorkingDirectoryError } from './error.ts'
|
||||
import type { WorkingDirectoryHistoryEntry } from './types.ts'
|
||||
|
||||
export { WorkingDirectoryError, type WorkingDirectoryErrorCode } from './error.ts'
|
||||
export type * from './types.ts'
|
||||
@@ -100,6 +101,20 @@ export class WorkingDirectoryService extends Service {
|
||||
apply: (state, event) => event.type === 'working-directory/change' ? event.data.cwd : state,
|
||||
wire: { viewSchema: directorySchema, view: state => state },
|
||||
})
|
||||
const historySchema: ZodType<readonly WorkingDirectoryHistoryEntry[]> = zod.array(zod.object({
|
||||
seq: zod.number().int().nonnegative().transform(SessionSeq),
|
||||
cwd: zod.string().min(1).refine(isAbsolute),
|
||||
}).strict())
|
||||
await ctx.sessionProjections.register({
|
||||
key: 'workingDirectoryHistory',
|
||||
stateVersion: 1,
|
||||
stateSchema: historySchema,
|
||||
init: header => header.cwd === undefined ? [] : [{ seq: SessionSeq(0), cwd: header.cwd }],
|
||||
apply: (state, event) => event.type === 'working-directory/change'
|
||||
? [...state, { seq: event.seq, cwd: event.data.cwd }]
|
||||
: state,
|
||||
wire: { viewSchema: historySchema, view: state => state, summary: false },
|
||||
})
|
||||
ctx.systemPrompt.context({
|
||||
name: 'working-directory:current',
|
||||
order: ctx.systemPrompt.getContextOrder('WORKING_DIRECTORY'),
|
||||
|
||||
@@ -1,18 +1,34 @@
|
||||
/**
|
||||
* Pure types of the working-directory domain: the one home of the
|
||||
* `workingDirectory` projection-key declaration, free of this package's
|
||||
* host-side value imports. `./client` projects it to client aggregates.
|
||||
* `workingDirectory` and `workingDirectoryHistory` projection-key
|
||||
* declarations, free of this package's host-side value imports. `./client`
|
||||
* projects them to client aggregates.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-working-directory/types
|
||||
*/
|
||||
|
||||
// Marks this file a module so the declaration below augments the projection
|
||||
// table instead of declaring an ambient module.
|
||||
export {}
|
||||
import type { SessionSeq } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionProjectionSummaryExcluded } from '@deepseek-ai/dsh-session-projection/types'
|
||||
|
||||
/** One effective directory and the log position from which it applies. */
|
||||
export interface WorkingDirectoryHistoryEntry {
|
||||
/** Seq of the `working-directory/change` that selected `cwd`; `0` for the header directory. */
|
||||
readonly seq: SessionSeq
|
||||
/** Absolute directory used by events after `seq` until the next entry. */
|
||||
readonly cwd: string
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-session-projection/types' {
|
||||
interface SessionProjectionMap {
|
||||
/** Recorded current directory for Session observations, or null when none is recorded. */
|
||||
workingDirectory: string | null
|
||||
/**
|
||||
* Every effective directory in ascending seq order: the header directory at
|
||||
* seq `0`, then one entry per `working-directory/change`. A path recorded by
|
||||
* an event resolves against the last entry whose seq is lower than that
|
||||
* event's. Excluded from Session summary payloads: it grows with directory
|
||||
* changes and no list row renders it.
|
||||
*/
|
||||
workingDirectoryHistory: SessionProjectionSummaryExcluded<readonly WorkingDirectoryHistoryEntry[]>
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,30 @@ describe('Session working directories', () => {
|
||||
expect(restored.header.cwd).toBe(f.root)
|
||||
})
|
||||
|
||||
it('records every effective directory with the seq it applies from, outside Session summaries', async () => {
|
||||
await using f = await fixture()
|
||||
const first = join(f.root, 'first')
|
||||
await mkdir(join(first, 'second'), { recursive: true })
|
||||
const history = (session: typeof f.agent.session) => f.ctx.sessionProjections.snapshot(session).values.workingDirectoryHistory
|
||||
expect(history(f.ctx.sessions.create(SessionId('history-without-origin')))).toEqual([])
|
||||
expect(history(f.agent.session)).toEqual([{ seq: 0, cwd: f.root }])
|
||||
await f.ctx.workingDirectory.set(f.agent, first)
|
||||
await f.ctx.workingDirectory.set(f.agent, 'second')
|
||||
const changes = f.agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')
|
||||
const expected = [
|
||||
{ seq: 0, cwd: f.root },
|
||||
{ seq: changes[0]!.seq, cwd: first },
|
||||
{ seq: changes[1]!.seq, cwd: join(first, 'second') },
|
||||
]
|
||||
expect(history(f.agent.session)).toEqual(expected)
|
||||
const restored = f.ctx.sessions.create(SessionId('history-restored'), {
|
||||
meta: { cwd: f.root }, seed: f.agent.session.snapshotEvents(),
|
||||
})
|
||||
expect(history(restored)).toEqual(expected)
|
||||
expect(f.ctx.sessionProjections.summaryKeys().has('workingDirectoryHistory')).toBe(false)
|
||||
expect(f.ctx.sessionProjections.summaryKeys().has('workingDirectory')).toBe(true)
|
||||
})
|
||||
|
||||
it('serializes concurrent relative changes and recovers after a rejected change', async () => {
|
||||
await using f = await fixture()
|
||||
await mkdir(join(f.root, 'a', 'b'), { recursive: true })
|
||||
|
||||
Reference in new issue
Block a user