Merge remote-tracking branch 'origin/master' into feat/session-workspace-root
This commit is contained in:
commit
6db6fb4e59
29 files changed
+830
-49
No files matched your search
@@ -87,8 +87,26 @@ jobs:
|
||||
if ! git merge-base "$HEAD_SHA" "$BASE_SHA" >/dev/null; then
|
||||
stop "the pull request shares no commit with $BASE_SHA within 150 commits of history, so nothing was merged or compiled; merge master into it and push, then this check runs again"
|
||||
fi
|
||||
git -c user.name=pr-check -c [email protected] merge --no-ff --no-edit -m "Merge $BASE_SHA into $HEAD_SHA" "$BASE_SHA" ||
|
||||
stop "the pull request cannot merge $BASE_SHA; merge master into it and push, then this check runs again"
|
||||
# The blobless history makes Git fetch missing blobs from origin on demand. Within one process, Git's cache of
|
||||
# loose-object directories does not see the merged blobs it writes, so a single `git merge` asks origin for
|
||||
# them while it checks out the result, and origin, which has never seen them, refuses the whole fetch.
|
||||
# The merge is computed by `git merge-tree` and checked out by a separate process, which rereads the
|
||||
# directories.
|
||||
set +e
|
||||
merge_output=$(git merge-tree --write-tree "$HEAD_SHA" "$BASE_SHA")
|
||||
merge_status=$?
|
||||
set -e
|
||||
if [ "$merge_status" -eq 1 ]; then
|
||||
echo "$merge_output"
|
||||
stop "the pull request conflicts with $BASE_SHA; merge master into it and push, then this check runs again"
|
||||
fi
|
||||
if [ "$merge_status" -ne 0 ]; then
|
||||
stop "git merge-tree could not merge $BASE_SHA (exit $merge_status), so nothing was compiled"
|
||||
fi
|
||||
merge_commit=$(git -c user.name=pr-check -c [email protected] commit-tree "${merge_output%%$'\n'*}" -p "$HEAD_SHA" -p "$BASE_SHA" -m "Merge $BASE_SHA into $HEAD_SHA") ||
|
||||
stop "the merged tree of $BASE_SHA could not be committed, so nothing was compiled"
|
||||
git checkout --quiet --detach "$merge_commit" ||
|
||||
stop "the merged tree of $BASE_SHA could not be checked out, so nothing was compiled"
|
||||
echo "merged=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: pnpm/[email protected]
|
||||
|
||||
@@ -217,6 +217,8 @@ describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s',
|
||||
await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).waitFor()
|
||||
await page.keyboard.press('End')
|
||||
expect(await page.getByRole('menuitem', { name: 'Save as…', exact: true }).count()).toBe(0)
|
||||
expect(await page.getByRole('menuitem', { name: 'Add to chat', exact: true }).evaluate(element => element === document.activeElement)).toBe(true)
|
||||
await page.keyboard.press('ArrowUp')
|
||||
expect(await page.getByRole('menuitem', { name: 'Download', exact: true }).evaluate(element => element === document.activeElement)).toBe(true)
|
||||
await page.keyboard.press('ArrowUp')
|
||||
expect(await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).evaluate(element => element === document.activeElement)).toBe(true)
|
||||
|
||||
@@ -11,9 +11,9 @@ import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type {} from '@deepseek-ai/dsh-session-title'
|
||||
import {
|
||||
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
|
||||
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
|
||||
launchWebScaffold, readPersistedEvents, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
import { expandOwningTurnProcess, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
|
||||
|
||||
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links', import.meta.url))
|
||||
const MODE = webSnapshotMode()
|
||||
@@ -161,7 +161,52 @@ describe('web e2e: Markdown file links', () => {
|
||||
expect(page.url()).toBe(beforeUrl)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'links.expected.md', 'preview.expected.md'])
|
||||
})
|
||||
|
||||
it('adds a recorded line-labeled file to the draft without its line suffix or a new turn', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-markdown-file-add-to-chat'))
|
||||
const sessionId = brandString<SessionId>('markdown-file-links')
|
||||
const beforeEvents = await readPersistedEvents(scaffold, sessionId)
|
||||
const beforeMessages = await page.locator('[data-chat-flow-kind="user"]').count()
|
||||
const input = page.locator('[data-composer-input]').first()
|
||||
const draft = 'Review this file next: '
|
||||
await writeComposerDraft(page, input, draft)
|
||||
await page.getByRole('button', { name: 'src/example.txt:24–30', exact: true }).click({ button: 'right' })
|
||||
const menu = page.getByRole('menu')
|
||||
const action = menu.getByRole('menuitem', { name: 'Add to chat', exact: true })
|
||||
await action.waitFor()
|
||||
expect(await menu.getByRole('menuitem').last().textContent()).toBe('Add to chat')
|
||||
const menuAria = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd)
|
||||
await action.click()
|
||||
await menu.waitFor({ state: 'hidden' })
|
||||
await expect.poll(() => input.evaluate(node => node === document.activeElement)).toBe(true)
|
||||
await expect.poll(() => input.textContent()).toBe(`${draft}example.txt `)
|
||||
const chip = input.locator('[data-composer-chip]')
|
||||
expect(await chip.count()).toBe(1)
|
||||
expect(await chip.textContent()).toBe('example.txt')
|
||||
expect(await chip.locator('svg').count()).toBe(1)
|
||||
const composerAria = await captureStableAria(page, '[data-composer-input]', scaffold.workspaceCwd)
|
||||
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'add-to-chat.expected.md'),
|
||||
`## File menu\n\n${menuAria}\n\n## Composer\n\n${composerAria}`, MODE)
|
||||
|
||||
await page.keyboard.press('ControlOrMeta+A')
|
||||
const copied = await input.evaluate((node) => {
|
||||
const clipboardData = new DataTransfer()
|
||||
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true }))
|
||||
return clipboardData.getData('text/plain')
|
||||
})
|
||||
const path = join(scaffold.workspaceCwd, 'src/example.txt')
|
||||
expect(copied).toBe(`${draft}@${path} `)
|
||||
expect(copied).not.toContain(':24')
|
||||
expect(copied).not.toContain('#L24')
|
||||
expect(await page.locator('[data-chat-flow-kind="user"]').count()).toBe(beforeMessages)
|
||||
expect(await readPersistedEvents(scaffold, sessionId)).toEqual(beforeEvents)
|
||||
await writeComposerDraft(page, input, '')
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
await assertFixtureInventory(SNAPSHOT_DIR, [
|
||||
'session.v3.jsonl', 'links.expected.md', 'preview.expected.md', 'add-to-chat.expected.md',
|
||||
])
|
||||
})
|
||||
|
||||
it('replays colon line suffixes as locations and shares tabs with fragment links', async () => {
|
||||
|
||||
@@ -165,6 +165,7 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through
|
||||
// stays out of the menu golden.
|
||||
await mkdir(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested'), { recursive: true })
|
||||
await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested', 'leaf.txt'), 'leaf fixture\n')
|
||||
await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested', 'space name.txt'), 'space fixture\n')
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
@@ -429,4 +430,108 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
await assertFixtureInventory(SNAPSHOT_DIR, ['menu.expected.md', 'order.expected.md'])
|
||||
})
|
||||
|
||||
it('adds a sidebar file after retained selection without sending and undoes it as one edit', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-add-to-chat'))
|
||||
const group = page.getByRole('treeitem', { name: /Ungrouped/ })
|
||||
await group.waitFor({ timeout: 15_000 })
|
||||
if (await group.getAttribute('aria-expanded') !== 'true') await group.click()
|
||||
await page.locator(`[data-row-key="session:${TARGET_SESSION_ID}"]`).click()
|
||||
await page.locator('[data-chat-flow-kind="user"]').filter({ hasText: 'Research notes' }).waitFor()
|
||||
const input = page.locator('[data-composer-input]').first()
|
||||
const suggestions = page.getByRole('listbox', { name: 'Trigger suggestions' })
|
||||
const directory = join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested')
|
||||
const file = join(directory, 'space name.txt')
|
||||
const sessionId = brandString<SessionId>(TARGET_SESSION_ID)
|
||||
const beforeEvents = (await readPersistedEvents(scaffold, sessionId))
|
||||
.filter(event => event.type === 'user/message' || event.type.startsWith('turn/'))
|
||||
const beforeMessages = await page.locator('[data-chat-flow-kind="user"]').count()
|
||||
|
||||
// An absolute query compares the same resource spelling as the sidebar.
|
||||
await replaceReferenceQuery(page, input, `@"${directory}/`)
|
||||
const option = suggestions.getByRole('option', { name: /^space name\.txt/ })
|
||||
await option.waitFor({ timeout: 15_000 })
|
||||
await option.click()
|
||||
const chip = input.locator('[data-composer-chip]')
|
||||
await expect.poll(() => chip.textContent()).toBe('space name.txt')
|
||||
const pickerAppearance = await chip.evaluate(node => ({
|
||||
source: node.getAttribute('data-composer-chip'),
|
||||
label: node.textContent,
|
||||
icons: node.querySelectorAll('svg').length,
|
||||
}))
|
||||
await page.keyboard.press('ControlOrMeta+A')
|
||||
// A page-local clipboard avoids interference with parallel browser workers.
|
||||
const pickerClipboard = await input.evaluate((node) => {
|
||||
const clipboardData = new DataTransfer()
|
||||
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true }))
|
||||
return clipboardData.getData('text/plain')
|
||||
})
|
||||
expect(pickerClipboard).toBe(`@"${file}" `)
|
||||
await writeComposerDraft(page, input, '')
|
||||
|
||||
const column = page.locator('[data-rightbar-col]')
|
||||
await page.locator('[data-sidebar-right-expand]').click()
|
||||
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
|
||||
const navigator = column.locator('[data-files-navigator]:visible')
|
||||
await navigator.waitFor()
|
||||
for (const name of ['workspace', 'folderx', 'nested']) {
|
||||
const folder = navigator.getByRole('button', { name, exact: true })
|
||||
await folder.waitFor()
|
||||
if (await folder.getAttribute('aria-expanded') !== 'true') await folder.click()
|
||||
}
|
||||
const row = navigator.getByRole('button', { name: 'space name.txt', exact: true })
|
||||
await row.waitFor()
|
||||
const draft = 'Review selected, then finish.'
|
||||
await writeComposerDraft(page, input, draft)
|
||||
const word = await input.evaluate((node) => {
|
||||
const text = document.createTreeWalker(node, NodeFilter.SHOW_TEXT).nextNode()
|
||||
if (text === null) throw new Error('Composer draft has no text')
|
||||
const range = document.createRange()
|
||||
range.setStart(text, 'Review '.length)
|
||||
range.setEnd(text, 'Review selected'.length)
|
||||
const rect = range.getBoundingClientRect()
|
||||
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
|
||||
})
|
||||
await page.mouse.dblclick(word.x, word.y)
|
||||
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe('selected')
|
||||
// Copy observes the editor's committed selection, not only the native range.
|
||||
await expect.poll(() => input.evaluate((node) => {
|
||||
const clipboardData = new DataTransfer()
|
||||
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true }))
|
||||
return clipboardData.getData('text/plain')
|
||||
})).toBe('selected')
|
||||
|
||||
await row.click({ button: 'right' })
|
||||
const menu = page.getByRole('menu')
|
||||
const action = menu.getByRole('menuitem', { name: 'Add to chat', exact: true })
|
||||
await action.waitFor()
|
||||
expect(await menu.getByRole('menuitem').last().textContent()).toBe('Add to chat')
|
||||
expect(await action.isEnabled()).toBe(true)
|
||||
await action.click()
|
||||
await menu.waitFor({ state: 'hidden' })
|
||||
await expect.poll(() => input.evaluate(node => node === document.activeElement)).toBe(true)
|
||||
await expect.poll(() => input.textContent()).toBe('Review selected space name.txt , then finish.')
|
||||
expect(await chip.evaluate(node => ({
|
||||
source: node.getAttribute('data-composer-chip'),
|
||||
label: node.textContent,
|
||||
icons: node.querySelectorAll('svg').length,
|
||||
}))).toEqual(pickerAppearance)
|
||||
await page.keyboard.press('ControlOrMeta+A')
|
||||
const menuClipboard = await input.evaluate((node) => {
|
||||
const clipboardData = new DataTransfer()
|
||||
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData, bubbles: true, cancelable: true }))
|
||||
return clipboardData.getData('text/plain')
|
||||
})
|
||||
expect(menuClipboard).toBe(`Review selected ${pickerClipboard}, then finish.`)
|
||||
|
||||
await page.keyboard.press('ControlOrMeta+Z')
|
||||
await expect.poll(() => input.textContent()).toBe(draft)
|
||||
expect(await chip.count()).toBe(0)
|
||||
expect(await input.evaluate(node => node === document.activeElement)).toBe(true)
|
||||
expect(await page.locator('[data-chat-flow-kind="user"]').count()).toBe(beforeMessages)
|
||||
expect((await readPersistedEvents(scaffold, sessionId))
|
||||
.filter(event => event.type === 'user/message' || event.type.startsWith('turn/'))).toEqual(beforeEvents)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -14,6 +14,9 @@
|
||||
/conversation-and-session-rules/retention-follows-one-lifecycle-rule:
|
||||
en: fcb40a31d0881e84
|
||||
zh: 779bc49cce81651e
|
||||
/conversation-and-session-rules/retained-excerpts-do-not-keep-their-source-string-alive:
|
||||
en: 6834b8020ee324b5
|
||||
zh: 10e76904d1470cec
|
||||
/conversation-and-session-rules/node-computation-is-incremental-and-streaming-publication-is-batched:
|
||||
en: 315c7ac2186d0721
|
||||
zh: 06bb4e072b242fe1
|
||||
|
||||
@@ -125,6 +125,26 @@ export function reclaimIdle(): void {
|
||||
|
||||
Nobody can count who still uses the Session, and the next state added to the Session escapes the enumeration and is never reclaimed.
|
||||
|
||||
## Retained excerpts do not keep their source string alive
|
||||
|
||||
Session events, tool result `meta`, and other values kept for a Session's lifetime copy any excerpt taken from a large transient string, such as decoded file text or command output. In V8, a `slice`, `substring`, `split` piece, or regular-expression capture of 13 or more characters can reference its whole parent string, a concatenation references its parts, and `Session.append` copies objects but not string storage. A 200-character line kept in `meta` can therefore keep a 16 MB file in memory until the Session closes.
|
||||
|
||||
- Judged condition: can a retained string be an excerpt of a larger string that would otherwise be garbage? The excerpt is copied with `Buffer.from(text, 'utf16le').toString('utf16le')` before it is retained, and a test drops a heap-allocated source, forces garbage collection, and checks that heap usage does not grow with the source size.
|
||||
- Boundary: the rule applies to excerpts that outlive the operation. It does not apply when the source itself is retained or when the value comes from `JSON.parse`, `TextDecoder`, or `Buffer#toString`. `String()`, `slice(0)`, `trim()`, `'' + text`, and `join` can return the input string itself and are not copies.
|
||||
- Ownership: the code that takes the excerpt copies it; the Session does not copy strings on append.
|
||||
|
||||
The `read` tool copies a returned line once when it was built from a slice:
|
||||
|
||||
```ts ignore-check
|
||||
const line = lineHasSlice ? Buffer.from(lineBuffer, 'utf16le').toString('utf16le') : lineBuffer
|
||||
```
|
||||
|
||||
Keeping the slice keeps the decoded file:
|
||||
|
||||
```ts ignore-check
|
||||
const line = lineBuffer // may be a slice of the whole decoded file
|
||||
```
|
||||
|
||||
## Node computation is incremental and streaming publication is batched
|
||||
|
||||
A new node computation states its complexity, and high-frequency streaming chunks never publish immediately and never recompute in full. A per-chunk full rebuild published at once puts the whole node collection on the frame budget, and the transcript stalls behind the stream. The append-path cost — with `D` registered Definitions, `D` matches and one constant-time Context-key lookup — and the publication vocabulary (`none`, `animation-frame`, `immediate`) are owned by [conversation.md](../subsystems/conversation.md#definition-and-typed-chat-payload).
|
||||
|
||||
@@ -125,6 +125,26 @@ export function reclaimIdle(): void {
|
||||
|
||||
没有人能数清谁仍在使用该 Session,下一个新增的 Session 状态也会漏出枚举、永远不被回收。
|
||||
|
||||
## 保留的摘录不会让来源字符串常驻内存
|
||||
|
||||
Session 事件、工具结果的 `meta`,以及其他在 Session 生命周期内保留的值,若取自大型临时字符串(例如解码后的文件文本或命令输出)的摘录,都要先复制该摘录。在 V8 中,长度不少于 13 个字符的 `slice`、`substring`、`split` 片段或正则表达式捕获可能引用整个父字符串,拼接结果会引用其各个组成部分,而 `Session.append` 复制对象,不复制字符串存储。因此,`meta` 中保留的一行 200 个字符的文本可能让一个 16 MB 的文件一直留在内存中,直到 Session 关闭。
|
||||
|
||||
- 判定条件:被保留的字符串是否可能是某个更大字符串的摘录,而该更大字符串本应被垃圾回收?摘录在保留之前用 `Buffer.from(text, 'utf16le').toString('utf16le')` 复制;测试丢弃一个分配在堆上的来源字符串、强制垃圾回收,并检查堆内存用量不随来源大小增长。
|
||||
- 边界:该规则适用于存活时间超过本次操作的摘录。来源本身被保留,或值来自 `JSON.parse`、`TextDecoder` 或 `Buffer#toString` 时,该规则不适用。`String()`、`slice(0)`、`trim()`、`'' + text` 和 `join` 可能返回输入字符串本身,不算复制。
|
||||
- 归口:截取摘录的代码负责复制;Session 在 append 时不复制字符串。
|
||||
|
||||
返回行由 slice 拼成时,`read` 工具把它复制一次:
|
||||
|
||||
```ts ignore-check
|
||||
const line = lineHasSlice ? Buffer.from(lineBuffer, 'utf16le').toString('utf16le') : lineBuffer
|
||||
```
|
||||
|
||||
保留 slice 会把解码后的文件一并保留:
|
||||
|
||||
```ts ignore-check
|
||||
const line = lineBuffer // may be a slice of the whole decoded file
|
||||
```
|
||||
|
||||
## 节点计算是增量的,流式发布是合批的
|
||||
|
||||
新增节点计算要说明其复杂度;高频流式 chunk 绝不立即发布、也不做全量计算。每个 chunk 全量重算并立即发布,等于把整个节点集合压进帧预算,转写区便会堵在流后面。追加速路径的开销——在 `D` 个已注册 Definition 下执行 `D` 次匹配与一次常量级 Context key 查找——以及发布节拍取值(`none`、`animation-frame`、`immediate`)归 [conversation.zh.md](../subsystems/conversation.zh.md#definition-and-typed-chat-payload)。
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 4a094cd97426ad18
|
||||
zh: 5faadddb7e2b0a43
|
||||
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props:
|
||||
en: 47d0496e21712f74
|
||||
zh: 3e9b8f8b5e419ed3
|
||||
en: ff204aa7b6c6666a
|
||||
zh: 5b437f63b8e18f95
|
||||
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry:
|
||||
en: 876be274c65b56d9
|
||||
zh: c3adbf5a16e0e38e
|
||||
|
||||
@@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc
|
||||
|
||||
`SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work.
|
||||
|
||||
Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration.
|
||||
Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text and structured file references. `SessionInput.addReferences` inserts references after the retained selection in one undo step without replacing selected text. `SessionInput.canInsertReferences()` reads the current precondition without notifying changes: it is false after disposal, during submission, for removed or non-continuable subagent Sessions, and while a composer block is set, and `addReferences` rechecks it. Quote insertion shares the Session and block conditions. Internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration.
|
||||
|
||||
A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty.
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项
|
||||
|
||||
`SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。
|
||||
|
||||
草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。
|
||||
草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本及结构化文件引用。`SessionInput.addReferences` 在保留选区之后插入引用,形成一个撤销步骤且不替换选中文字。`SessionInput.canInsertReferences()` 读取当前的前置条件,不通知变化:输入模型释放后、提交期间、Session 已移除或为不可继续的子智能体、存在输入框阻塞时为 false,`addReferences` 执行时会再次检查。引文(quote)插入共用其中的 Session 和阻塞条件。内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。
|
||||
|
||||
已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Frozen input-machine contract. Types
|
||||
* only. Three-tier visibility: business packages see InputState via the
|
||||
* InputZone currency; the scoped input events carry the mutation verbs; the
|
||||
* conversation wiring layer alone sees the full SessionInput. The draft text
|
||||
* and its reference chips live in the shell's Lexical editor; the machine
|
||||
* here is the submit plane (phase, claim, attempt) alone.
|
||||
* Input-machine types and Session-addressed draft operations. Business packages
|
||||
* read InputState through InputZone and use scoped input events for guarded
|
||||
* mutations. Conversation wiring and direct draft consumers resolve SessionInput
|
||||
* through conversation.input.for(), including reference insertion through addReferences.
|
||||
* Draft text and reference chips live in the shell's Lexical editor; the machine
|
||||
* here owns submission state (phase, claim, attempt).
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
@@ -195,6 +195,19 @@ export interface SessionInput extends InputTarget {
|
||||
setDraft(text: string): void
|
||||
/** Append ordered browser-owned attachment ids; busy admission phases refuse. */
|
||||
addAttachments(ids: readonly DraftAttachmentId[]): boolean
|
||||
/**
|
||||
* Insert file references after the retained selection in one undo step without replacing text.
|
||||
* @param references - validated reference chips in source order.
|
||||
* @returns false while {@link canInsertReferences} is false or when the editor refuses insertion.
|
||||
*/
|
||||
addReferences(references: readonly ReferenceInsert[]): boolean
|
||||
/**
|
||||
* Read whether {@link addReferences} can currently edit the draft. Callers read it when they
|
||||
* present the operation; the answer does not notify changes, and addReferences rechecks it.
|
||||
* @returns false after disposal, during submission, for removed or non-continuable subagent Sessions,
|
||||
* and while a composer block is set.
|
||||
*/
|
||||
canInsertReferences(): boolean
|
||||
/** Remove one browser-owned attachment id; busy admission phases refuse. @returns whether the id was removed. */
|
||||
removeAttachment(id: DraftAttachmentId): boolean
|
||||
/** Drop ids whose browser-owned objects no longer exist. */
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { InboxState } from '@deepseek-ai/dsh-agent/types'
|
||||
import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import {
|
||||
createSnapshotStore, type ObservableSnapshot, type SnapshotStore,
|
||||
} from '@deepseek-ai/dsh-client-store'
|
||||
@@ -24,6 +25,7 @@ import type {
|
||||
ArbitrateKey, ArbitrateOutcome, ComposerKeyboard, DraftInput, DraftSnapshot, ReferenceInsert, TokenSpan,
|
||||
} from '../contract/draft-editor.ts'
|
||||
import type { InputSubmitMode, MessageSubmission, MessageSubmissionState } from '../contract/composer-submission.ts'
|
||||
import type { ComposerBlock } from '../contract/composer-blocks.ts'
|
||||
import { serializeDraftPrompt } from './prompt.ts'
|
||||
import { SubmitMachine } from './machine.ts'
|
||||
import { resolveDraftInput, snapshotDraft } from '../draft.ts'
|
||||
@@ -71,8 +73,10 @@ export interface SessionInputDeps {
|
||||
signal: AbortSignal,
|
||||
accept: () => void,
|
||||
): Promise<SubmitOutcome>
|
||||
/** Live Session and composer-block policy for transcript insertion. */
|
||||
quoteInsertionAllowed?: () => boolean
|
||||
/** Read the Session facts whose removal and subagent mode gate quote and reference insertion; absent permits both. */
|
||||
session?: (() => Pick<SessionSnapshot, 'removed' | 'subagent'>) | undefined
|
||||
/** Read the Session's current composer block; absent means never blocked. */
|
||||
composerBlock?: (() => ComposerBlock | undefined) | undefined
|
||||
/** Current localized quote removal copy. */
|
||||
quoteRemoveLabel?: () => string
|
||||
/** Command-plane attachment plumbing (the hub owns the conversation face and the copy). */
|
||||
@@ -242,7 +246,7 @@ export class SessionInputShell implements SessionInput {
|
||||
* @returns whether the editable draft accepted the quote.
|
||||
*/
|
||||
insertQuote(text: string, summary?: QuoteSummary): boolean {
|
||||
if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.quoteInsertionAllowed?.() === false || text.trim() === '') return false
|
||||
if (this.disposed || this.snapshot.phase !== 'plain' || !this.sessionAcceptsInsertion() || text.trim() === '') return false
|
||||
const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }, summary)
|
||||
if (inserted) this.focus()
|
||||
return inserted
|
||||
@@ -331,6 +335,14 @@ export class SessionInputShell implements SessionInput {
|
||||
return this.disposed || frozen(this.core.state.phase)
|
||||
}
|
||||
|
||||
/** Whether the Session lets features outside the composer insert quotes or references. */
|
||||
private sessionAcceptsInsertion(): boolean {
|
||||
const session = this.deps.session?.()
|
||||
if (session !== undefined && (session.removed
|
||||
|| (session.subagent !== null && session.subagent.address.mode !== 'continuable'))) return false
|
||||
return this.deps.composerBlock?.() === undefined
|
||||
}
|
||||
|
||||
/** Append ordered attachment ids unless an admission transaction is locked. */
|
||||
addAttachments(ids: readonly DraftAttachmentId[]): boolean {
|
||||
if (frozen(this.snapshot.phase)) return false
|
||||
@@ -342,18 +354,33 @@ export class SessionInputShell implements SessionInput {
|
||||
|
||||
/**
|
||||
* Add validated file references and attachment ids while admission is editable.
|
||||
* Drop and paste use this wiring-layer method; other packages use {@link addReferences}.
|
||||
* @param references - reference chips in source order.
|
||||
* @param ids - newly allocated attachment ids.
|
||||
* @returns false when admission is locked or the editor refuses the insertion.
|
||||
* @returns false after disposal, when admission is locked, or when the editor refuses insertion.
|
||||
*/
|
||||
addFiles(references: readonly ReferenceInsert[], ids: readonly DraftAttachmentId[]): boolean {
|
||||
if (frozen(this.snapshot.phase)) return false
|
||||
if (this.disposed || frozen(this.snapshot.phase)) return false
|
||||
if (!this.draftEditor.insertFileReferences(references)) return false
|
||||
this.attachmentIds = [...this.attachmentIds, ...ids]
|
||||
this.publish()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* @param references - validated reference chips in source order.
|
||||
* @returns whether the draft accepted the references.
|
||||
*/
|
||||
addReferences(references: readonly ReferenceInsert[]): boolean {
|
||||
if (!this.canInsertReferences()) return false
|
||||
return this.addFiles(references, [])
|
||||
}
|
||||
|
||||
/** @inheritdoc */
|
||||
canInsertReferences(): boolean {
|
||||
return !this.disposed && !frozen(this.snapshot.phase) && this.sessionAcceptsInsertion()
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one attachment id from this draft. Busy admission phases refuse, like
|
||||
* {@link addAttachments}: a removal landing while a send serializes would
|
||||
|
||||
@@ -157,12 +157,8 @@ export class InputHub implements SessionInputResolver {
|
||||
inbox: session.projections.faceOf('inbox') as ObservableSnapshot<InboxState | undefined>,
|
||||
defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept),
|
||||
quoteRemoveLabel: () => this.t('quote.remove'),
|
||||
quoteInsertionAllowed: () => {
|
||||
const state = session.getSnapshot()
|
||||
return !state.removed && (state.subagent === null
|
||||
|| state.subagent.address.mode === 'continuable')
|
||||
&& this.conversation().blocks.storeFor(session.sessionId).getSnapshot() === undefined
|
||||
},
|
||||
session: () => session.getSnapshot(),
|
||||
composerBlock: () => this.conversation().blocks.storeFor(session.sessionId).getSnapshot(),
|
||||
steerQueue: () => { void this.steerQueue(session, shell) },
|
||||
commandAttachments: {
|
||||
serialize: async (ids) => {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render } from '@testing-library/react'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts'
|
||||
import {
|
||||
KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, REDO_COMMAND, UNDO_COMMAND,
|
||||
$getRoot, $getSelection, $isRangeSelection, $nodesOfType,
|
||||
@@ -16,7 +17,7 @@ import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts'
|
||||
|
||||
const quote = 'selected source text'
|
||||
|
||||
function bench(quoteInsertionAllowed?: () => boolean) {
|
||||
function bench(composerBlock?: () => ComposerBlock | undefined) {
|
||||
const sink = vi.fn(() => Promise.resolve<SubmitOutcome>({ kind: 'success' }))
|
||||
const shell = new SessionInputShell({
|
||||
actx: {} as Context,
|
||||
@@ -27,7 +28,7 @@ function bench(quoteInsertionAllowed?: () => boolean) {
|
||||
unsupportedNotice: () => 'unsupported',
|
||||
},
|
||||
quoteRemoveLabel: () => 'Remove quote',
|
||||
...(quoteInsertionAllowed === undefined ? {} : { quoteInsertionAllowed }),
|
||||
...(composerBlock === undefined ? {} : { composerBlock }),
|
||||
})
|
||||
return { shell, sink }
|
||||
}
|
||||
@@ -38,13 +39,13 @@ function quoteKeys(shell: SessionInputShell): string[] {
|
||||
|
||||
describe('QuoteNode composer lifecycle', () => {
|
||||
it('preserves the draft when its Session cannot accept an inserted quote', () => {
|
||||
let allowed = false
|
||||
const { shell } = bench(() => allowed)
|
||||
let block: ComposerBlock | undefined = { reason: 'Unavailable' }
|
||||
const { shell } = bench(() => block)
|
||||
shell.setDraft('base ')
|
||||
const before = shell.draftSnapshot
|
||||
expect(shell.insertQuote(quote)).toBe(false)
|
||||
expect(shell.draftSnapshot).toBe(before)
|
||||
allowed = true
|
||||
block = undefined
|
||||
expect(shell.insertQuote(quote)).toBe(true)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Reference insertion from outside the composer follows Session, submission, and disposal state. */
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ComposerBlock } from '../src/client/contract/composer-blocks.ts'
|
||||
import type { ReferenceInsert } from '../src/client/contract/draft-editor.ts'
|
||||
import type { SubmitOutcome } from '../src/client/contract/input.ts'
|
||||
import { SessionInputShell } from '../src/client/input/facade.ts'
|
||||
|
||||
const reference: ReferenceInsert = {
|
||||
source: 'reference', ref: '@"/work/a b.md"', label: 'a b.md', appearance: 'file', clipboardText: '@"/work/a b.md"',
|
||||
}
|
||||
|
||||
type SessionGate = Pick<SessionSnapshot, 'removed' | 'subagent'>
|
||||
|
||||
function bench() {
|
||||
const pending = Promise.withResolvers<SubmitOutcome>()
|
||||
const sink = vi.fn(() => pending.promise)
|
||||
const sources: { session: SessionGate; block: ComposerBlock | undefined } = {
|
||||
session: { removed: false, subagent: null }, block: undefined,
|
||||
}
|
||||
const shell = new SessionInputShell({
|
||||
actx: {} as Context,
|
||||
defaultSink: sink,
|
||||
commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token },
|
||||
session: () => sources.session,
|
||||
composerBlock: () => sources.block,
|
||||
})
|
||||
onTestFinished(() => { shell.dispose() })
|
||||
return { shell, sink, pending, sources }
|
||||
}
|
||||
|
||||
const child = (mode: 'one-shot' | 'continuable'): SessionGate['subagent'] => ({
|
||||
address: { parentSessionId: 'parent' as SessionId, childSessionId: 'child' as SessionId, mode },
|
||||
})
|
||||
|
||||
it('inserts references without attachments and refuses while a submission owns the draft', async () => {
|
||||
const { shell, pending } = bench()
|
||||
expect(shell.canInsertReferences()).toBe(true)
|
||||
shell.setDraft('Review')
|
||||
expect(shell.addReferences([reference])).toBe(true)
|
||||
expect(shell.snapshot.draft).toBe('Review @"/work/a b.md" ')
|
||||
expect(shell.snapshot.attachmentIds).toEqual([])
|
||||
shell.submit()
|
||||
expect(shell.canInsertReferences()).toBe(false)
|
||||
expect(shell.addReferences([reference])).toBe(false)
|
||||
pending.resolve({ kind: 'success' })
|
||||
await vi.waitFor(() => { expect(shell.canInsertReferences()).toBe(true) })
|
||||
})
|
||||
|
||||
it('reads Session removal, subagent mode, and composer blocks at each call', () => {
|
||||
const { shell, sources } = bench()
|
||||
sources.session = { removed: true, subagent: null }
|
||||
expect(shell.canInsertReferences()).toBe(false)
|
||||
expect(shell.addReferences([reference])).toBe(false)
|
||||
expect(shell.snapshot.draft).toBe('')
|
||||
sources.session = { removed: false, subagent: child('one-shot') }
|
||||
expect(shell.canInsertReferences()).toBe(false)
|
||||
sources.session = { removed: false, subagent: child('continuable') }
|
||||
expect(shell.canInsertReferences()).toBe(true)
|
||||
sources.block = { reason: 'Unavailable' }
|
||||
expect(shell.canInsertReferences()).toBe(false)
|
||||
expect(shell.addReferences([reference])).toBe(false)
|
||||
sources.block = undefined
|
||||
expect(shell.addReferences([reference])).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses after disposal and permits insertion without Session sources', () => {
|
||||
const { shell } = bench()
|
||||
shell.dispose()
|
||||
expect(shell.canInsertReferences()).toBe(false)
|
||||
expect(shell.addReferences([reference])).toBe(false)
|
||||
const bare = new SessionInputShell({
|
||||
actx: {} as Context,
|
||||
defaultSink: async () => ({ kind: 'success' }),
|
||||
commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token },
|
||||
})
|
||||
onTestFinished(() => { bare.dispose() })
|
||||
expect(bare.canInsertReferences()).toBe(true)
|
||||
expect(bare.addReferences([reference])).toBe(true)
|
||||
})
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 779a9a534eaad38b
|
||||
zh: 3dd159a2c35702d6
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts:
|
||||
en: 0b41c33743e5b422
|
||||
zh: 551896094c03f57e
|
||||
en: 43b5324fb871a3d1
|
||||
zh: 3d101edc38b60d39
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/sent-file-and-folder-mentions:
|
||||
en: 87c27115eae5a660
|
||||
zh: a9a20431928072ec
|
||||
|
||||
@@ -33,6 +33,8 @@ 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`.
|
||||
|
||||
The shared file context menu ends with **Add to chat**. It inserts the clicked file as the same kind of reference into that Session’s draft, preserves existing text and selection, and returns focus without sending. The reference captures the resolved absolute path; line numbers are not included. The action is disabled when the Session cannot be edited at the moment the menu opens or the path cannot use the mention grammar; a draft that becomes uneditable while the menu stays open makes the action report failure instead of inserting. An open menu updates its label and failure feedback when the interface language changes.
|
||||
|
||||
### 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 candidate picked and sent in the same Session during one page load counts as confirmed, so its echo shows the reference immediately.
|
||||
|
||||
@@ -33,6 +33,8 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。
|
||||
|
||||
共享文件右键菜单最底部提供**添加到对话**。它将所选文件作为同类引用插入该 Session 的草稿,保留现有文字和选中内容,恢复输入焦点但不发送。引用记录解析后的绝对路径,不包含行号。打开菜单时 Session 不可编辑,或路径无法用 mention 语法表示时,此入口不可用;菜单打开期间草稿变为不可编辑时,点击会提示失败而不插入。切换界面语言时,已打开菜单的标题和失败提示随之更新。
|
||||
|
||||
### 已发送的文件与目录引用
|
||||
|
||||
在已发送消息、排队行和本地回显中,`@path` 或 `@"path"` token 只有在 Session 的文件系统确认该路径存在后才渲染为文件或目录引用。确认之前,以及路径不存在时(例如手写的 `@notes`),原文保持不变;邮箱地址永远不会匹配。在同一 Session、同一次页面加载内从候选中选择并发送的路径视为已确认,因此其回显会立即显示引用。
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/** File references contributed to the shared file menu. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { formatFileMention } from '@deepseek-ai/dsh-file-reference/grammar'
|
||||
import { resolveWorkspacePath, workspaceTitleOf } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type { ReferenceKey } from './locales.ts'
|
||||
|
||||
/**
|
||||
* Add the captured file to its Session draft without submitting or replacing selected text.
|
||||
* @param ctx - reference plugin's menu and conversation dependencies.
|
||||
* @param t - localized labels and failure feedback.
|
||||
*/
|
||||
export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => string): void {
|
||||
ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({
|
||||
name: 'contextMenu.icon', key: 'reference.addToChat',
|
||||
}, IconPlusOutlineRegular))
|
||||
const targetInput = ({ sessionId }: ContextMenuTargetMap['file']) => {
|
||||
const binding = ctx.sessions.binding(sessionId)
|
||||
if (binding === undefined) return undefined
|
||||
const input = ctx.conversation.input.for(binding.ctx)
|
||||
// A released or replaced binding must not receive the reference captured for its predecessor.
|
||||
const editable = (): boolean => ctx.sessions.binding(sessionId) === binding && input.canInsertReferences()
|
||||
return { input, editable }
|
||||
}
|
||||
ctx.effect(() => ctx.contextMenus.register({
|
||||
id: 'reference.file', target: 'file', order: 300,
|
||||
// Draft editability is read when the menu opens; run rechecks it before inserting.
|
||||
observe: () => [ctx.locale],
|
||||
resolve: (target) => {
|
||||
const current = targetInput(target)
|
||||
const path = resolveWorkspacePath(ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd, target.path)
|
||||
const mention = formatFileMention({ path, kind: 'file' }, false)
|
||||
return [{
|
||||
id: 'addToChat', label: t('menu.addToChat'), icon: { key: 'reference.addToChat' }, separatorBefore: true,
|
||||
disabled: mention === undefined || current === undefined || !current.editable(),
|
||||
failureLabel: t('menu.addToChatFailed'),
|
||||
run: () => {
|
||||
if (mention === undefined || current === undefined || !current.editable()
|
||||
|| !current.input.addReferences([{
|
||||
source: 'reference', ref: mention, label: workspaceTitleOf(path),
|
||||
appearance: 'file', clipboardText: mention,
|
||||
}])) throw new Error('File reference insertion unavailable')
|
||||
current.input.focus()
|
||||
},
|
||||
}]
|
||||
},
|
||||
}), 'ui-reference: file context menu')
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import type { FileReferenceCandidate } from '@deepseek-ai/dsh-file-reference/typ
|
||||
import type { SessionReferenceMentionCandidate } from '@deepseek-ai/dsh-session-reference/types'
|
||||
import { abbreviateHomePath, fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import { en, ja, es, fr, de, ru, pt, NS, zh, type ReferenceKey } from './locales.ts'
|
||||
import { registerReferenceMenu } from './context-menu.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-api-session-controller/client' {
|
||||
interface SessionReferenceSourceMap {
|
||||
@@ -63,6 +64,7 @@ export const inject = [
|
||||
export function apply(ctx: ClientContext): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-reference: dictionaries')
|
||||
const t = ctx.locale.bind(NS)
|
||||
ctx.inject(['contextMenus', 'conversation'], (menuCtx) => { registerReferenceMenu(menuCtx, t) })
|
||||
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')
|
||||
|
||||
@@ -13,6 +13,8 @@ export const NS = 'reference'
|
||||
* bucketing they name is the one shared {@link relativeTime} in ui-primitives.
|
||||
*/
|
||||
export const zh = {
|
||||
'menu.addToChat': '添加到对话',
|
||||
'menu.addToChatFailed': '无法添加文件,请返回对话后重试',
|
||||
'section.files': '文件与文件夹',
|
||||
'section.subagents': '子智能体',
|
||||
'section.sessions': '对话',
|
||||
@@ -42,6 +44,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
|
||||
/** English dictionary, checked complete against the zh key set. */
|
||||
export const en = {
|
||||
'menu.addToChat': 'Add to chat',
|
||||
'menu.addToChatFailed': 'Couldn’t add file. Return to the chat and try again.',
|
||||
'section.files': 'Files & folders',
|
||||
'section.subagents': 'Subagents',
|
||||
'section.sessions': 'Sessions',
|
||||
@@ -61,6 +65,8 @@ export const en = {
|
||||
|
||||
/** Japanese copy, checked against the English keys. */
|
||||
export const ja = {
|
||||
'menu.addToChat': 'チャットに追加',
|
||||
'menu.addToChatFailed': 'ファイルを追加できませんでした。チャットに戻って再試行してください。',
|
||||
'section.files': 'ファイルとフォルダ',
|
||||
'section.subagents': 'サブエージェント',
|
||||
'section.sessions': 'セッション',
|
||||
@@ -80,6 +86,8 @@ export const ja = {
|
||||
|
||||
/** Spanish dictionary, checked against the English keys. */
|
||||
export const es = {
|
||||
'menu.addToChat': 'Añadir al chat',
|
||||
'menu.addToChatFailed': 'No se pudo añadir el archivo. Vuelve al chat e inténtalo de nuevo.',
|
||||
'section.files': 'Archivos y carpetas',
|
||||
'section.subagents': 'Subagentes',
|
||||
'section.sessions': 'Sesiones',
|
||||
@@ -99,6 +107,8 @@ export const es = {
|
||||
|
||||
/** French dictionary, checked against the English keys. */
|
||||
export const fr = {
|
||||
'menu.addToChat': 'Ajouter au chat',
|
||||
'menu.addToChatFailed': 'Impossible d’ajouter le fichier. Revenez au chat et réessayez.',
|
||||
'section.files': 'Fichiers et dossiers',
|
||||
'section.subagents': 'Sous-agents',
|
||||
'section.sessions': 'Séances',
|
||||
@@ -118,6 +128,8 @@ export const fr = {
|
||||
|
||||
/** German dictionary, checked against the English keys. */
|
||||
export const de = {
|
||||
'menu.addToChat': 'Zum Chat hinzufügen',
|
||||
'menu.addToChatFailed': 'Datei konnte nicht hinzugefügt werden. Kehren Sie zum Chat zurück und versuchen Sie es erneut.',
|
||||
'section.files': 'Dateien und Ordner',
|
||||
'section.subagents': 'Subagenten',
|
||||
'section.sessions': 'Sitzungen',
|
||||
@@ -137,6 +149,8 @@ export const de = {
|
||||
|
||||
/** Russian dictionary, checked against the English keys. */
|
||||
export const ru = {
|
||||
'menu.addToChat': 'Добавить в чат',
|
||||
'menu.addToChatFailed': 'Не удалось добавить файл. Вернитесь в чат и повторите попытку.',
|
||||
'section.files': 'Файлы и папки',
|
||||
'section.subagents': 'Субагенты',
|
||||
'section.sessions': 'Сессии',
|
||||
@@ -156,6 +170,8 @@ export const ru = {
|
||||
|
||||
/** Portuguese dictionary, checked against the English keys. */
|
||||
export const pt = {
|
||||
'menu.addToChat': 'Adicionar ao chat',
|
||||
'menu.addToChatFailed': 'Não foi possível adicionar o arquivo. Volte ao chat e tente novamente.',
|
||||
'section.files': 'Arquivos e pastas',
|
||||
'section.subagents': 'Subagentes',
|
||||
'section.sessions': 'Sessões',
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Shared file menus insert references through the Session's real draft editor. */
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts'
|
||||
import { SessionInputShell } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/facade.ts'
|
||||
import { ComposerBlockRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/input/blocks.ts'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client'
|
||||
import { registerReferenceMenu } from '../src/client/context-menu.ts'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
|
||||
const id = 'target' as SessionId
|
||||
const actionId = 'reference.file/addToChat'
|
||||
|
||||
async function bench() {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
onTestFinished(() => runtime.dispose())
|
||||
const locale = new LocaleRuntime(runtime.ctx)
|
||||
runtime.ctx.provide('locale', locale)
|
||||
runtime.ctx.effect(() => locale.register('reference', { en, zh }))
|
||||
locale.setLocale('en')
|
||||
await runtime.declare({ 'contextMenu.icon': { kind: 'keyed', scope: 'root', inline: true } })
|
||||
await runtime.sessions.add({ id, summary: { cwd: '/workspace' } })
|
||||
const owner = runtime.sessions.retain(id)
|
||||
onTestFinished(() => { owner.release() })
|
||||
const binding = runtime.sessions.binding(id)!
|
||||
const sink = vi.fn(async () => ({ kind: 'success' as const }))
|
||||
const blocks = new ComposerBlockRegistry()
|
||||
const shell = new SessionInputShell({
|
||||
actx: binding.ctx, defaultSink: sink,
|
||||
commandAttachments: { serialize: async () => [], release: () => {}, unsupportedNotice: token => token },
|
||||
session: () => binding.session.getSnapshot(),
|
||||
composerBlock: () => blocks.storeFor(id).getSnapshot(),
|
||||
})
|
||||
onTestFinished(() => { shell.dispose() })
|
||||
const focus = vi.spyOn(shell, 'focus').mockImplementation(() => {})
|
||||
const resolveInput = vi.fn(() => shell)
|
||||
runtime.ctx.provide('conversation', { input: { for: resolveInput } })
|
||||
const failed = vi.fn()
|
||||
const menus = new MenuRegistry(failed)
|
||||
onTestFinished(() => { menus.dispose() })
|
||||
runtime.ctx.provide('contextMenus', { register: menus.register.bind(menus) })
|
||||
const fiber = runtime.ctx.plugin({
|
||||
inject: ['slots', 'sessions', 'conversation', 'contextMenus', 'locale'],
|
||||
apply: (ctx) => { registerReferenceMenu(ctx, locale.bind('reference')) },
|
||||
})
|
||||
await fiber.await()
|
||||
const menu = async (value: Partial<ContextMenuTargetMap['file']> = {}) => {
|
||||
const result = menus.resolve({ kind: 'file', value: { sessionId: id, path: 'docs/a b.md', ...value } })
|
||||
onTestFinished(() => { result.dispose() })
|
||||
await result.ready
|
||||
return result
|
||||
}
|
||||
return { runtime, locale, owner, binding, shell, sink, focus, blocks, resolveInput, failed, menus, fiber, menu }
|
||||
}
|
||||
|
||||
it('appends the final action after other providers and inserts the captured file without sending', async () => {
|
||||
const b = await bench()
|
||||
const ready = Promise.withResolvers<undefined>()
|
||||
b.menus.register({ id: 'open', target: 'file', order: 100, resolve: async () => {
|
||||
await ready.promise
|
||||
return [{ id: 'preview', label: 'Preview' }]
|
||||
} })
|
||||
b.menus.register({ id: 'save', target: 'file', order: 200, resolve: () => [{ id: 'download', label: 'Download' }] })
|
||||
b.shell.setDraft('Review this')
|
||||
const pending = b.menu({ line: 24 })
|
||||
ready.resolve(undefined)
|
||||
const menu = await pending
|
||||
expect(menu.source.getSnapshot().map(row => row.label)).toEqual(['Preview', 'Download', en['menu.addToChat']])
|
||||
expect(menu.source.getSnapshot().at(-1)).toMatchObject({ separatorBefore: true, disabled: false })
|
||||
menu.select(actionId)
|
||||
expect(b.resolveInput).toHaveBeenCalledWith(b.binding.ctx)
|
||||
expect(b.shell.snapshot.draft).toBe('Review this @"/workspace/docs/a b.md" ')
|
||||
expect(b.shell.snapshot.occurrences).toMatchObject([{
|
||||
source: 'reference', ref: '@"/workspace/docs/a b.md"', label: 'a b.md', appearance: 'file',
|
||||
}])
|
||||
expect(b.shell.snapshot.attachmentIds).toEqual([])
|
||||
expect(b.focus).toHaveBeenCalledOnce()
|
||||
expect(b.sink).not.toHaveBeenCalled()
|
||||
expect(b.failed).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['bad"name.txt', 'bad\nname.txt'])('disables paths outside the mention grammar: %j', async (path) => {
|
||||
const b = await bench()
|
||||
const menu = await b.menu({ path })
|
||||
expect(menu.source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
menu.select(actionId)
|
||||
expect(b.shell.snapshot.draft).toBe('')
|
||||
expect(b.focus).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disables an unretained Session and never opens it or targets another draft', async () => {
|
||||
const b = await bench()
|
||||
const menu = await b.menu({ sessionId: 'absent' as SessionId })
|
||||
expect(menu.source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
expect(b.resolveInput).not.toHaveBeenCalled()
|
||||
menu.select(actionId)
|
||||
expect(b.shell.snapshot.draft).toBe('')
|
||||
})
|
||||
|
||||
it('reads composer blocks when the menu opens and rechecks them at execution', async () => {
|
||||
const b = await bench()
|
||||
b.blocks.set(id, { reason: 'Unavailable' })
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
b.blocks.set(id, undefined)
|
||||
const menu = await b.menu()
|
||||
expect(menu.source.getSnapshot()[0]?.disabled).toBe(false)
|
||||
b.blocks.set(id, { reason: 'Unavailable' })
|
||||
// An open menu keeps the state read when it opened; execution refuses the stale action.
|
||||
expect(menu.source.getSnapshot()[0]?.disabled).toBe(false)
|
||||
menu.select(actionId)
|
||||
expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed'])
|
||||
expect(b.shell.snapshot.draft).toBe('')
|
||||
expect(b.focus).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a stale Session binding at execution', async () => {
|
||||
const b = await bench()
|
||||
const menu = await b.menu()
|
||||
b.owner.release()
|
||||
menu.select(actionId)
|
||||
expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed'])
|
||||
expect(b.focus).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disables removed and one-shot Sessions but permits continuable Sessions', async () => {
|
||||
const b = await bench()
|
||||
await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.removed = true })
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
await b.runtime.sessions.updateSessionSnapshot(id, (state) => {
|
||||
state.removed = false
|
||||
state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'one-shot' } }
|
||||
})
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
await b.runtime.sessions.updateSessionSnapshot(id, (state) => {
|
||||
state.subagent = { address: { parentSessionId: 'parent' as SessionId, childSessionId: id, mode: 'continuable' } }
|
||||
})
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('disables the action while a submission owns the draft but not while a turn runs', async () => {
|
||||
const b = await bench()
|
||||
const pending = Promise.withResolvers<{ kind: 'success' }>()
|
||||
b.sink.mockImplementation(() => pending.promise)
|
||||
await b.runtime.sessions.updateSessionSnapshot(id, (state) => { state.running = true })
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false)
|
||||
b.shell.setDraft('Sending')
|
||||
b.shell.submit()
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
pending.resolve({ kind: 'success' })
|
||||
await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') })
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('reports insertion refusal without focusing or sending', async () => {
|
||||
const b = await bench()
|
||||
vi.spyOn(b.shell, 'addReferences').mockReturnValue(false)
|
||||
const menu = await b.menu()
|
||||
menu.select(actionId)
|
||||
expect(b.failed).toHaveBeenCalledWith(en['menu.addToChatFailed'])
|
||||
expect(b.focus).not.toHaveBeenCalled()
|
||||
expect(b.sink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('withdraws open menu actions and their icon on plugin disposal', async () => {
|
||||
const b = await bench()
|
||||
const menu = await b.menu()
|
||||
expect(b.runtime.ctx.slots.entries('contextMenu.icon').map(row => row.options.key)).toEqual(['reference.addToChat'])
|
||||
await b.fiber.dispose()
|
||||
expect(menu.source.getSnapshot()).toEqual([])
|
||||
expect(b.runtime.ctx.slots.entries('contextMenu.icon')).toEqual([])
|
||||
menu.select(actionId)
|
||||
expect(b.focus).not.toHaveBeenCalled()
|
||||
expect(zh['menu.addToChat']).toBe('添加到对话')
|
||||
})
|
||||
|
||||
it('refreshes open labels and failure feedback when the locale changes', async () => {
|
||||
const b = await bench()
|
||||
const menu = await b.menu()
|
||||
const unavailable = await b.menu({ sessionId: 'absent' as SessionId })
|
||||
expect(menu.source.getSnapshot()[0]?.label).toBe(en['menu.addToChat'])
|
||||
expect(unavailable.source.getSnapshot()[0]?.label).toBe(en['menu.addToChat'])
|
||||
b.locale.setLocale('zh')
|
||||
expect(menu.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat'])
|
||||
expect(unavailable.source.getSnapshot()[0]?.label).toBe(zh['menu.addToChat'])
|
||||
vi.spyOn(b.shell, 'addReferences').mockReturnValue(false)
|
||||
menu.select(actionId)
|
||||
expect(b.failed).toHaveBeenCalledWith(zh['menu.addToChatFailed'])
|
||||
await b.fiber.dispose()
|
||||
b.locale.setLocale('en')
|
||||
expect(unavailable.source.getSnapshot()).toEqual([])
|
||||
})
|
||||
|
||||
it.each(['/work/a b.md', 'C:\\work\\a b.md', '\\\\server\\share\\a b.md', '/work/a b.md/'])(
|
||||
'uses the final nonempty path segment as the reference label: %j', async (path) => {
|
||||
const b = await bench()
|
||||
const menu = await b.menu({ path })
|
||||
menu.select(actionId)
|
||||
expect(b.shell.snapshot.occurrences).toMatchObject([{ label: 'a b.md', ref: `@"${path}"` }])
|
||||
},
|
||||
)
|
||||
|
||||
it('disables the action and refuses direct insertion after the draft editor is disposed', async () => {
|
||||
const b = await bench()
|
||||
b.shell.setDraft('Keep this')
|
||||
b.shell.dispose()
|
||||
expect((await b.menu()).source.getSnapshot()[0]?.disabled).toBe(true)
|
||||
expect(b.shell.addReferences([{ source: 'reference', ref: '@file.txt', label: 'file.txt', clipboardText: '@file.txt' }])).toBe(false)
|
||||
expect(b.shell.snapshot.draft).toBe('Keep this')
|
||||
})
|
||||
@@ -157,7 +157,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
|
||||
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
|
||||
],
|
||||
keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: open-in-app.application, sidebar.close',
|
||||
keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: open-in-app.application, reference.addToChat, sidebar.close',
|
||||
hookContext: '',
|
||||
slotInject: '',
|
||||
declaredBy: 'an entry in \'shell.overlay\' (client-ui-context-menu), so it exists while that entry is mounted',
|
||||
@@ -165,6 +165,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
'client-ui-file-actions Icon',
|
||||
'client-ui-open-in-app Icon',
|
||||
'client-ui-open-in-app ContextMenuApplicationIcon key \'open-in-app.application\'',
|
||||
'client-ui-reference IconPlusOutlineRegular key \'reference.addToChat\'',
|
||||
'client-ui-sidebar-right IconCloseOutlineRegular key \'sidebar.close\'',
|
||||
'client-ui-workspace Icon',
|
||||
'session-log-export Icon',
|
||||
|
||||
@@ -137,11 +137,18 @@ export function grepSearchMeta(retained: RetainedPage<GrepMatch>, maxMetaBytes:
|
||||
return capMetaBytes(meta, maxMetaBytes)
|
||||
}
|
||||
|
||||
// Glob paths are V8 substrings of ripgrep's whole stdout, and the Session keeps `meta` for its
|
||||
// lifetime. A UTF-16LE round trip copies each path so the stdout string can be garbage-collected.
|
||||
function detachText(text: string): string {
|
||||
return Buffer.from(text, 'utf16le').toString('utf16le')
|
||||
}
|
||||
|
||||
/**
|
||||
* Project the retained `glob` paths into {@link SearchMeta} for the search card.
|
||||
* Consumes the same {@link RetainedItems} the model-facing render consumes (inline
|
||||
* path cap already applied), reports `total` (every discovered path) and
|
||||
* `truncated`, then bounds the serialized meta to `maxMetaBytes`.
|
||||
* `truncated`, then bounds the serialized meta to `maxMetaBytes`. Returned paths hold no reference
|
||||
* to the strings in `retained`.
|
||||
*
|
||||
* @param retained - the retention outcome over every discovered path (capped).
|
||||
* @param maxMetaBytes - the serialized-meta byte budget.
|
||||
@@ -150,7 +157,7 @@ export function grepSearchMeta(retained: RetainedPage<GrepMatch>, maxMetaBytes:
|
||||
export function globSearchMeta(retained: RetainedPage<string>, maxMetaBytes: number): SearchMeta {
|
||||
const meta: SearchMeta = {
|
||||
shape: 'paths',
|
||||
paths: retained.items,
|
||||
paths: retained.items.map(detachText),
|
||||
truncated: retained.truncated,
|
||||
total: retained.seen,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Memory retention of `glob` search metadata: paths split from a large ripgrep stdout string must
|
||||
* not keep that string alive once the Session holds only the metadata. The case forces full
|
||||
* garbage collection and checks that heap usage returns near its baseline.
|
||||
*/
|
||||
|
||||
import { setFlagsFromString } from 'node:v8'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { expect, it } from 'vitest'
|
||||
import { globSearchMeta } from '../src/presentation.ts'
|
||||
import type { SearchMeta } from '../src/presentation.ts'
|
||||
|
||||
setFlagsFromString('--expose-gc')
|
||||
const collect = runInNewContext('gc') as () => void
|
||||
|
||||
const STDOUT_CHARS = 32 * 1024 * 1024
|
||||
|
||||
function fullGc(): void {
|
||||
collect()
|
||||
collect()
|
||||
}
|
||||
|
||||
function metaFromLargeStdout(): SearchMeta {
|
||||
const line = `src/${'nested/'.repeat(20)}file.ts\n`
|
||||
const stdout = line.repeat(Math.ceil(STDOUT_CHARS / line.length))
|
||||
const paths = stdout.split('\n', 3)
|
||||
return globSearchMeta({ items: paths, truncated: true, seen: paths.length }, 1_000_000)
|
||||
}
|
||||
|
||||
it('globSearchMeta drops the stdout string behind its paths', () => {
|
||||
fullGc()
|
||||
const before = process.memoryUsage().heapUsed
|
||||
const meta = metaFromLargeStdout()
|
||||
fullGc()
|
||||
expect(process.memoryUsage().heapUsed - before).toBeLessThan(STDOUT_CHARS / 4)
|
||||
expect(meta).toMatchObject({ shape: 'paths', paths: Array.from({ length: 3 }, () => `src/${'nested/'.repeat(20)}file.ts`) })
|
||||
})
|
||||
@@ -29,7 +29,7 @@ export interface ReadWindow {
|
||||
export interface FileTextLine {
|
||||
/** 1-based line number in the file. */
|
||||
number: number
|
||||
/** Line text without its trailing newline. */
|
||||
/** Line text without its trailing newline; from {@link buildWindow}, it references no string larger than one input chunk. */
|
||||
text: string
|
||||
}
|
||||
|
||||
@@ -74,9 +74,14 @@ function lineByteSize(line: string, currentLineCount: number): number {
|
||||
return Buffer.byteLength(line, 'utf8') + (currentLineCount > 0 ? 1 : 0)
|
||||
}
|
||||
|
||||
function wantsNextLine(acc: WindowAccumulator, request: ReadWindow): boolean {
|
||||
return !acc.truncatedByBytes && acc.totalLines + 1 >= request.offset && acc.lines.length < request.limit
|
||||
}
|
||||
|
||||
function consumeLine(acc: WindowAccumulator, rawLine: string, request: ReadWindow): void {
|
||||
const wanted = wantsNextLine(acc, request)
|
||||
acc.totalLines += 1
|
||||
if (acc.truncatedByBytes || acc.totalLines < request.offset || acc.lines.length >= request.limit) return
|
||||
if (!wanted) return
|
||||
|
||||
const text = truncateLine(rawLine, request.maxLineLength)
|
||||
const bytes = lineByteSize(text, acc.lines.length)
|
||||
@@ -103,7 +108,8 @@ function finish(acc: WindowAccumulator, request: ReadWindow, displayPath: string
|
||||
* Build one window from streamed or whole-file chunks, enforcing line and byte caps while still
|
||||
* scanning to an exact total line count, and throwing `FS_NOT_FOUND` when the requested offset is
|
||||
* past EOF.
|
||||
* @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning.
|
||||
* @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning. A kept line
|
||||
* that is a whole chunk is returned as that chunk, so a chunk must not be a substring of a larger string.
|
||||
* @param request - the resolved window; the caller has already applied its defaults and caps.
|
||||
* @param displayPath - the caller-facing path used in the offset-out-of-range error.
|
||||
* @returns the numbered window lines, the total line count seen, and the byte-cap truncation flag.
|
||||
@@ -114,32 +120,46 @@ export async function buildWindow(
|
||||
displayPath: string,
|
||||
): Promise<WindowResult> {
|
||||
const acc = newAccumulator()
|
||||
// One char past the truncation point is enough to prove a line overflows.
|
||||
const lineBufferCap = request.maxLineLength + 1
|
||||
// Two chars past the truncation point still prove a line overflows after a trailing `\r` is stripped.
|
||||
const lineBufferCap = request.maxLineLength + 2
|
||||
let lineBuffer = ''
|
||||
let lineHasText = false
|
||||
let lineHasSlice = false
|
||||
|
||||
function appendToLineBuffer(segment: string): void {
|
||||
if (lineBuffer.length >= lineBufferCap) return
|
||||
lineBuffer += segment
|
||||
if (lineBuffer.length > lineBufferCap) lineBuffer = lineBuffer.slice(0, lineBufferCap)
|
||||
// Only lines the window still wants are collected, up to the truncation point.
|
||||
function appendToLineBuffer(chunk: string, start: number, end: number): void {
|
||||
const stop = Math.min(end, start + lineBufferCap - lineBuffer.length)
|
||||
if (stop <= start || !wantsNextLine(acc, request)) return
|
||||
if (start === 0 && stop === chunk.length) {
|
||||
lineBuffer += chunk
|
||||
} else {
|
||||
lineBuffer += chunk.slice(start, stop)
|
||||
lineHasSlice = true
|
||||
}
|
||||
}
|
||||
|
||||
function flushLine(): void {
|
||||
consumeLine(acc, stripCarriageReturn(lineBuffer), request)
|
||||
// A slice keeps its whole chunk alive, and kept lines outlive the read, so a line built from a
|
||||
// slice is copied once; a UTF-16LE round trip keeps lone surrogates.
|
||||
const line = lineHasSlice ? Buffer.from(lineBuffer, 'utf16le').toString('utf16le') : lineBuffer
|
||||
consumeLine(acc, stripCarriageReturn(line), request)
|
||||
lineBuffer = ''
|
||||
lineHasSlice = false
|
||||
}
|
||||
|
||||
for await (const chunk of chunks) {
|
||||
let startPos = 0
|
||||
let newlinePos: number
|
||||
while ((newlinePos = chunk.indexOf('\n', startPos)) !== -1) {
|
||||
appendToLineBuffer(chunk.slice(startPos, newlinePos))
|
||||
appendToLineBuffer(chunk, startPos, newlinePos)
|
||||
flushLine()
|
||||
lineHasText = false
|
||||
startPos = newlinePos + 1
|
||||
}
|
||||
appendToLineBuffer(chunk.slice(startPos))
|
||||
appendToLineBuffer(chunk, startPos, chunk.length)
|
||||
if (startPos < chunk.length) lineHasText = true
|
||||
}
|
||||
if (lineBuffer.length > 0) flushLine()
|
||||
if (lineHasText) flushLine()
|
||||
return finish(acc, request, displayPath)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Memory retention of returned read lines: a short retained line must not keep the decoded input
|
||||
* string alive after the caller drops it. Each case scans a large input string, keeps only
|
||||
* the returned window, forces full garbage collection, and checks that heap usage returns near its
|
||||
* baseline instead of staying at the input size. The input is allocated on the V8 heap because Node
|
||||
* frees external string memory asynchronously, which makes `memoryUsage().external` unstable here.
|
||||
* The cases cover whole-file and streamed input, lines that span chunks, and truncated lines.
|
||||
*/
|
||||
|
||||
import { setFlagsFromString } from 'node:v8'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildWindow, READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from '../src/read-render.ts'
|
||||
import type { FileTextLine } from '../src/read-render.ts'
|
||||
|
||||
setFlagsFromString('--expose-gc')
|
||||
const collect = runInNewContext('gc') as () => void
|
||||
|
||||
const INPUT_CHARS = 32 * 1024 * 1024
|
||||
const RETAINED_LIMIT = INPUT_CHARS / 4
|
||||
|
||||
function fullGc(): void {
|
||||
collect()
|
||||
collect()
|
||||
}
|
||||
|
||||
function largeText(line: string): string {
|
||||
return `${line}\r\n`.repeat(Math.ceil(INPUT_CHARS / (line.length + 2)))
|
||||
}
|
||||
|
||||
/** Measure the heap still held after `buildWindow` scans a large input and only its lines are kept. */
|
||||
async function measure(
|
||||
line: string,
|
||||
chunking: 'whole' | 'stream' | 'mid-line',
|
||||
maxLineLength: number,
|
||||
): Promise<{ bytes: number; lines: FileTextLine[] }> {
|
||||
async function* chunks(): AsyncIterable<string> {
|
||||
const input = largeText(line)
|
||||
if (chunking === 'whole') {
|
||||
yield input
|
||||
return
|
||||
}
|
||||
let at = 0
|
||||
if (chunking === 'mid-line') {
|
||||
// Chunk boundaries fall inside lines 2-4, so each kept line joins two chunks.
|
||||
for (const end of [1, 2, 3].map(index => index * (line.length + 2) + 100)) {
|
||||
yield input.slice(at, end)
|
||||
at = end
|
||||
}
|
||||
}
|
||||
for (; at < input.length; at += 1024 * 1024) yield input.slice(at, at + 1024 * 1024)
|
||||
}
|
||||
fullGc()
|
||||
const before = process.memoryUsage().heapUsed
|
||||
const window = await buildWindow(chunks(), { offset: 2, limit: 3, maxLineLength, maxBytes: READ_MAX_BYTES }, 'f')
|
||||
fullGc()
|
||||
return { bytes: process.memoryUsage().heapUsed - before, lines: window.lines }
|
||||
}
|
||||
|
||||
describe('buildWindow retention', () => {
|
||||
it.each([
|
||||
['whole-file ASCII lines', 'a'.repeat(200), 'whole', READ_MAX_LINE_LENGTH],
|
||||
['whole-file two-byte lines', '中'.repeat(200), 'whole', READ_MAX_LINE_LENGTH],
|
||||
['streamed lines', 'c'.repeat(200), 'stream', READ_MAX_LINE_LENGTH],
|
||||
['lines that span chunks', 'd'.repeat(200), 'mid-line', READ_MAX_LINE_LENGTH],
|
||||
['truncated lines', 'e'.repeat(5000), 'whole', 100],
|
||||
] as const)('drops the decoded input behind %s', async (_name, line, chunking, maxLineLength) => {
|
||||
const { bytes, lines } = await measure(line, chunking, maxLineLength)
|
||||
const text = line.length > maxLineLength ? `${line.slice(0, maxLineLength)}... (line truncated to ${maxLineLength} chars)` : line
|
||||
expect(lines).toEqual([2, 3, 4].map(number => ({ number, text })))
|
||||
expect(bytes).toBeLessThan(RETAINED_LIMIT)
|
||||
})
|
||||
})
|
||||
@@ -84,6 +84,21 @@ describe('buildWindow', () => {
|
||||
expect(result.lines[0]?.text).toBe('abcde... (line truncated to 5 chars)')
|
||||
})
|
||||
|
||||
it('truncates a long line whose lone \\r falls right after the truncation point', async () => {
|
||||
const result = await buildWindow(whole('abcde\rXYZ\nnext'), { offset: 1, limit: 10, maxLineLength: 5, maxBytes: READ_MAX_BYTES }, 'f')
|
||||
expect(result.lines[0]?.text).toBe('abcde... (line truncated to 5 chars)')
|
||||
})
|
||||
|
||||
it('keeps a CRLF line of exactly maxLineLength chars whole', async () => {
|
||||
const result = await buildWindow(chunked('abcde\r\nnext', 3), { offset: 1, limit: 10, maxLineLength: 5, maxBytes: READ_MAX_BYTES }, 'f')
|
||||
expect(result.lines).toEqual([{ number: 1, text: 'abcde' }, { number: 2, text: 'next' }])
|
||||
})
|
||||
|
||||
it('keeps the lone high surrogate left by truncating inside a surrogate pair', async () => {
|
||||
const result = await buildWindow(whole('abcd😀z'), { offset: 1, limit: 10, maxLineLength: 5, maxBytes: READ_MAX_BYTES }, 'f')
|
||||
expect(result.lines[0]?.text).toBe('abcd\uD83D... (line truncated to 5 chars)')
|
||||
})
|
||||
|
||||
it('caps output at a custom maxBytes', async () => {
|
||||
const result = await buildWindow(whole('aaaa\nbbbb\ncccc'), { offset: 1, limit: 10, maxLineLength: 2000, maxBytes: 9 }, 'f')
|
||||
expect(result.lines.map(l => l.text)).toEqual(['aaaa', 'bbbb'])
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
## File menu
|
||||
|
||||
- menu:
|
||||
- menuitem "Download"
|
||||
- separator
|
||||
- menuitem "Add to chat"
|
||||
|
||||
## Composer
|
||||
|
||||
- textbox "Message or run a task, / commands, @ files or sessions":
|
||||
- paragraph: "Review this file next: example.txt"
|
||||
Reference in new issue
Block a user