Merge master to refresh the CUA event graph
This commit is contained in:
commit
c65abe9934
150 files changed
+7415
-674
No files matched your search
@@ -18,9 +18,9 @@ The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes
|
||||
|
||||
The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. The publisher marks the head pending before Python setup or lexer installation, so failed setup or an interrupted history fetch cannot leave a previous success in place. Setup and evaluation failures publish an error status. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. The publisher also writes a `weighted approval decision` check run that reports the same decision as a conclusion — `action_required` while the policy is unmet, `success` when it holds, and `failure` on setup or evaluation failures — with the score or blocker in its title. Branch rules do not require that check run, so it never blocks a merge; it names the blocked state beside the status that gates the merge. The check run is published with a token minted from a dedicated approval App (`DSH_APPROVAL_APP_CLIENT_ID`, `DSH_APPROVAL_APP_PRIVATE_KEY`, `DSH_APPROVAL_APP_SLUG`, scope `checks: write`): GitHub attaches a check run created with the job token to the earliest Actions check suite on the head, and when that suite belongs to this `pull_request_target` workflow the merge box omits it, so the App identity makes the association stable. The App publishes only runs whose `app.slug` is the App; job-token runs from earlier evaluations stay untouched and can coexist on a head. When the token or slug is missing, the publisher falls back to the job token and updates job-token runs only, which keeps the label on the Checks page. The App token step runs with `continue-on-error`, so a missing App configuration fails only that step and leaves the job-token fallback; a failed check-run write is logged by the publisher and never changes the status.
|
||||
|
||||
Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count.
|
||||
Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@CreatixChu`, `@imccyu`, `@LegGasai`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count.
|
||||
|
||||
The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error.
|
||||
The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule, except that PRs authored by `@turtle2099` receive a fixed 0.2 points without a history lookup. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count, or the fixed credit, separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error.
|
||||
|
||||
A one-point approval receives weight `min(2, 1 + 4 × ownedLines / totalLines)` from modified or deleted old production-code lines, attributed by `git blame` at the merge base of the live base branch and exact reviewed head. Ownership of 0%, 12.5%, and 25% gives 1, 1.5, and 2 points; higher ownership remains capped at 2. The success threshold remains 2 total points, without rounding the score. New lines do not enter the denominator, and an empty denominator gives no boost. Existing two-point weights remain unchanged. GitHub commit-author accounts identify reviewers across author emails; unlinked authors remain in the denominator without contributing to a reviewer. The publisher logs measured ownership. It skips attribution when reviewer points plus author credit already meet the threshold or a blocking review exists. Displayed scores use at most three decimal places; the decision uses unrounded scores with a tolerance of `1e-12` points for floating-point error. The curve endpoints come from the policy’s default and required points.
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
"defaultPoints": 1,
|
||||
"reviewerPoints": {
|
||||
"07akioni": 2,
|
||||
"CreatixChu": 2,
|
||||
"imccyu": 2,
|
||||
"LegGasai": 2,
|
||||
"tianyicui": 2,
|
||||
"tianyicui-bot": 2,
|
||||
"turtle1999": 2,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/** Author credit from merged pull requests in the same repository. */
|
||||
/** Author credit from merged pull requests in the same repository, or fixed points for listed logins. */
|
||||
const CAP_COUNT = 100
|
||||
/** Author points that replace merged-history credit, keyed by lowercase login. */
|
||||
export const FIXED_AUTHOR_POINTS = new Map([['turtle2099', 0.2]])
|
||||
|
||||
/**
|
||||
* Convert merged PR count to author points, capped at 1.1.
|
||||
|
||||
@@ -5,7 +5,7 @@ import process from 'node:process'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
import { productionOwnership, LOGIN } from './blame-ownership.mjs'
|
||||
import { authorCreditPoints, countMergedAuthorPulls } from './author-weight.mjs'
|
||||
import { FIXED_AUTHOR_POINTS, authorCreditPoints, countMergedAuthorPulls } from './author-weight.mjs'
|
||||
|
||||
const API_VERSION = '2026-03-10'
|
||||
const MAX_PULL_REQUEST_RECORDS = 3_000
|
||||
@@ -211,7 +211,7 @@ function timestamp(value, subject) {
|
||||
/**
|
||||
* Evaluate approval points from current reviews and repository permissions.
|
||||
* @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>, getOwnership?: typeof productionOwnership, getMergedCount?: typeof countMergedAuthorPulls}} options Runtime inputs.
|
||||
* @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, authorCredit: {mergedCount: number, points: number} | null, requiredPoints: number, approvals: Array<{login: string, points: number, delegatedTo?: string, ownership?: {ownedLines: number, totalLines: number}}>, delegations: Array<{login: string, delegatedTo: string, commentId: number, reviewIds: number[], approved: boolean}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields; approval login owns the points, delegatedTo supplies its decision, delegations contains eligible active commands and their superseded decision review IDs, and null author credit means history was not evaluated.
|
||||
* @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, authorCredit: {mergedCount: number | null, points: number} | null, requiredPoints: number, approvals: Array<{login: string, points: number, delegatedTo?: string, ownership?: {ownedLines: number, totalLines: number}}>, delegations: Array<{login: string, delegatedTo: string, commentId: number, reviewIds: number[], approved: boolean}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields; approval login owns the points, delegatedTo supplies its decision, delegations contains eligible active commands and their superseded decision review IDs, null author credit means credit was not evaluated, and null mergedCount means fixed author points.
|
||||
*/
|
||||
export async function evaluateApproval({ event, policySource, api, getOwnership = productionOwnership, getMergedCount = countMergedAuthorPulls }) {
|
||||
const pull = pullRequestFromEvent(event)
|
||||
@@ -264,8 +264,9 @@ export async function evaluateApproval({ event, policySource, api, getOwnership
|
||||
let authorCredit = null
|
||||
const reviewerPoints = approvals.reduce((sum, approval) => sum + approval.points, 0)
|
||||
if (blockers.length === 0 && reviewerPoints < policy.requiredPoints) {
|
||||
const mergedCount = await getMergedCount(pull, api)
|
||||
authorCredit = { mergedCount, points: authorCreditPoints(mergedCount) }
|
||||
const fixedPoints = FIXED_AUTHOR_POINTS.get(pull.author.toLowerCase())
|
||||
const mergedCount = fixedPoints === undefined ? await getMergedCount(pull, api) : null
|
||||
authorCredit = { mergedCount, points: fixedPoints ?? authorCreditPoints(mergedCount) }
|
||||
}
|
||||
const pointsBeforeOwnership = reviewerPoints + (authorCredit?.points ?? 0)
|
||||
if (blockers.length === 0 && pointsBeforeOwnership < policy.requiredPoints
|
||||
@@ -338,7 +339,7 @@ export async function runApprovalCheck({ event, policySource, api, checkApi = ap
|
||||
throw error
|
||||
}
|
||||
write(result.authorCredit
|
||||
? `Author credit: ${result.authorCredit.points} (${result.authorCredit.mergedCount} merged PRs).`
|
||||
? `Author credit: ${result.authorCredit.points} (${result.authorCredit.mergedCount === null ? `fixed for @${pull.author}` : `${result.authorCredit.mergedCount} merged PRs`}).`
|
||||
: `Author credit: not evaluated (${pull.draft ? 'draft' : result.blockers.length ? 'blocking review' : 'reviewer points suffice'}).`)
|
||||
write(`Approval score: ${result.points}/${result.requiredPoints}.`)
|
||||
writeList(write, 'Counted approvals', result.approvals.map(({ login, points, ownership, delegatedTo }) =>
|
||||
|
||||
@@ -45,7 +45,9 @@ test('loads the repository approval score policy', () => {
|
||||
assert.equal(policy.defaultPoints, 1)
|
||||
assert.deepEqual([...policy.reviewerPoints], [
|
||||
['07akioni', 2],
|
||||
['creatixchu', 2],
|
||||
['imccyu', 2],
|
||||
['leggasai', 2],
|
||||
['tianyicui', 2],
|
||||
['tianyicui-bot', 2],
|
||||
['turtle1999', 2],
|
||||
@@ -668,6 +670,21 @@ for (const [mergedCount, credit] of [[0, 0], [1, 0.011], [50, 0.55], [99, 1.089]
|
||||
})
|
||||
}
|
||||
|
||||
test('turtle2099 contributes fixed author points without a history lookup', async () => {
|
||||
const output = []
|
||||
const result = await runApprovalCheck({
|
||||
event: pullRequestEvent({ author: 'Turtle2099' }), policySource, runUrl: 'https://github.example/run/1',
|
||||
getMergedCount: async () => { throw new Error('fixed author credit must skip history') },
|
||||
getOwnership: async () => ({ totalLines: 10, reviewerLines: { writer: 2 } }),
|
||||
api: async path => path.includes('/reviews?') ? [review('writer', 'APPROVED')] : { permission: 'write' },
|
||||
write: line => output.push(line),
|
||||
})
|
||||
assert.deepEqual(result.authorCredit, { mergedCount: null, points: 0.2 })
|
||||
assert.equal(result.approvals[0].points, 1.8)
|
||||
assert.equal(result.state, 'success')
|
||||
assert.ok(output.includes('Author credit: 0.2 (fixed for @Turtle2099).'))
|
||||
})
|
||||
|
||||
test('combines author credit and reviewer ownership at the passing threshold', async () => {
|
||||
for (let mergedCount = 0; mergedCount <= 90; mergedCount++) {
|
||||
const result = await evaluateApproval({
|
||||
|
||||
@@ -63,6 +63,7 @@
|
||||
"@deepseek-ai/dsh-schedule": "workspace:*",
|
||||
"@deepseek-ai/dsh-sdk-app": "workspace:*",
|
||||
"@deepseek-ai/dsh-sdk-minimal": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence-sqlite": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-reference": "workspace:*",
|
||||
"@deepseek-ai/dsh-skill": "workspace:*",
|
||||
|
||||
@@ -1141,7 +1141,7 @@ describe('a user preset declared from the shipped cordis rows', () => {
|
||||
expect(listed.isError).toBe(false)
|
||||
const providers = (JSON.parse(resultText(listed)) as { providers: Array<{ id: string; platform: string }> }).providers
|
||||
expect(providers.filter(provider => provider.platform === 'host').map(provider => provider.id))
|
||||
.toEqual(['Service', 'Event', 'Config', 'Tool'])
|
||||
.toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool'])
|
||||
|
||||
// The `Tool` provider is the one built over the host context: it
|
||||
// answers with the shared registry's view of the REQUESTING agent,
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
- text: "1"
|
||||
- list:
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
- text: "1"
|
||||
- list:
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -776,7 +776,7 @@ async function expectNumberedReference({ scaffold, page, project, tripwire }: Pa
|
||||
await page.getByRole('button', { name: TOGGLE_ATTENTION, exact: true }).waitFor({ timeout: 20_000 })
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
await change.getByText('等待评审', { exact: true }).waitFor()
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'),
|
||||
await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE)
|
||||
@@ -884,7 +884,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
await page.getByRole('tooltip').filter({ hasText: `工作树(基于 release):${abbreviateHomePath(directory, homedir())}` }).waitFor()
|
||||
await page.mouse.move(0, 0)
|
||||
const change = panel.locator(`[data-forge-change="${PULL}"]`)
|
||||
const title = change.getByRole('link', { name: 'Add the pull request panel', exact: true })
|
||||
const title = change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' })
|
||||
await title.waitFor({ timeout: 20_000 })
|
||||
// The only open change request starts expanded.
|
||||
await change.getByText('等待评审', { exact: true }).waitFor()
|
||||
@@ -954,6 +954,42 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('creates the requested worktree for the first message, not for the notice an access mode change queues before it', async () => {
|
||||
const { scaffold, page, project, tripwire } = await requestReleaseWorktree('web-e2e-forge-panel-access-mode')
|
||||
await page.locator('button[aria-label^="访问模式"]').first().click()
|
||||
await page.getByRole('menuitem', { name: '完全权限', exact: true }).click()
|
||||
const confirmation = page.getByRole('dialog', { name: '确认启用完全权限?' })
|
||||
await confirmation.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check()
|
||||
await confirmation.getByRole('button', { name: '启用完全权限' }).click()
|
||||
await page.locator('button[aria-label="访问模式,当前:完全权限"]').waitFor()
|
||||
// The switch queues its approval notice for the next step, which opens no turn. A hold would run as maintenance of
|
||||
// the Agent until the worktree exists, and the Session would then work in it.
|
||||
const noticed = () => scaffold.ctx.agents.list()
|
||||
.find(candidate => candidate.inbox.nextStep.some(message => message.source.kind === 'user-approval'))
|
||||
await expect.poll(() => noticed() !== undefined).toBe(true)
|
||||
const agent = noticed()
|
||||
if (agent === undefined) throw new Error('The access mode change must queue its notice')
|
||||
await agent.runMaintenance(() => Promise.resolve())
|
||||
expect(scaffold.ctx.workingDirectory.get(agent.session)).toBe(project)
|
||||
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
const sessionId = await settled
|
||||
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
|
||||
expect(sessionId).toBe(agent.session.id)
|
||||
|
||||
// The prompt opens the first turn, and its hold creates the worktree.
|
||||
const events = await readPersistedEvents(scaffold, sessionId)
|
||||
const queued = (target: 'next-step' | 'next-turn', kind: string): number => events.findIndex(event => event.type === 'agent/inbox/spliced'
|
||||
&& event.data.target === target && event.data.inserted.some(message => message.source.kind === kind))
|
||||
const created = events.findIndex(event => pluginRecordOf(event)?.type === 'plugin:worktree/created')
|
||||
expect(queued('next-step', 'user-approval')).toBeGreaterThan(-1)
|
||||
expect(queued('next-turn', 'user')).toBeGreaterThan(queued('next-step', 'user-approval'))
|
||||
expect(created).toBeGreaterThan(queued('next-turn', 'user'))
|
||||
expect(created).toBeLessThan(events.findIndex(event => event.type === 'turn/start'))
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree cannot be created, tries again, and sends it without the worktree', async () => {
|
||||
const { scaffold, page, project, tripwire } = await requestReleaseWorktree('web-e2e-forge-panel-failure')
|
||||
await git(project, 'branch', '--quiet', '-D', 'release')
|
||||
@@ -1004,7 +1040,7 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and
|
||||
scaffold.ctx.forgeSession.track(session, DRAFT)
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${DRAFT}"]`)
|
||||
await change.getByRole('link', { name: 'Add the merge button', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the merge button' }).waitFor({ timeout: 20_000 })
|
||||
|
||||
// The only open change request starts expanded, so its Merge action shows once it is ready.
|
||||
await chooseCardAction(page, change, '#9', '标记为可评审')
|
||||
@@ -1137,7 +1173,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
scaffold.ctx.forgeSession.track(session, PULL)
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).waitFor()
|
||||
// The open change request of the checked-out branch replaces the offer to create one.
|
||||
await card.getByRole('button', { name: '本地变更操作', exact: true }).click()
|
||||
@@ -1150,7 +1186,8 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).click()
|
||||
await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor()
|
||||
await showSessionPanel(page)
|
||||
await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
|
||||
// A press on the card's line opens the changes, as its Changes row and its View changes item do.
|
||||
await change.locator('[data-forge-opens="changes"]').click()
|
||||
const view = page.locator('[data-forge-changes="change"]')
|
||||
const panelFile = view.locator('[data-forge-diff-file="src/panel.ts"]')
|
||||
const title = await view.getByText('Add the pull request panel', { exact: true }).boundingBox()
|
||||
@@ -1774,9 +1811,9 @@ it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs in th
|
||||
width: document.documentElement.clientWidth,
|
||||
}
|
||||
})
|
||||
// The glyph starts 30px into the card, where the card's title starts.
|
||||
expect(geometry.iconInset).toBe(8)
|
||||
expect(geometry.rowInset).toBeGreaterThanOrEqual(6)
|
||||
expect(geometry.rowInset).toBeLessThanOrEqual(7)
|
||||
expect(geometry.rowInset).toBe(22)
|
||||
offsets.add(geometry.valueOffset)
|
||||
expect(geometry.gap).toBeGreaterThanOrEqual(8)
|
||||
expect(geometry.right).toBeLessThanOrEqual(geometry.width)
|
||||
@@ -2507,7 +2544,7 @@ it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state
|
||||
await showSessionPanel(page)
|
||||
const card = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
// The card chooses its default expansion once its first status arrives, which names the title.
|
||||
await card.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await card.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
if (await card.getAttribute('data-expanded') === null) await card.getByRole('button', { name: '展开 #7', exact: true }).click()
|
||||
const checks = card.locator('[data-forge-checks]')
|
||||
await expect.poll(() => checks.textContent(), { timeout: 20_000 }).toBe('检查3 项失败 · 1 项进行中')
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Typed `@` mentions render as file and folder chips only when the Session's filesystem has the path. */
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { chromium, type Browser, type Page } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import {
|
||||
captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, readPersistedEvents,
|
||||
watchConsole, webSnapshotMode, type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
|
||||
|
||||
const DIR = fileURLToPath(new URL('../../../snapshots/web/mention-path-presence', import.meta.url))
|
||||
const FIXTURE = join(DIR, 'session.v4.jsonl')
|
||||
const MODE = webSnapshotMode()
|
||||
const PROMPT = '@ceshi @随便写点文字 @LICENSE @docs/ mail@host'
|
||||
|
||||
describe.skipIf(MODE === 'record')('web e2e: mention path presence', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let page: Page
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
|
||||
beforeAll(async () => {
|
||||
scaffold = await launchWebScaffold({
|
||||
replayFixture: FIXTURE,
|
||||
compareReplaySession: true,
|
||||
paceMs: 10,
|
||||
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
|
||||
})
|
||||
await mkdir(join(scaffold.workspaceCwd, 'workspace', 'docs'), { recursive: true })
|
||||
await writeFile(join(scaffold.workspaceCwd, 'workspace', 'LICENSE'), 'Reference fixture license.\n')
|
||||
browser = await chromium.launch()
|
||||
page = await newEnglishPage(browser)
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]')
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await browser?.close()
|
||||
} finally {
|
||||
await scaffold?.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('decorates typed mentions of existing paths and keeps other @ text verbatim across reload', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'mention-path-presence'))
|
||||
const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
|
||||
await writeComposerDraft(page, composer, PROMPT)
|
||||
// The trailing token is not a mention, so no completion is open to take the Enter.
|
||||
await page.getByRole('listbox', { name: 'Trigger suggestions' }).waitFor({ state: 'hidden' })
|
||||
expect(await composer.locator('[data-composer-chip]').count()).toBe(0)
|
||||
|
||||
const settled = scaffold.whenTurnSettled()
|
||||
await composer.press('Enter')
|
||||
const sessionId = await settled
|
||||
const persisted = (await readPersistedEvents(scaffold, sessionId))
|
||||
.find(event => event.type === 'user/message' && event.data.source.kind === 'user')
|
||||
expect(persisted).toMatchObject({ data: { content: [{ type: 'text', text: PROMPT }] } })
|
||||
expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
|
||||
|
||||
for (const reload of [false, true]) {
|
||||
if (reload) await page.reload({ waitUntil: 'load' })
|
||||
const bubble = page.locator('[data-chat-flow-kind="user"]')
|
||||
await expect.poll(() => bubble.locator('[data-ref-chip]').allTextContents()).toEqual(['LICENSE', 'docs'])
|
||||
expect(await bubble.textContent()).toContain('@ceshi @随便写点文字 ')
|
||||
expect(await bubble.textContent()).toContain(' mail@host')
|
||||
await bubble.getByRole('button', { name: 'LICENSE', exact: true }).click()
|
||||
await page.getByText('Reference fixture license.', { exact: true }).waitFor()
|
||||
}
|
||||
await compareOrRefreshGolden(join(DIR, 'ui.expected.md'),
|
||||
await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -201,6 +201,7 @@
|
||||
"tests/markdown-file-links.e2e.ts",
|
||||
"tests/user-text-secret-mask.e2e.ts",
|
||||
"tests/reference-composer.e2e.ts",
|
||||
"tests/mention-path-presence.e2e.ts",
|
||||
"tests/markdown-wide-table.e2e.ts",
|
||||
"tests/thinking-markdown.e2e.ts",
|
||||
"tests/math-rendering.e2e.ts",
|
||||
|
||||
+15
-1
@@ -3269,7 +3269,7 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
||||
|
||||
## `@deepseek-ai/dsh-session-persistence-jsonl`
|
||||
|
||||
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:95`](../packages/session/session-persistence-jsonl/src/index.ts)
|
||||
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:107`](../packages/session/session-persistence-jsonl/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
|
||||
@@ -3297,6 +3297,20 @@ export type JsonlCompression = 'zstd' | 'none'
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-jsonl -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
|
||||
<a id="deepseek-aidsh-session-persistence-sqlite"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-session-persistence-sqlite`
|
||||
|
||||
- `refs`: [`JsonlConfigOptions`](#deepseek-aidsh-session-persistence-jsonl)
|
||||
- `source`: [`packages/session/session-persistence-sqlite/src/index.ts:11`](../packages/session/session-persistence-sqlite/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Storage root and JSONL settings used when importing legacy Sessions. */
|
||||
export type Config = JsonlConfigOptions
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-projection-cache -->
|
||||
<a id="deepseek-aidsh-session-projection-cache"></a>
|
||||
|
||||
|
||||
@@ -3271,7 +3271,7 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
||||
|
||||
## `@deepseek-ai/dsh-session-persistence-jsonl`
|
||||
|
||||
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:95`](../packages/session/session-persistence-jsonl/src/index.ts)
|
||||
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:107`](../packages/session/session-persistence-jsonl/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
|
||||
@@ -3299,6 +3299,20 @@ export type JsonlCompression = 'zstd' | 'none'
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-jsonl -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
|
||||
<a id="deepseek-aidsh-session-persistence-sqlite"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-session-persistence-sqlite`
|
||||
|
||||
- `refs`: [`JsonlConfigOptions`](#deepseek-aidsh-session-persistence-jsonl)
|
||||
- `source`: [`packages/session/session-persistence-sqlite/src/index.ts:11`](../packages/session/session-persistence-sqlite/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Storage root and JSONL settings used when importing legacy Sessions. */
|
||||
export type Config = JsonlConfigOptions
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-projection-cache -->
|
||||
<a id="deepseek-aidsh-session-projection-cache"></a>
|
||||
|
||||
|
||||
@@ -73,9 +73,9 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
|
||||
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
|
||||
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
|
||||
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
|
||||
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
|
||||
|
||||
@@ -75,9 +75,9 @@
|
||||
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
|
||||
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
|
||||
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) |
|
||||
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
|
||||
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
|
||||
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
|
||||
|
||||
@@ -419,6 +419,7 @@ flowchart TD
|
||||
pkg_session_log_deepseek["session-log-deepseek"]
|
||||
pkg_session_persistence["session-persistence"]
|
||||
pkg_session_persistence_jsonl["session-persistence-jsonl"]
|
||||
pkg_session_persistence_sqlite["session-persistence-sqlite"]
|
||||
pkg_session_projection["session-projection"]
|
||||
pkg_session_projection_cache["session-projection-cache"]
|
||||
pkg_session_stats["session-stats"]
|
||||
@@ -614,6 +615,8 @@ flowchart TD
|
||||
pkg_sandbox_windows_acl --> pkg_subprocess
|
||||
pkg_session_persistence_jsonl --> pkg_session
|
||||
pkg_session_persistence_jsonl --> pkg_session_persistence
|
||||
pkg_session_persistence_sqlite --> pkg_session
|
||||
pkg_session_persistence_sqlite --> pkg_session_persistence
|
||||
pkg_session_projection_cache --> pkg_session
|
||||
pkg_session_projection_cache --> pkg_session_projection
|
||||
pkg_session_projection_cache --> pkg_storage_domain
|
||||
@@ -1802,6 +1805,7 @@ flowchart TD
|
||||
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
|
||||
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
|
||||
| [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
|
||||
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
|
||||
| [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
|
||||
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
|
||||
|
||||
@@ -421,6 +421,7 @@ flowchart TD
|
||||
pkg_session_log_deepseek["session-log-deepseek"]
|
||||
pkg_session_persistence["session-persistence"]
|
||||
pkg_session_persistence_jsonl["session-persistence-jsonl"]
|
||||
pkg_session_persistence_sqlite["session-persistence-sqlite"]
|
||||
pkg_session_projection["session-projection"]
|
||||
pkg_session_projection_cache["session-projection-cache"]
|
||||
pkg_session_stats["session-stats"]
|
||||
@@ -616,6 +617,8 @@ flowchart TD
|
||||
pkg_sandbox_windows_acl --> pkg_subprocess
|
||||
pkg_session_persistence_jsonl --> pkg_session
|
||||
pkg_session_persistence_jsonl --> pkg_session_persistence
|
||||
pkg_session_persistence_sqlite --> pkg_session
|
||||
pkg_session_persistence_sqlite --> pkg_session_persistence
|
||||
pkg_session_projection_cache --> pkg_session
|
||||
pkg_session_projection_cache --> pkg_session_projection
|
||||
pkg_session_projection_cache --> pkg_storage_domain
|
||||
@@ -1804,6 +1807,7 @@ flowchart TD
|
||||
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
|
||||
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
|
||||
| [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
|
||||
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
|
||||
| [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
|
||||
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
|
||||
|
||||
@@ -33,5 +33,5 @@
|
||||
en: 142ff3bed547efcf
|
||||
zh: a73ca5ea4743d3e8
|
||||
/session-persistence/the-backend:
|
||||
en: adcd78909565b046
|
||||
zh: a09bcb6ec0ebad9e
|
||||
en: ec220159c6fcdb55
|
||||
zh: c2023bc5e09f5b7f
|
||||
@@ -336,9 +336,10 @@ The optional `eventCount`/`sizeBytes` fields remain cheap backend observations f
|
||||
|
||||
## The backend
|
||||
|
||||
The shipped provider implements the abstract `SessionPersistence` contract (`create`/`open`/`stat`/`list`, with per-session `SessionHandle`s carrying `read`/`append`/`flush`/`close` and optional cancellation throughout) and passes the shared persistence contract suite:
|
||||
The shipped providers implement the abstract `SessionPersistence` contract (`create`/`open`/`stat`/`list`, with per-session `SessionHandle`s carrying `read`/`append`/`flush`/`close` and optional cancellation throughout) and pass the shared persistence contract suite:
|
||||
|
||||
- **[dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl)** — an append-only logical JSONL log per session, stored as checksummed concatenated Zstandard frames by default or raw lines by configuration, with crash-safe atomic materialization, per-batch `fsync` appends, and torn-tail truncation before the first new append. `stat`/`list` carry `sizeBytes` and a best-effort `fs.stat`-derived revision.
|
||||
- **[dsh-session-persistence-sqlite](../../packages/session/session-persistence-sqlite)** — logical JSON event storage with indexed metadata and predecessor-linked Segments. The optional provider imports existing JSONL on first open and coordinates concurrent readers with a single writer per Session; `stat`/`list` do not import history.
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
@@ -392,8 +393,10 @@ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions
|
||||
/**
|
||||
* Open an existing stored session.
|
||||
*
|
||||
* `read` never takes ownership and works while another handle (or process)
|
||||
* holds write ownership. `write` atomically claims single-writer ownership;
|
||||
* Returned `read` handles retain no write ownership and work while another
|
||||
* handle (or process) holds write ownership. A first legacy read open may
|
||||
* acquire ownership temporarily to import history into the selected backend.
|
||||
* `write` atomically claims single-writer ownership;
|
||||
* an existing active owner rejects.
|
||||
* @param id - the stored session to open.
|
||||
* @param access - `read` or `write`.
|
||||
|
||||
@@ -336,9 +336,10 @@ interface SessionPersistenceSnapshot {
|
||||
|
||||
## 后端
|
||||
|
||||
随产品交付的 provider 实现抽象 `SessionPersistence` 约定(`create`/`open`/`stat`/`list`,逐会话 `SessionHandle` 承载 `read`/`append`/`flush`/`close`,全程可选支持取消),并通过共享的持久化契约套件:
|
||||
随产品交付的多个 provider 实现抽象 `SessionPersistence` 约定(`create`/`open`/`stat`/`list`,逐会话 `SessionHandle` 承载 `read`/`append`/`flush`/`close`,全程可选支持取消),并通过共享的持久化契约套件:
|
||||
|
||||
- **[dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl)**——逐会话仅追加的逻辑 JSONL 日志,默认存储为带 checksum 的连续 Zstandard frame,也可配置为原始行;具备崩溃安全的原子实体化、逐批 `fsync` 的 append,以及在第一次新 append 之前截断撕裂尾部。`stat`/`list` 携带 `sizeBytes` 与尽力而为的、由 `fs.stat` 派生的修订号。
|
||||
- **[dsh-session-persistence-sqlite](../../packages/session/session-persistence-sqlite)**——带索引元数据及前驱关联 Segment 的逻辑 JSON 事件存储。此可选提供者在首次打开时导入现有 JSONL,并协调并发读者及每个 Session 的唯一写者;`stat`/`list` 不导入历史。
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
@@ -392,8 +393,10 @@ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions
|
||||
/**
|
||||
* Open an existing stored session.
|
||||
*
|
||||
* `read` never takes ownership and works while another handle (or process)
|
||||
* holds write ownership. `write` atomically claims single-writer ownership;
|
||||
* Returned `read` handles retain no write ownership and work while another
|
||||
* handle (or process) holds write ownership. A first legacy read open may
|
||||
* acquire ownership temporarily to import history into the selected backend.
|
||||
* `write` atomically claims single-writer ownership;
|
||||
* an existing active owner rejects.
|
||||
* @param id - the stored session to open.
|
||||
* @param access - `read` or `write`.
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: e0143916bb634762
|
||||
zh: e0143916bb634762
|
||||
/tool-schema-catalog/deepseek-ai-dsh-plugin-manager/plugin-manager:
|
||||
en: 2fbe2e5b88e81a54
|
||||
zh: a9de46c13bda53d8
|
||||
en: 8ad01461754a9c3b
|
||||
zh: 67eb5c02a821643a
|
||||
/tool-schema-catalog/deepseek-ai-dsh-plugin-market:
|
||||
en: 1ec7b4cbc3d98e28
|
||||
zh: 1ec7b4cbc3d98e28
|
||||
|
||||
@@ -60,7 +60,7 @@ This table connects model-visible tool names to the plugin package and service s
|
||||
|
||||
### `plugin_manager`
|
||||
|
||||
List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.
|
||||
List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
|
||||
### `plugin_manager`
|
||||
|
||||
列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。支持热更新的 profile 立即应用变更,包括已安装包的升级;未直接应用的变更结果带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。
|
||||
列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。变更结果的 application 字段具有权威性:applied 表示变更已生效,无需重启;其他取值都带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -86,7 +86,7 @@ export const inject = ['tools', 'pluginManager', 'sandboxPolicy']
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.tools.register(defineTool({
|
||||
name: 'plugin_manager',
|
||||
description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.',
|
||||
description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.',
|
||||
parameters: {
|
||||
action: { type: 'string', required: true, enum: ['list_plugins', 'list_bundles', 'set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'list_version_exemptions', 'set_version_exemption'], description: 'Management operation.' },
|
||||
target: { type: 'string', description: 'Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle.' },
|
||||
|
||||
@@ -77,9 +77,11 @@ async function bench() {
|
||||
}, UserText)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'text' }, PlainUserText)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'session' }, SessionReference)
|
||||
// Every path mention in these units is Host-confirmed; ui-reference owns presence coverage.
|
||||
const keyedHooks = { pathPresence: () => ({ getSnapshot: () => 'present' as const, subscribe: () => () => {} }) }
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', locale: 'reference',
|
||||
inject: () => ({ openFile, resolveFilePath: path => path }) }, FileReference)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder' }, FolderReference)
|
||||
inject: () => ({ openFile, resolveFilePath: (path: string) => path, keyedHooks }) }, FileReference)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', inject: () => ({ keyedHooks }) }, FolderReference)
|
||||
ctx.slots.register({ name: 'conversation.user.text.node', key: 'skill', inject: () => ({ openSkill }) }, SkillReference)
|
||||
ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ name: 'conversation.chat.user.images' }, function ImageProbe(props) {
|
||||
imageCalls.push(props)
|
||||
|
||||
@@ -53,6 +53,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in
|
||||
const openFile = actions.openFile ?? (() => { throw new Error('This fixture has no file navigation action') })
|
||||
const openSkill = actions.openSkill ?? (() => { throw new Error('This fixture has no skill navigation action') })
|
||||
const t = makeTranslate(referenceZh, commonZh)
|
||||
// Composition units treat every path mention as Host-confirmed; ui-reference owns presence coverage.
|
||||
const usePathPresence = () => 'present' as const
|
||||
const renderSlot: UserTextProps['renderSlot'] = (name: string, input: object, options?: { fallback?: ReactNode }) => {
|
||||
if (name !== 'conversation.user.text.node') throw new Error(`Unexpected UserText Slot: ${name}`)
|
||||
const owner = input as UserTextNodeOwnerProps & { node: UserTextNode }
|
||||
@@ -62,8 +64,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in
|
||||
case 'secret': return createElement(SecretText, { ...owner, t } as ComponentProps<typeof SecretText>)
|
||||
case 'text': return createElement(PlainUserText, owner as ComponentProps<typeof PlainUserText>)
|
||||
case 'session': return createElement(SessionReference, owner as ComponentProps<typeof SessionReference>)
|
||||
case 'file': return createElement(FileReference, { ...owner, openFile, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps<typeof FileReference>)
|
||||
case 'folder': return createElement(FolderReference, owner as ComponentProps<typeof FolderReference>)
|
||||
case 'file': return createElement(FileReference, { ...owner, openFile, usePathPresence, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps<typeof FileReference>)
|
||||
case 'folder': return createElement(FolderReference, { ...owner, usePathPresence } as ComponentProps<typeof FolderReference>)
|
||||
case 'skill': return createElement(SkillReference, { ...owner, openSkill } as ComponentProps<typeof SkillReference>)
|
||||
case 'command': return createElement(GoalCommandReference, owner as ComponentProps<typeof GoalCommandReference>)
|
||||
default: return options?.fallback ?? null
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts:
|
||||
en: 0b41c33743e5b422
|
||||
zh: 551896094c03f57e
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/sent-file-and-folder-mentions:
|
||||
en: 87c27115eae5a660
|
||||
zh: a9a20431928072ec
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior:
|
||||
en: 386bbd9dc0a2c322
|
||||
zh: 3014a367157532b7
|
||||
@@ -30,8 +33,8 @@
|
||||
en: 6c77da1e946f72e1
|
||||
zh: b7b8e1e1d4f5a102
|
||||
/deepseek-ai-dsh-client-ui-reference/understand-the-implementation/serialization:
|
||||
en: c3fe8963ed80e403
|
||||
zh: ba3e057cd63e9189
|
||||
en: 1126dd5a1189cde8
|
||||
zh: 87866765edd7e343
|
||||
/deepseek-ai-dsh-client-ui-reference/further-exploration:
|
||||
en: 157b1bcf84b5c11b
|
||||
zh: 6b7e4f3326b19036
|
||||
@@ -42,8 +45,8 @@
|
||||
en: ff23f8026f7c6050
|
||||
zh: 6b0841800076bcd2
|
||||
/deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work:
|
||||
en: e79991a25b11e342
|
||||
zh: 15064e8374c8e63d
|
||||
en: f51b285964650dd2
|
||||
zh: 5a237964dff7f98a
|
||||
/deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -33,6 +33,10 @@ A file closes completion as an atomic inline reference displayed with a file gly
|
||||
|
||||
A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`.
|
||||
|
||||
### Sent file and folder mentions
|
||||
|
||||
In sent messages, queued rows, and local echoes, an `@path` or `@"path"` token renders as a file or folder reference only after the Session's filesystem confirms the path exists. Until then, and for a path that does not exist, such as a hand-typed `@notes`, the original text stays verbatim; email addresses never match. A candidate picked and sent in the same Session during one page load counts as confirmed, so its echo shows the reference immediately.
|
||||
|
||||
### Failure behavior
|
||||
|
||||
One unavailable or failed candidate domain yields no rows for that domain while the other still lists. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn.
|
||||
@@ -61,7 +65,7 @@ Candidate requests require an existing retained Client Session and share one tem
|
||||
|
||||
File picks preserve the natural text defined by the shared `@path` grammar as the hidden serialized and clipboard form. Session picks use the canonical `@[label](dsh-session:…)` mention; serialization never reconstructs identity from the visible title.
|
||||
|
||||
The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Interactive file nodes receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels.
|
||||
The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete candidate reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Both node renderers subscribe to a Session-bound `pathPresence` keyed Hook backed by `workspaceFiles/stat`: a stat result or a `workspace-file/not-regular-file` failure (a directory, a symbolic link whatever it points to, or another non-regular entry) confirms the path, `workspace-file/not-found` rejects it, and any other failure leaves it unconfirmed for the next subscriber to retry. The plugin owns these answers, keeps one per Session and path, and aborts outstanding stats on disposal; a settling pick records its path as confirmed. Presence does not read the [`file` resource](../../api/workspace-files/README.md) through `useResource`: that provider keeps one Host change subscription open per Session and path while a reader is mounted, and a mention needs a single answer. Interactive file nodes also receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -97,6 +101,7 @@ These limits define when the reference source cannot help; they are current pack
|
||||
|
||||
- **Candidate failure is intentionally quiet** — one unavailable or failed Remote discovery call yields no rows for that domain. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn.
|
||||
- **No browser-side file scan** — Web completion requires a mounted Host `ctx.fileReferences` provider; the browser cannot fall back to its own filesystem.
|
||||
- **Sent references do not follow file changes** — a path's confirmed or missing answer lasts for the page load; creating or removing the path later changes how its mentions render only after reload.
|
||||
- **Session search remains metadata-only** — discovery filters session id, cwd, and the latest log-backed title through `ctx.sessionReferenceResolver`; message bodies and full transcripts are not searched.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -33,6 +33,10 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。
|
||||
|
||||
### 已发送的文件与目录引用
|
||||
|
||||
在已发送消息、排队行和本地回显中,`@path` 或 `@"path"` token 只有在 Session 的文件系统确认该路径存在后才渲染为文件或目录引用。确认之前,以及路径不存在时(例如手写的 `@notes`),原文保持不变;邮箱地址永远不会匹配。在同一 Session、同一次页面加载内从候选中选择并发送的路径视为已确认,因此其回显会立即显示引用。
|
||||
|
||||
### 失败行为
|
||||
|
||||
某个候选领域不可用或失败时,该领域不产生任何行,另一领域仍正常列出。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。
|
||||
@@ -61,7 +65,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
文件选择把共享 `@path` 语法所定义的自然文本保留为隐藏的序列化与剪贴板形式。会话选择使用规范的 `@[label](dsh-session:…)` mention;序列化永远不会根据可见标题重建身份。
|
||||
|
||||
插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整引用,不执行文件发现;共享计算器按原文位置裁定重叠。可交互的文件节点通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。
|
||||
插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整候选引用,不执行文件发现;共享计算器按原文位置裁定重叠。两个节点 renderer 都订阅绑定 Session 的 `pathPresence` 键控 Hook,其背后是 `workspaceFiles/stat`:stat 成功或 `workspace-file/not-regular-file` 失败(目录、无论指向何处的符号链接或其他非普通条目)即确认路径存在,`workspace-file/not-found` 判定不存在,其他失败则保持未确认,由下一个订阅者重试。插件持有这些结果,每个 Session 与路径保留一份,并在卸载时中止未完成的 stat;选定 pick 会把其路径记为已确认。存在性不通过 `useResource` 读取 [`file` 资源](../../api/workspace-files/README.zh.md):该 provider 在有读取方挂载期间为每个 Session 与路径保持一个 Host 变更订阅,而一次提及只需要一个结果。可交互的文件节点还通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -97,6 +101,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
- **候选失败有意保持静默**:Remote 发现调用不可用或失败时,该领域不产生候选行。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。
|
||||
- **浏览器侧不扫描文件**:Web 补全需要挂载宿主 `ctx.fileReferences` 提供方;浏览器无法回退到自身文件系统。
|
||||
- **已发送引用不跟随文件变化**:路径的确认或不存在结果在一次页面加载内保持不变;之后创建或删除该路径,只有刷新页面后才会改变其引用的渲染。
|
||||
- **会话搜索仍仅使用元数据**:发现流程通过 `ctx.sessionReferenceResolver` 筛选 session id、cwd 与以日志为依据的最新标题;不搜索消息主体或完整 transcript。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
/** File navigation feedback belongs to the individual inline reference that requested it. */
|
||||
import { useState } from 'react'
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { Button, Modal, ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { Button, Modal, ReferenceChip, UserTextRun } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { NS } from './locales.ts'
|
||||
import type { PathPresence } from './path-presence.ts'
|
||||
import type {} from './user-text-rules.ts'
|
||||
|
||||
/** Host-confirmed presence of mention paths in the rendering Session. */
|
||||
export interface PathPresenceInjected {
|
||||
readonly keyedHooks: {
|
||||
/** Presence of one decoded mention path; subscribing starts its Host stat. */
|
||||
readonly pathPresence: (path: string) => HostObservable<PathPresence | undefined>
|
||||
}
|
||||
}
|
||||
|
||||
/** Session-authorized synchronous navigation; document reading belongs to the preview host. */
|
||||
export interface FileReferenceInjected {
|
||||
export interface FileReferenceInjected extends PathPresenceInjected {
|
||||
/**
|
||||
* Open or reveal a file in the current Sidebar using the originating Session's authority.
|
||||
* @param path - decoded path from the reference.
|
||||
@@ -20,15 +29,21 @@ export interface FileReferenceInjected {
|
||||
|
||||
type FileReferenceProps = UserTextNodeProps<'file'> & InjectFace<FileReferenceInjected> & PropsLocale<typeof NS>
|
||||
|
||||
type FolderReferenceProps = UserTextNodeProps<'folder'> & InjectFace<PathPresenceInjected>
|
||||
|
||||
/**
|
||||
* Render a file chip and contain synchronous navigation failures without hiding the reference.
|
||||
* @param props - JSON node, interaction policy, Session-authorized navigation, and locale seat.
|
||||
* @returns an inline chip and, after a navigation failure, its body-portaled dialog.
|
||||
* Render a file chip once the Host confirms its path exists, and contain synchronous navigation failures without hiding the reference.
|
||||
* @param props - JSON node, interaction policy, Session-authorized navigation and presence, and locale seat.
|
||||
* @returns the original spelling until confirmation; afterwards an inline chip and, after a navigation failure, its body-portaled dialog.
|
||||
*/
|
||||
export function FileReference({ node, raw, interactive, openFile, resolveFilePath, sessionId, useContextMenu, t }: FileReferenceProps) {
|
||||
export function FileReference({
|
||||
node, raw, interactive, openFile, resolveFilePath, sessionId, useContextMenu, usePathPresence, t,
|
||||
}: FileReferenceProps) {
|
||||
const { getTriggerProps } = useContextMenu()
|
||||
const [failedPath, setFailedPath] = useState<string | null>(null)
|
||||
const { path, label } = node.data
|
||||
const presence = usePathPresence(path)
|
||||
if (presence !== 'present') return <UserTextRun text={raw} />
|
||||
const close = () => { setFailedPath(null) }
|
||||
const open = () => {
|
||||
try {
|
||||
@@ -62,10 +77,12 @@ export function FileReference({ node, raw, interactive, openFile, resolveFilePat
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a directory as a label, even when the containing text permits file navigation.
|
||||
* @param props - resolved directory data and the original reference spelling.
|
||||
* @returns an inline non-interactive chip.
|
||||
* Render a directory as a label once the Host confirms its path exists, even when the containing text permits file navigation.
|
||||
* @param props - directory data, the original reference spelling, and Session-scoped presence.
|
||||
* @returns the original spelling until confirmation, then an inline non-interactive chip.
|
||||
*/
|
||||
export function FolderReference({ node, raw }: UserTextNodeProps<'folder'>) {
|
||||
return <ReferenceChip appearance="folder" label={node.data.label} title={raw} />
|
||||
export function FolderReference({ node, raw, usePathPresence }: FolderReferenceProps) {
|
||||
return usePathPresence(node.data.path) === 'present'
|
||||
? <ReferenceChip appearance="folder" label={node.data.label} title={raw} />
|
||||
: <UserTextRun text={raw} />
|
||||
}
|
||||
@@ -11,6 +11,11 @@
|
||||
* workspace is not the current one. A session is dated from the Host session
|
||||
* list, so the `@` menu and the session list never disagree about its age.
|
||||
*
|
||||
* A file or folder mention in sent text renders as a chip only after the
|
||||
* Session's filesystem confirms the path exists; picking a listed candidate
|
||||
* confirms it, and any other mention stays original text until a Host stat
|
||||
* answers.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-client-ui-reference/client
|
||||
*/
|
||||
// Type-only: pulls the generated Remote API and ctx.remote merge through the Client assembly boundary.
|
||||
@@ -23,8 +28,11 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis'
|
||||
import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { FileReference, FolderReference, type FileReferenceInjected } from './FileReference.tsx'
|
||||
import { fileReferenceRule, folderReferenceRule } from './user-text-rules.ts'
|
||||
import {
|
||||
FileReference, FolderReference, type FileReferenceInjected, type PathPresenceInjected,
|
||||
} from './FileReference.tsx'
|
||||
import { createPathPresence, type MentionSessionId } from './path-presence.ts'
|
||||
import { fileReferenceRule, folderReferenceRule, mentionPath } from './user-text-rules.ts'
|
||||
export type {} from './user-text-rules.ts'
|
||||
import type {
|
||||
ClientSessionContext, InputTriggerCrumb, InputTriggerServiceContract, InputTriggerSource,
|
||||
@@ -45,7 +53,7 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' {
|
||||
/** Required services: the trigger registry, the Remote namespaces, and the copy. */
|
||||
export const inject = [
|
||||
'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences',
|
||||
'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation',
|
||||
'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation',
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -56,12 +64,18 @@ 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)
|
||||
const sessions = ctx.get('sessions') as ISessions
|
||||
const presence = createPathPresence((sessionId, path, signal) => ctx.remote.workspaceFiles.stat(sessionId, path, signal))
|
||||
ctx.effect(() => () => { presence.dispose() }, 'ui-reference: mention path stats')
|
||||
const presenceFor = (sessionId: MentionSessionId): PathPresenceInjected => ({
|
||||
keyedHooks: { pathPresence: path => presence.source(sessionId, path) },
|
||||
})
|
||||
ctx.uiConversation.userText.register(fileReferenceRule)
|
||||
ctx.uiConversation.userText.register(folderReferenceRule)
|
||||
ctx.slots.inject('conversation.user.text.node', function* () {
|
||||
yield ctx.slots.register({
|
||||
name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS,
|
||||
inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({
|
||||
...presenceFor(sessionId),
|
||||
resolveFilePath: path => resolveWorkspacePath(sessions.list.getSnapshot().byId[sessionId]?.cwd, path),
|
||||
openFile: (path) => {
|
||||
const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd
|
||||
@@ -69,7 +83,9 @@ export function apply(ctx: ClientContext): void {
|
||||
},
|
||||
}),
|
||||
}, FileReference)
|
||||
yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', priority: 100 }, FolderReference)
|
||||
yield ctx.slots.register({
|
||||
name: 'conversation.user.text.node', key: 'folder', priority: 100, inject: presenceFor,
|
||||
}, FolderReference)
|
||||
})
|
||||
const source: InputTriggerSource = {
|
||||
trigger: '@',
|
||||
@@ -129,7 +145,7 @@ export function apply(ctx: ClientContext): void {
|
||||
header(_session: ClientSessionContext, req) {
|
||||
return crumbsFor(req.query, req.quoted === true, req.drilled, t)
|
||||
},
|
||||
onPick({ candidate, action }) {
|
||||
onPick({ candidate, session, action }) {
|
||||
const value = parseCandidate(candidate.value)
|
||||
if (value?.kind === 'file') {
|
||||
// A directory row carries two verbs: the settling pick resolves the
|
||||
@@ -139,6 +155,8 @@ export function apply(ctx: ClientContext): void {
|
||||
if (value.fileKind === 'directory' && action === 'drill') {
|
||||
return { text: value.mention, continue: true }
|
||||
}
|
||||
// The Host has just listed this path, so its sent echo renders as a chip without a stat.
|
||||
presence.confirm(session.sessionId, mentionPath(value.mention))
|
||||
return {
|
||||
insert: {
|
||||
source: 'reference',
|
||||
@@ -164,7 +182,7 @@ export function apply(ctx: ClientContext): void {
|
||||
},
|
||||
openReference(session, { ref, appearance }) {
|
||||
if (appearance !== 'file') return false
|
||||
const path = ref.startsWith('@"') ? ref.slice(2, -1) : ref.slice(1)
|
||||
const path = mentionPath(ref)
|
||||
const cwd = sessions.list.getSnapshot().byId[session.sessionId]?.cwd
|
||||
ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, cwd, path))
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Session-scoped Host confirmation that a mentioned path exists.
|
||||
*
|
||||
* Each Session and path pair is stat'ed at most once while the owning plugin
|
||||
* is live. Only a definitive Host answer is retained; any other failure leaves
|
||||
* the pair unconfirmed, and the next subscriber asks again. Retained answers
|
||||
* are not refreshed when the path is created or removed later. Entries live as
|
||||
* long as the plugin, one per distinct mention the client has rendered. Each
|
||||
* unconfirmed pair starts its own Host request when first subscribed; nothing
|
||||
* bounds how many are outstanding at once.
|
||||
*/
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
|
||||
/** Session whose filesystem resolves a mention. */
|
||||
export type MentionSessionId = UserTextNodeProps<'file'>['sessionId']
|
||||
|
||||
/** Host answer for one mentioned path; `undefined` means unconfirmed. */
|
||||
export type PathPresence = 'present' | 'absent'
|
||||
|
||||
/**
|
||||
* Session-authorized stat of one path, absolute or relative to the Session's workspace root.
|
||||
* @param sessionId - Session whose filesystem resolves the path.
|
||||
* @param path - path as the mention spells it.
|
||||
* @param signal - cancellation owned by the presence sources.
|
||||
* @returns the regular file's metadata, or the Host's typed failure.
|
||||
*/
|
||||
export type PathStat = (
|
||||
sessionId: MentionSessionId,
|
||||
path: string,
|
||||
signal: AbortSignal,
|
||||
) => Promise<RemoteResult<WorkspaceFileStat>>
|
||||
|
||||
/** Presence sources shared by every mention one plugin instance renders. */
|
||||
export interface PathPresenceSources {
|
||||
/**
|
||||
* Observe one path; the first subscription to an unconfirmed path starts its Host stat.
|
||||
* @param sessionId - Session whose filesystem resolves the path.
|
||||
* @param path - decoded mention path.
|
||||
* @returns the same source for the same pair until disposal.
|
||||
*/
|
||||
source(sessionId: MentionSessionId, path: string): HostObservable<PathPresence | undefined>
|
||||
/**
|
||||
* Record a path the Host has just listed, such as a picked completion candidate.
|
||||
* @param sessionId - Session whose filesystem listed the path.
|
||||
* @param path - decoded mention path.
|
||||
*/
|
||||
confirm(sessionId: MentionSessionId, path: string): void
|
||||
/** Abort outstanding stats; later subscriptions start none. */
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
presence: PathPresence | undefined
|
||||
probing: boolean
|
||||
readonly listeners: Set<() => void>
|
||||
readonly source: HostObservable<PathPresence | undefined>
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify one stat. A directory, a symbolic link whatever it points to, or
|
||||
* another non-regular entry still exists; failures that do not describe the
|
||||
* path leave it unconfirmed.
|
||||
* @param result - Host stat result.
|
||||
* @returns the definitive presence, or undefined.
|
||||
*/
|
||||
function presenceOf(result: RemoteResult<WorkspaceFileStat>): PathPresence | undefined {
|
||||
if (result.ok) return 'present'
|
||||
switch (result.error.code) {
|
||||
case 'workspace-file/not-regular-file':
|
||||
return 'present'
|
||||
case 'workspace-file/not-found':
|
||||
return 'absent'
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create presence sources over one stat function.
|
||||
* @param stat - Session-authorized Host stat.
|
||||
* @returns sources the caller disposes with its plugin.
|
||||
*/
|
||||
export function createPathPresence(stat: PathStat): PathPresenceSources {
|
||||
const lifetime = new AbortController()
|
||||
const entries = new Map<string, Entry>()
|
||||
|
||||
const publish = (entry: Entry, presence: PathPresence) => {
|
||||
entry.presence = presence
|
||||
for (const listener of [...entry.listeners]) listener()
|
||||
}
|
||||
|
||||
const probe = (entry: Entry, sessionId: MentionSessionId, path: string) => {
|
||||
if (entry.probing || entry.presence !== undefined || lifetime.signal.aborted) return
|
||||
entry.probing = true
|
||||
// Cancellation and carrier faults resolve as failures. Only a Remote
|
||||
// assembly fault rejects: it stays an unhandled rejection so the fault is
|
||||
// reported, and the pair stays unconfirmed for the next subscriber.
|
||||
void stat(sessionId, path, lifetime.signal).then((result) => {
|
||||
const presence = presenceOf(result)
|
||||
// A confirmation recorded while this stat was outstanding is newer.
|
||||
if (presence === undefined || entry.presence !== undefined || lifetime.signal.aborted) return
|
||||
publish(entry, presence)
|
||||
}).finally(() => { entry.probing = false })
|
||||
}
|
||||
|
||||
const entryFor = (sessionId: MentionSessionId, path: string): Entry => {
|
||||
const key = JSON.stringify([sessionId, path])
|
||||
const existing = entries.get(key)
|
||||
if (existing !== undefined) return existing
|
||||
const entry: Entry = {
|
||||
presence: undefined,
|
||||
probing: false,
|
||||
listeners: new Set(),
|
||||
source: {
|
||||
getSnapshot: () => entry.presence,
|
||||
subscribe: (listener) => {
|
||||
entry.listeners.add(listener)
|
||||
probe(entry, sessionId, path)
|
||||
return () => { entry.listeners.delete(listener) }
|
||||
},
|
||||
},
|
||||
}
|
||||
entries.set(key, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
return {
|
||||
source: (sessionId, path) => entryFor(sessionId, path).source,
|
||||
confirm(sessionId, path) {
|
||||
const entry = entryFor(sessionId, path)
|
||||
if (entry.presence !== 'present') publish(entry, 'present')
|
||||
},
|
||||
dispose() {
|
||||
lifetime.abort()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
/** Forward file and folder recognition in original text, without Facts or discovery. */
|
||||
/**
|
||||
* Forward file and folder mention candidates in original text, without Facts or discovery.
|
||||
* The node components decide whether a candidate names an existing path.
|
||||
*/
|
||||
import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
|
||||
interface PathReferenceData {
|
||||
@@ -13,6 +16,15 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the path a complete `@path` or `@"quoted path"` mention names.
|
||||
* @param mention - mention spelling starting with `@`, without trailing sentence punctuation.
|
||||
* @returns the path that file and folder nodes carry.
|
||||
*/
|
||||
export function mentionPath(mention: string): string {
|
||||
return mention.slice(1).replace(/^"|"$/gu, '')
|
||||
}
|
||||
|
||||
function nextPath(text: string, from: number, folder: boolean) {
|
||||
const tokens = /(?<!\S)(@"[^"\n]+"|@[^\s]+)/gu
|
||||
tokens.lastIndex = from
|
||||
@@ -20,7 +32,7 @@ function nextPath(text: string, from: number, folder: boolean) {
|
||||
const token = match[0]
|
||||
const raw = token.startsWith('@"') ? token : token.replace(/[.,;:!?,。;:!?]+$/u, '')
|
||||
if (raw.length <= 1) continue
|
||||
const path = raw.slice(1).replace(/^"|"$/gu, '')
|
||||
const path = mentionPath(raw)
|
||||
if (path.endsWith('/') !== folder) continue
|
||||
const label = path.split(/[\\/]/u).filter(Boolean).at(-1) ?? raw.slice(1)
|
||||
return { start: match.index, end: match.index + raw.length, data: { path, label } }
|
||||
|
||||
@@ -9,7 +9,10 @@ import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts'
|
||||
import { FileReference, FolderReference, type FileReferenceInjected } from '../src/client/FileReference.tsx'
|
||||
import {
|
||||
FileReference, FolderReference, type FileReferenceInjected, type PathPresenceInjected,
|
||||
} from '../src/client/FileReference.tsx'
|
||||
import type { PathStat } from '../src/client/path-presence.ts'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { RemoteError, TestSessions } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { SessionFixture } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
@@ -99,6 +102,7 @@ async function bench(
|
||||
projectionValues?: { title?: string | null }
|
||||
}> = {},
|
||||
opening: Pick<SessionFixture, 'initialOpen' | 'snapshot'> = {},
|
||||
stat: PathStat = vi.fn<PathStat>(() => new Promise(() => {})),
|
||||
) {
|
||||
const ctx = new Context()
|
||||
ctx.provide('sidebarRight', { openResource: vi.fn() })
|
||||
@@ -119,6 +123,7 @@ async function bench(
|
||||
new RemoteService(ctx)
|
||||
ctx.provide('remote.fileReferences', { list: files })
|
||||
ctx.provide('remote.sessionReferenceResolver', { candidates: sessions })
|
||||
ctx.provide('remote.workspaceFiles', { stat })
|
||||
ctx.provide('locale', new LocaleRuntime(ctx))
|
||||
const sessionStore = new TestSessions(async (action) => { await action() }, ctx)
|
||||
onTestFinished(async () => {
|
||||
@@ -139,11 +144,17 @@ async function bench(
|
||||
return { ctx, fiber, source, sessions: sessionStore, owner }
|
||||
}
|
||||
|
||||
/** The Session-bound presence face a file or folder text node entry injects. */
|
||||
function injectedPresence(ctx: Context, key: 'file' | 'folder'): (id: SessionId) => PathPresenceInjected {
|
||||
const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === key)!
|
||||
return entry.inject as NonNullable<typeof entry.inject> & ((id: SessionId) => PathPresenceInjected)
|
||||
}
|
||||
|
||||
describe('apply', () => {
|
||||
it('declares its services and releases the @ reference registration on disposal', async () => {
|
||||
expect(inject).toEqual([
|
||||
'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences',
|
||||
'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation',
|
||||
'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation',
|
||||
])
|
||||
const { fiber } = await bench()
|
||||
let registered: InputTriggerSource | undefined
|
||||
@@ -166,6 +177,7 @@ describe('apply', () => {
|
||||
new RemoteService(ctx)
|
||||
ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) })
|
||||
ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) })
|
||||
ctx.provide('remote.workspaceFiles', { stat: vi.fn() })
|
||||
ctx.provide('locale', new LocaleRuntime(ctx))
|
||||
const sessions = new TestSessions(async (action) => { await action() }, ctx)
|
||||
onTestFinished(() => sessions.disposeScopes())
|
||||
@@ -671,6 +683,23 @@ describe('pick and codec', () => {
|
||||
await expect(source.codec?.serialize(mention, new AbortController().signal)).resolves.toBe(mention)
|
||||
})
|
||||
|
||||
it('confirms settled file and folder picks for the picking Session; a drill confirms nothing', async () => {
|
||||
const stat = vi.fn<PathStat>(() => new Promise(() => {}))
|
||||
const { ctx, source } = await bench(undefined, undefined, {}, {}, stat)
|
||||
const [directory, file] = await source.candidates(session, request(''))
|
||||
const folderFace = injectedPresence(ctx, 'folder')
|
||||
const fileFace = injectedPresence(ctx, 'file')
|
||||
drill(source, directory!)
|
||||
expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined()
|
||||
pick(source, directory!)
|
||||
pick(source, file!)
|
||||
expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBe('present')
|
||||
expect(fileFace(session.sessionId).keyedHooks.pathPresence('docs/a b.md').getSnapshot()).toBe('present')
|
||||
expect(folderFace(sid('other')).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined()
|
||||
folderFace(session.sessionId).keyedHooks.pathPresence('src/').subscribe(vi.fn())
|
||||
expect(stat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores candidates that do not carry a source-owned value', async () => {
|
||||
const { source } = await bench()
|
||||
expect(pick(source, { name: 'foreign candidate' })).toBeUndefined()
|
||||
@@ -678,6 +707,17 @@ describe('pick and codec', () => {
|
||||
})
|
||||
|
||||
describe('reference preview', () => {
|
||||
it('stats each mention through its rendering Session and aborts outstanding stats on disposal', async () => {
|
||||
const stat = vi.fn<PathStat>(() => new Promise(() => {}))
|
||||
const { ctx, fiber } = await bench(undefined, undefined, {}, {}, stat)
|
||||
injectedPresence(ctx, 'file')(session.sessionId).keyedHooks.pathPresence('LICENSE').subscribe(vi.fn())
|
||||
injectedPresence(ctx, 'folder')(sid('other')).keyedHooks.pathPresence('docs/').subscribe(vi.fn())
|
||||
expect(stat.mock.calls.map(([id, path]) => [id, path])).toEqual([['target', 'LICENSE'], ['other', 'docs/']])
|
||||
expect(stat.mock.calls.some(([, , signal]) => signal.aborted)).toBe(false)
|
||||
await fiber.dispose()
|
||||
expect(stat.mock.calls.every(([, , signal]) => signal.aborted)).toBe(true)
|
||||
})
|
||||
|
||||
it('binds each inline file action to its originating Session', async () => {
|
||||
const { ctx, sessions } = await bench()
|
||||
const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === 'file')!
|
||||
|
||||
@@ -12,17 +12,41 @@ import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
afterEach(cleanup)
|
||||
|
||||
type Props = ComponentProps<typeof FileReference>
|
||||
type Presence = ReturnType<Props['usePathPresence']>
|
||||
|
||||
function props(openFile: Props['openFile']): Props {
|
||||
function presenceHook(presence: Record<string, Presence>): Props['usePathPresence'] {
|
||||
const hook = (path: string) => presence[path]
|
||||
return hook as Props['usePathPresence']
|
||||
}
|
||||
|
||||
const PRESENT = presenceHook({ 'docs/a b.md': 'present', 'docs/': 'present' })
|
||||
|
||||
function props(openFile: Props['openFile'], usePathPresence = PRESENT): Props {
|
||||
return {
|
||||
node: { id: 'file', start: 0, end: 14, data: { path: 'docs/a b.md', label: 'a b.md' } },
|
||||
raw: '@"docs/a b.md"', interactive: true, openFile, t: makeTranslate(en),
|
||||
raw: '@"docs/a b.md"', interactive: true, openFile, usePathPresence, t: makeTranslate(en),
|
||||
useContextMenu: contextMenuHook(), sessionId: brandString<SessionId>('original'),
|
||||
resolveFilePath: path => `/workspace/${path}`,
|
||||
} as Props
|
||||
}
|
||||
|
||||
describe('FileReference', () => {
|
||||
it('keeps the original spelling until the Host confirms the path exists', () => {
|
||||
const openFile = vi.fn()
|
||||
const folder = { id: 'folder', start: 0, end: 6, data: { path: 'docs/', label: 'docs' } } as const
|
||||
for (const presence of [undefined, 'absent'] as const) {
|
||||
const usePathPresence = presenceHook({ 'docs/a b.md': presence, 'docs/': presence })
|
||||
const view = render(<>
|
||||
<FileReference {...props(openFile, usePathPresence)} />
|
||||
<FolderReference {...props(openFile, usePathPresence)} node={folder} raw="@docs/" />
|
||||
</>)
|
||||
expect(view.container.textContent).toBe('@"docs/a b.md"@docs/')
|
||||
expect(view.container.querySelector('[data-ref-chip]')).toBeNull()
|
||||
view.unmount()
|
||||
}
|
||||
expect(openFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the decoded path and leaves summaries and folders non-interactive', () => {
|
||||
const openFile = vi.fn()
|
||||
const input = props(openFile)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { createPathPresence, type MentionSessionId, type PathStat } from '../src/client/path-presence.ts'
|
||||
|
||||
const sid = (value: string): MentionSessionId => value as MentionSessionId
|
||||
const STAT: WorkspaceFileStat = { absolutePath: '/w/LICENSE', version: 'v1' }
|
||||
|
||||
interface StatCall {
|
||||
readonly sessionId: MentionSessionId
|
||||
readonly path: string
|
||||
readonly signal: AbortSignal
|
||||
readonly resolve: (result: RemoteResult<WorkspaceFileStat>) => void
|
||||
}
|
||||
|
||||
function deferredStat() {
|
||||
const calls: StatCall[] = []
|
||||
const stat = vi.fn<PathStat>((sessionId, path, signal) => new Promise((resolve) => {
|
||||
calls.push({ sessionId, path, signal, resolve })
|
||||
}))
|
||||
return { stat, calls }
|
||||
}
|
||||
|
||||
const failure = (error: RemoteFailure): RemoteResult<WorkspaceFileStat> => ({ ok: false, error })
|
||||
|
||||
describe('createPathPresence', () => {
|
||||
it('shares one stat per Session and path and publishes the Host answer to every subscriber', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'LICENSE')
|
||||
expect(presence.source(sid('a'), 'LICENSE')).toBe(source)
|
||||
expect(presence.source(sid('b'), 'LICENSE')).not.toBe(source)
|
||||
expect(source.getSnapshot()).toBeUndefined()
|
||||
expect(stat).not.toHaveBeenCalled()
|
||||
const first = vi.fn()
|
||||
const second = vi.fn()
|
||||
const unsubscribe = source.subscribe(first)
|
||||
source.subscribe(second)
|
||||
expect(calls.map(call => [call.sessionId, call.path])).toEqual([['a', 'LICENSE']])
|
||||
unsubscribe()
|
||||
calls[0]!.resolve({ ok: true, value: STAT })
|
||||
await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') })
|
||||
expect(first).not.toHaveBeenCalled()
|
||||
expect(second).toHaveBeenCalledOnce()
|
||||
source.subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('treats a non-regular entry as present, a missing entry as absent, and retries any other failure', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const folder = presence.source(sid('a'), 'docs/')
|
||||
const missing = presence.source(sid('a'), 'ceshi')
|
||||
const offline = presence.source(sid('a'), 'notes.md')
|
||||
folder.subscribe(vi.fn())
|
||||
missing.subscribe(vi.fn())
|
||||
offline.subscribe(vi.fn())
|
||||
calls[0]!.resolve(failure(new RemoteError('workspace-file/not-regular-file', 'directory', { path: 'docs/', kind: 'directory' })))
|
||||
calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'ceshi' })))
|
||||
calls[2]!.resolve(failure(new RemoteError('gateway/internal', 'offline', {})))
|
||||
await vi.waitFor(() => { expect(missing.getSnapshot()).toBe('absent') })
|
||||
expect(folder.getSnapshot()).toBe('present')
|
||||
expect(offline.getSnapshot()).toBeUndefined()
|
||||
offline.subscribe(vi.fn())
|
||||
expect(calls.map(call => call.path)).toEqual(['docs/', 'ceshi', 'notes.md', 'notes.md'])
|
||||
calls[3]!.resolve({ ok: true, value: STAT })
|
||||
await vi.waitFor(() => { expect(offline.getSnapshot()).toBe('present') })
|
||||
})
|
||||
|
||||
it('lets a picked confirmation stand over an older outstanding stat and over an earlier absence', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'new.md')
|
||||
const listener = vi.fn()
|
||||
source.subscribe(listener)
|
||||
presence.confirm(sid('a'), 'new.md')
|
||||
presence.confirm(sid('a'), 'new.md')
|
||||
expect(source.getSnapshot()).toBe('present')
|
||||
expect(listener).toHaveBeenCalledOnce()
|
||||
calls[0]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'new.md' })))
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(source.getSnapshot()).toBe('present')
|
||||
|
||||
const created = presence.source(sid('a'), 'later.md')
|
||||
created.subscribe(vi.fn())
|
||||
calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'later.md' })))
|
||||
await vi.waitFor(() => { expect(created.getSnapshot()).toBe('absent') })
|
||||
presence.confirm(sid('a'), 'later.md')
|
||||
expect(created.getSnapshot()).toBe('present')
|
||||
const picked = presence.source(sid('a'), 'picked.md')
|
||||
presence.confirm(sid('a'), 'picked.md')
|
||||
picked.subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reports a rejected stat as an unhandled rejection and asks again for the next subscriber', async () => {
|
||||
const fault = new Error('client api: workspaceFiles/stat has no active Connection')
|
||||
const stat = vi.fn<PathStat>()
|
||||
.mockRejectedValueOnce(fault)
|
||||
.mockResolvedValueOnce({ ok: true, value: STAT })
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
try {
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'LICENSE')
|
||||
source.subscribe(vi.fn())
|
||||
await vi.waitFor(() => { expect(rejections).toEqual([fault]) })
|
||||
expect(source.getSnapshot()).toBeUndefined()
|
||||
source.subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledTimes(2)
|
||||
await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') })
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('aborts outstanding stats on disposal, drops their answers, and starts no further stats', async () => {
|
||||
const { stat, calls } = deferredStat()
|
||||
const presence = createPathPresence(stat)
|
||||
const source = presence.source(sid('a'), 'LICENSE')
|
||||
const listener = vi.fn()
|
||||
source.subscribe(listener)
|
||||
presence.dispose()
|
||||
expect(calls[0]!.signal.aborted).toBe(true)
|
||||
calls[0]!.resolve({ ok: true, value: STAT })
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(source.getSnapshot()).toBeUndefined()
|
||||
expect(listener).not.toHaveBeenCalled()
|
||||
presence.source(sid('a'), 'other.md').subscribe(vi.fn())
|
||||
expect(stat).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: f63d4a049eea1ede
|
||||
zh: e61269b6df6afcd4
|
||||
en: b077aea8c5f4cb0c
|
||||
zh: 6ca6d6ead647d870
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: 43e18d718e1bda7b
|
||||
zh: c58f6b5bda5c0c45
|
||||
en: a88671f87adb5e84
|
||||
zh: a31d5f186c40683f
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
|
||||
@@ -37,7 +37,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
|
||||
- **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row.
|
||||
- **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away.
|
||||
- **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll.
|
||||
- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request card shows a glyph for its state, its title on one line, which crawls into view on hover and opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu offers Open in browser, Copy change request link, View changes for a change request a provider serves, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended, on one line: while the line with failed checks does not fit, they take the shorter wording without their count, and a line that still does not fit ends in an ellipsis and crawls into view with the title. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default.
|
||||
- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request is a compact card, a filled block on the panel's row columns: one line with a glyph for its state, its title, its number, and a glyph for the outcome of its checks. A press on the line opens the change request's changes in the right sidebar; with Cmd or Ctrl held, with the middle button, and for a change request no provider serves or has read yet, it opens the host's page. The state glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu, which shows on hover or focus as on the panel's other rows, offers View changes for a change request a provider serves, Open in browser, Copy change request link, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. While collapsed, the line reads its status in words to assistive technology, and the card's hover card shows the full title, the number with draft state and the head and base branches, and that status: the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended; a failed read or an unserved URL stands there instead. Cancelled checks have a separate count, which the status names when no listed check failed. The checks glyphs share one ring: a check for passed, a cross for failed, a half fill while they run, and a dash otherwise. An expanded card shows one row per fact below its line, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. The list shows three cards; with more, the panel's fold control after them shows the rest and folds them again, and the Session keeps that choice while it stays open. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default.
|
||||
- **Local changes row** — whenever the `branch` scope changes files, independently of bound change requests, the row names the number of changed files with the added and deleted lines and opens the changes view. Its More menu offers View changes and, when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, Create change request, which sends the Session a user message in the UI language that asks the Agent to create a change request for these changes; a toast reports whether it was sent.
|
||||
- **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open in browser name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. While the view reads changes it has not shown yet, it says Reading changes above file cards drawn as pulsing placeholders, one changed file in two columns when sides are split, and the files menu names no count; reduced motion keeps the placeholders still. The view reads again on Refresh and the page refresh shortcut, on each navigation, Line truncated
|
||||
|
||||
@@ -65,7 +65,7 @@ All files opens a searchable directory tree with the selected file scrolled to i
|
||||
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes/<remote>/HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy.
|
||||
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the next-turn queue of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. A message queued for the next step, such as a notice another plugin injects, opens no turn and starts no hold. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each next-turn message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
|
||||
|
||||
Restoration records `restoring` before mutation and `restored` only after success. Projection version 3 retains incomplete restoration across reloads. Directory existence alone cannot release a waiting message: the checkout root and shared Git directory must match the recorded worktree. Plugin unload cancels and joins all creation, restoration, and waiting tasks before releasing panel readers and the projection.
|
||||
|
||||
@@ -37,7 +37,7 @@ kind: "package-reference"
|
||||
- **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。
|
||||
- **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。
|
||||
- **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。
|
||||
- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。这些内容只占一行:含失败检查的一行放不下时,失败检查改用不带数量的短文案;仍放不下的一行末尾显示省略号,并随标题一起滚动显示。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。
|
||||
- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每个变更请求是一张紧凑卡片,即面板行列上的一块底色:一行内依次是状态图标、标题、编号和检查结果图标。点击这一行在右侧边栏打开该变更请求的变更;按住 Cmd 或 Ctrl 点击、用中键点击,以及没有提供方服务或尚未读取的变更请求,则打开托管平台上的页面。状态图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单与面板其他行一样在悬停或聚焦时出现,提供由提供方服务的变更请求的“查看变更”、“在浏览器中打开”“复制变更请求链接”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。收起时,这一行把状态以文字读给辅助技术,卡片的悬停卡片显示完整标题、编号(带草稿状态与源分支、目标分支)和这段状态:打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则是结束时间;读取失败或没有提供方服务的 URL 则显示相应说明。已取消的检查单独计数,列出的检查没有失败项时状态显示取消数量。检查结果图标共用同一个圆环:通过为勾,失败为叉,进行中为半填充,其余为短横。展开的卡片在这一行下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。列表显示三张卡片;更多时,卡片之后是面板的折叠控件,用来显示其余卡片或再次收起,Session 保持打开期间保留这一选择。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。
|
||||
- **本地变更行**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。这一行显示变更的文件数以及新增、删除行数,点击打开变更视图。它的“更多”菜单提供“查看变更”;识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,还提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。
|
||||
- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏的“在浏览器中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。视图读取尚未显示过的变更时,会在显示为脉动占位的文件卡片上方写出“正在读取变更…”,并排视图下其中一个已修改文件画成两栏,文件菜单不显示数量;开启“减少动态效果”时占位不动。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更Line truncated
|
||||
|
||||
@@ -65,7 +65,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后
|
||||
|
||||
检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes/<remote>/HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。
|
||||
|
||||
worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。
|
||||
worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的下一轮队列时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。排给下一步的消息(例如其他插件注入的通知)不开启一轮,也不启动暂留。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入下一轮队列的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。
|
||||
|
||||
|
||||
恢复在修改前记录 `restoring`,仅在成功后记录 `restored`。投影版本 3 在重载后保留未完成的恢复。目录存在本身不能放行等待的消息:检出根目录与公共 Git 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
/**
|
||||
* One change request as a card: its one-line title links to the host and
|
||||
* crawls into view while the pointer rests on the card's head, a one-line
|
||||
* summary shows while collapsed, taking the short wording of failed checks
|
||||
* while the full one does not fit and crawling with the title past that, and
|
||||
* while expanded one row per fact (checks, review, merge state, the changed
|
||||
* lines, which open its changes, and the linked issues) above the merge
|
||||
* action. Opening, copying, viewing changes, marking a draft ready, and
|
||||
* removing live in the card's actions menu.
|
||||
* One change request as a compact card of the Session panel: one line with
|
||||
* the state glyph, the title, the number, and the checks outcome, which opens
|
||||
* the changes view, and, while expanded, one row per fact (checks, review,
|
||||
* merge state, the changed lines, which open its changes too, and the linked
|
||||
* issues) above the merge action. Opening on the host, copying, viewing
|
||||
* changes, marking a draft ready, and removing live in the card's actions
|
||||
* menu, which shows on hover or focus as on the panel's other rows.
|
||||
*/
|
||||
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, type RefObject } from 'react'
|
||||
import { useId, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular,
|
||||
IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, MarqueeText, Menu,
|
||||
MenuItemButton, StateDot, Tooltip, useHoverMarquee,
|
||||
type MenuEntry, type MenuItem,
|
||||
Button, HoverCard, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular,
|
||||
IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, Menu,
|
||||
MenuItemButton, StateDot, Tooltip,
|
||||
type MenuEntry, type MenuItem, type StateDotState,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {
|
||||
ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest,
|
||||
@@ -27,7 +27,7 @@ import { formatAgo } from './format.ts'
|
||||
import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
import type { ForgeChangeRequestCardActionsProps } from './slots.ts'
|
||||
import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts'
|
||||
import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf, type ChangeRequestTone } from './status.ts'
|
||||
import css from './Forge.module.css'
|
||||
|
||||
type Translate = PropsLocale<typeof NS>['t']
|
||||
@@ -55,6 +55,10 @@ export interface ChangeRequestActions extends OverviewActions {
|
||||
readonly viewChanges?: ((entry: ForgePanelChangeRequest) => void) | undefined
|
||||
/** Draw the icon buttons plugins add to the card's head through `forge.change-request.card.actions`. */
|
||||
readonly renderActions?: ((owner: ForgeChangeRequestCardActionsProps) => ReactNode) | undefined
|
||||
/**
|
||||
* Draw the content of the card's hover card, as the Session panel's rows do. A surface without it shows none.
|
||||
*/
|
||||
readonly renderDetails?: ((details: PanelDetailsProps) => ReactNode) | undefined
|
||||
}
|
||||
|
||||
/** Props of one change request card. */
|
||||
@@ -173,97 +177,50 @@ function finished(snapshot: ChangeRequestSnapshot, now: number, t: Translate): s
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress.
|
||||
* With `short`, failed checks take the wording without their count.
|
||||
* The checks outcome after the number: a spinner before the first read, the combined outcome of an open change
|
||||
* request that has checks, and nothing for a finished one, whose glyph already says how it ended.
|
||||
*/
|
||||
function Summary({ snapshot, now, short, t }: {
|
||||
readonly snapshot: ChangeRequestSnapshot | null
|
||||
readonly now: number
|
||||
readonly short: boolean
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
if (snapshot === null) return <StateDot state="ongoing" size={11} />
|
||||
if (snapshot.state !== 'open') {
|
||||
return <span className={css.finished} data-tone={snapshot.state}>{finished(snapshot, now, t)}</span>
|
||||
}
|
||||
function Mark({ snapshot }: { readonly snapshot: ChangeRequestSnapshot | null }): ReactNode {
|
||||
if (snapshot === null) return <StateDot state="ongoing" size={12} />
|
||||
if (snapshot.state !== 'open') return null
|
||||
const ci = ciSummary(snapshot)
|
||||
const flag = flagOf(snapshot)
|
||||
return (
|
||||
<>
|
||||
<span className={css.ci} data-tone={ci.kind === 'failed' ? 'error' : undefined}>
|
||||
{ci.kind !== 'none' && <CheckGlyph state={ci.kind === 'cancelled' ? 'cancelled' : ROLLUP[snapshot.checksRollup]} size={12} />}
|
||||
{ci.kind === 'failed'
|
||||
? ci.count > 0 && !short ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted')
|
||||
: ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`)}
|
||||
</span>
|
||||
{flag !== undefined && <span className={css.flag} data-flag={flag}>{t(`change.flag.${flag}`)}</span>}
|
||||
</>
|
||||
)
|
||||
if (ci.kind === 'none') return null
|
||||
return <CheckGlyph state={ci.kind === 'cancelled' ? 'cancelled' : ROLLUP[snapshot.checksRollup]} size={12} />
|
||||
}
|
||||
|
||||
/**
|
||||
* What the collapsed status line shows when its failed checks can take the shorter wording without their count: the full
|
||||
* wording and the flag, which decide the line's width. Null for any other status, and where the language's short wording
|
||||
* is no shorter.
|
||||
* The status in words: the checks and the most urgent flag of an open change request, or the merge or close time.
|
||||
* The card's line shows it as glyphs, so assistive technology and the hover card read it here.
|
||||
* @param snapshot - change request status.
|
||||
* @param now - current epoch milliseconds for the relative time.
|
||||
* @param t - copy.
|
||||
* @returns the line's full text after the number, or null.
|
||||
* @returns the status text.
|
||||
*/
|
||||
function shortenable(snapshot: ChangeRequestSnapshot | null, t: Translate): string | null {
|
||||
if (snapshot?.state !== 'open') return null
|
||||
function statusText(snapshot: ChangeRequestSnapshot, now: number, t: Translate): string {
|
||||
if (snapshot.state !== 'open') return finished(snapshot, now, t)
|
||||
const ci = ciSummary(snapshot)
|
||||
if (ci.kind !== 'failed' || ci.count === 0) return null
|
||||
const full = t('change.ci.failed', { count: ci.count })
|
||||
if (t('change.ci.failedUnlisted').length >= full.length) return null
|
||||
const checks = ci.kind === 'failed'
|
||||
? ci.count > 0 ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted')
|
||||
: ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`)
|
||||
const flag = flagOf(snapshot)
|
||||
return flag === undefined ? full : `${full} ${t(`change.flag.${flag}`)}`
|
||||
return flag === undefined ? checks : `${checks} · ${t(`change.flag.${flag}`)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the collapsed status line shows the short wording of failed checks: only while the line with the full wording
|
||||
* does not fit. A change of the line's width, of the fonts, or of `full` shows the full wording again for one layout pass,
|
||||
* which measures it and switches before the frame is painted.
|
||||
* @param line - the clipping status line.
|
||||
* @param full - the line's full text after the number, from {@link shortenable}; null measures nothing.
|
||||
* @returns whether the line takes the short wording.
|
||||
*/
|
||||
function useShortWording(line: RefObject<HTMLElement | null>, full: string | null): boolean {
|
||||
const [measured, setMeasured] = useState<{ readonly full: string | null; readonly short: boolean }>({ full: null, short: false })
|
||||
const short = full !== null && measured.full === full && measured.short
|
||||
useLayoutEffect(() => {
|
||||
if (full === null || short) return
|
||||
const element = line.current
|
||||
/* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */
|
||||
if (element === null) return
|
||||
if (element.scrollWidth > element.clientWidth) setMeasured({ full, short: true })
|
||||
})
|
||||
useEffect(() => {
|
||||
if (full === null) return
|
||||
const element = line.current
|
||||
/* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */
|
||||
if (element === null) return
|
||||
// A new object renders again even when the line already shows the full wording, so the layout effect measures.
|
||||
const measure = (): void => { setMeasured({ full, short: false }) }
|
||||
const observer = new ResizeObserver(measure)
|
||||
observer.observe(element)
|
||||
const fonts = document.fonts
|
||||
fonts.addEventListener('loadingdone', measure)
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
fonts.removeEventListener('loadingdone', measure)
|
||||
}
|
||||
}, [line, full])
|
||||
return short
|
||||
/** The state dot of the hover card: red for what needs the user, and a spinner while the checks run. */
|
||||
function dotOf(tone: ChangeRequestTone, snapshot: ChangeRequestSnapshot): StateDotState {
|
||||
if (tone === 'blocked') return 'error'
|
||||
if (snapshot.state !== 'open') return snapshot.state === 'merged' ? 'done' : 'idle'
|
||||
return snapshot.checksRollup === 'pending' ? 'ongoing' : snapshot.checksRollup === 'success' ? 'done' : 'idle'
|
||||
}
|
||||
|
||||
/** Expanded identity after the number: draft state and the head and base branches. */
|
||||
function Target({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; readonly t: Translate }): ReactNode {
|
||||
return (
|
||||
<>
|
||||
{snapshot.state === 'open' && snapshot.draft && <span>{t('change.state.draft')}</span>}
|
||||
<span className={css.ellipsis}>{`${snapshot.headBranch} → ${snapshot.baseBranch}`}</span>
|
||||
</>
|
||||
)
|
||||
/** The hover card's line under the title: the number, draft state, and the head and base branches. */
|
||||
function identity(number: number | null, snapshot: ChangeRequestSnapshot | null, t: Translate): string[] {
|
||||
const parts = [
|
||||
...number === null ? [] : [t('change.number', { number })],
|
||||
...snapshot?.state === 'open' && snapshot.draft ? [t('change.state.draft')] : [],
|
||||
...snapshot === null ? [] : [`${snapshot.headBranch} → ${snapshot.baseBranch}`],
|
||||
]
|
||||
return parts.length === 0 ? [] : [parts.join(' · ')]
|
||||
}
|
||||
|
||||
/** The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation. */
|
||||
@@ -369,8 +326,8 @@ function Primary({ entry, snapshot, name, actions, t }: {
|
||||
}
|
||||
|
||||
/**
|
||||
* The card's actions menu: open on the host, copy the link, view the changes
|
||||
* of a served change request, mark an open draft ready, and remove the binding.
|
||||
* The card's actions menu: view the changes of a served change request, open
|
||||
* on the host, copy the link, mark an open draft ready, and remove the binding.
|
||||
*/
|
||||
function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
readonly entry: ForgePanelChangeRequest
|
||||
@@ -392,12 +349,12 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
: undefined
|
||||
// Each item carries the action it runs, so a selection never reaches another item's action.
|
||||
const choices: { readonly item: MenuItem; readonly run: () => void }[] = [
|
||||
{ item: { id: 'open', label: t('change.view'), icon: <IconRightUpOutlineRegular size={14} /> }, run: () => { actions.openLink(url) } },
|
||||
{ item: { id: 'copy', label: t('change.copy'), icon: <IconCopyOutlineRegular size={14} /> }, run: () => { actions.copyLink(url) } },
|
||||
...viewChanges !== undefined && snapshot !== null && entry.ref !== null ? [{
|
||||
item: { id: 'changes', label: t('change.viewChanges'), icon: <IconFilesDiffOutlineRegular size={14} /> },
|
||||
run: () => { viewChanges(entry) },
|
||||
}] : [],
|
||||
{ item: { id: 'open', label: t('change.view'), icon: <IconRightUpOutlineRegular size={14} /> }, run: () => { actions.openLink(url) } },
|
||||
{ item: { id: 'copy', label: t('change.copy'), icon: <IconCopyOutlineRegular size={14} /> }, run: () => { actions.copyLink(url) } },
|
||||
...ready === undefined ? [] : [{
|
||||
item: { id: 'ready', label: t('change.markReady'), icon: <IconCheckCircleOutlineRegular size={14} />, disabled: busy },
|
||||
run: ready,
|
||||
@@ -423,13 +380,12 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
anchor={(
|
||||
<button
|
||||
type="button"
|
||||
className={`${css.iconButton} ${css.moreButton}`}
|
||||
aria-label={t('change.actions', { name })}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => { setOpen(!open) }}
|
||||
>
|
||||
<IconEllipsisOutlineRegular size={14} />
|
||||
<IconEllipsisOutlineRegular size={16} />
|
||||
</button>
|
||||
)}
|
||||
items={items}
|
||||
@@ -480,7 +436,10 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one change request.
|
||||
* Render one change request. A press on the card's line opens the changes view of a change request a provider serves
|
||||
* and has read; with the platform's modifier key or the middle button, and for any other change request, it opens
|
||||
* the host's page. The line shows its status as glyphs and, while collapsed, reads it in words to assistive
|
||||
* technology, which the expanded rows do otherwise; the hover card names the full title, the branches, and that status.
|
||||
* @param props - change request, expansion, current time, actions, and copy.
|
||||
* @returns the card.
|
||||
*/
|
||||
@@ -492,68 +451,60 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc
|
||||
const notice = entry.ref === null ? 'change.unserved' : failure === undefined ? undefined : FAILURE[failure.code]
|
||||
const tone = toneOf(snapshot)
|
||||
const name = number === null ? snapshot?.title ?? url : t('change.number', { number })
|
||||
const titleRef = useRef<HTMLSpanElement>(null)
|
||||
const lineRef = useRef<HTMLSpanElement>(null)
|
||||
const titleMarquee = useHoverMarquee(titleRef)
|
||||
const lineMarquee = useHoverMarquee(lineRef)
|
||||
// One hover on the head carries every text it clips: the title, and the collapsed number and status line.
|
||||
const marquee = useMemo(() => ({
|
||||
onPointerEnter: (event: PointerEvent): void => {
|
||||
titleMarquee.onPointerEnter(event)
|
||||
lineMarquee.onPointerEnter(event)
|
||||
},
|
||||
onPointerLeave: (): void => {
|
||||
titleMarquee.onPointerLeave()
|
||||
lineMarquee.onPointerLeave()
|
||||
},
|
||||
}), [titleMarquee, lineMarquee])
|
||||
const short = useShortWording(lineRef, expanded || notice !== undefined ? null : shortenable(snapshot, t))
|
||||
// A notice replaces the collapsed summary, so a failed read never shows its stale status beside it.
|
||||
const meta = expanded
|
||||
? snapshot === null ? null : <Target snapshot={snapshot} t={t} />
|
||||
: notice === undefined ? <Summary snapshot={snapshot} now={now} short={short} t={t} /> : null
|
||||
const parts = (
|
||||
<>
|
||||
{number !== null && <span>{t('change.number', { number })}</span>}
|
||||
{number !== null && meta !== null && <span className={css.dot} aria-hidden="true">·</span>}
|
||||
{meta}
|
||||
</>
|
||||
)
|
||||
return (
|
||||
<li className={css.change} data-forge-change={entry.url} data-expanded={expanded ? '' : undefined}>
|
||||
<div className={css.changeHead} {...marquee}>
|
||||
<ChangeRequestGlyph tone={tone} size={16} label={t('change.stateAria', { state: t(TONE_LABEL[tone]) })} />
|
||||
<div className={css.headText}>
|
||||
<a
|
||||
className={css.changeTitle}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
actions.openLink(url)
|
||||
}}
|
||||
>
|
||||
<MarqueeText ref={titleRef}>{snapshot?.title ?? url.replace(/^https?:\/\//i, '')}</MarqueeText>
|
||||
</a>
|
||||
{(number !== null || meta !== null) && (
|
||||
<div className={css.meta}>
|
||||
{expanded ? parts : <MarqueeText ref={lineRef} className={css.statusLine}>{parts}</MarqueeText>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
const title = snapshot?.title ?? url.replace(/^https?:\/\//i, '')
|
||||
// A notice replaces the status, so a failed read never reads its stale status beside it.
|
||||
const status: PanelDetailsProps['status'] = notice !== undefined
|
||||
? { state: 'warning', label: t(notice) }
|
||||
: snapshot === null ? undefined : { state: dotOf(tone, snapshot), label: statusText(snapshot, now, t) }
|
||||
const viewChanges = snapshot !== null && entry.ref !== null ? actions.viewChanges : undefined
|
||||
const open = (event: MouseEvent): void => {
|
||||
if (viewChanges === undefined || event.metaKey || event.ctrlKey) actions.openLink(url)
|
||||
else viewChanges(entry)
|
||||
}
|
||||
const head = (
|
||||
<div className={css.changeHead} data-session-panel-row="">
|
||||
<button
|
||||
type="button"
|
||||
data-row-part="body"
|
||||
data-forge-opens={viewChanges === undefined ? 'link' : 'changes'}
|
||||
onClick={open}
|
||||
onAuxClick={(event) => { if (event.button === 1) actions.openLink(url) }}
|
||||
>
|
||||
<span data-row-part="icon">
|
||||
<ChangeRequestGlyph tone={tone} size={16} label={t('change.stateAria', { state: t(TONE_LABEL[tone]) })} />
|
||||
</span>
|
||||
<span data-row-part="content">{title}</span>
|
||||
</button>
|
||||
<span data-row-part="trailing" className={css.status}>
|
||||
{number !== null && <span className={css.number}>{t('change.number', { number })}</span>}
|
||||
{notice === undefined && <Mark snapshot={snapshot} />}
|
||||
{!expanded && notice === undefined && status !== undefined && <span className={css.visuallyHidden}>{status.label}</span>}
|
||||
{actions.renderActions?.({ url: entry.url, ref: entry.ref, headSha: snapshot?.headSha ?? null, state: snapshot?.state ?? null })}
|
||||
</span>
|
||||
<span data-row-part="menu">
|
||||
<CardMenu entry={entry} snapshot={snapshot} name={name} url={url} actions={actions} t={t} />
|
||||
</span>
|
||||
<span data-row-part="trailing" className={css.end}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
className={css.expand}
|
||||
aria-expanded={expanded}
|
||||
aria-label={t(expanded ? 'change.collapse' : 'change.expand', { name })}
|
||||
onClick={onToggle}
|
||||
>
|
||||
<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, expanded && css.chevronOpen)} />
|
||||
<IconChevronDownOutlineRegular size={14} className={clsx(css.chevron, expanded && css.chevronOpen)} />
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
const details = actions.renderDetails?.({
|
||||
title,
|
||||
lines: identity(number, snapshot, t),
|
||||
...status === undefined ? {} : { status },
|
||||
})
|
||||
return (
|
||||
<li className={css.change} data-forge-change={entry.url} data-expanded={expanded ? '' : undefined}>
|
||||
{details === undefined ? head : <HoverCard grouped anchor={head} content={details} />}
|
||||
{notice !== undefined && (
|
||||
<div className={css.notice}>
|
||||
<span>{t(notice)}</span>
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
}
|
||||
|
||||
.avatars > .avatar {
|
||||
box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-layer-1);
|
||||
box-shadow: 0 0 0 1.5px var(--forge-card-surface, var(--dsw-alias-bg-layer-1));
|
||||
}
|
||||
|
||||
.moreCount {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/** Session panel section listing the Session's change requests, and its title control. */
|
||||
|
||||
import { useRef, type ReactNode } from 'react'
|
||||
import { useCallback, useRef, type ReactNode } from 'react'
|
||||
import {
|
||||
Button, IconWarningTriangleOutlineRegular, MarqueeText, useHoverMarquee,
|
||||
Button, HoverCardGroup, IconWarningTriangleOutlineRegular, MarqueeText, useHoverMarquee,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type {
|
||||
HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore,
|
||||
HostObservable, InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ForgeReadiness, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { ForgePanelChangeRequest, ForgePanelState } from '../types.ts'
|
||||
import { ChangeRequestCard, type ChangeRequestActions } from './ChangeRequestCard.tsx'
|
||||
import type { createChangeRequestsSectionStore } from './change-requests-store.ts'
|
||||
@@ -59,6 +59,7 @@ export interface ChangeRequestsSectionInjected {
|
||||
export type ChangeRequestsSectionProps =
|
||||
PropsRuntime<'conversation.session.panel.section'>
|
||||
& Pick<PropsRenderSlots<'forge.change-request.card.actions'>, 'renderSlot'>
|
||||
& PropsRenderFactories
|
||||
& InjectFace<ChangeRequestsSectionInjected>
|
||||
& PropsStore<ReturnType<typeof createChangeRequestsSectionStore>>
|
||||
& PropsLocale<typeof NS>
|
||||
@@ -77,6 +78,9 @@ export type ChangeRequestsActionsProps =
|
||||
|
||||
type Translate = ChangeRequestsSectionProps['t']
|
||||
|
||||
/** Cards the list shows before its fold control holds the rest back. */
|
||||
const FOLD_LIMIT = 3
|
||||
|
||||
/** Sign-in the repository's host still needs before its change requests show. */
|
||||
interface SignInNeed {
|
||||
readonly host: string
|
||||
@@ -144,20 +148,27 @@ function SignInRow({ need, copyText, t }: {
|
||||
* Render the Session's change request cards. The section shows while the
|
||||
* Session binds a change request or the repository's host needs sign-in, which
|
||||
* a status row above the cards says; a lost stream shows in the Environment
|
||||
* section instead. A card starts expanded when the Session binds
|
||||
* exactly one change request; a card the user expands or collapses keeps that
|
||||
* choice in the Session's store, across updates and while the panel is hidden.
|
||||
* Viewing changes closes the panel's overlay.
|
||||
* @param props - panel snapshot hooks, card actions, panel owner values, and copy.
|
||||
* section instead. The list shows three cards and then the panel's fold
|
||||
* control, which shows the rest; the choice is kept per Session. A card starts
|
||||
* expanded when the Session binds exactly one change request; a card the user
|
||||
* expands or collapses keeps that choice in the Session's store, across
|
||||
* updates and while the panel is hidden. Viewing changes closes the panel's
|
||||
* overlay.
|
||||
* @param props - panel snapshot hooks, card actions, panel owner values, the store, and copy.
|
||||
* @returns the cards, or null with neither bound change requests nor a sign-in to complete.
|
||||
*/
|
||||
export function ChangeRequestsSection({
|
||||
usePanel, useLocale, dismissOverlay, refresh, remove, markReady, merge, readChecks,
|
||||
rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot, t,
|
||||
rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot,
|
||||
renderFactorySlot, t,
|
||||
}: ChangeRequestsSectionProps): ReactNode {
|
||||
const snapshot = usePanel(current => current)
|
||||
const locale = useLocale(value => value)
|
||||
const chosen = useStore(current => current.expanded)
|
||||
const unfolded = useStore(current => current.unfolded)
|
||||
const renderDetails = useCallback(
|
||||
(details: PanelDetailsProps) => renderFactorySlot('conversation.session.panel.details', details), [renderFactorySlot],
|
||||
)
|
||||
const state = snapshot.state
|
||||
if (state === null) return null
|
||||
const signIn = signInNeedOf(state)
|
||||
@@ -170,30 +181,43 @@ export function ChangeRequestsSection({
|
||||
dismissOverlay()
|
||||
},
|
||||
renderActions: owner => renderSlot('forge.change-request.card.actions', owner),
|
||||
renderDetails,
|
||||
}
|
||||
const defaults = defaultExpanded(state.changeRequests)
|
||||
const expanded = (url: string): boolean => chosen[url] ?? defaults.has(url)
|
||||
const toggle = (url: string): void => { store.toggled(url, !expanded(url)) }
|
||||
const now = Date.now()
|
||||
const foldable = state.changeRequests.length > FOLD_LIMIT
|
||||
const shown = foldable && !unfolded ? state.changeRequests.slice(0, FOLD_LIMIT) : state.changeRequests
|
||||
const label = unfolded ? t('fold.less') : t('fold.more', { count: state.changeRequests.length - FOLD_LIMIT })
|
||||
return (
|
||||
<div className={css.cards} data-forge-panel="">
|
||||
{signIn !== null && <SignInRow need={signIn} copyText={copyText} t={t} />}
|
||||
{state.changeRequests.length > 0 && (
|
||||
<ul className={css.list}>
|
||||
{state.changeRequests.map(entry => (
|
||||
<ChangeRequestCard
|
||||
key={entry.url}
|
||||
entry={entry}
|
||||
expanded={expanded(entry.url)}
|
||||
onToggle={() => { toggle(entry.url) }}
|
||||
now={now}
|
||||
actions={actions}
|
||||
locale={locale}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{shown.length > 0 && (
|
||||
// Moving between cards swaps their hover cards without another dwell.
|
||||
<HoverCardGroup>
|
||||
<ul className={css.list}>
|
||||
{shown.map(entry => (
|
||||
<ChangeRequestCard
|
||||
key={entry.url}
|
||||
entry={entry}
|
||||
expanded={expanded(entry.url)}
|
||||
onToggle={() => { toggle(entry.url) }}
|
||||
now={now}
|
||||
actions={actions}
|
||||
locale={locale}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</HoverCardGroup>
|
||||
)}
|
||||
{foldable && renderFactorySlot('conversation.session.panel.fold', {
|
||||
expanded: unfolded,
|
||||
label,
|
||||
name: t('fold.name', { label }),
|
||||
onToggle: () => { store.unfoldedSet(!unfolded) },
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,134 +1,90 @@
|
||||
/* Change request cards in the Session panel section, at the panel's 13px row size. */
|
||||
.cards {
|
||||
--forge-fill: var(--dsw-alias-card-fill);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font-size: var(--dsh-content-font-size-secondary, 13px);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.iconButton {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.iconButton:focus-visible {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.iconButton:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
}
|
||||
|
||||
/* A More button shares its surface: the glyph darkens without a fill, as on Session panel rows. */
|
||||
.iconButton.moreButton:focus-visible {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.iconButton.moreButton:hover {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: 4px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* One change request: a filled block without a border, on the panel's row columns. The platform fill stands apart
|
||||
from the panel's surface in both themes; the card fill is nearly that surface's own color in the dark theme. */
|
||||
.change {
|
||||
min-width: 0;
|
||||
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||
border-radius: var(--dsw-radius-md);
|
||||
background: var(--dsw-alias-bg-layer-1);
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
/* Named for what the block draws on itself, such as the ring that sets overlapping avatars apart. */
|
||||
--forge-card-surface: var(--dsw-alias-bg-module-platform);
|
||||
background: var(--forge-card-surface);
|
||||
}
|
||||
|
||||
/* Glyph, title link with the number line below it, then the actions menu
|
||||
and the expansion toggle. */
|
||||
.changeHead {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding: 12px 8px 10px 14px;
|
||||
/* The card's line is a panel row, 36px instead of 28px: the glyph in the icon column, the title, the number and the
|
||||
checks outcome, the actions menu the panel reveals on hover, and the expansion toggle in the end column. */
|
||||
.change .changeHead {
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
.changeHead > .glyph {
|
||||
margin: 3px 10px 0 0;
|
||||
.change .changeHead > [data-row-part='body'] {
|
||||
height: 36px;
|
||||
}
|
||||
|
||||
/* The buttons center on the title's first line. */
|
||||
.changeHead > .iconButton {
|
||||
margin-top: -3px;
|
||||
/* The number and the checks outcome after the title. */
|
||||
.status {
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.headText {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding-top: 1px;
|
||||
.number {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.changeTitle {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
text-decoration: none;
|
||||
/* The expansion toggle in the row's end column, 16px wide like the menu column: a 24px target around the chevron. */
|
||||
.change .changeHead > .end {
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
.expand {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
margin: -4px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-xs);
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.expand:focus-visible {
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.changeTitle:hover {
|
||||
.expand:hover {
|
||||
color: var(--dsw-alias-label-primary);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.changeTitle:focus-visible,
|
||||
.rowButton:focus-visible {
|
||||
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* Number line below the title: the status while collapsed, the branches while expanded. */
|
||||
.meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
padding: 1px 0;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
/* Lifecycle glyph; drawn in the current color unless the state tints it. */
|
||||
.glyph {
|
||||
display: inline-flex;
|
||||
@@ -200,82 +156,27 @@
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.ci {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.ci[data-tone='error'],
|
||||
.flag[data-flag='changesRequested'],
|
||||
.flag[data-flag='conflicting'] {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.flag {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* Only the branch names and the collapsed status line shorten; the number, checks, and flags keep whole words on one line. */
|
||||
.meta > :not(.ellipsis):not(.statusLine) {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The collapsed number and status: one line as wide as the row, so a change of its wording never resizes it. It clips
|
||||
with an ellipsis and crawls with the title; its parts sit inline so the ellipsis cuts between characters. */
|
||||
.statusLine {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.statusLine .dot {
|
||||
margin: 0 6px;
|
||||
}
|
||||
|
||||
.statusLine .ci {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.statusLine .checkGlyph {
|
||||
margin-inline-end: 5px;
|
||||
vertical-align: -2px;
|
||||
}
|
||||
|
||||
.statusLine .flag {
|
||||
margin-inline-start: 6px;
|
||||
}
|
||||
|
||||
.finished {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.finished[data-tone='merged'] {
|
||||
color: var(--dsw-alias-state-done-primary);
|
||||
}
|
||||
|
||||
/* Read failure or unsupported host below the head, with its one action. */
|
||||
/* Read failure or unsupported host below the card's line, from where the title starts, with its one action. */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 0 10px 10px 33px;
|
||||
padding: 0 8px 8px 30px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
/* Expanded facts, one sentence per row: an icon under the glyph, the value, an optional trailing part, and a chevron
|
||||
on a row that opens something. */
|
||||
/* Expanded facts inside the card's block, one sentence per row: an icon under the title's start, the value, an
|
||||
optional trailing part, and a chevron in the card's end column on a row that opens something. */
|
||||
.rows {
|
||||
/* Contains the visually hidden row labels, so they never extend a scroll area outside the panel. */
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: 24px minmax(0, 1fr) auto 12px;
|
||||
gap: 0 8px;
|
||||
padding: 4px 6px 6px;
|
||||
border-top: 0.5px solid var(--dsw-alias-border-l2);
|
||||
padding: 0 8px 4px 22px;
|
||||
}
|
||||
|
||||
.row {
|
||||
@@ -286,7 +187,7 @@
|
||||
column-gap: 8px;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
min-height: 28px;
|
||||
margin: 0;
|
||||
padding: 0 8px;
|
||||
border: 0;
|
||||
@@ -415,7 +316,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 2px 14px 12px;
|
||||
padding: 4px 8px 8px 26px;
|
||||
}
|
||||
|
||||
.primaryAction {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* The expansion the user chose for the change request cards of one Session. The
|
||||
* The expansion the user chose for the change request cards of one Session, and whether its list shows every card. The
|
||||
* registration declares it as an exclusive store, so each Session keeps its
|
||||
* choices while its scope is retained, across hiding and showing the panel.
|
||||
*/
|
||||
@@ -10,11 +10,14 @@ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-sto
|
||||
export interface ChangeRequestsSectionState {
|
||||
/** Whether the user expanded (true) or collapsed (false) a card, by change request URL; unchosen cards are absent. */
|
||||
expanded: Record<string, boolean>
|
||||
/** Whether the list shows the cards past its first three. */
|
||||
unfolded: boolean
|
||||
}
|
||||
|
||||
/** The change requests section store's write set. */
|
||||
type ChangeRequestsSectionActions = {
|
||||
toggled: (draft: ChangeRequestsSectionState, url: string, expanded: boolean) => void
|
||||
unfoldedSet: (draft: ChangeRequestsSectionState, unfolded: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,7 +26,7 @@ type ChangeRequestsSectionActions = {
|
||||
*/
|
||||
export function createChangeRequestsSectionStore(): EngineStoreHandle<ChangeRequestsSectionState, ChangeRequestsSectionActions> {
|
||||
return defineStore({
|
||||
init: (): ChangeRequestsSectionState => ({ expanded: {} }),
|
||||
init: (): ChangeRequestsSectionState => ({ expanded: {}, unfolded: false }),
|
||||
actions: {
|
||||
/**
|
||||
* Record the user's choice for one card.
|
||||
@@ -34,6 +37,14 @@ export function createChangeRequestsSectionStore(): EngineStoreHandle<ChangeRequ
|
||||
toggled: (d, url: string, expanded: boolean) => {
|
||||
d.expanded[url] = expanded
|
||||
},
|
||||
/**
|
||||
* Show every card of the list, or fold it to its first three again.
|
||||
* @param d - draft state.
|
||||
* @param unfolded - whether the list now shows every card.
|
||||
*/
|
||||
unfoldedSet: (d, unfolded: boolean) => {
|
||||
d.unfolded = unfolded
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { IconCheckCircleFillRegular, IconCloseCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconCheckCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { CheckState, ChecksRollup } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ChangeRequestTone } from './status.ts'
|
||||
import css from './Forge.module.css'
|
||||
@@ -125,25 +125,24 @@ const CHECK_TONE: Record<CheckState, string | undefined> = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the decorative outcome of one check beside its text: a filled circle
|
||||
* for success or failure, a half-filled ring while it runs, and an empty ring
|
||||
* for neutral, skipped, and cancelled checks.
|
||||
* Draw the decorative outcome of one check beside its text, each inside the same ring: a check for success, a cross
|
||||
* for failure, a half fill while it runs, and a dash for neutral, skipped, and cancelled checks. The ring has the
|
||||
* radius and width of the success icon's, so mixed outcomes read as one set.
|
||||
* @param props.state - check outcome.
|
||||
* @param props.size - width and height in pixels, 16 by default.
|
||||
* @returns the glyph.
|
||||
*/
|
||||
export function CheckGlyph({ state, size = 16 }: { readonly state: CheckState; readonly size?: number | undefined }): ReactNode {
|
||||
const running = state === 'pending'
|
||||
return (
|
||||
<span className={clsx(css.checkGlyph, CHECK_TONE[state])} data-forge-check={state} aria-hidden="true">
|
||||
{state === 'success' && <IconCheckCircleFillRegular size={size} />}
|
||||
{state === 'failure' && <IconCloseCircleFillRegular size={size} />}
|
||||
{state !== 'success' && state !== 'failure' && (
|
||||
{state === 'success' ? <IconCheckCircleFillRegular size={size} /> : (
|
||||
<svg width={size} height={size} viewBox="0 0 16 16" fill="none">
|
||||
<circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeWidth={1.5} />
|
||||
{running
|
||||
? <path d="M8 3.5A4.5 4.5 0 0 1 8 12.5Z" fill="currentColor" />
|
||||
: <path d="M5.5 8H10.5" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" />}
|
||||
<circle cx="8" cy="8" r="7.25" stroke="currentColor" strokeWidth={1.3} />
|
||||
{state === 'failure'
|
||||
? <path d="M5.9 5.9L10.1 10.1M10.1 5.9L5.9 10.1" stroke="currentColor" strokeWidth={1.5} strokeLinecap="square" />
|
||||
: state === 'pending'
|
||||
? <path d="M8 2.8A5.2 5.2 0 0 1 8 13.2Z" fill="currentColor" />
|
||||
: <path d="M5.5 8H10.5" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" />}
|
||||
</svg>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -97,6 +97,9 @@ export const zh = {
|
||||
'list.worktree': '在自己的工作树中',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '还有 {count} 个变更请求',
|
||||
'fold.more': '显示其余 {count} 个',
|
||||
'fold.less': '收起',
|
||||
'fold.name': '{label}(变更请求)',
|
||||
'change.expand': '展开 {name}',
|
||||
'change.collapse': '收起 {name}',
|
||||
'change.ci.none': '没有检查',
|
||||
@@ -585,6 +588,9 @@ export const en: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'In its own worktree',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} more change requests',
|
||||
'fold.more': 'Show {count} more',
|
||||
'fold.less': 'Show less',
|
||||
'fold.name': '{label} (change requests)',
|
||||
'change.expand': 'Expand {name}',
|
||||
'change.collapse': 'Collapse {name}',
|
||||
'change.ci.none': 'No checks',
|
||||
@@ -1043,6 +1049,9 @@ export const ja: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': '専用のワークツリー内',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '他 {count} 件の変更リクエスト',
|
||||
'fold.more': '残り{count}件を表示',
|
||||
'fold.less': '折りたたむ',
|
||||
'fold.name': '{label}(変更リクエスト)',
|
||||
'tab.title': '変更リクエスト',
|
||||
'header.attention': 'このセッションの変更リクエストに対応が必要です',
|
||||
'checkout.worktree': 'ワークツリー',
|
||||
@@ -1528,6 +1537,9 @@ export const es: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'En su propio árbol de trabajo',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} solicitudes de cambio más',
|
||||
'fold.more': 'Mostrar {count} más',
|
||||
'fold.less': 'Mostrar menos',
|
||||
'fold.name': '{label} (solicitudes de cambio)',
|
||||
'tab.title': 'Solicitudes de cambio',
|
||||
'header.attention': 'Las solicitudes de cambio de esta sesión requieren atención',
|
||||
'checkout.worktree': 'Árbol de trabajo',
|
||||
@@ -2013,6 +2025,9 @@ export const fr: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'Dans son propre arbre de travail',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} demandes de changement supplémentaires',
|
||||
'fold.more': 'Afficher {count} de plus',
|
||||
'fold.less': 'Afficher moins',
|
||||
'fold.name': '{label} (demandes de modification)',
|
||||
'tab.title': 'Demandes de modification',
|
||||
'header.attention': 'Les demandes de modification de cette session nécessitent une intervention',
|
||||
'checkout.worktree': 'Arbre de travail',
|
||||
@@ -2498,6 +2513,9 @@ export const de: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'Im eigenen Arbeitsbaum',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} weitere Änderungsanfragen',
|
||||
'fold.more': '{count} weitere anzeigen',
|
||||
'fold.less': 'Weniger anzeigen',
|
||||
'fold.name': '{label} (Änderungsanfragen)',
|
||||
'tab.title': 'Änderungsanfragen',
|
||||
'header.attention': 'Änderungsanfragen dieser Sitzung erfordern Aufmerksamkeit',
|
||||
'checkout.worktree': 'Arbeitsbaum',
|
||||
@@ -2983,6 +3001,9 @@ export const ru: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'В собственном рабочем дереве',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': 'Ещё запросов на изменение: {count}',
|
||||
'fold.more': 'Показать ещё {count}',
|
||||
'fold.less': 'Свернуть',
|
||||
'fold.name': '{label} (запросы на изменение)',
|
||||
'tab.title': 'Запросы на изменение',
|
||||
'header.attention': 'Запросы на изменение этого сеанса требуют внимания',
|
||||
'checkout.worktree': 'Рабочее дерево',
|
||||
@@ -3468,6 +3489,9 @@ export const pt: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'Na sua própria árvore de trabalho',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': 'Mais {count} solicitações de alteração',
|
||||
'fold.more': 'Mostrar mais {count}',
|
||||
'fold.less': 'Mostrar menos',
|
||||
'fold.name': '{label} (solicitações de alteração)',
|
||||
'tab.title': 'Solicitações de alteração',
|
||||
'header.attention': 'As solicitações de alteração desta sessão precisam de atenção',
|
||||
'checkout.worktree': 'Árvore de trabalho',
|
||||
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
import { appendPluginRecord } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection-cache'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
@@ -178,7 +178,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
this.creations = new WorktreeCreations(ctx, this.worktreeStates, this.config.worktreePrefix, (session) => {
|
||||
this.panels.get(session)?.updateWorktree()
|
||||
})
|
||||
const inbox = ctx.on('agent/inbox/inserted', ({ agent }) => { this.holdTurn(agent) })
|
||||
const inbox = ctx.on('agent/inbox/inserted', ({ agent, message }) => { this.holdTurn(agent, message) })
|
||||
const events = ctx.on('session/event', (session: Session, event: SessionEvent) => {
|
||||
this.panels.get(session)?.observe(event)
|
||||
})
|
||||
@@ -967,14 +967,17 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
/* oxlint-enable typescript/require-await */
|
||||
|
||||
/**
|
||||
* Hold the turn of a message entering a Session's inbox while the
|
||||
* Hold the turn of a message entering a Session's next-turn queue while the
|
||||
* Session's requested worktree does not exist yet, or while the worktree
|
||||
* the Session works in is checked and, when gone, until it is restored or
|
||||
* left. The message is entering, so the delivery has not woken the Agent
|
||||
* yet and its wake waits for the hold.
|
||||
* yet and its wake waits for the hold. A message for the next step, such as
|
||||
* a notice another plugin queues, opens no turn and gets no hold.
|
||||
* @param agent - Agent whose inbox receives the message.
|
||||
* @param message - the entering message.
|
||||
*/
|
||||
private holdTurn(agent: Agent): void {
|
||||
private holdTurn(agent: Agent, message: UserMessage): void {
|
||||
if (!agent.inbox.nextTurn.some(queued => queued.id === message.id)) return
|
||||
const session = agent.session
|
||||
const state = this.worktreeState(session)
|
||||
if (state.request !== null && state.created === null && !state.locked) {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
// @vitest-environment jsdom
|
||||
/** One change request card: state glyph, title link, collapsed summary, read notices, and expanded details and actions. */
|
||||
/**
|
||||
* One change request card: its line of state glyph, title, number, and checks outcome, the hover details, read notices,
|
||||
* and expanded details and actions.
|
||||
*/
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { ForgeFailure, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import { ChangeRequestCard, type ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx'
|
||||
@@ -35,9 +38,10 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act
|
||||
)
|
||||
const item = view.container.querySelector('[data-forge-change]')
|
||||
const head = item?.querySelector(`.${css.changeHead}`)
|
||||
if (!(item instanceof HTMLElement) || !(head instanceof HTMLElement)) throw new Error('no change request card')
|
||||
/** The number and status line below the title, or null when it names neither. */
|
||||
const meta = (): HTMLElement | null => head.querySelector(`.${css.meta}`)
|
||||
const line = head?.querySelector('[data-row-part="body"]')
|
||||
const status = head?.querySelector(`.${css.status}`)
|
||||
const drawn = item instanceof HTMLElement && head instanceof HTMLElement && line instanceof HTMLElement && status instanceof HTMLElement
|
||||
if (!drawn) throw new Error('no change request card')
|
||||
const menuButton = (): HTMLElement => within(head).getByRole('button', { name: /^Actions for / })
|
||||
/** Labels of the actions menu, closing it again. */
|
||||
const menuItems = (): string[] => {
|
||||
@@ -51,14 +55,13 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act
|
||||
fireEvent.click(menuButton())
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: label }))
|
||||
}
|
||||
return { view, item, head, meta, menuButton, menuItems, choose, title: within(head).getByRole('link'), openLink, copyLink, retry, remove, onToggle }
|
||||
}
|
||||
|
||||
/** The number and status line of a card that has one. */
|
||||
function metaOf(b: ReturnType<typeof card>): HTMLElement {
|
||||
const meta = b.meta()
|
||||
if (meta === null) throw new Error('no number or status line')
|
||||
return meta
|
||||
/** The title the line shows. */
|
||||
const title = (): string | null => line.querySelector('[data-row-part="content"]')?.textContent ?? null
|
||||
/** The status the line reads to assistive technology, or null when it reads none. */
|
||||
const spoken = (): string | null => status.querySelector(`.${css.visuallyHidden}`)?.textContent ?? null
|
||||
return {
|
||||
view, item, head, line, status, title, spoken, menuButton, menuItems, choose, openLink, copyLink, retry, remove, onToggle,
|
||||
}
|
||||
}
|
||||
|
||||
/** The value a details row shows after its name, which only assistive technology reads. */
|
||||
@@ -111,63 +114,68 @@ describe('ChangeRequestCard head', () => {
|
||||
expect(glyph?.getAttribute('aria-label')).toBe(`Change request state: ${en['change.state.unknown']}`)
|
||||
})
|
||||
|
||||
it('opens the snapshot URL from the title instead of following the link in the page', () => {
|
||||
const b = card(entry(7, snapshot(7, { url: 'https://github.com/octo/demo/pull/7#web' })))
|
||||
expect(b.title.textContent).toBe('Change 7')
|
||||
expect(b.title.getAttribute('href')).toBe('https://github.com/octo/demo/pull/7#web')
|
||||
expect(fireEvent.click(b.title)).toBe(false)
|
||||
expect(b.openLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/7#web')
|
||||
it('lays its line out by the panel row marks: the body, the status, the actions menu, and the toggle in the end column', () => {
|
||||
const b = card(entry(7, snapshot(7)))
|
||||
expect(b.head.hasAttribute('data-session-panel-row')).toBe(true)
|
||||
expect([...b.head.children].map(part => part.getAttribute('data-row-part'))).toEqual(['body', 'trailing', 'menu', 'trailing'])
|
||||
expect([...b.line.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content'])
|
||||
expect(b.line.tagName).toBe('BUTTON')
|
||||
expect(b.line.querySelector('[data-row-part="icon"] [data-forge-glyph]')).not.toBeNull()
|
||||
expect(b.title()).toBe('Change 7')
|
||||
expect(b.menuButton().closest('[data-row-part]')?.getAttribute('data-row-part')).toBe('menu')
|
||||
expect(within(b.head).getByRole('button', { name: 'Expand #7' }).closest(`.${css.end}`)).toBe(b.head.lastElementChild)
|
||||
})
|
||||
|
||||
it('opens the changes of a served change request from its line, and its page with a modifier key or the middle button', () => {
|
||||
const viewChanges = vi.fn<(entry: ForgePanelChangeRequest) => void>()
|
||||
const value = entry(7, snapshot(7, { url: 'https://github.com/octo/demo/pull/7#web' }))
|
||||
const b = card(value, { actions: { viewChanges } })
|
||||
expect(b.line.getAttribute('data-forge-opens')).toBe('changes')
|
||||
|
||||
fireEvent.click(b.line)
|
||||
expect(viewChanges.mock.calls).toEqual([[value]])
|
||||
expect(b.openLink).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(b.line, { metaKey: true })
|
||||
fireEvent.click(b.line, { ctrlKey: true })
|
||||
fireEvent(b.line, new MouseEvent('auxclick', { bubbles: true, button: 1 }))
|
||||
fireEvent(b.line, new MouseEvent('auxclick', { bubbles: true, button: 2 }))
|
||||
expect(viewChanges).toHaveBeenCalledOnce()
|
||||
expect(b.openLink.mock.calls).toEqual(Array.from({ length: 3 }, () => ['https://github.com/octo/demo/pull/7#web']))
|
||||
expect(b.onToggle).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('crawls a title the card clips while the pointer rests on the card head, expanded or not', () => {
|
||||
for (const expanded of [false, true]) {
|
||||
const b = card(entry(7, snapshot(7)), { expanded })
|
||||
const text = b.title.firstElementChild
|
||||
if (!(text instanceof HTMLElement)) throw new Error('no title text')
|
||||
expect(text.textContent).toBe('Change 7')
|
||||
Object.defineProperty(text, 'scrollWidth', { value: 240, configurable: true })
|
||||
Object.defineProperty(text, 'clientWidth', { value: 120, configurable: true })
|
||||
fireEvent.pointerEnter(b.head)
|
||||
expect([text.hasAttribute('data-marquee'), text.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '120px'])
|
||||
fireEvent.pointerLeave(b.head)
|
||||
expect([text.hasAttribute('data-marquee'), text.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
|
||||
cleanup()
|
||||
}
|
||||
it.each([
|
||||
['no provider serves', unserved('https://example.test/review/17'), true, 'https://example.test/review/17'],
|
||||
['is not read yet', entry(1, null), true, 'https://github.com/octo/demo/pull/1'],
|
||||
['shows on a surface without a changes view', entry(1, snapshot(1)), false, 'https://github.com/octo/demo/pull/1'],
|
||||
] as const)('opens the page of a change request that %s from its line', (_label, value, changes, url) => {
|
||||
const viewChanges = vi.fn<(entry: ForgePanelChangeRequest) => void>()
|
||||
const b = card(value, { actions: changes ? { viewChanges } : {} })
|
||||
expect(b.line.getAttribute('data-forge-opens')).toBe('link')
|
||||
fireEvent.click(b.line)
|
||||
expect(b.openLink.mock.calls).toEqual([[url]])
|
||||
expect(viewChanges).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('crawls the collapsed number and status line with the title while the pointer rests on the head', () => {
|
||||
const b = card(entry(7, snapshot(7)))
|
||||
const line = metaOf(b).firstElementChild
|
||||
if (!(line instanceof HTMLElement)) throw new Error('no status line')
|
||||
expect(line.className).toContain(css.statusLine)
|
||||
Object.defineProperty(line, 'scrollWidth', { value: 200, configurable: true })
|
||||
Object.defineProperty(line, 'clientWidth', { value: 150, configurable: true })
|
||||
fireEvent.pointerEnter(b.head)
|
||||
expect([line.hasAttribute('data-marquee'), line.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '50px'])
|
||||
fireEvent.pointerLeave(b.head)
|
||||
expect([line.hasAttribute('data-marquee'), line.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
|
||||
})
|
||||
|
||||
it('toggles from the chevron, while the number line stays plain text', () => {
|
||||
it('toggles from the chevron, which the line does not contain', () => {
|
||||
const b = card(entry(7, snapshot(7)))
|
||||
expect(b.item.hasAttribute('data-expanded')).toBe(false)
|
||||
expect(metaOf(b).closest('button')).toBeNull()
|
||||
const chevron = within(b.head).getByRole('button', { name: 'Expand #7' })
|
||||
expect(chevron.getAttribute('aria-expanded')).toBe('false')
|
||||
expect(b.line.contains(chevron)).toBe(false)
|
||||
fireEvent.click(chevron)
|
||||
expect(b.onToggle).toHaveBeenCalledOnce()
|
||||
expect(b.openLink).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('collapsed ChangeRequestCard', () => {
|
||||
it('summarizes an open change request by its number and checks beside its header actions, without its rows', () => {
|
||||
it('shows the number and the checks outcome of an open change request after its title, without its rows', () => {
|
||||
const b = card(entry(7, snapshot(7)))
|
||||
const meta = metaOf(b)
|
||||
expect(within(meta).getByText('#7')).toBeTruthy()
|
||||
expect(within(meta).getByText('·')).toBeTruthy()
|
||||
expect(within(meta).getByText(en['change.ci.passed']).querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('success')
|
||||
expect(meta.querySelector('[data-flag]')).toBeNull()
|
||||
expect(within(b.status).getByText('#7').className).toBe(css.number)
|
||||
expect(b.status.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('success')
|
||||
expect(b.spoken()).toBe(en['change.ci.passed'])
|
||||
expect(within(b.item).queryByText(en['change.row.changes'])).toBeNull()
|
||||
expect(within(b.item).queryByText('+12')).toBeNull()
|
||||
expect(b.menuButton().getAttribute('aria-label')).toBe('Actions for #7')
|
||||
@@ -180,102 +188,44 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
})
|
||||
|
||||
it.each([
|
||||
['no checks', { checksRollup: 'none' }, en['change.ci.none'], undefined, null],
|
||||
['running checks', { checksRollup: 'pending' }, en['change.ci.running'], 'pending', null],
|
||||
['no checks', { checksRollup: 'none' }, en['change.ci.none'], undefined],
|
||||
['running checks', { checksRollup: 'pending' }, en['change.ci.running'], 'pending'],
|
||||
['listed failed checks', {
|
||||
checksRollup: 'failure',
|
||||
checks: [check('lint', { state: 'failure' }), check('test'), check('types', { state: 'failure' })],
|
||||
}, '2 checks failed', 'failure', 'error'],
|
||||
['cancelled checks', { checksRollup: 'failure', checks: [check('build', { state: 'cancelled' })] }, '1 checks cancelled', 'cancelled', null],
|
||||
['failed checks the host did not list', { checksRollup: 'failure', checksTruncated: true }, en['change.ci.failedUnlisted'], 'failure', 'error'],
|
||||
] as const)('states %s', (_label, overrides, text, glyph, tone) => {
|
||||
const ci = within(metaOf(card(entry(1, snapshot(1, overrides))))).getByText(text)
|
||||
expect(ci.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe(glyph)
|
||||
expect(ci.getAttribute('data-tone')).toBe(tone)
|
||||
}, '2 checks failed', 'failure'],
|
||||
['cancelled checks', { checksRollup: 'failure', checks: [check('build', { state: 'cancelled' })] }, '1 checks cancelled', 'cancelled'],
|
||||
['failed checks the host did not list', { checksRollup: 'failure', checksTruncated: true }, en['change.ci.failedUnlisted'], 'failure'],
|
||||
] as const)('marks %s with a glyph and reads them in words', (_label, overrides, text, glyph) => {
|
||||
const b = card(entry(1, snapshot(1, overrides)))
|
||||
expect(b.status.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe(glyph)
|
||||
expect(b.spoken()).toBe(text)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['requested changes', { reviewDecision: 'changes-requested', mergeability: 'conflicting' }, 'changesRequested', en['change.flag.changesRequested']],
|
||||
['merge conflicts', { mergeability: 'conflicting', draft: true }, 'conflicting', en['change.flag.conflicting']],
|
||||
['draft state', { draft: true }, 'draft', en['change.flag.draft']],
|
||||
] as const)('flags %s after the checks', (_label, overrides, flag, text) => {
|
||||
const meta = metaOf(card(entry(1, snapshot(1, overrides))))
|
||||
expect(meta.querySelector('[data-flag]')?.getAttribute('data-flag')).toBe(flag)
|
||||
expect(within(meta).getByText(text)).toBeTruthy()
|
||||
})
|
||||
|
||||
/**
|
||||
* Give status lines the given width and their content a width by wording, 200px with the full failed-checks wording and
|
||||
* 150px with the short one, and capture the resize observer. Returns the setter of the width and the resize trigger.
|
||||
*/
|
||||
function fitting(initial: number) {
|
||||
let available = initial
|
||||
let resized: () => void = () => {}
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
constructor(callback: () => void) { resized = callback }
|
||||
observe = vi.fn()
|
||||
disconnect = vi.fn()
|
||||
})
|
||||
const isLine = (element: Element): boolean => element.matches(`.${css.statusLine}`)
|
||||
const client = vi.spyOn(Element.prototype, 'clientWidth', 'get').mockImplementation(function (this: Element) {
|
||||
return isLine(this) ? available : 0
|
||||
})
|
||||
const scroll = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockImplementation(function (this: Element) {
|
||||
return isLine(this) ? (this.textContent ?? '').includes('2 checks failed') ? 200 : 150 : 0
|
||||
})
|
||||
onTestFinished(() => {
|
||||
vi.unstubAllGlobals()
|
||||
client.mockRestore()
|
||||
scroll.mockRestore()
|
||||
})
|
||||
return {
|
||||
resize: (width: number): void => { available = width; act(() => { resized() }) },
|
||||
set: (width: number): void => { available = width },
|
||||
}
|
||||
}
|
||||
|
||||
const FAILING = {
|
||||
checksRollup: 'failure', mergeability: 'conflicting',
|
||||
checks: [check('lint', { state: 'failure' }), check('test'), check('types', { state: 'failure' })],
|
||||
} as const
|
||||
|
||||
it('takes the short wording of failed checks while the full line does not fit, and measures again on width and font changes', () => {
|
||||
const fit = fitting(160)
|
||||
const b = card(entry(1, snapshot(1, FAILING)))
|
||||
const short = `#1·${en['change.ci.failedUnlisted']}${en['change.flag.conflicting']}`
|
||||
expect(metaOf(b).textContent).toBe(short)
|
||||
fit.resize(250)
|
||||
expect(metaOf(b).textContent).toBe(`#1·2 checks failed${en['change.flag.conflicting']}`)
|
||||
fit.set(160)
|
||||
act(() => { document.fonts.dispatchEvent(new Event('loadingdone')) })
|
||||
expect(metaOf(b).textContent).toBe(short)
|
||||
})
|
||||
|
||||
it('keeps the full wording of failed checks where the language has no shorter one', () => {
|
||||
fitting(100)
|
||||
const long = makeTranslate({ ...en, 'change.ci.failedUnlisted': 'Every check that ran has failed' })
|
||||
expect(metaOf(card(entry(1, snapshot(1, FAILING)), { t: long })).textContent).toBe(`#1·2 checks failed${en['change.flag.conflicting']}`)
|
||||
['requested changes', { reviewDecision: 'changes-requested', mergeability: 'conflicting' }, en['change.flag.changesRequested']],
|
||||
['merge conflicts', { mergeability: 'conflicting', draft: true }, en['change.flag.conflicting']],
|
||||
['draft state', { draft: true }, en['change.flag.draft']],
|
||||
] as const)('reads %s after the checks', (_label, overrides, text) => {
|
||||
expect(card(entry(1, snapshot(1, overrides))).spoken()).toBe(`${en['change.ci.passed']} · ${text}`)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['merged three hours ago', { state: 'merged', closedAt: '2026-10-09T09:00:00Z' }, 'merged', 'Merged into main · 3 h ago'],
|
||||
['closed without a close time', { state: 'closed' }, 'closed', en['change.state.closed']],
|
||||
['closed at a time that does not parse', { state: 'closed', closedAt: 'last week' }, 'closed', en['change.state.closed']],
|
||||
] as const)('states a change request %s instead of its checks', (_label, overrides, tone, text) => {
|
||||
const meta = metaOf(card(entry(1, snapshot(1, { ...overrides, checksRollup: 'failure', reviewDecision: 'changes-requested' }))))
|
||||
expect(within(meta).getByText(text).getAttribute('data-tone')).toBe(tone)
|
||||
expect(within(meta).queryByText(en['change.ci.failedUnlisted'])).toBeNull()
|
||||
expect(meta.querySelector('[data-flag]')).toBeNull()
|
||||
['merged three hours ago', { state: 'merged', closedAt: '2026-10-09T09:00:00Z' }, 'Merged into main · 3 h ago'],
|
||||
['closed without a close time', { state: 'closed' }, en['change.state.closed']],
|
||||
['closed at a time that does not parse', { state: 'closed', closedAt: 'last week' }, en['change.state.closed']],
|
||||
] as const)('reads a change request %s instead of its checks, without a checks glyph', (_label, overrides, text) => {
|
||||
const b = card(entry(1, snapshot(1, { ...overrides, checksRollup: 'failure', reviewDecision: 'changes-requested' })))
|
||||
expect(b.spoken()).toBe(text)
|
||||
expect(b.status.querySelector('[data-forge-check]')).toBeNull()
|
||||
})
|
||||
|
||||
it('names the URL and the number of a change request with a spinner before its first poll', () => {
|
||||
const b = card(entry(1, null))
|
||||
expect(b.title.textContent).toBe('github.com/octo/demo/pull/1')
|
||||
expect(b.title.getAttribute('href')).toBe('https://github.com/octo/demo/pull/1')
|
||||
const meta = metaOf(b)
|
||||
expect(within(meta).getByText('#1')).toBeTruthy()
|
||||
expect(within(meta).getByText('·')).toBeTruthy()
|
||||
expect(meta.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(b.title()).toBe('github.com/octo/demo/pull/1')
|
||||
expect(within(b.status).getByText('#1')).toBeTruthy()
|
||||
expect(b.status.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(b.spoken()).toBeNull()
|
||||
expect(b.item.querySelector(`.${css.notice}`)).toBeNull()
|
||||
})
|
||||
|
||||
@@ -283,10 +233,10 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
['not-found', en['change.failure.notFound']],
|
||||
['unauthenticated', en['change.failure.unauthenticated']],
|
||||
['unavailable', en['change.failure.unavailable']],
|
||||
] as const)('explains a %s read failure in place of the summary and retries it', (code, text) => {
|
||||
] as const)('explains a %s read failure below the line in place of the status and retries it', (code, text) => {
|
||||
const failure: ForgeFailure = { code, message: 'detail' }
|
||||
const b = card(entry(1, failure))
|
||||
expect(metaOf(b).textContent).toBe('#1')
|
||||
expect(b.status.textContent).toBe('#1')
|
||||
const notice = b.item.querySelector(`.${css.notice}`)
|
||||
if (!(notice instanceof HTMLElement)) throw new Error('no failure notice')
|
||||
expect(within(notice).getByText(text)).toBeTruthy()
|
||||
@@ -296,17 +246,17 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
expect(b.openLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the title of the last snapshot after a failed read but not its stale summary', () => {
|
||||
it('keeps the title of the last snapshot after a failed read but not its stale status', () => {
|
||||
const b = card(entry(4, { code: 'unavailable', message: 'down' }, { kept: snapshot(4, { checksRollup: 'failure' }) }))
|
||||
expect(b.title.textContent).toBe('Change 4')
|
||||
expect(metaOf(b).textContent).toBe('#4')
|
||||
expect(b.title()).toBe('Change 4')
|
||||
expect(b.status.textContent).toBe('#4')
|
||||
expect(within(b.item).getByText(en['change.failure.unavailable'])).toBeTruthy()
|
||||
})
|
||||
|
||||
it('opens a URL no provider serves instead of retrying it, without a number line when the URL names no number', () => {
|
||||
it('opens a URL no provider serves instead of retrying it, without a number when the URL names none', () => {
|
||||
const b = card(unserved('http://example.test/review/latest'))
|
||||
expect(b.title.textContent).toBe('example.test/review/latest')
|
||||
expect(b.meta()).toBeNull()
|
||||
expect(b.title()).toBe('example.test/review/latest')
|
||||
expect(b.status.textContent).toBe('')
|
||||
const notice = b.item.querySelector(`.${css.notice}`)
|
||||
if (!(notice instanceof HTMLElement)) throw new Error('no unserved notice')
|
||||
expect(within(notice).getByText(en['change.unserved'])).toBeTruthy()
|
||||
@@ -319,17 +269,69 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
})
|
||||
|
||||
it('reads the number of an unserved URL from its path', () => {
|
||||
expect(metaOf(card(unserved('https://example.test/review/17'))).textContent).toBe('#17')
|
||||
expect(card(unserved('https://example.test/review/17')).status.textContent).toBe('#17')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ChangeRequestCard hover card', () => {
|
||||
/** Render a card on a surface that draws hover details, and return what the card asked it to draw. */
|
||||
function described(value: ForgePanelChangeRequest, expanded = false) {
|
||||
const renderDetails = vi.fn<NonNullable<ChangeRequestActions['renderDetails']>>(() => <span data-details="" />)
|
||||
const b = card(value, { expanded, actions: { renderDetails } })
|
||||
return { ...b, details: renderDetails.mock.lastCall?.[0] }
|
||||
}
|
||||
|
||||
it('names the full title, the number with the branches, and the status in words', () => {
|
||||
expect(described(entry(7, snapshot(7))).details).toEqual({
|
||||
title: 'Change 7', lines: ['#7 · feat → main'], status: { state: 'done', label: en['change.ci.passed'] },
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a draft', snapshot(1, { draft: true, checksRollup: 'none' }), ['#1 · Draft · feat → main'], 'idle', `${en['change.ci.none']} · ${en['change.flag.draft']}`],
|
||||
['running checks', snapshot(1, { checksRollup: 'pending' }), ['#1 · feat → main'], 'ongoing', en['change.ci.running']],
|
||||
['what needs the author', snapshot(1, { mergeability: 'conflicting' }), ['#1 · feat → main'], 'error', `${en['change.ci.passed']} · ${en['change.flag.conflicting']}`],
|
||||
['a merge', snapshot(1, { state: 'merged' }), ['#1 · feat → main'], 'done', 'Merged into main'],
|
||||
['a close', snapshot(1, { state: 'closed' }), ['#1 · feat → main'], 'idle', en['change.state.closed']],
|
||||
] as const)('gives %s its state dot', (_label, value, lines, state, label) => {
|
||||
expect(described(entry(1, value)).details).toEqual({ title: 'Change 1', lines, status: { state, label } })
|
||||
})
|
||||
|
||||
it('names only the URL and the number before the first poll', () => {
|
||||
expect(described(entry(1, null)).details).toEqual({ title: 'github.com/octo/demo/pull/1', lines: ['#1'] })
|
||||
})
|
||||
|
||||
it('states a failed read and an unserved URL as its status', () => {
|
||||
expect(described(entry(4, { code: 'unavailable', message: 'down' }, { kept: snapshot(4) })).details).toEqual({
|
||||
title: 'Change 4', lines: ['#4 · feat → main'], status: { state: 'warning', label: en['change.failure.unavailable'] },
|
||||
})
|
||||
cleanup()
|
||||
expect(described(unserved('http://example.test/review/latest')).details).toEqual({
|
||||
title: 'example.test/review/latest', lines: [], status: { state: 'warning', label: en['change.unserved'] },
|
||||
})
|
||||
})
|
||||
|
||||
it('anchors the hover card to the line, expanded or not, and draws the line alone on a surface without details', () => {
|
||||
for (const expanded of [false, true]) {
|
||||
const b = described(entry(7, snapshot(7)), expanded)
|
||||
expect(b.head.parentElement).not.toBe(b.item)
|
||||
expect(b.item.contains(b.head)).toBe(true)
|
||||
cleanup()
|
||||
}
|
||||
const plain = card(entry(7, snapshot(7)))
|
||||
expect(plain.head.parentElement).toBe(plain.item)
|
||||
})
|
||||
})
|
||||
|
||||
describe('expanded ChangeRequestCard', () => {
|
||||
it('shows the target, details, and diff size of an open change request and runs its actions on the snapshot URL', () => {
|
||||
it('shows the details and diff size of an open change request below its line and runs its actions on the snapshot URL', () => {
|
||||
const value = entry(7, snapshot(7, { url: 'https://github.com/octo/demo/pull/7#web', additions: 12345 }))
|
||||
const b = card(value, { expanded: true })
|
||||
expect(b.item.getAttribute('data-forge-change')).toBe('https://github.com/octo/demo/pull/7')
|
||||
expect(b.item.hasAttribute('data-expanded')).toBe(true)
|
||||
expect(metaOf(b).textContent).toBe('#7·feat → main')
|
||||
// The rows below state the status, so the line no longer reads it.
|
||||
expect(b.status.textContent).toBe('#7')
|
||||
expect(b.spoken()).toBeNull()
|
||||
expect(within(b.head).getByRole('button', { name: 'Collapse #7' }).getAttribute('aria-expanded')).toBe('true')
|
||||
expect(rowValue(b.item, en['change.row.checks']).textContent).toBe(en['change.ci.none'])
|
||||
expect(within(b.item).getByText(en['change.row.checks']).closest('button')).toBeNull()
|
||||
@@ -351,12 +353,6 @@ describe('expanded ChangeRequestCard', () => {
|
||||
expect(b.remove).toHaveBeenCalledWith(value)
|
||||
})
|
||||
|
||||
it('marks a draft before its branches', () => {
|
||||
const meta = metaOf(card(entry(7, snapshot(7, { draft: true })), { expanded: true }))
|
||||
expect(within(meta).getByText(en['change.state.draft'])).toBeTruthy()
|
||||
expect(meta.textContent).toBe('#7·Draftfeat → main')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['merge conflicts', { mergeability: 'conflicting' }, 'Conflicts with main', 'error'],
|
||||
['an unknown mergeability', { mergeability: 'unknown' }, en['change.merge.unknown'], null],
|
||||
@@ -571,7 +567,7 @@ describe('expanded ChangeRequestCard', () => {
|
||||
|
||||
it('shows only the link actions before the first poll', () => {
|
||||
const b = card(entry(1, null), { expanded: true })
|
||||
expect(metaOf(b).textContent).toBe('#1')
|
||||
expect(b.status.textContent).toBe('#1')
|
||||
expect(within(b.item).queryByText(en['change.row.checks'])).toBeNull()
|
||||
expect(within(b.item).queryByText('+12')).toBeNull()
|
||||
expect(b.menuItems()).toEqual([en['change.view'], en['change.copy'], en['change.remove']])
|
||||
@@ -579,10 +575,11 @@ describe('expanded ChangeRequestCard', () => {
|
||||
expect(b.copyLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/1')
|
||||
})
|
||||
|
||||
it('shows the branches and opens the snapshot URL of an unnumbered change request', () => {
|
||||
it('names an unnumbered change request by its title and opens its snapshot URL', () => {
|
||||
const b = card({ ...unserved('https://example.test/review/latest'), snapshot: snapshot(3, { url: 'https://example.test/review/latest#web' }) }, { expanded: true })
|
||||
expect(b.title.textContent).toBe('Change 3')
|
||||
expect(metaOf(b).textContent).toBe('feat → main')
|
||||
expect(b.title()).toBe('Change 3')
|
||||
// No provider serves the URL, so the unserved notice stands in for the status.
|
||||
expect(b.status.textContent).toBe('')
|
||||
expect(b.menuButton().getAttribute('aria-label')).toBe('Actions for Change 3')
|
||||
b.choose(en['change.remove'])
|
||||
expect(b.remove).toHaveBeenCalledOnce()
|
||||
|
||||
@@ -60,6 +60,9 @@ function reader(opened: Bench): Follower {
|
||||
|
||||
const ready = (state: ForgePanelState): boolean => state.checkout.state === 'ready' && state.readiness !== null
|
||||
|
||||
/** Text of a notice a plugin queues for the next step, as the approval service does after a policy change. */
|
||||
const POLICY_NOTICE = 'The user changed the approval policy from "ask the user for approval" to "never ask the user for approval".'
|
||||
|
||||
/** Worktree facts of a Session without a worktree service, request, or creation, whose checkout can host a worktree. */
|
||||
const UNAVAILABLE = {
|
||||
editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null,
|
||||
@@ -1255,6 +1258,31 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('creates no worktree for a notice queued for the next step, and creates it when the first message arrives', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const maintenance = vi.spyOn(opened.agent, 'runMaintenance')
|
||||
const policy = prompt(POLICY_NOTICE)
|
||||
|
||||
opened.agent.inject(policy)
|
||||
const afterNotice = maintenance.mock.calls.length
|
||||
const untouched = worktreeState(opened).created
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
const created = worktreeState(opened)?.created ?? null
|
||||
expect(afterNotice).toBe(0)
|
||||
expect(untouched).toBeNull()
|
||||
expect(maintenance).toHaveBeenCalledTimes(1)
|
||||
expect(created?.repositoryRoot).toBe(repo)
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
expect(opened.agent.inbox.nextStep).toEqual([policy, notice(created?.path ?? '')])
|
||||
expect(queued(opened)).toEqual(['first'])
|
||||
})
|
||||
|
||||
it('keeps the message waiting with the failure the panel shows, and tries again with a new branch when asked', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
@@ -1652,6 +1680,23 @@ describe('forgePanel removed worktrees', () => {
|
||||
expect(queued(opened)).toEqual(['before', 'first', 'inside', 'removed', 'outside'])
|
||||
})
|
||||
|
||||
it('starts no check of a removed worktree for a notice queued for the next step', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const created = await startInWorktree(opened)
|
||||
await rm(created.path, { recursive: true, force: true })
|
||||
const maintenance = vi.spyOn(opened.agent, 'runMaintenance')
|
||||
|
||||
opened.agent.inject(prompt(POLICY_NOTICE))
|
||||
const afterNotice = maintenance.mock.calls.length
|
||||
sendPrompt(opened.agent, 'removed')
|
||||
await vi.waitFor(async () => { await expect(opened.ctx.forgePanel.continueInProject(opened.session, signal)).resolves.toBeUndefined() })
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
expect(afterNotice).toBe(0)
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo)
|
||||
})
|
||||
|
||||
it('leaves a worktree whose directory exists unchanged', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client'
|
||||
import type { PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import {
|
||||
@@ -70,6 +71,12 @@ function section(state: ForgePanelState | null, options: { disconnected?: boolea
|
||||
dismissOverlay: vi.fn<() => void>(),
|
||||
// Plugins' card actions: a marker naming the change request it was drawn for.
|
||||
renderSlot: vi.fn((_name: string, owner: { url: string }) => <span data-plugin-action={owner.url} />),
|
||||
// The panel's Component Factories: the fold control as a button, and a row's hover details as a marker.
|
||||
renderFactorySlot: vi.fn((name: string, input: object) => {
|
||||
if (name !== 'conversation.session.panel.fold') return <span data-panel-details="" />
|
||||
const fold = input as PanelFoldProps
|
||||
return <button type="button" data-fold="" aria-expanded={fold.expanded} aria-label={fold.name} onClick={fold.onToggle}>{fold.label}</button>
|
||||
}),
|
||||
}
|
||||
const props = {
|
||||
sessionId: SESSION,
|
||||
@@ -82,7 +89,7 @@ function section(state: ForgePanelState | null, options: { disconnected?: boolea
|
||||
t,
|
||||
} as Pick<ChangeRequestsSectionProps,
|
||||
'sessionId' | 'presentation' | 'usePanel' | 'useLocale' | 'useStore' | 'actions' | 'dismissOverlay' | 'refresh'
|
||||
| 'remove' | 'markReady' | 'merge' | 'readChecks' | 'openLink' | 'copyText' | 'viewChanges' | 'renderSlot'
|
||||
| 'remove' | 'markReady' | 'merge' | 'readChecks' | 'openLink' | 'copyText' | 'viewChanges' | 'renderSlot' | 'renderFactorySlot'
|
||||
| 't'> as ChangeRequestsSectionProps
|
||||
const view = render(<ChangeRequestsSection {...props} />)
|
||||
return { view, panel, store, ...handlers }
|
||||
@@ -154,6 +161,65 @@ describe('ChangeRequestsSection', () => {
|
||||
expect(expansion(section(ready({ changeRequests: [entry(1, snapshot(1))] })).view)).toEqual([true])
|
||||
})
|
||||
|
||||
/** The numbers of the rendered cards, in list order. */
|
||||
const numbers = (view: ReturnType<typeof render>): string[] =>
|
||||
[...view.container.querySelectorAll('[data-forge-change]')].map(card => card.getAttribute('data-forge-change')?.split('/').at(-1) ?? '')
|
||||
const several = (count: number): ForgePanelState =>
|
||||
ready({ changeRequests: Array.from({ length: count }, (_unused, index) => entry(index + 1, snapshot(index + 1))) })
|
||||
|
||||
it('shows up to three cards without a fold control', () => {
|
||||
const b = section(several(3))
|
||||
expect(numbers(b.view)).toEqual(['1', '2', '3'])
|
||||
expect(b.view.container.querySelector('[data-fold]')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows three cards of four or more and then the fold control, which shows the rest and folds them again', () => {
|
||||
const b = section(several(4))
|
||||
expect(numbers(b.view)).toEqual(['1', '2', '3'])
|
||||
const fold = (): HTMLElement => b.view.container.querySelector('[data-fold]') as HTMLElement
|
||||
expect([fold().textContent, fold().getAttribute('aria-label'), fold().getAttribute('aria-expanded')])
|
||||
.toEqual(['Show 1 more', 'Show 1 more (change requests)', 'false'])
|
||||
// The control is the list's last row, after the cards.
|
||||
expect(fold().compareDocumentPosition(b.view.container.querySelector('ul') as HTMLElement) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy()
|
||||
|
||||
fireEvent.click(fold())
|
||||
expect(numbers(b.view)).toEqual(['1', '2', '3', '4'])
|
||||
expect([fold().textContent, fold().getAttribute('aria-label'), fold().getAttribute('aria-expanded')])
|
||||
.toEqual(['Show less', 'Show less (change requests)', 'true'])
|
||||
act(() => { b.panel.set({ state: several(6), disconnected: false }) })
|
||||
expect(numbers(b.view)).toEqual(['1', '2', '3', '4', '5', '6'])
|
||||
|
||||
fireEvent.click(fold())
|
||||
expect(numbers(b.view)).toEqual(['1', '2', '3'])
|
||||
expect(fold().textContent).toBe('Show 3 more')
|
||||
})
|
||||
|
||||
it('keeps the fold choice of the Session while the panel is hidden and shown again', () => {
|
||||
const b = section(several(5))
|
||||
fireEvent.click(b.view.container.querySelector('[data-fold]') as HTMLElement)
|
||||
b.view.unmount()
|
||||
expect(numbers(section(several(5), { store: b.store }).view)).toEqual(['1', '2', '3', '4', '5'])
|
||||
expect(numbers(section(several(5)).view)).toEqual(['1', '2', '3'])
|
||||
})
|
||||
|
||||
it('draws each card\'s hover details through the panel\'s details Factory', () => {
|
||||
const b = section(ready({ changeRequests: [entry(7, snapshot(7)), entry(8, null)] }))
|
||||
expect(b.renderFactorySlot).toHaveBeenCalledWith('conversation.session.panel.details', {
|
||||
title: 'Change 7', lines: ['#7 · feat → main'], status: { state: 'done', label: en['change.ci.passed'] },
|
||||
})
|
||||
expect(b.renderFactorySlot).toHaveBeenCalledWith('conversation.session.panel.details', { title: 'github.com/octo/demo/pull/8', lines: ['#8'] })
|
||||
})
|
||||
|
||||
it('opens the changes of a card from its line and closes the panel\'s overlay', () => {
|
||||
const value = entry(7, snapshot(7))
|
||||
const b = section(ready({ changeRequests: [value, entry(8, snapshot(8))] }))
|
||||
const line = b.view.container.querySelector('[data-forge-change="https://github.com/octo/demo/pull/7"] [data-row-part="body"]') as HTMLElement
|
||||
fireEvent.click(line)
|
||||
expect(b.viewChanges.mock.calls).toEqual([[value]])
|
||||
expect(b.dismissOverlay).toHaveBeenCalledOnce()
|
||||
expect(b.openLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('draws the actions plugins add to each card before its actions menu', () => {
|
||||
const b = section(ready({ changeRequests: [entry(7, snapshot(7)), entry(8, null)] }))
|
||||
expect(b.renderSlot).toHaveBeenCalledWith('forge.change-request.card.actions', {
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 3a2f21ff0dc3420d
|
||||
/deepseek-ai-dsh-tool-cordis/use-this-package:
|
||||
en: 3dfbc3694e112e7f
|
||||
zh: c8e32e111455f24a
|
||||
en: 6a03f434a773ec43
|
||||
zh: d2d7c48df1a29e0b
|
||||
/deepseek-ai-dsh-tool-cordis/understand-the-implementation:
|
||||
en: 8e9ef81505922995
|
||||
zh: 2909fe682cf66f7c
|
||||
en: c4d39015cdf9a6b6
|
||||
zh: 9ca8a882bdea7529
|
||||
/deepseek-ai-dsh-tool-cordis/further-exploration:
|
||||
en: 1863373f02bcc196
|
||||
zh: 3efdbf5569411562
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 72ffb7cae674c31a
|
||||
zh: 85674f298a78592a
|
||||
/deepseek-ai-dsh-tool-cordis/model-experience/runtime-inspection/what-the-model-sees:
|
||||
en: f73493581a266830
|
||||
zh: d47bf0bf369f9b90
|
||||
en: 63d8b2a3ac2c6bc9
|
||||
zh: 2ada02dd993f3d4f
|
||||
/deepseek-ai-dsh-tool-cordis/model-experience/runtime-inspection/token-effect:
|
||||
en: b393ba67aaa0a600
|
||||
zh: 89a899e2401e9a34
|
||||
|
||||
@@ -25,7 +25,7 @@ Inspect Host and Client runtime APIs before writing plugin code. Standard and Cr
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Standard and Creator modes include this tool. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tool; a preset row alone registers no Host providers. Call `cordis_inspect` without `query` to discover providers, then pass a `query` object with `platform`, `provider`, `method`, and optional `input` to read a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration.
|
||||
Standard and Creator modes include this tool. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tool; a preset row alone registers no Host providers. Call `cordis_inspect` without `query` to discover providers, then pass a `query` object with `platform`, `provider`, `method`, and optional `input` to read a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. The Host `Runtime` provider's `getVersion` returns `{ version }`, the exact running DSH version that plugin `engines.dsh` ranges and DSH peer dependencies are checked against. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration.
|
||||
|
||||
-----
|
||||
|
||||
@@ -35,7 +35,7 @@ Standard and Creator modes include this tool. Other compositions mount `@deepsee
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
Host providers combine generated Service/Event catalogs, the live Loader tree projected through the app-boot Config projector, and the requesting agent's tool registry. Client providers synchronize their manifests through the existing inspection registry and answer queries from a connected page. The host entry owns the Host provider registrations and the preset row owns the tool, each through Cordis effects; the registry rejects a duplicate provider id, which is why the providers register once per process rather than per preset.
|
||||
Host providers combine generated Service/Event catalogs, the live Loader tree projected through the app-boot Config projector, the requesting agent's tool registry, and the app-boot runtime version. Client providers synchronize their manifests through the existing inspection registry and answer queries from a connected page. The host entry owns the Host provider registrations and the preset row owns the tool, each through Cordis effects; the registry rejects a duplicate provider id, which is why the providers register once per process rather than per preset.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -54,7 +54,7 @@ Host providers combine generated Service/Event catalogs, the live Loader tree pr
|
||||
|
||||
#### What the model sees
|
||||
|
||||
The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-cordis) describes one read-only inspection tool whose description explains directory discovery and queries without adding a system prompt section. In the `standard` and `cordis` presets, the first-turn skill catalog carries the description of the shipped `dsh-doc` skill, which covers questions about DSH and requests to build or change DSH plugins, MCP connections, and agent presets; its references cover Plugin Manager, MCP setup, Client packaging, and slot registration. Query results contain the requested API declarations, live tool schemas, the live entry directory with Config status, or one entry's projected Config JSON Schema.
|
||||
The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-cordis) describes one read-only inspection tool whose description explains directory discovery and queries without adding a system prompt section. In the `standard` and `cordis` presets, the first-turn skill catalog carries the description of the shipped `dsh-doc` skill, which covers questions about DSH and requests to build or change DSH plugins, MCP connections, and agent presets; its references cover Plugin Manager, MCP setup, Client packaging, and slot registration. Query results contain the requested API declarations, live tool schemas, the live entry directory with Config status, one entry's projected Config JSON Schema, or the running DSH version.
|
||||
|
||||
#### Token effect
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
标准模式和创造模式包含这个工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这个工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect` 时省略 `query` 以发现 provider,再传入包含 `platform`、`provider`、`method` 及可选 `input` 的 `query` 对象,读取 provider 的具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。
|
||||
标准模式和创造模式包含这个工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这个工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect` 时省略 `query` 以发现 provider,再传入包含 `platform`、`provider`、`method` 及可选 `input` 的 `query` 对象,读取 provider 的具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。Host 的 `Runtime` provider 的 `getVersion` 返回 `{ version }`,即插件 `engines.dsh` 范围和 DSH peer 依赖所比对的当前运行 DSH 的精确版本。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。
|
||||
|
||||
-----
|
||||
|
||||
@@ -35,7 +35,7 @@ kind: "package-reference"
|
||||
<details>
|
||||
<summary>实现细节 — 点击展开</summary>
|
||||
|
||||
Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影器投影的运行中 Loader 树,以及请求 agent 的工具注册表。Client provider 通过现有检查注册表同步清单,并从已连接页面回答查询。宿主入口持有 Host provider 的注册,preset 行持有这个工具,都通过 Cordis effect;注册表拒绝重复的 provider id,所以 provider 按进程注册一次而不是按 preset 注册。
|
||||
Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影器投影的运行中 Loader 树、请求 agent 的工具注册表,以及 app-boot 运行时版本。Client provider 通过现有检查注册表同步清单,并从已连接页面回答查询。宿主入口持有 Host provider 的注册,preset 行持有这个工具,都通过 Cordis effect;注册表拒绝重复的 provider id,所以 provider 按进程注册一次而不是按 preset 注册。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -54,7 +54,7 @@ Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影
|
||||
|
||||
#### 模型所见
|
||||
|
||||
[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-cordis) 描述一个只读检查工具,其描述说明目录发现和查询方式,不添加 system prompt 段落。在 `standard` 和 `cordis` preset 中,首轮 skill catalog 携带随附的 `dsh-doc` 技能的描述,该技能覆盖关于 DSH 的问题,以及构建或修改 DSH 插件、MCP 连接和 agent preset 的请求;其参考资料覆盖 Plugin Manager、MCP 设置、Client 打包和 slot 注册。查询结果包含所请求的 API 声明、当前工具 schema、带 Config 状态的运行中 entry 目录,或单个 entry 投影后的 Config JSON Schema。
|
||||
[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-cordis) 描述一个只读检查工具,其描述说明目录发现和查询方式,不添加 system prompt 段落。在 `standard` 和 `cordis` preset 中,首轮 skill catalog 携带随附的 `dsh-doc` 技能的描述,该技能覆盖关于 DSH 的问题,以及构建或修改 DSH 插件、MCP 连接和 agent preset 的请求;其参考资料覆盖 Plugin Manager、MCP 设置、Client 打包和 slot 注册。查询结果包含所请求的 API 声明、当前工具 schema、带 Config 状态的运行中 entry 目录、单个 entry 投影后的 Config JSON Schema,或当前运行的 DSH 版本。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
|
||||
@@ -3235,7 +3235,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
{
|
||||
signature: 'abstract open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>',
|
||||
description: 'Open an existing stored session.\n\n`read` never takes ownership and works while another handle (or process) holds write ownership. `write` atomically claims single-writer ownership; an existing active owner rejects.',
|
||||
description: 'Open an existing stored session.\n\nReturned `read` handles retain no write ownership and work while another handle (or process) holds write ownership. A first legacy read open may acquire ownership temporarily to import history into the selected backend. `write` atomically claims single-writer ownership; an existing active owner rejects.',
|
||||
parameters: [{ name: 'id', description: 'the stored session to open.' }, { name: 'access', description: '`read` or `write`.' }, { name: 'options', description: 'optional cancellation.' }],
|
||||
returns: 'the open handle.',
|
||||
throws: ['{SessionPersistenceNotFoundError} when the session does not exist.', '{SessionAlreadyOwnedError} for `write` when ownership is taken.'],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** First-party Host inspect providers registered by the Cordis tool package. */
|
||||
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
|
||||
import { InspectError, type HostCordisInspectProviderRegistration } from '@deepseek-ai/dsh-cordis-host-runner'
|
||||
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
|
||||
import { EVENT_API, queryEventApi, queryServiceApi } from './api-catalog.ts'
|
||||
@@ -29,6 +30,9 @@ const CONFIG_INPUT: JsonValue = {
|
||||
const CONFIG_OUTPUT = {
|
||||
description: 'One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry\'s projected JSON Schema with shared definitions, omission acceptance, and projection limitations.',
|
||||
} as const
|
||||
const RUNTIME_OUTPUT = {
|
||||
description: 'Object whose version field is the exact running DSH version.',
|
||||
} as const
|
||||
const HOST_EVENTS = EVENT_API.filter(event => !event.name.startsWith('cordis/'))
|
||||
|
||||
/**
|
||||
@@ -62,6 +66,14 @@ export function hostInspectProviders(ctx: Context): HostCordisInspectProviderReg
|
||||
CONFIG_INPUT,
|
||||
CONFIG_OUTPUT,
|
||||
),
|
||||
registration(
|
||||
'Runtime',
|
||||
'Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.',
|
||||
'getVersion',
|
||||
() => ({ version: getDshRuntimeVersion() }),
|
||||
undefined,
|
||||
RUNTIME_OUTPUT,
|
||||
),
|
||||
{
|
||||
manifest: {
|
||||
id: 'Tool',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { CordisInspectRegistryService } from '@deepseek-ai/dsh-cordis-host-runner'
|
||||
@@ -31,12 +32,21 @@ describe('the cordis-inspect-providers host entry', () => {
|
||||
const fiber = ctx.plugin(CordisInspectProviders)
|
||||
await fiber
|
||||
|
||||
expect(ctx.cordisInspect.list().map(provider => provider.id)).toEqual(['Service', 'Event', 'Config', 'Tool'])
|
||||
expect(ctx.cordisInspect.list().map(provider => provider.id)).toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool'])
|
||||
|
||||
await fiber.dispose()
|
||||
expect(ctx.cordisInspect.list()).toEqual([])
|
||||
})
|
||||
|
||||
it('answers the Runtime version query with the running DSH version', async () => {
|
||||
const ctx = await host()
|
||||
await ctx.plugin(CordisInspectProviders)
|
||||
const agent = { ctx } as never
|
||||
const signal = new AbortController().signal
|
||||
expect(await ctx.cordisInspect.query('host', 'Runtime', 'getVersion', undefined, agent, signal)).toEqual({ version: (createRequire(import.meta.url)('@deepseek-ai/dsh-app-boot/package.json') as { version: string }).version })
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('reports a missing Agent and an undeclared provider method with error codes', async () => {
|
||||
const ctx = await host()
|
||||
await ctx.plugin(CordisInspectProviders)
|
||||
@@ -46,7 +56,7 @@ describe('the cordis-inspect-providers host entry', () => {
|
||||
await expect(query?.execute({ query: { platform: 'host', provider: 'Tool', method: 'listTools' } }, { signal } as never)).rejects.toMatchObject({
|
||||
name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE', message: 'Cordis inspection requires an Agent-backed session',
|
||||
})
|
||||
for (const provider of hostInspectProviders(ctx).filter(candidate => ['Service', 'Tool'].includes(candidate.manifest.id))) {
|
||||
for (const provider of hostInspectProviders(ctx).filter(candidate => ['Service', 'Runtime', 'Tool'].includes(candidate.manifest.id))) {
|
||||
await expect(Promise.resolve().then(() => provider.query('undeclared', undefined, { agent: undefined as never, signal })))
|
||||
.rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_METHOD_NOT_FOUND' })
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ The files below live in this skill's base directory, which the `skill` tool repo
|
||||
| Find the installed version's documentation and package sources | `references/locate-docs.md` |
|
||||
| Build, install, enable, or debug a plugin or bundle | `references/plugin-development.md` |
|
||||
| Bundle manifest, locale resources, detail document, icons, installation, Host exports and Config | `references/host-plugin.md` |
|
||||
| Read the running DSH version; declare `engines.dsh` | `references/dsh-version.md` |
|
||||
| Bundle descriptions, optional single-image details, locale paths and preview verification | `references/plugin-details.md` |
|
||||
| Save plugin configuration or credentials | `references/configuration.md` |
|
||||
| Web UI: Client manifest, module loader, slot registration | `references/ui-plugin.md` |
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# DSH version and `engines.dsh`
|
||||
|
||||
Read the running DSH version before writing a version requirement. With `cordis_inspect`, pass `query: { platform: 'host', provider: 'Runtime', method: 'getVersion' }` and use the returned `version`; installation and activation check plugins against exactly this version. Otherwise use the version that `references/locate-docs.md` identifies. A `package.json` under the profile's `node_modules`, a lockfile, or an unrelated checkout may be an older copy and does not identify the running version.
|
||||
|
||||
Declare the versions the plugin supports as a SemVer range in `engines.dsh`. Use the running version as the lower bound, copied exactly with any prerelease suffix: for a running `0.2.2-alpha.2`, `^0.2.2` rejects it, while `^0.2.2-alpha.2` accepts it.
|
||||
|
||||
```json
|
||||
{ "engines": { "dsh": "^0.2.2-alpha.2" } }
|
||||
```
|
||||
|
||||
Prerelease versions take part in matching, so `^0.2.2-alpha.2` accepts `0.2.2-rc.1`, `0.2.2`, and `0.2.9`, but not `0.3.0`. When `engines.dsh` is present it alone decides; DSH peer dependencies are then ignored. Without it, every `@deepseek-ai/dsh` or `@deepseek-ai/dsh-*` range in `peerDependencies` must match. An empty, invalid, or `workspace:` range in `engines.dsh` rejects every version; a non-string value makes the manifest malformed. A plugin without either declaration loads on any version. A refusal returns the `incompatible-version` code with `runtimeVersion` and the unmet `requirements`; correct the range rather than requesting a version exemption for a plugin you are writing.
|
||||
@@ -26,6 +26,8 @@ A Host-only bundle needs no dependencies, install scripts, or build tool:
|
||||
config: {}
|
||||
```
|
||||
|
||||
To declare the DSH versions the bundle supports in `engines.dsh`, read `references/dsh-version.md` first.
|
||||
|
||||
## Display metadata, detail document, and icon
|
||||
|
||||
Plugin Manager and Settings read `meta.title` and `meta.description` from exported locale JSON and an icon from exported resources without activating plugins. The bundle's page in Plugin Manager shows the detail document that `meta.detail` names, otherwise the package README. Complete this checklist before installation:
|
||||
|
||||
@@ -6,7 +6,7 @@ Answer for the running installation, not an unrelated checkout in the current wo
|
||||
|
||||
These runtime facts are not necessarily in model context. Print only the needed variables: in bash, `printf '%s\n' "$DSH_PROFILE" "$DSH_INSTALL_DIR" "$DSH_NODE_EXECUTABLE"`; in PowerShell, `$env:DSH_PROFILE; $env:DSH_INSTALL_DIR; $env:DSH_NODE_EXECUTABLE`. Keep the loaded skill's reported Base directory. `DSH_PROFILE=desktop` identifies the Desktop profile, including development launches; `web` can run from npm or source. Profile and distribution are not one-to-one: verify ASAR or checkout markers below. `DSH_PROFILE_DIR` holds the user's profile and added plugins, not the DSH installation root. Standard and Creator are agent modes, not installation layouts.
|
||||
|
||||
Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools.
|
||||
When `cordis_inspect` is available, its Host `Runtime` provider's `getVersion` returns the running DSH version. Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Copies of `@deepseek-ai/dsh` under the profile's `node_modules` may be stale and do not identify the running version. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools.
|
||||
|
||||
## Source checkout
|
||||
|
||||
|
||||
@@ -401,6 +401,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
|
||||
| `@deepseek-ai/dsh-session-checkpoint-policy` | no | Semantic session durability checkpoints before model requests and tool side effects |
|
||||
| `@deepseek-ai/dsh-session-log-deepseek` | yes | Incremental lossless session-log request extension for the official DeepSeek LLM API |
|
||||
| `@deepseek-ai/dsh-session-persistence-jsonl` | yes | JSONL durable session persistence backend for the DeepSeek Harness |
|
||||
| `@deepseek-ai/dsh-session-persistence-sqlite` | yes | SQLite Session event storage backend for the DeepSeek Harness |
|
||||
| `@deepseek-ai/dsh-session-projection` | no | Session-projection seam: the merge-extensible projection type table, the provider contract, and the ctx.sessionProjections registry serving whole current values of log-derived per-session state |
|
||||
| `@deepseek-ai/dsh-session-projection-cache` | yes | Persisted projection cache (ctx.sessionProjectionCache): durable per-session checkpoint records on the session_projcache storage domain (per-record layout), throttled write-behind, and the cached listing read |
|
||||
| `@deepseek-ai/dsh-session-stats` | no | Whole-log conversation counts and wall times projection (sessionStats) for the DeepSeek Harness |
|
||||
|
||||
@@ -18,9 +18,10 @@ export interface ColdSessionLog {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one complete stored session log without taking ownership or mutating
|
||||
* storage: open a read handle, read the validated contiguous log, close the
|
||||
* handle, and append `interruptedTurnClosers` so a log whose writer crashed
|
||||
* Read one complete stored session log without retaining write ownership.
|
||||
* The backend may import legacy history before returning the read handle.
|
||||
* Read the validated contiguous log, close the handle, and append
|
||||
* `interruptedTurnClosers` so a log whose writer crashed
|
||||
* mid-turn folds as a balanced transcript. Backend failures propagate
|
||||
* unmapped — each caller owns its error taxonomy.
|
||||
* @param persistence - the mounted persistence service.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: d6112142a705ec43
|
||||
zh: f0914d9e37216f97
|
||||
/deepseek-ai-dsh-session-persistence-jsonl/use-this-package/when-to-choose-it:
|
||||
en: 37c10302bbbde268
|
||||
zh: 3d5c027bac868efd
|
||||
en: 8fca7647035f8795
|
||||
zh: 0bfb12da95611091
|
||||
/deepseek-ai-dsh-session-persistence-jsonl/use-this-package/minimal-configuration:
|
||||
en: b6c2f0f11f2fa9cf
|
||||
zh: 9fac03fcbe5bbad4
|
||||
|
||||
@@ -29,7 +29,7 @@ Mount this backend when a composition needs durable sessions backed by per-sessi
|
||||
|
||||
### When to choose it
|
||||
|
||||
Choose this backend when consumers benefit from one artifact per session — navigation, external tooling, or a raw line-readable log. It is the sole first-party Session-persistence provider. The backend keeps sessions under a deployment-controlled root: project-local, shared, temporary, or centralized.
|
||||
Choose this backend when consumers benefit from one artifact per session — navigation, external tooling, or a raw line-readable log. Shipped profiles use this provider by default. The [SQLite provider](../session-persistence-sqlite/README.md) is a separate plugin that imports existing JSONL history on first open. The backend keeps sessions under a deployment-controlled root: project-local, shared, temporary, or centralized.
|
||||
|
||||
### Minimal configuration
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ kind: "package-reference"
|
||||
|
||||
### 何时选择
|
||||
|
||||
当消费方受益于每会话一份产物——导航、外部工具或可逐行读取的原始日志——时选择此后端。它是唯一的第一方会话持久化提供方。后端把会话保存在部署控制的根下:项目本地、共享、临时或集中式。
|
||||
当消费方受益于每会话一份产物——导航、外部工具或可逐行读取的原始日志——时选择此后端。内置 profile 默认使用此提供者。[SQLite 提供者](../session-persistence-sqlite/README.zh.md) 是独立插件,在首次打开时导入现有 JSONL 历史。后端把会话保存在部署控制的根下:项目本地、共享、临时或集中式。
|
||||
|
||||
### 最小配置
|
||||
|
||||
|
||||
@@ -58,6 +58,18 @@ import {
|
||||
type PreparedJsonlMigration,
|
||||
} from './generation.ts'
|
||||
|
||||
/** Logical JSONL history retained until its destination commits under write ownership. */
|
||||
interface LegacySessionSnapshot {
|
||||
readonly header: SessionHeader
|
||||
readonly inheritedEventCount: SessionLogOffsetType
|
||||
readonly events: readonly SessionEvent[]
|
||||
}
|
||||
|
||||
/** Prepared legacy history whose related sources are checked before destination publication. */
|
||||
interface PreparedLegacySession {
|
||||
commit(publish: (snapshot: LegacySessionSnapshot) => Promise<void>): Promise<void>
|
||||
}
|
||||
|
||||
export type { JsonlCompression } from './format.ts'
|
||||
|
||||
/**
|
||||
@@ -305,15 +317,12 @@ function waitWithAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<
|
||||
}
|
||||
|
||||
/**
|
||||
* The JSONL backend registered as `ctx.sessionPersistence` by the plugin.
|
||||
* JSONL Session persistence with historical-format migration.
|
||||
* Sessions materialize lazily: a created session is
|
||||
* visible to this process immediately, reaches disk on its first append or
|
||||
* flush, and never existed if the process crashes before that.
|
||||
*/
|
||||
class JsonlSessionPersistence extends SessionPersistence {
|
||||
/** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
|
||||
override readonly name = 'session-persistence-jsonl'
|
||||
|
||||
export class JsonlSessionPersistence extends SessionPersistence {
|
||||
private root: string
|
||||
private compression: JsonlCompression
|
||||
/**
|
||||
@@ -348,7 +357,13 @@ class JsonlSessionPersistence extends SessionPersistence {
|
||||
/** One joinable decode/migration operation per selected historical Session file revision. */
|
||||
private readonly migrationPreparations = new Map<SessionId, MigrationPreparation>()
|
||||
|
||||
constructor(ctx: Context, public config: Config, private readonly tracker: JsonlBackendTracker) {
|
||||
/**
|
||||
* @param ctx - context used for scoped diagnostics and filesystem reads.
|
||||
* @param config - JSONL root, physical encoding, and listing concurrency.
|
||||
* @param tracker - handle bookkeeping; omitted creates bookkeeping for legacy reads.
|
||||
*/
|
||||
constructor(ctx: Context, public config: Config,
|
||||
private readonly tracker = new JsonlBackendTracker('session-persistence-jsonl')) {
|
||||
super(ctx)
|
||||
/* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */
|
||||
if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) {
|
||||
@@ -381,6 +396,35 @@ class JsonlSessionPersistence extends SessionPersistence {
|
||||
return { kind: 'jsonl', path: logPath(this.root, meta.cwd, meta.id, this.compression) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare logical history while the caller retains Session write ownership.
|
||||
* @param id - stored Session identity.
|
||||
* @param signal - optional cancellation for decoding and destination publication.
|
||||
* @returns a commit operation that validates related sources before publishing the history.
|
||||
*/
|
||||
async prepare(id: SessionId, signal?: AbortSignal): Promise<PreparedLegacySession> {
|
||||
await this.ensureRootEncoding()
|
||||
signal?.throwIfAborted()
|
||||
const stored = await this.requireStoredLog(id, signal)
|
||||
const snapshot = { header: stored.meta, inheritedEventCount: stored.inheritedEventCount, events: stored.events }
|
||||
return { commit: async (publish) => {
|
||||
signal?.throwIfAborted()
|
||||
if (stored.status === 'prepared') await stored.validateRelatedSources()
|
||||
signal?.throwIfAborted()
|
||||
await publish(snapshot)
|
||||
} }
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a JSONL artifact occupies the Session identity.
|
||||
* @param id - stored Session identity.
|
||||
* @returns whether the artifact exists.
|
||||
*/
|
||||
async hasStoredJsonl(id: SessionId): Promise<boolean> {
|
||||
await this.ensureRootEncoding()
|
||||
return await this.findLog(id) !== undefined
|
||||
}
|
||||
|
||||
// --- SessionPersistence service API ---
|
||||
|
||||
/**
|
||||
@@ -712,7 +756,7 @@ class JsonlSessionPersistence extends SessionPersistence {
|
||||
const sources = await children()
|
||||
const related = await prepareCatalogFacts(id, sources, this.compression, signal)
|
||||
for (const failure of related.failures) {
|
||||
this.ctx.logger.warn(`${this.name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`)
|
||||
this.ctx.logger.warn(`${name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`)
|
||||
}
|
||||
const membership = sources.map(source => source.path).sort()
|
||||
validateRelatedSources = async () => {
|
||||
@@ -967,7 +1011,7 @@ class JsonlSessionPersistence extends SessionPersistence {
|
||||
async truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void> {
|
||||
this.coldLogMemo.delete(header.id)
|
||||
await this.repair(header, truncateTo)
|
||||
this.ctx.logger.warn(`${this.name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`)
|
||||
this.ctx.logger.warn(`${name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/session/session-persistence-sqlite/README.md
|
||||
/:
|
||||
en: 45c507cd1be83a49
|
||||
zh: 0892f22bc67f3c2b
|
||||
/deepseek-ai-dsh-session-persistence-sqlite:
|
||||
en: 22cf683fb8ec6976
|
||||
zh: c4c0244b1b7340bd
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/summary:
|
||||
en: fe7d7d6b65eb14b8
|
||||
zh: e979ace0de85182b
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 3a2f21ff0dc3420d
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/use-this-package:
|
||||
en: e9211101131a5db2
|
||||
zh: 0d34955cfaadbbeb
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/use-this-package/minimal-configuration:
|
||||
en: 4b80aca7e9524b84
|
||||
zh: 44bb710bf7c5a442
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/use-this-package/opening-existing-history:
|
||||
en: 3a0476996102dcce
|
||||
zh: c0692ddc53045ff2
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/use-this-package/durability-and-shutdown:
|
||||
en: e420c74a70699060
|
||||
zh: 83d37ea617216ac9
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/understand-the-implementation:
|
||||
en: d2f152e5f3020a77
|
||||
zh: c40f206b7a73dc35
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/further-exploration:
|
||||
en: 6c9f517924d25414
|
||||
zh: 0a8400a08ec55dbf
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/model-experience:
|
||||
en: 215e7ba838619b7b
|
||||
zh: a311da3843709f90
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history:
|
||||
en: af9a6e2fdfb3eb09
|
||||
zh: 5cee3d5d560a6df8
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history/what-the-model-sees:
|
||||
en: 37ef7b6c32cafb45
|
||||
zh: a0b53fe40abc64de
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history/token-effect:
|
||||
en: 9f80b2e96a1c9c01
|
||||
zh: 23c96e7f02d087be
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history/kv-cache-effect:
|
||||
en: 3a849c807fae4040
|
||||
zh: cb3a122553040b79
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/known-limitations-and-deferred-work:
|
||||
en: a50bf9d3b012d7c4
|
||||
zh: 880fd4c27465ba5c
|
||||
/deepseek-ai-dsh-session-persistence-sqlite/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: e88aeb617ffb74ea
|
||||
@@ -0,0 +1,127 @@
|
||||
---
|
||||
description: "Save and reopen Session histories in SQLite, import existing JSONL histories, and coordinate concurrent readers and writers."
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-session-persistence-sqlite
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Save Session histories in SQLite and reopen them through the existing persistence API. Existing JSONL histories import on first open while their source files remain intact. Readers can share a database with an active writer; each Session permits one writer. Choose this provider explicitly: shipped profiles continue to use JSONL.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Use this package](#use-this-package)
|
||||
- [Understand the implementation](#understand-the-implementation)
|
||||
- [Further Exploration](#further-exploration)
|
||||
- [Model Experience](#model-experience)
|
||||
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
||||
- [Dev Note](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Mount this provider for the storage root whose Sessions should use SQLite.
|
||||
|
||||
### Minimal configuration
|
||||
|
||||
Replace the JSONL provider's package name in your composition, preserving its root and legacy encoding settings:
|
||||
|
||||
```yaml
|
||||
- name: '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
config:
|
||||
root: './.sessions'
|
||||
```
|
||||
|
||||
The database lives at `<root>/.segments/sessions.sqlite`. Application callers continue to use `ctx.sessionPersistence` and its Session handles.
|
||||
|
||||
| Field | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `root` | Required | Storage root containing the database and any existing JSONL histories. |
|
||||
| `compression` | `zstd` | Existing JSONL encoding; SQLite events use ordinary JSON. |
|
||||
| `listConcurrency` | `3` | Concurrent filesystem reads for legacy metadata and routing records. |
|
||||
|
||||
The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-persistence-sqlite) documents all accepted fields.
|
||||
|
||||
### Opening existing history
|
||||
|
||||
A first read or write open decodes the selected JSONL generation through its version migration chain, then imports the current logical history into SQLite. Import preserves metadata, event order, source coordinates and the inheritance marker. It creates an independent root Segment and retains the JSONL source bytes. The imported Session and its later events reopen through SQLite.
|
||||
|
||||
An active JSONL writer retains ownership until it closes. A SQLite read open waits for that ownership; a competing write open rejects. Cancellation or provider disposal stops the wait. After import, readers can open while the SQLite writer remains active. `stat()` and `list()` observe metadata without importing history.
|
||||
|
||||
### Durability and shutdown
|
||||
|
||||
Direct append, live Session events and durability checkpoints use the same handle. `flush()` drains pending events; writer close and provider disposal finish admitted writes before releasing ownership. An automatic write failure retains its pending batch and pauses automatic writes; the next explicit checkpoint retries and reports any remaining failure.
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
The plugin supplies the existing persistence service and uses a JSONL provider in an isolated service context to read legacy histories. Import acquires the Session's artifact lease, commits its metadata and events in a database transaction, then records SQLite routing. A write open retains the lease through the handoff.
|
||||
|
||||
SQLite keeps thread metadata, predecessor-linked Segment metadata and indexed JSON event rows. WAL is enabled before schema publication so a concurrent reader cannot prevent the first mode switch. The backend owns write queues, live-event buffering, transaction completion and handle cleanup; callers do not address Segments.
|
||||
|
||||
| Source | Responsibility |
|
||||
|---|---|
|
||||
| [persistence.ts](src/persistence.ts) | Service routing and durable JSONL takeover. |
|
||||
| [migration.ts](src/migration.ts) | Import sequencing, ownership handoff and cancellation. |
|
||||
| [sqlite.ts](src/sqlite.ts) | Database, Segment access, handles and durability. |
|
||||
|
||||
</details>
|
||||
|
||||
-----
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## Further Exploration
|
||||
|
||||
- [Session persistence](../session-persistence/README.md) — the shared service and handle semantics.
|
||||
- [JSONL persistence](../session-persistence-jsonl/README.md) — physical generations and version migration.
|
||||
- [Persistence subsystem](../../../docs/subsystems/persistence.md) — recovery and consumer-facing APIs.
|
||||
|
||||
-----
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
### Restored history
|
||||
|
||||
#### What the model sees
|
||||
|
||||
This provider adds no prompt or tool schema. Restored `user/message` and `assistant/message` events supply the same conversation history; the Session consumer owns interrupted-turn repair.
|
||||
|
||||
#### Token effect
|
||||
|
||||
Storage adds no tokens. Restored history has its usual conversation cost.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
Storage preserves event order and does not rewrite model request prefixes.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
These constraints apply when selecting this provider.
|
||||
|
||||
- The first legacy read open writes the SQLite database and requires write access to the storage root.
|
||||
- Retained JSONL files contain the imported prefix and exclude later SQLite events; they cannot restore the latest history on their own.
|
||||
- All processes writing imported Sessions must use the SQLite provider.
|
||||
- SQLite accepts the current Session format; a future event-format upgrade needs its own SQLite history migration.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
<details>
|
||||
<summary>Working context for maintainers — click to expand</summary>
|
||||
|
||||
None.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,127 @@
|
||||
---
|
||||
description: "在 SQLite 中保存和重新打开 Session 历史,导入现有 JSONL 历史,并协调并发读写。"
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-session-persistence-sqlite
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
## 概述
|
||||
|
||||
在 SQLite 中保存 Session 历史,并通过原有持久化 API 重新打开。现有 JSONL 历史在首次打开时导入,源文件保持不变。读者可以与活跃写者共享数据库;每个 Session 只允许一个写者。需要显式选择此提供者:内置 profile 继续使用 JSONL。
|
||||
|
||||
## 目录
|
||||
|
||||
- [使用本包](#use-this-package)
|
||||
- [理解实现](#understand-the-implementation)
|
||||
- [进一步探索](#further-exploration)
|
||||
- [模型体验](#model-experience)
|
||||
- [已知限制与待办](#known-limitations-and-deferred-work)
|
||||
- [开发备注](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
为需要使用 SQLite 的 Session 存储根目录挂载此提供者。
|
||||
|
||||
### 最小配置
|
||||
|
||||
在组合配置中替换 JSONL 提供者的包名,保留其根目录和旧历史编码设置:
|
||||
|
||||
```yaml
|
||||
- name: '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
config:
|
||||
root: './.sessions'
|
||||
```
|
||||
|
||||
数据库位于 `<root>/.segments/sessions.sqlite`。应用调用方继续使用 `ctx.sessionPersistence` 及其 Session 句柄。
|
||||
|
||||
| 字段 | 默认值 | 含义 |
|
||||
|---|---|---|
|
||||
| `root` | 必填 | 包含数据库和现有 JSONL 历史的存储根目录。 |
|
||||
| `compression` | `zstd` | 现有 JSONL 的编码;SQLite 事件使用普通 JSON。 |
|
||||
| `listConcurrency` | `3` | 旧历史元数据及路由记录的并发文件系统读取数。 |
|
||||
|
||||
生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-persistence-sqlite)记录了所有可用字段。
|
||||
|
||||
### 打开现有历史
|
||||
|
||||
首次 read 或 write open 通过版本迁移链解码选定的 JSONL 代次,然后将当前逻辑历史导入 SQLite。导入保留元数据、事件顺序、来源坐标和继承标记。它创建独立根 Segment,并保留 JSONL 源文件字节。导入后的 Session 及其后续事件通过 SQLite 重新打开。
|
||||
|
||||
活跃的 JSONL 写者保持所有权,直到关闭。SQLite read open 等待该所有权释放;竞争的 write open 会被拒绝。取消或提供者卸载会停止等待。导入后,读者可以在 SQLite 写者仍活跃时打开。`stat()` 和 `list()` 只观察元数据,不导入历史。
|
||||
|
||||
### 持久化与关闭
|
||||
|
||||
直接 append、实时 Session 事件和持久化检查点使用同一个句柄。`flush()` 排空待写事件;写句柄关闭及提供者卸载会完成已接收的写入,再释放所有权。自动写入失败会保留待写批次并暂停自动写入;下一个显式检查点重试,并报告仍然存在的失败。
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
<details>
|
||||
<summary>实现内部细节——点击展开</summary>
|
||||
|
||||
插件提供原有持久化服务,并在隔离的服务上下文中使用 JSONL 提供者读取旧历史。导入取得 Session 的文件租约,在数据库事务中提交元数据和事件,然后记录 SQLite 路由。write open 在交接过程中保持租约。
|
||||
|
||||
SQLite 保存 thread 元数据、前驱关联的 Segment 元数据及带索引的 JSON 事件行。发布 schema 前先启用 WAL,防止并发读者阻碍首次模式切换。后端负责写入队列、实时事件缓冲、事务完成和句柄清理;调用方不直接访问 Segment。
|
||||
|
||||
| 源码 | 职责 |
|
||||
|---|---|
|
||||
| [persistence.ts](src/persistence.ts) | 服务路由和 JSONL 的持久接管。 |
|
||||
| [migration.ts](src/migration.ts) | 导入排序、所有权交接和取消。 |
|
||||
| [sqlite.ts](src/sqlite.ts) | 数据库、Segment 访问、句柄和持久化。 |
|
||||
|
||||
</details>
|
||||
|
||||
-----
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## 进一步探索
|
||||
|
||||
- [Session 持久化](../session-persistence/README.zh.md) — 公共服务和句柄语义。
|
||||
- [JSONL 持久化](../session-persistence-jsonl/README.zh.md) — 物理代次和版本迁移。
|
||||
- [持久化子系统](../../../docs/subsystems/persistence.zh.md) — 恢复及面向调用方的 API。
|
||||
|
||||
-----
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
### 恢复的历史
|
||||
|
||||
#### 模型实际看到什么
|
||||
|
||||
此提供者不增加提示词或工具 schema。恢复的 `user/message` 和 `assistant/message` 事件提供相同的对话历史;Session 调用方负责 interrupted-turn 修复。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
存储不增加 token。恢复历史仍有正常的对话成本。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
存储保留事件顺序,不改写模型请求前缀。
|
||||
|
||||
## 已知限制与待办
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
选择此提供者时适用以下约束。
|
||||
|
||||
- 首次读取旧历史会写入 SQLite 数据库,因此需要存储根目录的写权限。
|
||||
- 保留的 JSONL 文件只包含导入前缀,不包含后续 SQLite 事件;单靠它们无法恢复最新历史。
|
||||
- 所有写入已导入 Session 的进程都必须使用 SQLite 提供者。
|
||||
- SQLite 接受当前 Session 格式;未来事件格式升级需要独立的 SQLite 历史迁移。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
<details>
|
||||
<summary>维护者工作上下文——点击展开</summary>
|
||||
|
||||
无。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "session-persistence-sqlite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-session-persistence-sqlite",
|
||||
"description": "SQLite Session event storage backend for the DeepSeek Harness",
|
||||
"version": "0.2.2-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "packages/session/session-persistence-sqlite"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json",
|
||||
"./locale/*.json": "./locale/*.json"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
"lib/index.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"lib/**/*.js.map",
|
||||
"src"
|
||||
],
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
|
||||
"@deepseek-ai/dsh-brand": "workspace:*",
|
||||
"@deepseek-ai/dsh-llm": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-format": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-format-v3-to-v4": "workspace:*",
|
||||
"zod": "4.6.6",
|
||||
"@deepseek-ai/node-addon-system": "workspace:~",
|
||||
"p-limit": "7.3.3",
|
||||
"koffi": "3.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/** Ordered live-event batching shared by the persistence backends. @module */
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
|
||||
/** Backend-owned serialization and commit operations for a live batch. */
|
||||
interface LiveWriteOptions {
|
||||
delayMs: number
|
||||
maxEvents: number
|
||||
enqueue(operation: () => Promise<void>): Promise<unknown>
|
||||
persist(batch: readonly SessionEvent[]): Promise<void>
|
||||
retry(error: unknown): boolean
|
||||
canSchedule(): boolean
|
||||
}
|
||||
|
||||
/** Retains admitted copies until commit, pausing automatic retries after failure. */
|
||||
export class LiveWriteBuffer {
|
||||
private events: SessionEvent[] = []
|
||||
private timer: ReturnType<typeof setTimeout> | undefined
|
||||
private draining: Promise<void> | undefined
|
||||
private paused = false
|
||||
private report: ((error: unknown) => void) | undefined
|
||||
|
||||
constructor(private readonly options: LiveWriteOptions) {}
|
||||
|
||||
/** Number of admitted events awaiting commit. */
|
||||
get length(): number { return this.events.length }
|
||||
|
||||
/** Whether a durability drain is in progress. */
|
||||
get active(): boolean { return this.draining !== undefined }
|
||||
|
||||
/**
|
||||
* Admit exclusively owned event copies and schedule their durability deadline.
|
||||
* @param events - backend-validated or snapshotted live events.
|
||||
* @param report - observes automatic write failures.
|
||||
*/
|
||||
append(events: readonly SessionEvent[], report: (error: unknown) => void): void {
|
||||
this.events.push(...events)
|
||||
this.report = report
|
||||
if (this.paused || !this.options.canSchedule()) return
|
||||
if (this.events.length >= this.options.maxEvents) {
|
||||
void this.drain().catch(report)
|
||||
} else if (this.timer === undefined) {
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = undefined
|
||||
void this.drain().catch(report)
|
||||
}, this.options.delayMs)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit all admitted events in order; concurrent callers join one drain.
|
||||
* @returns durability completion, rejecting with the backend's write failure.
|
||||
*/
|
||||
drain(): Promise<void> {
|
||||
if (this.draining !== undefined) return this.draining
|
||||
this.cancelTimer()
|
||||
this.paused = false
|
||||
return this.draining = this.commit().finally(() => {
|
||||
this.draining = undefined
|
||||
if (this.events.length > 0 && !this.paused && this.options.canSchedule() && this.report !== undefined) {
|
||||
void this.drain().catch(this.report)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private cancelTimer(): void {
|
||||
if (this.timer !== undefined) { clearTimeout(this.timer); this.timer = undefined }
|
||||
}
|
||||
|
||||
private async commit(): Promise<void> {
|
||||
while (this.events.length > 0) {
|
||||
try { await this.options.enqueue(async () => {
|
||||
this.cancelTimer()
|
||||
const batch = this.events.splice(0, this.options.maxEvents)
|
||||
try { await this.options.persist(batch) }
|
||||
catch (error: unknown) {
|
||||
if (this.options.retry(error)) this.events = batch.concat(this.events)
|
||||
this.paused = true
|
||||
throw error
|
||||
}
|
||||
}) } catch (error: unknown) {
|
||||
this.paused = true
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/** SQLite stores logical Session headers and events without JSONL row encoding. @module */
|
||||
import { isAbsolute } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import { SESSION_FORMAT_VERSION, SessionId, KNOWN_SESSION_EVENT_TYPES, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format'
|
||||
import { assertV4RowAdmission } from '@deepseek-ai/dsh-session-format-v3-to-v4'
|
||||
|
||||
/** SQLite's logical format version; a new Session version requires an explicit storage migration. */
|
||||
export const SQLITE_SESSION_FORMAT_VERSION = 4 satisfies typeof SESSION_FORMAT_VERSION
|
||||
|
||||
const header = z.object({
|
||||
version: z.literal(SQLITE_SESSION_FORMAT_VERSION),
|
||||
id: z.string().transform(SessionId),
|
||||
createdAt: z.number().int().nonnegative(),
|
||||
isSeeded: z.boolean(),
|
||||
cwd: z.string().refine(isAbsolute).optional(),
|
||||
parentSession: z.string().transform(SessionId).optional(),
|
||||
origin: z.literal('subagent').optional(),
|
||||
delegationDepth: z.number().int().nonnegative().default(0),
|
||||
agentPreset: z.string().optional(),
|
||||
}).strict()
|
||||
const event = z.object({
|
||||
type: z.string(),
|
||||
seq: z.number().int().nonnegative(),
|
||||
time: z.number().int(),
|
||||
data: z.unknown().refine(value => value !== undefined),
|
||||
ignorable: z.literal(true).optional(),
|
||||
sourceEventSeqs: z.array(z.number().int().nonnegative()).optional(),
|
||||
surfaceOp: z.union([z.literal('append'), z.object({
|
||||
op: z.literal('replace'), startSeq: z.number().int().nonnegative(), endSeq: z.number().int().nonnegative(),
|
||||
}).strict()]).optional(),
|
||||
}).strict()
|
||||
|
||||
/**
|
||||
* Read current logical Session metadata from a stored JSON object.
|
||||
* @param value - untrusted SQLite header parsed from JSON.
|
||||
* @returns validated metadata with an explicit delegation depth.
|
||||
*/
|
||||
export function decodeHeader(value: unknown): SessionHeader {
|
||||
const { cwd, parentSession, origin, agentPreset, ...metadata } = header.parse(value)
|
||||
return { ...metadata,
|
||||
...cwd === undefined ? {} : { cwd },
|
||||
...parentSession === undefined ? {} : { parentSession },
|
||||
...origin === undefined ? {} : { origin },
|
||||
...agentPreset === undefined ? {} : { agentPreset },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preserve the existing seeded/cut checks before reserving or importing a Session.
|
||||
* @param metadata - detached creation or import header.
|
||||
* @param inheritedEventCount - exact inherited prefix, required for seeded Sessions.
|
||||
* @returns normalized logical metadata for SQLite JSON storage.
|
||||
*/
|
||||
export function materializeHeader(metadata: SessionHeader, inheritedEventCount?: SessionLogOffset): SessionHeader {
|
||||
if (metadata.isSeeded && inheritedEventCount === undefined) throw new Error('seeded session header requires an inherited event count')
|
||||
const cut = SessionLogOffset(inheritedEventCount ?? 0)
|
||||
if (!metadata.isSeeded && cut !== 0) throw new Error('unseeded session header inherited event count must be 0')
|
||||
return decodeHeader(metadata)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a logical event envelope; native payload validation remains in Session adoption.
|
||||
* Source coordinates stay as arrays and are never decoded from JSONL ranges.
|
||||
* @param value - untrusted SQLite event parsed from JSON.
|
||||
* @returns logical event for vocabulary validation and Session adoption.
|
||||
*/
|
||||
export function decodeEvent(value: unknown): SessionFormatEvent & SessionEvent {
|
||||
assertV4RowAdmission(value, KNOWN_SESSION_EVENT_TYPES)
|
||||
return event.parse(value) as SessionFormatEvent & SessionEvent
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** SQLite Session persistence and event storage. @module */
|
||||
import { Context, type Fiber } from '@deepseek-ai/cordis'
|
||||
import { Config as JsonlConfig, JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import type { Config as JsonlConfigOptions } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import { SqliteSessionPersistence } from './persistence.ts'
|
||||
|
||||
/** Loader label for the SQLite Session persistence provider. */
|
||||
export const name = 'session-persistence-sqlite'
|
||||
|
||||
/** Storage root and JSONL settings used when importing legacy Sessions. */
|
||||
export type Config = JsonlConfigOptions
|
||||
|
||||
/** Validate the storage root and legacy JSONL reader settings. */
|
||||
export const Config = JsonlConfig
|
||||
|
||||
/**
|
||||
* Provide SQLite persistence and retain storage resources through consumer unload.
|
||||
* @param ctx - plugin context owning the provider and its resources.
|
||||
* @param config - storage root and legacy JSONL reader settings.
|
||||
* @returns resolves after the persistence service is registered.
|
||||
*/
|
||||
export async function apply(ctx: Context, config: Config): Promise<void> {
|
||||
let service!: Fiber
|
||||
ctx.effect(function* () {
|
||||
const resources = ctx.plugin({ name: 'session-segment-resources', apply() {} })
|
||||
yield resources.dispose
|
||||
service = ctx.plugin({
|
||||
name: 'session-persistence-sqlite-service',
|
||||
apply(serviceCtx: Context) {
|
||||
const legacy = new JsonlSessionPersistence(serviceCtx.isolate('sessionPersistence'), config)
|
||||
new SqliteSessionPersistence(serviceCtx, resources.ctx, config, legacy)
|
||||
},
|
||||
})
|
||||
yield service.dispose
|
||||
}, 'session-persistence-sqlite resources')
|
||||
await service.await()
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Cross-process write-ownership lock for one session's artifact directory,
|
||||
* held for the whole life of a write handle. The arbiter is the kernel:
|
||||
* POSIX takes a non-blocking `flock(2)` via native system support on `session.lock`
|
||||
* beside the log, and Windows holds a named kernel semaphore derived from
|
||||
* that path — never a file lock or handle, so readers, searches, and
|
||||
* directory removal proceed freely while the lock is held. Contention maps
|
||||
* to `SessionAlreadyOwnedError`; the kernel releases the lock when the
|
||||
* holder's descriptor or last object handle closes, including on any process
|
||||
* death, so a crashed holder never blocks a successor. A live but wedged
|
||||
* holder keeps the lock until its process exits: there is deliberately no
|
||||
* expiry that could expropriate a stalled writer whose resumed appends would
|
||||
* tear the log.
|
||||
* A POSIX lock names an inode, not a path, so after locking the holder
|
||||
* verifies the locked inode is still the file at the lock path and retries
|
||||
* otherwise: an unlinked-and-recreated lock file carries a fresh inode, and
|
||||
* a lock on the orphaned one proves nothing. Removing a live session's lock
|
||||
* file therefore forfeits exclusion on POSIX (nothing in the harness does
|
||||
* so); Windows has no lock file at all. Readers never touch the lock.
|
||||
* The lock is acquired at write-open of an existing artifact and, for a
|
||||
* created session, only right before its first materializing write — an
|
||||
* unmaterialized session has no filesystem footprint. Release never removes
|
||||
* the POSIX lock file: every acquired lock belongs to a materialized or
|
||||
* materializing session, and the surviving file keeps the stable inode later
|
||||
* lockers verify against. The browser worker stubs the native flock entry to
|
||||
* immediate success: it is single-process, so the in-process write claim
|
||||
* already excludes every writer.
|
||||
* @module @deepseek-ai/dsh-session-persistence-sqlite/lease
|
||||
*/
|
||||
// JSONL retains a separate copy so the two backends need no shared helper exports.
|
||||
/* jscpd:ignore-start */
|
||||
|
||||
import { mkdir, open, stat } from 'node:fs/promises'
|
||||
import type { FileHandle } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tryLockExclusive } from '@deepseek-ai/node-addon-system/flock'
|
||||
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { acquireLockHandleWin32, releaseLockHandleWin32 } from './win32.ts'
|
||||
|
||||
/** Base name of the kernel lock file inside a session's directory. */
|
||||
export const LEASE_FILENAME = 'session.lock'
|
||||
|
||||
/** The held kernel lock: a POSIX descriptor or a Win32 semaphore handle. */
|
||||
type HeldLock =
|
||||
| { readonly kind: 'posix'; readonly handle: FileHandle }
|
||||
| { readonly kind: 'win32'; readonly handle: number }
|
||||
|
||||
/** Whether a flock failure means another descriptor holds the lock. */
|
||||
function isLockContention(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | null)?.code
|
||||
// flock(2) reports EAGAIN; some libcs spell it EWOULDBLOCK.
|
||||
return code === 'EAGAIN' || code === 'EWOULDBLOCK'
|
||||
}
|
||||
|
||||
/**
|
||||
* One held write lock. Constructed only by {@link SessionWriteLease.acquire};
|
||||
* `release` closes the descriptor or handle, which is what releases the lock.
|
||||
*/
|
||||
export class SessionWriteLease {
|
||||
private released = false
|
||||
|
||||
private constructor(private readonly held: HeldLock) {}
|
||||
|
||||
/**
|
||||
* Acquire the session directory's kernel write lock.
|
||||
* @param dir - the session's artifact directory (created if absent).
|
||||
* @param id - the session the lock guards, for error identities.
|
||||
* @returns the held lock.
|
||||
* @throws {SessionAlreadyOwnedError} while another holder keeps the lock.
|
||||
*/
|
||||
static async acquire(dir: string, id: SessionId): Promise<SessionWriteLease> {
|
||||
const path = join(dir, LEASE_FILENAME)
|
||||
// Owner-only like materializePosix's directories: the lock may create the
|
||||
// session directory first, and both creators must agree on the mode.
|
||||
await mkdir(dir, { recursive: true, mode: 0o700 })
|
||||
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
||||
if (process.platform === 'win32') {
|
||||
let handle: number
|
||||
try {
|
||||
handle = await acquireLockHandleWin32(path)
|
||||
} catch (error: unknown) {
|
||||
// Sharing violation: another handle already holds the write exclusion.
|
||||
if ((error as NodeJS.ErrnoException | null)?.code === 'EBUSY') throw new SessionAlreadyOwnedError(id)
|
||||
throw error
|
||||
}
|
||||
return new SessionWriteLease({ kind: 'win32', handle })
|
||||
}
|
||||
/* v8 ignore stop */
|
||||
// Bounded retry: locking an inode a releasing creator just unlinked (or a
|
||||
// recreated path) re-opens the fresh file; steady state needs one pass.
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const handle = await open(path, 'w')
|
||||
try {
|
||||
try {
|
||||
await tryLockExclusive(handle.fd)
|
||||
} catch (error: unknown) {
|
||||
if (isLockContention(error)) throw new SessionAlreadyOwnedError(id)
|
||||
throw error
|
||||
}
|
||||
const held = await handle.stat({ bigint: true })
|
||||
const current = await stat(path, { bigint: true }).catch((error: unknown) => {
|
||||
if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return undefined
|
||||
throw error
|
||||
})
|
||||
if (current !== undefined && current.ino === held.ino && current.dev === held.dev) {
|
||||
return new SessionWriteLease({ kind: 'posix', handle })
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
await handle.close()
|
||||
throw error
|
||||
}
|
||||
// The locked inode is no longer the file at the lock path: start over
|
||||
// against whatever now stands there.
|
||||
await handle.close()
|
||||
}
|
||||
throw new SessionAlreadyOwnedError(id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the kernel lock by closing its descriptor or handle. The POSIX
|
||||
* lock file is never removed: every acquired lock belongs to a
|
||||
* materialized or materializing session, and keeping the file preserves
|
||||
* the stable inode later lockers verify against. Idempotent.
|
||||
*/
|
||||
async release(): Promise<void> {
|
||||
if (this.released) return
|
||||
this.released = true
|
||||
/* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */
|
||||
if (this.held.kind === 'win32') {
|
||||
await releaseLockHandleWin32(this.held.handle)
|
||||
return
|
||||
}
|
||||
/* v8 ignore stop */
|
||||
await this.held.handle.close()
|
||||
}
|
||||
}
|
||||
/* jscpd:ignore-end */
|
||||
@@ -0,0 +1,95 @@
|
||||
/** Exclusive legacy Session import with same-provider open sequencing. @module */
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import { HarnessError } from '@deepseek-ai/dsh-llm'
|
||||
import { setTimeout } from 'node:timers/promises'
|
||||
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionAccess, SessionHandle, SessionPersistenceOpenOptions } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SqliteStore } from './sqlite.ts'
|
||||
|
||||
/** Historical reads used by the persistence service; no JSONL writes or live handles. */
|
||||
export type JsonlBackend = Pick<JsonlSessionPersistence, 'stat' | 'hasStoredJsonl' | 'prepare' | 'list'>
|
||||
|
||||
/** Owns pending legacy opens until import, ownership handoff, and cleanup finish. */
|
||||
export class LegacySessionMigration {
|
||||
private readonly pending = new Map<SessionId, Promise<unknown>>()
|
||||
private closing = false
|
||||
private readonly stopped = new AbortController()
|
||||
constructor(private readonly jsonl: JsonlBackend, private readonly sqlite: SqliteStore,
|
||||
private readonly selected: (id: SessionId) => Promise<boolean>, private readonly publish: (id: SessionId) => Promise<void>) {}
|
||||
|
||||
/**
|
||||
* Serialize legacy opens within this provider. Readers wait for another provider's import; writers reject contention.
|
||||
* @param id - legacy Session identity.
|
||||
* @param access - requested access after import.
|
||||
* @param options - optional cancellation checked when the queued open starts.
|
||||
* @returns SQLite handle; a write handle retains the import lease without a release/reacquire gap.
|
||||
*/
|
||||
open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle> {
|
||||
if (this.closing) return Promise.reject(new HarnessError('Session migration is closing', 'SESSION_STORAGE_CLOSED'))
|
||||
const previous = this.pending.get(id) ?? Promise.resolve()
|
||||
const next = previous.catch((_error: unknown) => { /* A failed caller does not cancel the next open. */ })
|
||||
.then(() => this.migrate(id, access, options?.signal))
|
||||
this.pending.set(id, next)
|
||||
const settled = (): void => { if (this.pending.get(id) === next) this.pending.delete(id) }
|
||||
void next.then(settled, settled)
|
||||
return next
|
||||
}
|
||||
|
||||
private async migrate(id: SessionId, access: SessionAccess, signal?: AbortSignal): Promise<SessionHandle> {
|
||||
signal?.throwIfAborted()
|
||||
// The caller observed no SQLite row before queueing; the lease loop below rechecks before each attempt.
|
||||
// Header inspection does not decode history; the full snapshot is read only under ownership.
|
||||
const metadata = await this.jsonl.stat(id, signal === undefined ? undefined : { signal })
|
||||
if (metadata === undefined) {
|
||||
// A Session committed to SQLite while this open was queued has no legacy metadata.
|
||||
if (await this.selected(id)) return this.sqlite.open(id, access, signal)
|
||||
// The reader owns precise absent/malformed-header diagnostics.
|
||||
await this.jsonl.prepare(id, signal)
|
||||
throw new HarnessError('Legacy Session has no readable metadata', 'SESSION_STORAGE_CORRUPT')
|
||||
}
|
||||
let lease: Awaited<ReturnType<SqliteStore['acquireSessionLease']>> | undefined
|
||||
const waitingSignal = signal === undefined ? this.stopped.signal : AbortSignal.any([signal, this.stopped.signal])
|
||||
for (;;) {
|
||||
waitingSignal.throwIfAborted()
|
||||
if (await this.selected(id)) return this.sqlite.open(id, access, signal)
|
||||
try {
|
||||
lease = await this.sqlite.acquireSessionLease(metadata.header)
|
||||
break
|
||||
} catch (error: unknown) {
|
||||
if (access !== 'read' || !(error instanceof SessionAlreadyOwnedError)) throw error
|
||||
// Kernel leases have no completion notification; observe the committed row between acquisition attempts.
|
||||
await setTimeout(50, undefined, { signal: waitingSignal })
|
||||
}
|
||||
}
|
||||
let handle: SessionHandle | undefined
|
||||
try {
|
||||
signal?.throwIfAborted()
|
||||
if (!await this.selected(id)) {
|
||||
const prepared = await this.jsonl.prepare(id, signal)
|
||||
await prepared.commit(snapshot => this.sqlite.importLegacy(snapshot.header, snapshot.inheritedEventCount, snapshot.events, signal))
|
||||
} else await this.publish(id)
|
||||
signal?.throwIfAborted()
|
||||
handle = await this.sqlite.open(id, access, signal, access === 'write' ? lease : undefined)
|
||||
if (access === 'write') lease = undefined
|
||||
else {
|
||||
const imported = lease
|
||||
lease = undefined
|
||||
await imported.release()
|
||||
}
|
||||
return handle
|
||||
} catch (error: unknown) {
|
||||
const cleanup = await Promise.allSettled([handle?.close(), lease?.release()])
|
||||
const failures = cleanup.filter(result => result.status === 'rejected').map((result): unknown => result.reason)
|
||||
if (failures.length > 0) throw new AggregateError([error, ...failures], 'Session migration and cleanup failed')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop admission and settle accepted imports before SQLite closes. @returns settled cleanup. */
|
||||
async close(): Promise<void> {
|
||||
this.closing = true
|
||||
this.stopped.abort(new HarnessError('Session migration is closing', 'SESSION_STORAGE_CLOSED'))
|
||||
await Promise.allSettled([...this.pending.values()])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/** Session artifact directories shared by persistence backends. @module */
|
||||
// JSONL retains a separate copy so the two backends need no shared helper exports.
|
||||
/* jscpd:ignore-start */
|
||||
import { join } from 'node:path'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
|
||||
/**
|
||||
* Encode an arbitrary string as a single safe path segment, injectively over ALL JS (UTF-16)
|
||||
* strings — including lone surrogates. A {@link SessionId} is an unvalidated branded string,
|
||||
* so this neutralizes `../`, absolute paths, NUL, and separators before any filesystem use.
|
||||
* Safe code units remain literal; every other unit, including `~`, becomes
|
||||
* `~XXXX`. Operating on code units preserves lone surrogates, while special-
|
||||
* casing `.` and `..` prevents traversal by an otherwise safe whole segment.
|
||||
*
|
||||
* @param raw - the string to encode; must be non-empty (throws on `''`).
|
||||
* @returns the escaped single path segment, decodable back to `raw`.
|
||||
*/
|
||||
export function encodeSegment(raw: string): string {
|
||||
if (raw.length === 0) throw new Error('cannot encode an empty path segment')
|
||||
if (raw === '.') return '~002E'
|
||||
if (raw === '..') return '~002E~002E'
|
||||
let out = ''
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const code = raw.charCodeAt(i)
|
||||
const ch = String.fromCharCode(code)
|
||||
if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
|
||||
out += ch
|
||||
} else {
|
||||
out += '~' + code.toString(16).toUpperCase().padStart(4, '0')
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the readable directory key for a project path.
|
||||
* Filesystem separators and drive separators become `-`; unsafe code units use
|
||||
* the same `~XXXX` escape as session ids. The key is bounded for filesystem
|
||||
* component limits. Separator replacement and truncation are intentionally
|
||||
* lossy, following the common human-navigable project-directory convention.
|
||||
* @param cwd - the session's project directory.
|
||||
* @returns a single filesystem-safe project directory name.
|
||||
*/
|
||||
export function projectKey(cwd: string): string {
|
||||
if (cwd.length === 0) throw new Error('cannot encode an empty project path')
|
||||
let readable = ''
|
||||
let separatorRun = false
|
||||
for (let i = 0; i < cwd.length; i++) {
|
||||
const code = cwd.charCodeAt(i)
|
||||
const ch = String.fromCharCode(code)
|
||||
if (ch === '/' || ch === '\\' || ch === ':') {
|
||||
if (!separatorRun) readable += '-'
|
||||
separatorRun = true
|
||||
} else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
|
||||
readable += ch
|
||||
separatorRun = false
|
||||
} else {
|
||||
readable += '~' + code.toString(16).toUpperCase().padStart(4, '0')
|
||||
separatorRun = false
|
||||
}
|
||||
}
|
||||
const slug = readable.replace(/^-+/, '') || 'root'
|
||||
return `--${slug.slice(0, 251)}--`
|
||||
}
|
||||
|
||||
/**
|
||||
* The configured root's human-navigable project directory. A configured root
|
||||
* may be local or shared; this grouping does not prescribe its deployment.
|
||||
* @param root - the backend's session root directory.
|
||||
* @param cwd - the session's project directory; `undefined` selects `_no-cwd`.
|
||||
* @returns the project directory path under `root`.
|
||||
*/
|
||||
export function projectDir(root: string, cwd: string | undefined): string {
|
||||
if (cwd === undefined) return join(root, '_no-cwd')
|
||||
return join(root, projectKey(cwd))
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory owned by one session and available for future session-local
|
||||
* artifacts.
|
||||
* @param root - the backend's session root directory.
|
||||
* @param cwd - the session's project directory.
|
||||
* @param id - the session id, encoded to one safe path segment.
|
||||
* @returns the session directory beneath its project directory.
|
||||
*/
|
||||
export function sessionDir(root: string, cwd: string | undefined, id: SessionId): string {
|
||||
return join(projectDir(root, cwd), encodeSegment(id))
|
||||
}
|
||||
/* jscpd:ignore-end */
|
||||
@@ -0,0 +1,204 @@
|
||||
/** SQLite Session persistence and durable takeover of legacy JSONL identities. @module */
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { link, mkdir, open, readFile, readdir, rm } from 'node:fs/promises'
|
||||
import { basename, join, resolve } from 'node:path'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Config } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import pLimit, { type LimitFunction } from 'p-limit'
|
||||
import { z } from 'zod'
|
||||
import { HarnessError } from '@deepseek-ai/dsh-llm'
|
||||
import { SessionPersistence, SessionAlreadyExistsError, SessionPersistenceNotFoundError, materializeCreateHeader } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionAccess, SessionPersistenceCreateOptions, SessionPersistenceOpenOptions,
|
||||
SessionPersistenceStatOptions, SessionPersistenceListOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { publishNewFileWin32, ensureDurableDirectoryWin32 } from './win32.ts'
|
||||
import { SqliteStore, isAbsent } from './sqlite.ts'
|
||||
import { SessionWriteLease } from './lease.ts'
|
||||
import { sessionDir } from './paths.ts'
|
||||
import { LegacySessionMigration } from './migration.ts'
|
||||
import type { JsonlBackend } from './migration.ts'
|
||||
|
||||
const marker = z.object({ id: z.string().transform(SessionId), database: z.string() }).strict()
|
||||
|
||||
/** Routes the existing logical Session API; Segment identifiers never cross this service. */
|
||||
export class SqliteSessionPersistence extends SessionPersistence {
|
||||
private readonly directory: string
|
||||
private readonly sqlite: SqliteStore
|
||||
private readonly migration: LegacySessionMigration
|
||||
private readonly rootPath: string
|
||||
private readonly jsonl: JsonlBackend
|
||||
private readonly listLimit: LimitFunction
|
||||
private readonly publishedRoutes = new Set<SessionId>()
|
||||
constructor(ctx: Context, owner: Context, config: Config,
|
||||
jsonl: JsonlBackend) {
|
||||
super(ctx)
|
||||
this.rootPath = resolve(config.root)
|
||||
this.listLimit = pLimit(config.listConcurrency ?? 3)
|
||||
this.directory = join(this.rootPath, '.segments')
|
||||
this.sqlite = new SqliteStore({
|
||||
path: join(this.directory, 'sessions.sqlite'),
|
||||
legacyRoot: this.rootPath,
|
||||
publish: id => this.publish(id),
|
||||
acquireCreationLease: header => this.acquireCreationLease(header),
|
||||
report: (id, error) => { owner.logger.error(`Segment persistence failed for ${id}; durability checkpoint will reject: ${String(error)}`) },
|
||||
})
|
||||
this.jsonl = jsonl
|
||||
this.migration = new LegacySessionMigration(jsonl, this.sqlite,
|
||||
async id => await this.selected(id) !== undefined, id => this.publish(id))
|
||||
this.sqlite.install(owner, () => this.migration.close())
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize SQLite before a Session is created or opened.
|
||||
* @returns resolves once SQLite is ready.
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
await this.sqlite.start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim the existing artifact lock before a new Session first commits.
|
||||
* @param header - pending Session metadata.
|
||||
* @returns the held artifact lock.
|
||||
*/
|
||||
protected async acquireCreationLease(header: SessionHeader): Promise<SessionWriteLease> {
|
||||
const lease = await SessionWriteLease.acquire(sessionDir(this.rootPath, header.cwd, header.id), header.id)
|
||||
try {
|
||||
if (await this.jsonl.hasStoredJsonl(header.id)) {
|
||||
throw new SessionAlreadyExistsError(header.id)
|
||||
}
|
||||
return lease
|
||||
} catch (error: unknown) {
|
||||
try { await lease.release() }
|
||||
catch (releaseError: unknown) { throw new AggregateError([error, releaseError], 'Session creation and lock release failed') }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private markerPath(id: SessionId): string {
|
||||
return join(this.directory, `${createHash('sha256').update(id).digest('hex')}.json`)
|
||||
}
|
||||
|
||||
/** Decode one routing record and require it to name `id` in the configured database. */
|
||||
private readMarker(text: string, path: string, id: SessionId): void {
|
||||
let stored: z.infer<typeof marker>
|
||||
try { stored = marker.parse(JSON.parse(text)) }
|
||||
catch (error: unknown) {
|
||||
throw new HarnessError(`Stored Segment routing record is invalid: ${path}`, 'SESSION_STORAGE_CORRUPT', { cause: error })
|
||||
}
|
||||
if (stored.id !== id || stored.database !== this.sqlite.path) {
|
||||
throw new HarnessError('Recorded Segment storage differs from the configured database; restore the original configuration', 'SESSION_STORAGE_IDENTITY')
|
||||
}
|
||||
}
|
||||
|
||||
private async selected(id: SessionId, signal?: AbortSignal): Promise<SessionPersistenceSnapshot | undefined> {
|
||||
let text: string
|
||||
try { text = await readFile(this.markerPath(id), 'utf8') }
|
||||
catch (error: unknown) {
|
||||
if (!isAbsent(error)) throw error
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
return this.sqlite.stat(id, signal)
|
||||
}
|
||||
this.readMarker(text, this.markerPath(id), id)
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
const snapshot = await this.sqlite.stat(id, signal)
|
||||
if (snapshot === undefined) {
|
||||
if (!await this.sqlite.hasDatabase()) {
|
||||
throw new HarnessError('Recorded Segment database is missing; restore it before opening the Session', 'SESSION_STORAGE_MISSING')
|
||||
}
|
||||
throw new SessionPersistenceNotFoundError(id)
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically publish durable backend selection once per Session in this provider after the database commit.
|
||||
* @param id - committed Session identity.
|
||||
*/
|
||||
protected async publish(id: SessionId): Promise<void> {
|
||||
if (this.publishedRoutes.has(id)) return
|
||||
if (process.platform === 'win32') await ensureDurableDirectoryWin32(this.directory)
|
||||
else await mkdir(this.directory, { recursive: true, mode: 0o700 })
|
||||
const path = this.markerPath(id)
|
||||
try {
|
||||
this.readMarker(await readFile(path, 'utf8'), path, id)
|
||||
await this.syncDirectory()
|
||||
this.publishedRoutes.add(id)
|
||||
return
|
||||
} catch (error: unknown) { if (!isAbsent(error)) throw error }
|
||||
const temporary = join(this.directory, `.route-${randomUUID()}.tmp`)
|
||||
const file = await open(temporary, 'wx', 0o600)
|
||||
try {
|
||||
try { await file.writeFile(JSON.stringify({ id, database: this.sqlite.path }) + '\n'); await file.sync() }
|
||||
finally { await file.close() }
|
||||
try {
|
||||
if (process.platform === 'win32') await publishNewFileWin32(temporary, path)
|
||||
else await link(temporary, path)
|
||||
} catch (error: unknown) {
|
||||
if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
|
||||
this.readMarker(await readFile(path, 'utf8'), path, id)
|
||||
} else throw error
|
||||
}
|
||||
await this.syncDirectory()
|
||||
} finally { await rm(temporary, { force: true }) }
|
||||
this.publishedRoutes.add(id)
|
||||
}
|
||||
|
||||
private async syncDirectory(): Promise<void> {
|
||||
if (process.platform === 'win32') return
|
||||
const directory = await open(this.directory, 'r')
|
||||
try { await directory.sync() } finally { await directory.close() }
|
||||
}
|
||||
|
||||
async create(header: SessionHeader, options?: SessionPersistenceCreateOptions) {
|
||||
options?.signal?.throwIfAborted()
|
||||
const snapshot = materializeCreateHeader(header)
|
||||
await this.start()
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
// SQLite rejects an existing row itself; only the retained JSONL identity needs this check.
|
||||
if (await this.jsonl.hasStoredJsonl(snapshot.id)) throw new SessionAlreadyExistsError(snapshot.id)
|
||||
return this.sqlite.create(snapshot, options)
|
||||
}
|
||||
|
||||
async open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions) {
|
||||
options?.signal?.throwIfAborted()
|
||||
await this.start()
|
||||
return await this.selected(id) ? this.sqlite.open(id, access, options?.signal) : this.migration.open(id, access, options)
|
||||
}
|
||||
|
||||
async stat(id: SessionId, options?: SessionPersistenceStatOptions) {
|
||||
options?.signal?.throwIfAborted()
|
||||
const snapshot = await this.selected(id, options?.signal)
|
||||
options?.signal?.throwIfAborted()
|
||||
return snapshot === undefined ? this.jsonl.stat(id, options) : snapshot
|
||||
}
|
||||
|
||||
async list(options?: SessionPersistenceListOptions) {
|
||||
options?.signal?.throwIfAborted()
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
// Routing records publish after their commit, so reading them first guarantees each one's row is in the later scan.
|
||||
let names: string[] = []
|
||||
try { names = await this.listLimit(async () => {
|
||||
options?.signal?.throwIfAborted()
|
||||
return readdir(this.directory)
|
||||
}) } catch (error: unknown) { if (!isAbsent(error)) throw error }
|
||||
const [{ entries: segmented, omitted }, entries] = await Promise.all([
|
||||
this.sqlite.scan(options?.signal),
|
||||
this.jsonl.list(options),
|
||||
])
|
||||
// A row omitted for its header is still stored; only a routing record without a row is lost state.
|
||||
const known = new Set([...segmented.map(entry => entry.header.id), ...omitted])
|
||||
// Routing records are named by their Session hash, so membership needs no record reads.
|
||||
const routed = new Set([...known].map(id => basename(this.markerPath(id))))
|
||||
for (const name of names) {
|
||||
if (name.endsWith('.json') && !routed.has(name)) {
|
||||
throw new HarnessError('Recorded Segment Session is missing; restore its database before listing Sessions', 'SESSION_STORAGE_MISSING')
|
||||
}
|
||||
}
|
||||
options?.signal?.throwIfAborted()
|
||||
return [...entries.filter(entry => !known.has(entry.header.id)), ...segmented]
|
||||
}
|
||||
|
||||
async flush(): Promise<void> { await this.sqlite.flush() }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Windows durable namespace helpers for Session persistence backends.
|
||||
*
|
||||
* POSIX publishes a newly-created log by creating a directory entry and then
|
||||
* fsyncing the parent directory. Windows does not expose that parent-directory
|
||||
* fsync contract through Node, so the Windows path uses the native durable
|
||||
* namespace primitive instead: create a staging object in the target directory
|
||||
* and publish it with `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` without
|
||||
* replacement or cross-volume copy fallback.
|
||||
*
|
||||
* @module dsh-session-persistence-sqlite/win32
|
||||
*/
|
||||
// JSONL retains a separate copy so the two backends need no shared helper exports.
|
||||
/* jscpd:ignore-start */
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdtemp, rm, stat } from 'node:fs/promises'
|
||||
import { join, parse, resolve, toNamespacedPath } from 'node:path'
|
||||
|
||||
type MoveFileExW = (existing: string, replacement: string, flags: number) => number
|
||||
type CreateSemaphoreW = (security: null, initial: number, maximum: number, name: string) => number
|
||||
type WaitForSingleObject = (handle: number, milliseconds: number) => number
|
||||
type ReleaseSemaphore = (handle: number, count: number, previous: null) => number
|
||||
type CloseHandle = (handle: number) => number
|
||||
type GetLastError = () => number
|
||||
|
||||
interface Win32Bindings {
|
||||
moveFileExW: MoveFileExW
|
||||
createSemaphoreW: CreateSemaphoreW
|
||||
waitForSingleObject: WaitForSingleObject
|
||||
releaseSemaphore: ReleaseSemaphore
|
||||
closeHandle: CloseHandle
|
||||
getLastError: GetLastError
|
||||
}
|
||||
|
||||
interface Win32ErrnoException extends NodeJS.ErrnoException {
|
||||
win32Code: number
|
||||
dest: string
|
||||
}
|
||||
|
||||
const MOVEFILE_WRITE_THROUGH = 0x00000008
|
||||
const WAIT_OBJECT_0 = 0
|
||||
const WAIT_TIMEOUT = 0x00000102
|
||||
const ERROR_FILE_NOT_FOUND = 2
|
||||
const ERROR_PATH_NOT_FOUND = 3
|
||||
const ERROR_ACCESS_DENIED = 5
|
||||
const ERROR_NOT_SAME_DEVICE = 17
|
||||
const ERROR_SHARING_VIOLATION = 32
|
||||
const ERROR_FILE_EXISTS = 80
|
||||
const ERROR_INVALID_NAME = 123
|
||||
const ERROR_ALREADY_EXISTS = 183
|
||||
|
||||
let bindings: Win32Bindings | undefined
|
||||
|
||||
/** Load the small Win32 API lazily so non-Windows processes never load Koffi. */
|
||||
async function win32(): Promise<Win32Bindings> {
|
||||
if (bindings !== undefined) return bindings
|
||||
const koffi = (await import('koffi')).default
|
||||
const kernel32 = koffi.load('kernel32.dll')
|
||||
bindings = {
|
||||
moveFileExW: kernel32.func('__stdcall', 'MoveFileExW', 'int', ['str16', 'str16', 'uint']) as MoveFileExW,
|
||||
createSemaphoreW: kernel32.func('__stdcall', 'CreateSemaphoreW', 'intptr', ['void*', 'int', 'int', 'str16']) as CreateSemaphoreW,
|
||||
waitForSingleObject: kernel32.func('__stdcall', 'WaitForSingleObject', 'uint', ['intptr', 'uint']) as WaitForSingleObject,
|
||||
releaseSemaphore: kernel32.func('__stdcall', 'ReleaseSemaphore', 'int', ['intptr', 'int', 'void*']) as ReleaseSemaphore,
|
||||
closeHandle: kernel32.func('__stdcall', 'CloseHandle', 'int', ['intptr']) as CloseHandle,
|
||||
getLastError: kernel32.func('__stdcall', 'GetLastError', 'uint', []) as GetLastError,
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
|
||||
function errnoCode(win32Code: number): string {
|
||||
switch (win32Code) {
|
||||
case ERROR_FILE_NOT_FOUND:
|
||||
case ERROR_PATH_NOT_FOUND:
|
||||
return 'ENOENT'
|
||||
case ERROR_ACCESS_DENIED:
|
||||
return 'EACCES'
|
||||
case ERROR_NOT_SAME_DEVICE:
|
||||
return 'EXDEV'
|
||||
case ERROR_SHARING_VIOLATION:
|
||||
return 'EBUSY'
|
||||
case ERROR_FILE_EXISTS:
|
||||
case ERROR_ALREADY_EXISTS:
|
||||
return 'EEXIST'
|
||||
case ERROR_INVALID_NAME:
|
||||
return 'EINVAL'
|
||||
default:
|
||||
return 'EIO'
|
||||
}
|
||||
}
|
||||
|
||||
function win32Error(syscall: string, win32Code: number, path: string, dest: string): Win32ErrnoException {
|
||||
const code = errnoCode(win32Code)
|
||||
const error = new Error(`${syscall} ${code} (Win32 ${win32Code}): ${path} -> ${dest}`) as Win32ErrnoException
|
||||
error.code = code
|
||||
error.errno = win32Code
|
||||
error.syscall = syscall
|
||||
error.path = path
|
||||
error.dest = dest
|
||||
error.win32Code = win32Code
|
||||
return error
|
||||
}
|
||||
|
||||
function isENOENT(error: unknown): boolean {
|
||||
return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
|
||||
}
|
||||
|
||||
function isEEXIST(error: unknown): boolean {
|
||||
return (error as NodeJS.ErrnoException | null)?.code === 'EEXIST'
|
||||
}
|
||||
|
||||
async function assertDirectory(path: string): Promise<boolean> {
|
||||
try {
|
||||
// A bare drive root is already short, and Node rejects its extended-length
|
||||
// spelling as EISDIR. Descendants retain the namespace for long-path probes.
|
||||
const probe = path === parse(path).root ? path : toNamespacedPath(path)
|
||||
const info = await stat(probe)
|
||||
if (info.isDirectory()) return true
|
||||
const error = new Error(`path exists but is not a directory: ${path}`) as NodeJS.ErrnoException
|
||||
error.code = 'ENOTDIR'
|
||||
error.path = path
|
||||
throw error
|
||||
} catch (error) {
|
||||
if (isENOENT(error)) return false
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish `existing` at `replacement` with Windows write-through rename
|
||||
* semantics. The destination must not already exist; the move must stay within
|
||||
* the volume (no copy fallback flag is set).
|
||||
* @param existing - the synced staging path to move.
|
||||
* @param replacement - the final path, which must not already exist.
|
||||
*/
|
||||
export async function publishNewFileWin32(existing: string, replacement: string): Promise<void> {
|
||||
const api = await win32()
|
||||
const ok = api.moveFileExW(toNamespacedPath(existing), toNamespacedPath(replacement), MOVEFILE_WRITE_THROUGH)
|
||||
if (ok === 0) throw win32Error('MoveFileExW', api.getLastError(), existing, replacement)
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire the session write lock as a named kernel semaphore (count 1) whose
|
||||
* name is derived from the canonical lock path. A kernel object never touches
|
||||
* the filesystem, so readers, searches, and directory removal proceed freely
|
||||
* while the lock is held; a second acquirer's zero-timeout wait times out
|
||||
* (`EBUSY`); and when the last handle closes — including on any process
|
||||
* death — the object is destroyed, so a successor's create starts fresh.
|
||||
* @param path - the lock file path the name is derived from (case-folded:
|
||||
* Windows paths are case-insensitive).
|
||||
* @returns the open semaphore handle, released via {@link releaseLockHandleWin32}.
|
||||
*/
|
||||
export async function acquireLockHandleWin32(path: string): Promise<number> {
|
||||
const api = await win32()
|
||||
const name = `Local\\dsh-session-lock-${createHash('sha256').update(resolve(path).toLowerCase()).digest('hex')}`
|
||||
const handle = api.createSemaphoreW(null, 1, 1, name)
|
||||
if (handle === 0) throw win32Error('CreateSemaphoreW', api.getLastError(), path, name)
|
||||
const wait = api.waitForSingleObject(handle, 0)
|
||||
if (wait === WAIT_OBJECT_0) return handle
|
||||
api.closeHandle(handle)
|
||||
if (wait === WAIT_TIMEOUT) throw win32Error('WaitForSingleObject', ERROR_SHARING_VIOLATION, path, name)
|
||||
throw win32Error('WaitForSingleObject', api.getLastError(), path, name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Release a lock from {@link acquireLockHandleWin32}: restore the semaphore
|
||||
* count and close the handle (the object dies with its last handle).
|
||||
* @param handle - the open semaphore handle.
|
||||
*/
|
||||
export async function releaseLockHandleWin32(handle: number): Promise<void> {
|
||||
const api = await win32()
|
||||
const released = api.releaseSemaphore(handle, 1, null)
|
||||
const closed = api.closeHandle(handle)
|
||||
if (released === 0 || closed === 0) throw win32Error('ReleaseSemaphore', api.getLastError(), `handle:${handle}`, `handle:${handle}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `target` and its missing ancestors with durable Windows namespace
|
||||
* publication. Each missing directory is first created as a random staging
|
||||
* sibling, then moved to its final name with `MOVEFILE_WRITE_THROUGH`; races
|
||||
* with another creator are accepted only after verifying the winner is a
|
||||
* directory.
|
||||
* @param target - the absolute directory path to create durably when absent.
|
||||
*/
|
||||
export async function ensureDurableDirectoryWin32(target: string): Promise<void> {
|
||||
const absolute = resolve(target)
|
||||
const root = parse(absolute).root
|
||||
await assertDirectory(root)
|
||||
|
||||
const segments = absolute.slice(root.length).split(/[\\/]+/).filter(part => part.length > 0)
|
||||
let current = root
|
||||
for (const segment of segments) {
|
||||
const next = join(current, segment)
|
||||
if (!await assertDirectory(next)) await createLeafDirectoryWin32(current, next)
|
||||
current = next
|
||||
}
|
||||
}
|
||||
|
||||
async function createLeafDirectoryWin32(parent: string, target: string): Promise<void> {
|
||||
// Keep the staging component independent of the target basename so a legal
|
||||
// 255-byte target component does not make mkdtemp's sibling name too long.
|
||||
const staging = await mkdtemp(toNamespacedPath(join(parent, '.dsh-mkdir-')))
|
||||
try {
|
||||
await publishNewFileWin32(staging, target)
|
||||
} catch (error) {
|
||||
await rm(staging, { recursive: true, force: true })
|
||||
if (isEEXIST(error) && await assertDirectory(target)) return
|
||||
throw error
|
||||
}
|
||||
}
|
||||
/* jscpd:ignore-end */
|
||||
@@ -0,0 +1,109 @@
|
||||
/** Shared live batching retains ordered work across backend and queue failures. @module */
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { LiveWriteBuffer } from '../src/buffer.ts'
|
||||
|
||||
const event = (seq: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq + 1 } })
|
||||
afterEach(() => { vi.useRealTimers() })
|
||||
|
||||
it('keeps the first event deadline when later events arrive before the batch limit', async () => {
|
||||
vi.useFakeTimers()
|
||||
const persist = vi.fn(async (_events: readonly SessionEvent[]) => {})
|
||||
const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 8,
|
||||
enqueue: async operation => operation(), persist, retry: () => true, canSchedule: () => true,
|
||||
})
|
||||
buffer.append([event(0)], vi.fn())
|
||||
await vi.advanceTimersByTimeAsync(5)
|
||||
buffer.append([event(1)], vi.fn())
|
||||
await vi.advanceTimersByTimeAsync(5)
|
||||
expect(persist).toHaveBeenCalledExactlyOnceWith([event(0), event(1)])
|
||||
expect(buffer.length).toBe(0)
|
||||
})
|
||||
|
||||
it('retains an uncommitted batch after a write fails and retries it at the explicit checkpoint', async () => {
|
||||
vi.useFakeTimers()
|
||||
const failure = new Error('disk full')
|
||||
const persist = vi.fn(async (_events: readonly SessionEvent[]) => {}).mockRejectedValueOnce(failure)
|
||||
const report = vi.fn()
|
||||
const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2,
|
||||
enqueue: async operation => operation(), persist, retry: () => true, canSchedule: () => true,
|
||||
})
|
||||
buffer.append([event(0)], report)
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(report).toHaveBeenCalledWith(failure)
|
||||
expect(buffer.length).toBe(1)
|
||||
await buffer.drain()
|
||||
expect(persist).toHaveBeenCalledTimes(2)
|
||||
expect(buffer.length).toBe(0)
|
||||
})
|
||||
|
||||
it('does not replay a batch whose database commit succeeded before routing publication failed', async () => {
|
||||
vi.useFakeTimers()
|
||||
const failure = new Error('routing publication failed')
|
||||
const persist = vi.fn(async (_events: readonly SessionEvent[]) => { throw failure })
|
||||
const report = vi.fn()
|
||||
const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2,
|
||||
enqueue: async operation => operation(), persist, retry: () => false, canSchedule: () => true,
|
||||
})
|
||||
buffer.append([event(0)], report)
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(report).toHaveBeenCalledWith(failure)
|
||||
expect(buffer.length).toBe(0)
|
||||
await buffer.drain()
|
||||
expect(persist).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('holds events when automatic scheduling stops and drains them explicitly', async () => {
|
||||
vi.useFakeTimers()
|
||||
const persist = vi.fn(async (_events: readonly SessionEvent[]) => {})
|
||||
const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2,
|
||||
enqueue: async operation => operation(), persist, retry: () => true, canSchedule: () => false,
|
||||
})
|
||||
buffer.append([event(0)], vi.fn())
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(persist).not.toHaveBeenCalled()
|
||||
await buffer.drain()
|
||||
expect(persist).toHaveBeenCalledExactlyOnceWith([event(0)])
|
||||
})
|
||||
|
||||
it('pauses automatic writes when serialization rejects before taking a batch, then retries without losing events', async () => {
|
||||
vi.useFakeTimers()
|
||||
const failure = new Error('queue unavailable')
|
||||
const enqueue = vi.fn(async (operation: () => Promise<void>) => operation()).mockRejectedValueOnce(failure)
|
||||
const persist = vi.fn(async (_events: readonly SessionEvent[]) => {})
|
||||
const report = vi.fn()
|
||||
const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2, enqueue, persist, retry: () => true, canSchedule: () => true })
|
||||
buffer.append([event(0)], report)
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(report).toHaveBeenCalledWith(failure)
|
||||
buffer.append([event(1), event(2)], report)
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(enqueue).toHaveBeenCalledOnce()
|
||||
expect(buffer.length).toBe(3)
|
||||
await buffer.drain()
|
||||
expect(persist.mock.calls.map(([batch]) => batch.map(item => item.seq))).toEqual([[0, 1], [2]])
|
||||
expect(buffer.length).toBe(0)
|
||||
})
|
||||
|
||||
it('joins concurrent drains and keeps events admitted during a commit in the next bounded batch', async () => {
|
||||
vi.useFakeTimers()
|
||||
const release = Promise.withResolvers<undefined>(), entered = Promise.withResolvers<undefined>()
|
||||
const batches: number[][] = []
|
||||
const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2,
|
||||
enqueue: async operation => operation(),
|
||||
persist: async (batch) => { batches.push(batch.map(item => item.seq)); entered.resolve(undefined); await release.promise },
|
||||
retry: () => true, canSchedule: () => true,
|
||||
})
|
||||
buffer.append([event(0)], vi.fn())
|
||||
const drain = buffer.drain()
|
||||
await entered.promise
|
||||
expect(buffer.active).toBe(true)
|
||||
expect(buffer.drain()).toBe(drain)
|
||||
buffer.append([event(1), event(2), event(3)], vi.fn())
|
||||
release.resolve(undefined)
|
||||
await drain
|
||||
expect(batches).toEqual([[0], [1, 2], [3]])
|
||||
expect(buffer.active).toBe(false)
|
||||
await vi.runAllTimersAsync()
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
/** SQLite JSON decoding preserves logical Session records. @module */
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
||||
import { decodeHeader, decodeEvent, materializeHeader } from '../src/codec.ts'
|
||||
|
||||
const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('codec'), createdAt: 0, isSeeded: false }
|
||||
|
||||
describe('SQLite header decoding', () => {
|
||||
it('reads logical metadata and preserves optional parent metadata', () => {
|
||||
expect(decodeHeader(header)).toEqual({ ...header, delegationDepth: 0 })
|
||||
const parent = { ...header, cwd: '/work', parentSession: SessionId('parent'), origin: 'subagent' as const, delegationDepth: 1, agentPreset: 'worker' }
|
||||
expect(decodeHeader(parent)).toEqual(parent)
|
||||
})
|
||||
|
||||
it.each([null, { ...header, version: 100 }, { ...header, version: 3 }, { ...header, delegationDepth: -1 }])(
|
||||
'refuses malformed or unsupported logical metadata %j', (value) => {
|
||||
expect(() => decodeHeader(value)).toThrow()
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('SQLite event decoding', () => {
|
||||
const event = { type: 'feedback/record', seq: 0, time: 0, data: { text: 'fixture' } }
|
||||
|
||||
it('preserves decoded fields and accepts ignorable extension events', () => {
|
||||
expect(decodeEvent(event)).toEqual(event)
|
||||
expect(decodeEvent({ ...event, type: 'fixture/extension', ignorable: true })).toEqual({
|
||||
...event, type: 'fixture/extension', ignorable: true,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([-1, 0.5, Number.MAX_SAFE_INTEGER + 1, '0', null])(
|
||||
'refuses invalid sequence %s before Session adoption', (seq) => {
|
||||
expect(() => decodeEvent({ ...event, seq })).toThrow()
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['type', 'seq', 'time', 'data'])('refuses a missing %s field', (key) => {
|
||||
const row = Object.fromEntries(Object.entries(event).filter(([field]) => field !== key))
|
||||
expect(() => decodeEvent(row)).toThrow()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ type: 1 }, { time: 0.5 }, { time: Number.MAX_SAFE_INTEGER + 1 },
|
||||
{ ignorable: false }, { extra: true }, { data: undefined },
|
||||
])('refuses malformed envelope fields %j', (fields) => {
|
||||
expect(() => decodeEvent({ ...event, ...fields })).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
it('requires the inherited count to agree with seeded metadata', () => {
|
||||
expect(() => materializeHeader({ ...header, isSeeded: true })).toThrow('seeded session header requires')
|
||||
expect(() => materializeHeader(header, SessionLogOffset(1))).toThrow('unseeded session header inherited')
|
||||
expect(materializeHeader(header)).toEqual({ ...header, delegationDepth: 0 })
|
||||
expect(materializeHeader({ ...header, isSeeded: true }, SessionLogOffset(0))).toMatchObject({ isSeeded: true })
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
/** Session creation identity and consumer teardown across persistence instances. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionHeader, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { SessionAlreadyExistsError, SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionWriteLease } from '../src/lease.ts'
|
||||
import { generationLogPath, toHeaderLine } from '../../session-persistence-jsonl/src/format.ts'
|
||||
import { persistenceFixture } from './fixtures/persistence.ts'
|
||||
|
||||
const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('competing'), createdAt: 0, isSeeded: false }
|
||||
const event = (turn: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn } })
|
||||
|
||||
async function fixture() {
|
||||
const storage = await persistenceFixture()
|
||||
const mount = async () => {
|
||||
const backend = await storage.mount('sqlite')
|
||||
return backend.context
|
||||
}
|
||||
return { root: storage.root, mount }
|
||||
}
|
||||
|
||||
it('preserves the identity refusal and release failure without retaining either lock', async () => {
|
||||
const { mount, root } = await fixture()
|
||||
const a = await mount(), b = await mount()
|
||||
const first = await a.sessionPersistence.create(header)
|
||||
const second = await b.sessionPersistence.create({ ...header, cwd: join(root, 'other-project') })
|
||||
await first.flush(); await first.close()
|
||||
await writeFile(generationLogPath(root, header.cwd, header.id, header.version, 'none'), JSON.stringify(toHeaderLine(header)) + '\n')
|
||||
const failure = new Error('creation lease release failed')
|
||||
const spy = vi.spyOn(SessionWriteLease.prototype, 'release').mockImplementationOnce(async function (this: SessionWriteLease) {
|
||||
spy.mockRestore()
|
||||
await this.release()
|
||||
throw failure
|
||||
})
|
||||
try {
|
||||
await expect(second.flush()).rejects.toMatchObject({ errors: [expect.any(SessionAlreadyExistsError), failure] })
|
||||
} finally { spy.mockRestore() }
|
||||
await expect(second.flush()).rejects.toBeInstanceOf(SessionAlreadyExistsError)
|
||||
await second.close()
|
||||
})
|
||||
|
||||
it('excludes another provider while the first creation holds the Session write lock', async () => {
|
||||
const { mount, root } = await fixture()
|
||||
const a = await mount(), b = await mount()
|
||||
const first = await a.sessionPersistence.create(header)
|
||||
const second = await b.sessionPersistence.create({ ...header, cwd: join(root, 'other-project') })
|
||||
const acquired = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
|
||||
const acquire = SessionWriteLease.acquire.bind(SessionWriteLease)
|
||||
const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementationOnce(async (...args) => {
|
||||
const lease = await acquire(...args)
|
||||
acquired.resolve(undefined)
|
||||
await release.promise
|
||||
return lease
|
||||
})
|
||||
onTestFinished(() => { release.resolve(undefined); spy.mockRestore() })
|
||||
const writing = first.append([event(1)])
|
||||
try {
|
||||
await acquired.promise
|
||||
await expect(second.append([event(2)])).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
} finally { release.resolve(undefined); spy.mockRestore(); await writing; await first.close() }
|
||||
await expect(second.append([event(2)])).rejects.toBeInstanceOf(SessionAlreadyExistsError)
|
||||
await second.close()
|
||||
})
|
||||
|
||||
it.each([false, true])('refuses a losing create with different cwd=%s', async (differentCwd) => {
|
||||
const { mount, root } = await fixture()
|
||||
const a = await mount(), b = await mount()
|
||||
const first = await a.sessionPersistence.create(header)
|
||||
const second = await b.sessionPersistence.create({ ...header, ...differentCwd ? { cwd: join(root, 'project') } : {} })
|
||||
await first.append([event(1)]); await first.close()
|
||||
const result = await second.append([event(2)]).then(() => 'committed', (error: unknown) => error)
|
||||
await second.close()
|
||||
const restarted = await mount()
|
||||
const listed = await restarted.sessionPersistence.list()
|
||||
const reader = await restarted.sessionPersistence.open(header.id, 'read')
|
||||
let stored: readonly SessionEvent[]
|
||||
try { stored = (await reader.read()).events } finally { await reader.close() }
|
||||
expect(result).toBeInstanceOf(SessionAlreadyExistsError)
|
||||
expect(listed.map(entry => entry.header.id)).toEqual([header.id])
|
||||
expect(stored).toEqual([event(1)])
|
||||
})
|
||||
|
||||
it.each(['provider', 'root', 'consumer-first'] as const)('preserves the final event during %s teardown', async (owner) => {
|
||||
const storage = await persistenceFixture()
|
||||
const { context: ctx, provider } = await storage.mount('sqlite')
|
||||
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
|
||||
onTestFinished(() => { release.resolve(undefined) })
|
||||
const consumer = await ctx.plugin({ name: 'final-writer', inject: ['sessionPersistence', 'sessions'],
|
||||
async apply(consumerCtx: Context) {
|
||||
const sessions = consumerCtx.sessions
|
||||
const live = sessions.prepare(SessionId('final'))
|
||||
// Own the Session and final dependency use in one ordered effect, as the Agent factory does.
|
||||
consumerCtx.effect(function* () {
|
||||
yield sessions.enter(live)
|
||||
sessions.announce(live)
|
||||
yield async () => {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
live.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
await sessions.flush(live)
|
||||
}
|
||||
})
|
||||
await consumerCtx.sessionPersistence.create(live.header)
|
||||
live.append('turn/start', { turn: 1 })
|
||||
await consumerCtx.sessions.flush(live)
|
||||
},
|
||||
})
|
||||
const consumerStop = owner === 'consumer-first' ? consumer.dispose() : undefined
|
||||
if (consumerStop !== undefined) await entered.promise
|
||||
let finished = false
|
||||
const stop = (owner === 'root' ? ctx.fiber.dispose() : provider.dispose()).then(() => { finished = true })
|
||||
await entered.promise
|
||||
// Immediate inspection after a microtask only checks the known consumer barrier.
|
||||
await Promise.resolve(undefined)
|
||||
expect(finished).toBe(false)
|
||||
expect(ctx.events.dispatch('emit', ['session/event'])).toHaveLength(1)
|
||||
release.resolve(undefined)
|
||||
await stop
|
||||
await consumerStop
|
||||
const { context: fresh } = await storage.mount('sqlite')
|
||||
const reader = await fresh.sessionPersistence.open(SessionId('final'), 'read')
|
||||
try { expect((await reader.read()).events.map(item => item.type)).toEqual(['turn/start', 'turn/end']) }
|
||||
finally { await reader.close() }
|
||||
})
|
||||
|
||||
it('rejects creation of an existing legacy JSONL identity before reserving a SQLite writer', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const jsonl = await fixture.mount('jsonl')
|
||||
const writer = await jsonl.persistence.create(header)
|
||||
await writer.flush(); await writer.close()
|
||||
const sqlite = await fixture.mount('sqlite')
|
||||
await expect(sqlite.persistence.create(header)).rejects.toBeInstanceOf(SessionAlreadyExistsError)
|
||||
const reader = await sqlite.persistence.open(header.id, 'read')
|
||||
await reader.close()
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
/** SQLite directory entries settle before database creation, including initialization retries. @module */
|
||||
import { mkdtemp, rm, stat } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { sqliteLogs } from './fixtures/store.ts'
|
||||
|
||||
const observed = vi.hoisted(() => ({ database: '', failAt: '', creationError: undefined as Error | undefined,
|
||||
events: [] as { path: string; operation: string }[] }))
|
||||
vi.mock('node:fs/promises', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs/promises')>()
|
||||
return { ...actual, open: async (...args: Parameters<typeof actual.open>) => {
|
||||
const path = String(args[0])
|
||||
if (path === observed.database && args[1] === 'wx' && observed.creationError !== undefined) throw observed.creationError
|
||||
const handle = await actual.open(...args)
|
||||
if (path === observed.database) observed.events.push({ path, operation: 'database-open' })
|
||||
if (args[1] === 'r') {
|
||||
const sync = handle.sync.bind(handle), close = handle.close.bind(handle)
|
||||
handle.sync = async () => {
|
||||
observed.events.push({ path, operation: 'sync' })
|
||||
if (path === observed.failAt) throw new Error('fixture directory sync failed')
|
||||
await sync()
|
||||
}
|
||||
handle.close = async () => {
|
||||
observed.events.push({ path, operation: 'close' })
|
||||
await close()
|
||||
}
|
||||
}
|
||||
return handle
|
||||
} }
|
||||
})
|
||||
|
||||
afterEach(() => { observed.database = ''; observed.failAt = ''; observed.creationError = undefined; observed.events = [] })
|
||||
|
||||
async function fixture(custom: boolean) {
|
||||
const base = await mkdtemp(join(tmpdir(), 'sqlite-directory-'))
|
||||
const root = join(base, 'profiles', 'sessions')
|
||||
const path = custom ? join(base, 'databases', 'nested', 'sessions.sqlite') : join(root, '.segments', 'sessions.sqlite')
|
||||
const logs = sqliteLogs(path, root)
|
||||
observed.database = path
|
||||
onTestFinished(async () => { try { await logs.close() } finally { await rm(base, { recursive: true, force: true }) } })
|
||||
return { base, root, path, logs }
|
||||
}
|
||||
|
||||
// Windows publishes new directories with MOVEFILE_WRITE_THROUGH rather than opening them for fsync.
|
||||
it.skipIf(process.platform === 'win32').each([false, true])(
|
||||
'syncs new directory ancestors before creating SQLite (custom path: %s)', async (custom) => {
|
||||
const { base, root, logs } = await fixture(custom)
|
||||
await logs.start()
|
||||
const databaseOpen = observed.events.findIndex(event => event.operation === 'database-open')
|
||||
expect(databaseOpen).toBeGreaterThan(0)
|
||||
const synced = observed.events.slice(0, databaseOpen).filter(event => event.operation === 'sync').map(event => event.path)
|
||||
expect(synced).toEqual(expect.arrayContaining(custom
|
||||
? [base, join(base, 'databases'), join(base, 'profiles'), root]
|
||||
: [base, join(base, 'profiles'), root]))
|
||||
expect(synced).not.toContain(dirname(base))
|
||||
},
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')('closes a failed directory sync and repeats ancestor sync on initialization retry', async () => {
|
||||
const { base, path, logs } = await fixture(true)
|
||||
observed.failAt = base
|
||||
await expect(logs.start()).rejects.toThrow('fixture directory sync failed')
|
||||
await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect(observed.events.at(-1)).toEqual({ path: base, operation: 'close' })
|
||||
observed.failAt = ''
|
||||
observed.events = []
|
||||
await logs.start()
|
||||
expect(observed.events).toContainEqual({ path: base, operation: 'sync' })
|
||||
})
|
||||
|
||||
it('preserves a database creation failure after directory preparation and permits retry', async () => {
|
||||
const { path, logs } = await fixture(true)
|
||||
const failure = Object.assign(new Error('fixture database creation denied'), { code: 'EACCES' })
|
||||
observed.creationError = failure
|
||||
await expect(logs.start()).rejects.toBe(failure)
|
||||
await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
observed.creationError = undefined
|
||||
await expect(logs.start()).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
// Existing directory entries need no new publication; POSIX is the only directory-fsync path.
|
||||
it.skipIf(process.platform === 'win32')('opens existing storage without synchronizing shared ancestor directories', async () => {
|
||||
const { root, path, logs } = await fixture(true)
|
||||
await logs.start()
|
||||
await logs.close()
|
||||
observed.events = []
|
||||
const reopened = sqliteLogs(path, root)
|
||||
try {
|
||||
await reopened.start()
|
||||
expect(observed.events.filter(event => event.operation === 'sync')).toEqual([])
|
||||
} finally { await reopened.close() }
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Built-package import holder with stdin barriers for ownership handoff. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { createInterface } from 'node:readline'
|
||||
import * as persistence from '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
|
||||
const [root, id, access, pause] = process.argv.slice(2)
|
||||
const ctx = new Context()
|
||||
const lines = createInterface({ input: process.stdin })
|
||||
const commands = lines[Symbol.asyncIterator]()
|
||||
try {
|
||||
if (pause === 'start') {
|
||||
process.stdout.write('ready\n')
|
||||
await commands.next()
|
||||
}
|
||||
await ctx.plugin(persistence, { root, compression: 'none' })
|
||||
if (pause === 'pause') {
|
||||
const reader = Reflect.get(ctx.sessionPersistence, 'jsonl')
|
||||
const prepare = reader.prepare.bind(reader)
|
||||
reader.prepare = async (...args) => {
|
||||
process.stdout.write('reading\n')
|
||||
await commands.next()
|
||||
return prepare(...args)
|
||||
}
|
||||
}
|
||||
if (pause === 'wait') {
|
||||
const sqlite = Reflect.get(ctx.sessionPersistence, 'sqlite')
|
||||
const acquire = sqlite.acquireSessionLease.bind(sqlite)
|
||||
let reported = false
|
||||
sqlite.acquireSessionLease = async (...args) => {
|
||||
try { return await acquire(...args) }
|
||||
catch (error) {
|
||||
if (!reported && error.name === 'SessionAlreadyOwnedError') {
|
||||
reported = true
|
||||
process.stdout.write('contended\n')
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await using handle = await ctx.sessionPersistence.open(id, access)
|
||||
process.stdout.write('opened\n')
|
||||
await commands.next()
|
||||
} catch (error) {
|
||||
process.stdout.write(`${error.name}\n`)
|
||||
// The suite asserts on the name; the message and cause go to the inherited stderr for diagnosis.
|
||||
process.stderr.write(`legacy opener ${access} ${id}: ${String(error)}${error.cause === undefined ? '' : ` (cause: ${String(error.cause)})`}\n`)
|
||||
}
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
lines.close()
|
||||
process.stdin.destroy()
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Isolated persistence providers sharing one test-owned storage directory. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { onTestFinished } from 'vitest'
|
||||
import * as SqlitePersistence from '../../src/index.ts'
|
||||
import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import type { JsonlCompression } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
|
||||
/**
|
||||
* Allocate private storage and close every mounted provider before removing it.
|
||||
* @returns storage root and factories for independently owned providers.
|
||||
*/
|
||||
export async function persistenceFixture() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-persistence-'))
|
||||
const contexts: Context[] = []
|
||||
onTestFinished(async () => {
|
||||
let failures: unknown[]
|
||||
try {
|
||||
const results = await Promise.allSettled(contexts.map(context => context.fiber.dispose()))
|
||||
failures = results.filter(result => result.status === 'rejected').map((result): unknown => result.reason)
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
if (failures.length > 0) throw new AggregateError(failures, 'Persistence fixture disposal failed')
|
||||
})
|
||||
async function mount(storage: 'sqlite' | 'jsonl', compression: JsonlCompression = 'none') {
|
||||
const context = new Context()
|
||||
contexts.push(context)
|
||||
await context.plugin(SessionStore)
|
||||
const plugin = storage === 'sqlite' ? SqlitePersistence : JsonlPersistence
|
||||
const provider = await context.plugin(plugin, { root, compression })
|
||||
return { context, persistence: context.sessionPersistence, provider }
|
||||
}
|
||||
return { root, mount }
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/** SQLite store fixtures and observations of durable event rows. @module */
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { readdir } from 'node:fs/promises'
|
||||
import { basename, join } from 'node:path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import type { StatementSync } from 'node:sqlite'
|
||||
import { z } from 'zod'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { onTestFinished, vi } from 'vitest'
|
||||
import { SESSION_FORMAT_VERSION, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { SqliteStore } from '../../src/sqlite.ts'
|
||||
import type { SqliteStoreOptions } from '../../src/sqlite.ts'
|
||||
import { SessionWriteLease } from '../../src/lease.ts'
|
||||
import { sessionDir } from '../../src/paths.ts'
|
||||
|
||||
/**
|
||||
* Construct a store with the plugin defaults and no-op provider callbacks.
|
||||
* @param path - database path.
|
||||
* @param root - legacy root holding lock directories and routing records.
|
||||
* @param overrides - option replacements for the test.
|
||||
* @returns an unopened store.
|
||||
*/
|
||||
export function sqliteLogs(path: string, root: string, overrides: Partial<SqliteStoreOptions> = {}): SqliteStore {
|
||||
return new SqliteStore({ path, legacyRoot: root,
|
||||
acquireCreationLease: header => SessionWriteLease.acquire(sessionDir(root, header.cwd, header.id), header.id),
|
||||
publish: async () => {}, report: () => {}, ...overrides })
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate a persisted shared prefix for Segment read and cut-selection tests.
|
||||
* @param logs - store containing the durable source.
|
||||
* @param source - source Session.
|
||||
* @param target - child fixture identity.
|
||||
* @param prefix - prefix selecting the shared length.
|
||||
*/
|
||||
export async function sharedHistory(logs: SqliteStore, source: SessionId, target: SessionId,
|
||||
prefix: readonly SessionEvent[]): Promise<void> {
|
||||
const snapshot = await logs.stat(source)
|
||||
if (snapshot === undefined) throw new Error('Missing source fixture')
|
||||
// Cached statements must use the connection owned by this store.
|
||||
const db = await logs['database']()
|
||||
{
|
||||
const stored = z.object({ header: z.string(), inherited_count: z.number(), base_seq: z.number(),
|
||||
tail_segment_uuid: z.string().transform(value => brandString<Parameters<SqliteStore['cut']>[1]['tail_segment_uuid']>(value)) })
|
||||
.parse(db.prepare('SELECT header, inherited_count, tail_segment_uuid, base_seq FROM traces JOIN segments ON segment_uuid = tail_segment_uuid WHERE trace_uuid = ?').get(source))
|
||||
const cut = logs.cut(db, { ...stored, event_count: z.number().parse(snapshot.eventCount) }, prefix.length)
|
||||
const segment = randomUUID()
|
||||
const marker: SessionEvent<'session/end-seed'> = { type: 'session/end-seed', seq: SessionSeq(prefix.length), time: 0, data: { inherited: true } }
|
||||
db.exec('BEGIN IMMEDIATE')
|
||||
try {
|
||||
const id = brandString<Parameters<SqliteStore['cut']>[1]['tail_segment_uuid']>(segment)
|
||||
logs['newSegment'](db, id, cut.parent, cut.end)
|
||||
db.prepare('INSERT INTO traces VALUES (?, ?, ?, ?)').run(target,
|
||||
JSON.stringify({ version: SESSION_FORMAT_VERSION, id: target, createdAt: 0, isSeeded: true,
|
||||
delegationDepth: 0 }), segment, prefix.length)
|
||||
db.prepare('INSERT INTO events VALUES (?, 0, ?)').run(segment, JSON.stringify(marker))
|
||||
db.exec('COMMIT')
|
||||
} catch (error) { db.exec('ROLLBACK'); throw error }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report the backend that durably holds one Session from its routing record.
|
||||
* @param root - legacy root.
|
||||
* @param id - Session identity.
|
||||
* @returns `sqlite` when a routing record exists, otherwise `jsonl`.
|
||||
*/
|
||||
export async function routeOf(root: string, id: SessionId): Promise<'sqlite' | 'jsonl'> {
|
||||
const marker = join(root, '.segments', `${createHash('sha256').update(id).digest('hex')}.json`)
|
||||
return (await readdir(join(root, '.segments'))).includes(basename(marker)) ? 'sqlite' : 'jsonl'
|
||||
}
|
||||
|
||||
/**
|
||||
* Count event payload rows and Segment metadata queries issued by the store.
|
||||
* @returns live counters, restored when the test finishes.
|
||||
*/
|
||||
export function countSqliteReads(): { payloadRows: () => number; segmentQueries: () => number } {
|
||||
let payloadRows = 0, segmentQueries = 0
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below.
|
||||
const prepare = DatabaseSync.prototype.prepare
|
||||
const spy = vi.spyOn(DatabaseSync.prototype, 'prepare').mockImplementation(function (this: DatabaseSync, sql: string) {
|
||||
const statement = prepare.call(this, sql)
|
||||
if (sql.startsWith('SELECT s.*')) {
|
||||
const get = statement.get.bind(statement), all = statement.all.bind(statement)
|
||||
Object.defineProperty(statement, 'get', { value: (...args: Parameters<StatementSync['get']>) => {
|
||||
segmentQueries++
|
||||
return get(...args)
|
||||
} })
|
||||
Object.defineProperty(statement, 'all', { value: (...args: Parameters<StatementSync['all']>) => {
|
||||
segmentQueries++
|
||||
return all(...args)
|
||||
} })
|
||||
}
|
||||
if (sql === 'SELECT payload FROM events WHERE segment_uuid = ? AND seq >= ? AND seq < ? ORDER BY seq') {
|
||||
const all = statement.all.bind(statement)
|
||||
Object.defineProperty(statement, 'all', { value: (...args: Parameters<StatementSync['all']>) => {
|
||||
const rows = all(...args)
|
||||
payloadRows += rows.length
|
||||
return rows
|
||||
} })
|
||||
}
|
||||
return statement
|
||||
})
|
||||
onTestFinished(() => { spy.mockRestore() })
|
||||
return { payloadRows: () => payloadRows, segmentQueries: () => segmentQueries }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one imported root Segment directly from durable SQLite rows.
|
||||
* @param root - persistence root using the default database.
|
||||
* @param id - imported Session identity.
|
||||
* @returns logical current header and event records in sequence order.
|
||||
*/
|
||||
export function importedRows(root: string, id: SessionId): unknown[] {
|
||||
const db = new DatabaseSync(join(root, '.segments', 'sessions.sqlite'))
|
||||
try {
|
||||
const row = db.prepare('SELECT header, tail_segment_uuid FROM traces WHERE trace_uuid = ?').get(id)
|
||||
if (typeof row?.header !== 'string' || typeof row.tail_segment_uuid !== 'string') throw new Error('Missing imported Session')
|
||||
const rootSegment = db.prepare('SELECT parent_segment_uuid FROM segments WHERE segment_uuid = ?').get(row.tail_segment_uuid)
|
||||
if (rootSegment?.parent_segment_uuid !== null) throw new Error('Expected an imported root Segment')
|
||||
return [JSON.parse(row.header), ...db.prepare('SELECT payload FROM events WHERE segment_uuid = ? ORDER BY seq')
|
||||
.all(row.tail_segment_uuid).map((event) => {
|
||||
if (typeof event.payload !== 'string') throw new Error('Invalid event payload')
|
||||
const value: unknown = JSON.parse(event.payload)
|
||||
return value
|
||||
})]
|
||||
} finally { db.close() }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/** Concurrent schema initialization and WAL publication. @module */
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { join } from 'node:path'
|
||||
import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
|
||||
import { persistenceFixture } from './fixtures/persistence.ts'
|
||||
|
||||
it('initializes the schema once when two providers create Sessions simultaneously', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const first = await fixture.mount('sqlite')
|
||||
const second = await fixture.mount('sqlite')
|
||||
const writers = await Promise.all([
|
||||
first.persistence.create(meta('first-provider')),
|
||||
second.persistence.create(meta('second-provider')),
|
||||
])
|
||||
await Promise.all(writers.map(writer => writer.append(oneTurnLog())))
|
||||
await Promise.all(writers.map(writer => writer.close()))
|
||||
expect((await first.persistence.list()).map(entry => entry.header.id).sort()).toEqual(['first-provider', 'second-provider'])
|
||||
})
|
||||
|
||||
it('enables WAL before publishing the schema to a concurrent reader', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const backend = await fixture.mount('sqlite')
|
||||
let snapshot: DatabaseSync | undefined
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Forwarded with its database receiver.
|
||||
const execute = DatabaseSync.prototype.exec
|
||||
const spy = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) {
|
||||
execute.call(this, sql)
|
||||
if (sql === 'COMMIT' && snapshot === undefined) {
|
||||
snapshot = new DatabaseSync(join(fixture.root, '.segments', 'sessions.sqlite'), { readOnly: true })
|
||||
execute.call(snapshot, 'BEGIN')
|
||||
expect(snapshot.prepare('SELECT COUNT(*) AS count FROM traces').get()?.count).toBe(0)
|
||||
}
|
||||
})
|
||||
try {
|
||||
const header = meta('wal-reader')
|
||||
const writer = await backend.persistence.create(header)
|
||||
await writer.append(oneTurnLog())
|
||||
await writer.close()
|
||||
expect(snapshot).toBeDefined()
|
||||
expect(snapshot?.prepare('SELECT COUNT(*) AS count FROM traces').get()?.count).toBe(0)
|
||||
expect((await backend.persistence.stat(header.id))?.eventCount).toBe(oneTurnLog().length)
|
||||
} finally {
|
||||
spy.mockRestore()
|
||||
snapshot?.close()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
/** Kernel lease contention, filesystem failures, and inode verification. @module */
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionWriteLease, LEASE_FILENAME } from '../src/lease.ts'
|
||||
|
||||
const faults = vi.hoisted(() => ({ flock: '', stat: false, swap: 0, remove: false }))
|
||||
vi.mock('@deepseek-ai/node-addon-system/flock', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@deepseek-ai/node-addon-system/flock')>()
|
||||
return { ...actual, tryLockExclusive: async (fd: number) => {
|
||||
if (faults.flock !== '') {
|
||||
const code = faults.flock
|
||||
faults.flock = ''
|
||||
throw Object.assign(new Error(`flock failed: ${code}`), { code })
|
||||
}
|
||||
await actual.tryLockExclusive(fd)
|
||||
} }
|
||||
})
|
||||
vi.mock('node:fs/promises', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs/promises')>()
|
||||
return { ...actual, stat: async (...args: Parameters<typeof actual.stat>) => {
|
||||
if (String(args[0]).endsWith('session.lock')) {
|
||||
if (faults.stat) {
|
||||
faults.stat = false
|
||||
throw Object.assign(new Error('lock path denied'), { code: 'EACCES' })
|
||||
}
|
||||
if (faults.remove) {
|
||||
faults.remove = false
|
||||
await actual.unlink(args[0])
|
||||
} else if (faults.swap > 0) {
|
||||
faults.swap--
|
||||
await actual.unlink(args[0])
|
||||
await actual.writeFile(args[0], '')
|
||||
}
|
||||
}
|
||||
return actual.stat(...args)
|
||||
} }
|
||||
})
|
||||
afterEach(() => { faults.flock = ''; faults.stat = false; faults.swap = 0; faults.remove = false })
|
||||
|
||||
async function fixtureRoot() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-lease-'))
|
||||
const leases: SessionWriteLease[] = []
|
||||
onTestFinished(async () => {
|
||||
try { await Promise.all(leases.map(lease => lease.release())) }
|
||||
finally { await rm(root, { recursive: true, force: true }) }
|
||||
})
|
||||
async function acquire() {
|
||||
const lease = await SessionWriteLease.acquire(root, SessionId('lease'))
|
||||
leases.push(lease)
|
||||
return lease
|
||||
}
|
||||
return { root, acquire }
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('POSIX SQLite leases', () => {
|
||||
it('excludes a second descriptor until the holder releases its lock', async () => {
|
||||
const fixture = await fixtureRoot()
|
||||
const first = await fixture.acquire()
|
||||
await expect(fixture.acquire()).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
await first.release()
|
||||
const next = await fixture.acquire()
|
||||
await next.release()
|
||||
await next.release()
|
||||
expect(await readFile(join(fixture.root, LEASE_FILENAME), 'utf8')).toBe('')
|
||||
})
|
||||
|
||||
it.each(['EACCES', 'EWOULDBLOCK'])('releases the descriptor after flock reports %s', async (code) => {
|
||||
const fixture = await fixtureRoot()
|
||||
faults.flock = code
|
||||
const failed = expect(fixture.acquire()).rejects
|
||||
if (code === 'EWOULDBLOCK') await failed.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
else await failed.toMatchObject({ code })
|
||||
await fixture.acquire()
|
||||
})
|
||||
|
||||
it('releases the descriptor when inode verification cannot read the lock path', async () => {
|
||||
const fixture = await fixtureRoot()
|
||||
faults.stat = true
|
||||
await expect(fixture.acquire()).rejects.toMatchObject({ code: 'EACCES' })
|
||||
await fixture.acquire()
|
||||
})
|
||||
|
||||
it.each(['removed', 'replaced', 'unstable'] as const)('verifies the current inode when its path is %s', async (mode) => {
|
||||
const fixture = await fixtureRoot()
|
||||
if (mode === 'removed') faults.remove = true
|
||||
else faults.swap = mode === 'replaced' ? 1 : 3
|
||||
if (mode === 'unstable') await expect(fixture.acquire()).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
else await (await fixture.acquire()).release()
|
||||
await fixture.acquire()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,195 @@
|
||||
import { describe, expect, it, vi, onTestFinished } from 'vitest'
|
||||
import { appendFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import type { JsonlCompression } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import { generationLogPath } from '../../session-persistence-jsonl/src/format.ts'
|
||||
import { SessionWriteLease } from '../src/lease.ts'
|
||||
import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
|
||||
import { persistenceFixture } from './fixtures/persistence.ts'
|
||||
|
||||
type Fixture = Awaited<ReturnType<typeof persistenceFixture>>
|
||||
|
||||
async function writeLegacy(fixture: Fixture, compression: JsonlCompression, header = meta('legacy', '/workspace'), events = oneTurnLog(), inheritedEventCount?: SessionLogOffset) {
|
||||
const backend = await fixture.mount('jsonl', compression)
|
||||
const writer = await backend.persistence.create(header, inheritedEventCount === undefined ? undefined : { inheritedEventCount })
|
||||
await writer.append(events)
|
||||
await writer.close()
|
||||
await backend.context.fiber.dispose()
|
||||
const path = generationLogPath(fixture.root, header.cwd, header.id, header.version, compression)
|
||||
return { header, events, path, bytes: await readFile(path) }
|
||||
}
|
||||
|
||||
describe('JSONL import through the SQLite provider', () => {
|
||||
it('runs the released version migration before importing historical JSONL', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const header = meta('released-v3', '/workspace')
|
||||
const bytes = Buffer.from([
|
||||
JSON.stringify({ type: 'session', ...header, version: 3, delegationDepth: 0 }),
|
||||
...oneTurnLog().map(event => JSON.stringify(event)),
|
||||
'',
|
||||
].join('\n'))
|
||||
const path = generationLogPath(fixture.root, header.cwd, header.id, 3, 'none')
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
await writeFile(path, bytes)
|
||||
const jsonl = await fixture.mount('jsonl')
|
||||
const source = await jsonl.persistence.open(header.id, 'read')
|
||||
const expected = await source.read()
|
||||
const currentHeader = source.header
|
||||
await source.close()
|
||||
await jsonl.context.fiber.dispose()
|
||||
const sqlite = await fixture.mount('sqlite')
|
||||
const imported = await sqlite.persistence.open(header.id, 'read')
|
||||
expect(imported.header).toEqual(currentHeader)
|
||||
expect((await imported.read()).events).toEqual(expected.events)
|
||||
await imported.close()
|
||||
expect(await readFile(path)).toEqual(bytes)
|
||||
expect(await readdir(dirname(path))).toContain('session.v3.jsonl')
|
||||
expect(await readdir(dirname(path))).not.toContain('session.v4.jsonl')
|
||||
})
|
||||
|
||||
it('imports the complete prefix of a torn JSONL tail without adding semantic repair events', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const legacy = await writeLegacy(fixture, 'none', meta('torn-tail'), oneTurnLog().slice(0, 3))
|
||||
await appendFile(legacy.path, '{"type":"assistant/message"')
|
||||
const bytes = await readFile(legacy.path)
|
||||
const sqlite = await fixture.mount('sqlite')
|
||||
const reader = await sqlite.persistence.open(legacy.header.id, 'read')
|
||||
expect((await reader.read()).events).toEqual(legacy.events)
|
||||
await reader.close()
|
||||
expect(await readFile(legacy.path)).toEqual(bytes)
|
||||
})
|
||||
|
||||
it.each(['none', 'zstd'] as const)('imports %s history into one root segment and preserves logical inheritance and source bytes', async (compression) => {
|
||||
const fixture = await persistenceFixture()
|
||||
const header: SessionHeader = { ...meta('seeded-legacy', '/workspace'), isSeeded: true, parentSession: meta('parent').id, delegationDepth: 0 }
|
||||
const original = oneTurnLog()
|
||||
const events: SessionEvent[] = [
|
||||
...original.slice(0, 2),
|
||||
{ type: 'session/end-seed', seq: SessionSeq(2), time: 2, data: { inherited: true } },
|
||||
...original.slice(2).map(event => ({ ...event, seq: SessionSeq(event.seq + 1) })),
|
||||
]
|
||||
const legacy = await writeLegacy(fixture, compression, header, events, SessionLogOffset(2))
|
||||
const { persistence } = await fixture.mount('sqlite', compression)
|
||||
expect((await persistence.stat(header.id))?.header).toEqual(header)
|
||||
expect((await persistence.list()).map(entry => entry.header.id)).toEqual([header.id])
|
||||
expect(await readdir(fixture.root)).not.toContain('.segments')
|
||||
const reader = await persistence.open(header.id, 'read')
|
||||
expect(reader.header).toEqual(header)
|
||||
expect(reader.inheritedEventCount).toBe(2)
|
||||
expect((await reader.read()).events).toEqual(events)
|
||||
await reader.close()
|
||||
expect(await readFile(legacy.path)).toEqual(legacy.bytes)
|
||||
expect((await persistence.list()).map(entry => entry.header.id)).toEqual([header.id])
|
||||
const db = new DatabaseSync(join(fixture.root, '.segments', 'sessions.sqlite'), { readOnly: true })
|
||||
try {
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM traces').get()?.count).toBe(1)
|
||||
expect(db.prepare('SELECT parent_segment_uuid, parent_end_seq, base_seq FROM segments').all()).toEqual([
|
||||
{ parent_segment_uuid: null, parent_end_seq: null, base_seq: 0 },
|
||||
])
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM events').get()?.count).toBe(events.length)
|
||||
} finally { db.close() }
|
||||
})
|
||||
|
||||
it('continues writing in SQLite after reopening and leaves the imported JSONL unchanged', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const legacy = await writeLegacy(fixture, 'none')
|
||||
const first = await fixture.mount('sqlite')
|
||||
const writer = await first.persistence.open(legacy.header.id, 'write')
|
||||
const continuation: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(6), time: 10, data: { turn: 2 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(7), time: 11, data: { turn: 2, reason: { kind: 'completed' } } },
|
||||
]
|
||||
await writer.append(continuation)
|
||||
await writer.close()
|
||||
await first.context.fiber.dispose()
|
||||
const reopened = await fixture.mount('sqlite')
|
||||
const reader = await reopened.persistence.open(legacy.header.id, 'read')
|
||||
expect((await reader.read()).events).toEqual([...legacy.events, ...continuation])
|
||||
await reader.close()
|
||||
expect(await readFile(legacy.path)).toEqual(legacy.bytes)
|
||||
})
|
||||
|
||||
it('imports once when two readers open the same legacy Session simultaneously', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const legacy = await writeLegacy(fixture, 'none')
|
||||
const { persistence } = await fixture.mount('sqlite')
|
||||
const prepare = vi.spyOn(JsonlSessionPersistence.prototype, 'prepare')
|
||||
onTestFinished(() => { prepare.mockRestore() })
|
||||
const readers = await Promise.all([
|
||||
persistence.open(legacy.header.id, 'read'),
|
||||
persistence.open(legacy.header.id, 'read'),
|
||||
])
|
||||
expect(prepare).toHaveBeenCalledTimes(1)
|
||||
for (const reader of readers) {
|
||||
expect((await reader.read()).events).toEqual(legacy.events)
|
||||
await reader.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('allows another provider to read an imported Session while its writer retains ownership', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const legacy = await writeLegacy(fixture, 'none')
|
||||
const first = await fixture.mount('sqlite')
|
||||
const second = await fixture.mount('sqlite')
|
||||
const writer = await first.persistence.open(legacy.header.id, 'write')
|
||||
const reader = await second.persistence.open(legacy.header.id, 'read')
|
||||
expect((await reader.read()).events).toEqual(legacy.events)
|
||||
await expect(second.persistence.open(legacy.header.id, 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError)
|
||||
await reader.close()
|
||||
await writer.close()
|
||||
const next = await second.persistence.open(legacy.header.id, 'write')
|
||||
await next.close()
|
||||
})
|
||||
|
||||
it('waits for the active JSONL writer before importing its final committed prefix', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const jsonl = await fixture.mount('jsonl')
|
||||
const header = meta('active-legacy', '/workspace')
|
||||
const writer = await jsonl.persistence.create(header)
|
||||
await writer.append(oneTurnLog().slice(0, 3))
|
||||
const sqlite = await fixture.mount('sqlite')
|
||||
const attempted = Promise.withResolvers<undefined>()
|
||||
const acquire = SessionWriteLease.acquire.bind(SessionWriteLease)
|
||||
const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (...args) => {
|
||||
try { return await acquire(...args) } finally { attempted.resolve(undefined) }
|
||||
})
|
||||
onTestFinished(() => { spy.mockRestore() })
|
||||
const pending = sqlite.persistence.open(header.id, 'read')
|
||||
await attempted.promise
|
||||
await writer.append(oneTurnLog().slice(3))
|
||||
await writer.close()
|
||||
const reader = await pending
|
||||
expect((await reader.read()).events).toEqual(oneTurnLog())
|
||||
await reader.close()
|
||||
})
|
||||
|
||||
it('cancels a read waiting for JSONL ownership and permits a later import', async () => {
|
||||
const fixture = await persistenceFixture()
|
||||
const jsonl = await fixture.mount('jsonl')
|
||||
const header = meta('cancel-import')
|
||||
const writer = await jsonl.persistence.create(header)
|
||||
await writer.append(oneTurnLog())
|
||||
const sqlite = await fixture.mount('sqlite')
|
||||
const attempted = Promise.withResolvers<undefined>()
|
||||
const acquire = SessionWriteLease.acquire.bind(SessionWriteLease)
|
||||
const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (...args) => {
|
||||
try { return await acquire(...args) } finally { attempted.resolve(undefined) }
|
||||
})
|
||||
onTestFinished(() => { spy.mockRestore() })
|
||||
const controller = new AbortController()
|
||||
const reason = new Error('cancelled import')
|
||||
const rejected = expect(sqlite.persistence.open(header.id, 'read', { signal: controller.signal })).rejects.toMatchObject({ name: 'AbortError', cause: reason })
|
||||
await attempted.promise
|
||||
controller.abort(reason)
|
||||
await rejected
|
||||
await writer.close()
|
||||
const reader = await sqlite.persistence.open(header.id, 'read')
|
||||
expect((await reader.read()).events).toEqual(oneTurnLog())
|
||||
await reader.close()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
/** Built-package ownership during concurrent legacy import and SQLite handoff. @module */
|
||||
import { spawn } from 'node:child_process'
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
import { createInterface } from 'node:readline'
|
||||
import type { Interface } from 'node:readline'
|
||||
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it, onTestFinished } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import * as persistence from '../src/index.ts'
|
||||
import { eventLines, generationLogPath, toHeaderLine } from '../../session-persistence-jsonl/src/format.ts'
|
||||
import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts'
|
||||
|
||||
const opener = fileURLToPath(new URL('./fixtures/legacy-opener.mjs', import.meta.url))
|
||||
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-import-process-'))
|
||||
const contexts: Context[] = []
|
||||
const children: { child: ChildProcess; closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; lines: Interface }[] = []
|
||||
onTestFinished(async () => {
|
||||
try {
|
||||
for (const { child } of children) {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
|
||||
}
|
||||
await Promise.all(children.map(async (probe) => {
|
||||
await probe.closed
|
||||
probe.lines.close()
|
||||
}))
|
||||
for (const context of contexts) await context.fiber.dispose()
|
||||
} finally { await rm(root, { recursive: true, force: true }) }
|
||||
})
|
||||
const id = SessionId('legacy-process')
|
||||
const path = await store(id)
|
||||
const bytes = await readFile(path)
|
||||
async function store(target: SessionId) {
|
||||
const header = meta(target)
|
||||
const path = generationLogPath(root, header.cwd, target, header.version, 'none')
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
await writeFile(path, JSON.stringify(toHeaderLine(header)) + '\n' + eventLines(oneTurnLog()) + '\n')
|
||||
return path
|
||||
}
|
||||
function launch(access = 'read', pause = '', target = id) {
|
||||
const child = spawn(process.execPath, [opener, root, target, access, pause], { stdio: ['pipe', 'pipe', 'inherit'] })
|
||||
const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve, reject) => {
|
||||
child.once('error', reject)
|
||||
child.once('close', (code, signal) => { resolve({ code, signal }) })
|
||||
})
|
||||
const lines = createInterface({ input: child.stdout })
|
||||
const iterator = lines[Symbol.asyncIterator]()
|
||||
const probe = {
|
||||
child, closed, lines,
|
||||
async status() {
|
||||
const line = await iterator.next()
|
||||
if (line.done) throw new Error('Legacy opener closed before reporting status')
|
||||
return line.value
|
||||
},
|
||||
async close() {
|
||||
child.stdin.end('close\n')
|
||||
expect(await closed).toEqual({ code: 0, signal: null })
|
||||
},
|
||||
}
|
||||
children.push(probe)
|
||||
return probe
|
||||
}
|
||||
async function mount() {
|
||||
const context = new Context()
|
||||
contexts.push(context)
|
||||
await context.plugin(persistence, { root, compression: 'none' })
|
||||
return context.sessionPersistence
|
||||
}
|
||||
return { root, id, path, bytes, store, launch, mount }
|
||||
}
|
||||
|
||||
describe('legacy import across processes', { retry: 0 }, () => {
|
||||
it('initializes one database while two processes first open different Sessions', async () => {
|
||||
const b = await fixture()
|
||||
const otherId = SessionId('other-legacy-process')
|
||||
await b.store(otherId)
|
||||
const first = b.launch('read', 'start'), second = b.launch('read', 'start', otherId)
|
||||
expect(await Promise.all([first.status(), second.status()])).toEqual(['ready', 'ready'])
|
||||
first.child.stdin.write('continue\n')
|
||||
second.child.stdin.write('continue\n')
|
||||
expect(await Promise.all([first.status(), second.status()])).toEqual(['opened', 'opened'])
|
||||
await Promise.all([first.close(), second.close()])
|
||||
const persistence = await b.mount()
|
||||
expect((await persistence.list()).map(entry => entry.header.id).sort()).toEqual([b.id, otherId].sort())
|
||||
for (const id of [b.id, otherId]) {
|
||||
await using read = await persistence.open(id, 'read')
|
||||
expect((await read.read()).events).toEqual(oneTurnLog())
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['read', 'write'])('waits for another process to import and hands off %s access', async (access) => {
|
||||
const b = await fixture(), first = b.launch(access, 'pause')
|
||||
expect(await first.status()).toBe('reading')
|
||||
const competing = b.launch('read', 'wait')
|
||||
expect(await competing.status()).toBe('contended')
|
||||
first.child.stdin.write('continue\n')
|
||||
expect(await first.status()).toBe('opened')
|
||||
expect(await competing.status()).toBe('opened')
|
||||
await competing.close()
|
||||
const currentReader = b.launch()
|
||||
expect(await currentReader.status()).toBe('opened')
|
||||
await currentReader.close()
|
||||
if (access === 'write') {
|
||||
const competingWriter = b.launch('write')
|
||||
expect(await competingWriter.status()).toBe('SessionAlreadyOwnedError')
|
||||
expect(await competingWriter.closed).toEqual({ code: 0, signal: null })
|
||||
}
|
||||
await first.close()
|
||||
expect(await readFile(b.path)).toEqual(b.bytes)
|
||||
const persistence = await b.mount()
|
||||
await using read = await persistence.open(b.id, 'read')
|
||||
expect((await read.read()).events).toEqual(oneTurnLog())
|
||||
})
|
||||
|
||||
it('releases import ownership after process death and retries the complete import', async () => {
|
||||
const b = await fixture(), first = b.launch('write', 'pause')
|
||||
expect(await first.status()).toBe('reading')
|
||||
first.child.kill('SIGKILL')
|
||||
const result = await first.closed
|
||||
// Windows reports forced termination as an exit code rather than a POSIX signal.
|
||||
if (process.platform === 'win32') expect(result.code).not.toBe(0)
|
||||
else expect(result.signal).toBe('SIGKILL')
|
||||
const retry = b.launch('write')
|
||||
expect(await retry.status()).toBe('opened')
|
||||
await retry.close()
|
||||
expect(await readFile(b.path)).toEqual(b.bytes)
|
||||
const persistence = await b.mount()
|
||||
await using read = await persistence.open(b.id, 'read')
|
||||
expect((await read.read()).events).toEqual(oneTurnLog())
|
||||
})
|
||||
})
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user