Merge remote-tracking branch 'origin/master' into feat/session-workspace-root
# Conflicts: # docs/subsystems/worktrees.i18n.yaml # packages/experimental/client-ui-forge/README.i18n.yaml # packages/experimental/client-ui-forge/README.md # packages/experimental/client-ui-forge/README.zh.md # packages/experimental/client-ui-forge/src/worktree.ts # packages/experimental/tool-worktree/README.i18n.yaml # packages/experimental/tool-worktree/README.md # packages/experimental/tool-worktree/README.zh.md # packages/experimental/tool-worktree/src/index.ts # packages/experimental/tool-worktree/tests/loader-composition.spec.ts # packages/experimental/worktree/README.i18n.yaml
This commit is contained in:
commit
2decbbc718
111 files changed
+4479
-1158
No files matched your search
@@ -37,7 +37,7 @@
|
||||
"boolean",
|
||||
"null"
|
||||
],
|
||||
"description": "Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation."
|
||||
"description": "Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation."
|
||||
},
|
||||
"disabled": {
|
||||
"anyOf": [
|
||||
@@ -249,6 +249,28 @@
|
||||
{
|
||||
"$ref": "#/$defs/entryMetadata"
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"group": {
|
||||
"const": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"group"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"config": {
|
||||
"$ref": "#/$defs/entryList"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"config"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
||||
@@ -839,8 +839,8 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
expect(await git(directory, 'rev-parse', 'HEAD')).toBe(baseCommit)
|
||||
const events = await readPersistedEvents(scaffold, sessionId)
|
||||
expect(worktreeRecords(events)).toEqual([
|
||||
{ action: 'request', from: 'main' },
|
||||
{ action: 'request', from: 'release' },
|
||||
{ action: 'request', from: 'refs/heads/main' },
|
||||
{ action: 'request', from: 'refs/heads/release' },
|
||||
{ created: { path: directory, branch, baseCommit, repositoryRoot: project } },
|
||||
])
|
||||
// The worktree existed before the turn, so the first model request carried its directory notice.
|
||||
@@ -978,7 +978,9 @@ it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree
|
||||
if (session === undefined) throw new Error('The Session must stay loaded')
|
||||
expect(scaffold.ctx.workingDirectory.get(session)).toBe(project)
|
||||
const events = await readPersistedEvents(scaffold, sessionId)
|
||||
expect(worktreeRecords(events)).toEqual([{ action: 'request', from: 'main' }, { action: 'request', from: 'release' }, { action: 'cancel' }])
|
||||
expect(worktreeRecords(events)).toEqual([
|
||||
{ action: 'request', from: 'refs/heads/main' }, { action: 'request', from: 'refs/heads/release' }, { action: 'cancel' },
|
||||
])
|
||||
expect(events.filter(event => event.type === 'turn/start')).toHaveLength(1)
|
||||
expect(events.some(event => event.type === 'user/message' && event.data.source.kind === 'working-directory')).toBe(false)
|
||||
const checkout = (await showSessionPanel(page)).locator('[data-forge-checkout]')
|
||||
|
||||
@@ -259,6 +259,8 @@ export default defineConfig({
|
||||
// internal slot the shell boot fills with the client module loader).
|
||||
'process.versions.node': '"0.0.0"',
|
||||
'process.execArgv': '[]',
|
||||
// vendored loader tree.ts: import() converts drive-letter names only on win32.
|
||||
'process.platform': '"browser"',
|
||||
// vendored loader index.ts: envData falls to its default branch.
|
||||
'process.env.CORDIS_SHARED': 'undefined',
|
||||
},
|
||||
|
||||
@@ -1182,7 +1182,7 @@ export interface CotTranslationPreferences {
|
||||
## `@deepseek-ai/dsh-experimental-client-ui-forge`
|
||||
|
||||
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
|
||||
@@ -1184,7 +1184,7 @@ export interface CotTranslationPreferences {
|
||||
## `@deepseek-ai/dsh-experimental-client-ui-forge`
|
||||
|
||||
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
|
||||
@@ -28,7 +28,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:58`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` |
|
||||
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
|
||||
| `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` |
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:58`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` |
|
||||
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
|
||||
| `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` |
|
||||
|
||||
+90
-30
@@ -915,7 +915,10 @@ interface ForgeSessionWorktree {
|
||||
readonly path: string
|
||||
/** Branch created for the checkout. */
|
||||
readonly branch: string
|
||||
/** Requested base branch, or null when the checkout started from HEAD of the source checkout. */
|
||||
/**
|
||||
* Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels
|
||||
* recorded, or null when the checkout started from HEAD of the source checkout.
|
||||
*/
|
||||
readonly from: string | null
|
||||
/** Commit object name the branch started from. */
|
||||
readonly baseCommit: string
|
||||
@@ -928,8 +931,11 @@ interface ForgeSessionWorktree {
|
||||
```ts type-equiv
|
||||
/** Payload of the `plugin:client-ui-forge/worktree` record. */
|
||||
type WorktreeRecord =
|
||||
/** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */
|
||||
| { readonly action: 'request'; readonly from: string | null }
|
||||
/**
|
||||
* Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the
|
||||
* branch `name`, or on a generated branch name when `name` is absent.
|
||||
*/
|
||||
| { readonly action: 'request'; readonly from: string | null; readonly name?: string }
|
||||
/** Withdraw the open request. */
|
||||
| { readonly action: 'cancel' }
|
||||
/** The requested worktree was created and became the Session's working directory. */
|
||||
@@ -943,8 +949,13 @@ type WorktreeRecord =
|
||||
```ts type-equiv
|
||||
/** One open worktree request. */
|
||||
interface ForgeWorktreeRequest {
|
||||
/** Base branch, or null for HEAD of the source checkout. */
|
||||
/**
|
||||
* Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or
|
||||
* null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it.
|
||||
*/
|
||||
readonly from: string | null
|
||||
/** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */
|
||||
readonly name: string | null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -962,12 +973,17 @@ type ForgeWorktreeBlocker =
|
||||
```ts type-equiv
|
||||
/** One running worktree creation. */
|
||||
interface ForgeWorktreeCreation {
|
||||
/** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
/**
|
||||
* Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then
|
||||
* `checkout` writes the files.
|
||||
*/
|
||||
readonly phase: 'fetch' | 'prepare' | 'checkout'
|
||||
/** Branch the attempt creates. */
|
||||
readonly branch: string
|
||||
/** Base branch, or null for HEAD. */
|
||||
/** Base as the request names it, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetches its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/**
|
||||
* Whether a message waits for the creation before its turn starts. Only
|
||||
* such a creation can be stopped, after which the message keeps waiting; a
|
||||
@@ -990,12 +1006,16 @@ interface ForgeWorktreeRestoration {
|
||||
interface ForgeWorktreeFailure {
|
||||
/** Branch the attempt created, or null when it failed before naming one. */
|
||||
readonly branch: string | null
|
||||
/** Base branch of the attempt, or null for HEAD. */
|
||||
/** Base of the attempt as the request names it, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetched, or tried to fetch, its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/** Step that failed. */
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
readonly phase: 'fetch' | 'prepare' | 'checkout'
|
||||
/** Failure text. */
|
||||
readonly message: string
|
||||
/** Whether the branch or the checkout directory of that name already existed, which another name avoids. */
|
||||
readonly exists: boolean
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1026,6 +1046,8 @@ interface ForgePanelWorktree {
|
||||
readonly editable: boolean
|
||||
/** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */
|
||||
readonly blocker: ForgeWorktreeBlocker | null
|
||||
/** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */
|
||||
readonly namePrefix: string
|
||||
/** Open request, or null without one. */
|
||||
readonly request: ForgeWorktreeRequest | null
|
||||
/** Created worktree, or null before creation. */
|
||||
@@ -1086,12 +1108,39 @@ interface ForgePanelState {
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Local branches offered as the base of a new worktree. */
|
||||
interface ForgeBranches {
|
||||
/** Checked-out branch, or null when HEAD is detached. */
|
||||
readonly current: string | null
|
||||
/** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */
|
||||
readonly branches: readonly string[]
|
||||
/** Branches offered as the base of a new worktree whose names contain a query. */
|
||||
interface ForgeWorktreeBases {
|
||||
/** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */
|
||||
readonly current: ForgeBaseBranch | null
|
||||
/** Default branch of each remote that names one with `refs/remotes/<remote>/HEAD`, in remote order. */
|
||||
readonly defaults: readonly ForgeRemoteDefault[]
|
||||
/** Other local branches, most recently committed first, at most `maxBranches`. */
|
||||
readonly local: readonly ForgeBaseBranch[]
|
||||
/**
|
||||
* Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks,
|
||||
* then `origin`, then the others as Git lists them. Remotes without a matching branch are left out.
|
||||
*/
|
||||
readonly remotes: readonly ForgeRemoteBranches[]
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** A remote's default branch, which `refs/remotes/<remote>/HEAD` names. */
|
||||
interface ForgeRemoteDefault extends ForgeBaseBranch {
|
||||
/** Remote the branch belongs to; it may contain `/`. */
|
||||
readonly remote: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Remote-tracking branches of one remote, without its default branch. */
|
||||
interface ForgeRemoteBranches {
|
||||
/** Remote name such as `origin`; it may contain `/`. */
|
||||
readonly name: string
|
||||
/** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */
|
||||
readonly repository: string | null
|
||||
/** Branches named `<remote>/<branch>`, most recently committed first, at most `maxBranches`. */
|
||||
readonly branches: readonly ForgeBaseBranch[]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1775,13 +1824,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null>
|
||||
|
||||
/**
|
||||
* List the local branches that can start a worktree of the Session's current checkout.
|
||||
* @param session - Session whose current directory is listed.
|
||||
* List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each
|
||||
* remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the
|
||||
* order the panel recognizes code hosts.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first.
|
||||
* @throws when the current directory is not inside a checkout or Git fails.
|
||||
* @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
*/
|
||||
@Remote async branches(session: Session, signal: AbortSignal): Promise<ForgeBranches>
|
||||
@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases>
|
||||
|
||||
/**
|
||||
* List the branches the `branch` scope of the Session's current checkout can compare with.
|
||||
@@ -2114,18 +2166,23 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
/**
|
||||
* Ask for a new worktree before the Session's first turn, replacing an open
|
||||
* request and forgetting a failed attempt. While the next message waits in
|
||||
* the inbox, or else at the first step proposal, the panel creates a branch
|
||||
* from `from`, or from HEAD of the current checkout when it is null, and
|
||||
* enters its checkout. A message that already waits after a failed or
|
||||
* stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}.
|
||||
* the inbox, or else at the first step proposal, the panel creates the
|
||||
* branch `name`, or a generated branch per attempt when it is null, from
|
||||
* `from`, or from HEAD of the current checkout when it is null, and enters
|
||||
* its checkout; a remote-tracking `from` is fetched first. A message that
|
||||
* already waits after a failed or stopped attempt keeps waiting for
|
||||
* {@link ForgePanelController.retryWorktree}.
|
||||
* @param session - Session without a started turn.
|
||||
* @param from - local base branch, or null for HEAD.
|
||||
* @param from - full name of a local or remote-tracking base branch, or null for HEAD.
|
||||
* @param name - new branch name, or null to generate one per attempt.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable`
|
||||
* @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks
|
||||
* a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`;
|
||||
* `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable`
|
||||
* without a worktree service; `forgePanel/session-started` after a turn started or the worktree was
|
||||
* created; `forgePanel/session-busy` while the worktree is being created.
|
||||
*/
|
||||
@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise<void>
|
||||
@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Withdraw the open worktree request of a Session with its failed attempt,
|
||||
@@ -2148,13 +2205,16 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
@Remote async stopCreation(session: Session, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Make another attempt, with a new branch name, at the worktree a message
|
||||
* of the Session waits for after a failed or stopped attempt.
|
||||
* Make another attempt, on the requested branch name or a new generated
|
||||
* one, at the worktree a message of the Session waits for after a failed or
|
||||
* stopped attempt.
|
||||
* @param session - Session whose message waits.
|
||||
* @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the
|
||||
* commit last fetched.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/not-waiting` when no message waits or an attempt is running.
|
||||
*/
|
||||
@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise<void>
|
||||
@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Check out the created worktree of a Session again at its recorded
|
||||
|
||||
+90
-30
@@ -917,7 +917,10 @@ interface ForgeSessionWorktree {
|
||||
readonly path: string
|
||||
/** Branch created for the checkout. */
|
||||
readonly branch: string
|
||||
/** Requested base branch, or null when the checkout started from HEAD of the source checkout. */
|
||||
/**
|
||||
* Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels
|
||||
* recorded, or null when the checkout started from HEAD of the source checkout.
|
||||
*/
|
||||
readonly from: string | null
|
||||
/** Commit object name the branch started from. */
|
||||
readonly baseCommit: string
|
||||
@@ -930,8 +933,11 @@ interface ForgeSessionWorktree {
|
||||
```ts type-equiv
|
||||
/** Payload of the `plugin:client-ui-forge/worktree` record. */
|
||||
type WorktreeRecord =
|
||||
/** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */
|
||||
| { readonly action: 'request'; readonly from: string | null }
|
||||
/**
|
||||
* Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the
|
||||
* branch `name`, or on a generated branch name when `name` is absent.
|
||||
*/
|
||||
| { readonly action: 'request'; readonly from: string | null; readonly name?: string }
|
||||
/** Withdraw the open request. */
|
||||
| { readonly action: 'cancel' }
|
||||
/** The requested worktree was created and became the Session's working directory. */
|
||||
@@ -945,8 +951,13 @@ type WorktreeRecord =
|
||||
```ts type-equiv
|
||||
/** One open worktree request. */
|
||||
interface ForgeWorktreeRequest {
|
||||
/** Base branch, or null for HEAD of the source checkout. */
|
||||
/**
|
||||
* Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or
|
||||
* null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it.
|
||||
*/
|
||||
readonly from: string | null
|
||||
/** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */
|
||||
readonly name: string | null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -964,12 +975,17 @@ type ForgeWorktreeBlocker =
|
||||
```ts type-equiv
|
||||
/** One running worktree creation. */
|
||||
interface ForgeWorktreeCreation {
|
||||
/** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
/**
|
||||
* Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then
|
||||
* `checkout` writes the files.
|
||||
*/
|
||||
readonly phase: 'fetch' | 'prepare' | 'checkout'
|
||||
/** Branch the attempt creates. */
|
||||
readonly branch: string
|
||||
/** Base branch, or null for HEAD. */
|
||||
/** Base as the request names it, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetches its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/**
|
||||
* Whether a message waits for the creation before its turn starts. Only
|
||||
* such a creation can be stopped, after which the message keeps waiting; a
|
||||
@@ -992,12 +1008,16 @@ interface ForgeWorktreeRestoration {
|
||||
interface ForgeWorktreeFailure {
|
||||
/** Branch the attempt created, or null when it failed before naming one. */
|
||||
readonly branch: string | null
|
||||
/** Base branch of the attempt, or null for HEAD. */
|
||||
/** Base of the attempt as the request names it, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetched, or tried to fetch, its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/** Step that failed. */
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
readonly phase: 'fetch' | 'prepare' | 'checkout'
|
||||
/** Failure text. */
|
||||
readonly message: string
|
||||
/** Whether the branch or the checkout directory of that name already existed, which another name avoids. */
|
||||
readonly exists: boolean
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1028,6 +1048,8 @@ interface ForgePanelWorktree {
|
||||
readonly editable: boolean
|
||||
/** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */
|
||||
readonly blocker: ForgeWorktreeBlocker | null
|
||||
/** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */
|
||||
readonly namePrefix: string
|
||||
/** Open request, or null without one. */
|
||||
readonly request: ForgeWorktreeRequest | null
|
||||
/** Created worktree, or null before creation. */
|
||||
@@ -1088,12 +1110,39 @@ interface ForgePanelState {
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Local branches offered as the base of a new worktree. */
|
||||
interface ForgeBranches {
|
||||
/** Checked-out branch, or null when HEAD is detached. */
|
||||
readonly current: string | null
|
||||
/** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */
|
||||
readonly branches: readonly string[]
|
||||
/** Branches offered as the base of a new worktree whose names contain a query. */
|
||||
interface ForgeWorktreeBases {
|
||||
/** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */
|
||||
readonly current: ForgeBaseBranch | null
|
||||
/** Default branch of each remote that names one with `refs/remotes/<remote>/HEAD`, in remote order. */
|
||||
readonly defaults: readonly ForgeRemoteDefault[]
|
||||
/** Other local branches, most recently committed first, at most `maxBranches`. */
|
||||
readonly local: readonly ForgeBaseBranch[]
|
||||
/**
|
||||
* Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks,
|
||||
* then `origin`, then the others as Git lists them. Remotes without a matching branch are left out.
|
||||
*/
|
||||
readonly remotes: readonly ForgeRemoteBranches[]
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** A remote's default branch, which `refs/remotes/<remote>/HEAD` names. */
|
||||
interface ForgeRemoteDefault extends ForgeBaseBranch {
|
||||
/** Remote the branch belongs to; it may contain `/`. */
|
||||
readonly remote: string
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Remote-tracking branches of one remote, without its default branch. */
|
||||
interface ForgeRemoteBranches {
|
||||
/** Remote name such as `origin`; it may contain `/`. */
|
||||
readonly name: string
|
||||
/** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */
|
||||
readonly repository: string | null
|
||||
/** Branches named `<remote>/<branch>`, most recently committed first, at most `maxBranches`. */
|
||||
readonly branches: readonly ForgeBaseBranch[]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1777,13 +1826,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async worktreeCleanup(session: Session, revision: number | null): Promise<WorktreeCleanup | null>
|
||||
|
||||
/**
|
||||
* List the local branches that can start a worktree of the Session's current checkout.
|
||||
* @param session - Session whose current directory is listed.
|
||||
* List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each
|
||||
* remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the
|
||||
* order the panel recognizes code hosts.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first.
|
||||
* @throws when the current directory is not inside a checkout or Git fails.
|
||||
* @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
*/
|
||||
@Remote async branches(session: Session, signal: AbortSignal): Promise<ForgeBranches>
|
||||
@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases>
|
||||
|
||||
/**
|
||||
* List the branches the `branch` scope of the Session's current checkout can compare with.
|
||||
@@ -2116,18 +2168,23 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
/**
|
||||
* Ask for a new worktree before the Session's first turn, replacing an open
|
||||
* request and forgetting a failed attempt. While the next message waits in
|
||||
* the inbox, or else at the first step proposal, the panel creates a branch
|
||||
* from `from`, or from HEAD of the current checkout when it is null, and
|
||||
* enters its checkout. A message that already waits after a failed or
|
||||
* stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}.
|
||||
* the inbox, or else at the first step proposal, the panel creates the
|
||||
* branch `name`, or a generated branch per attempt when it is null, from
|
||||
* `from`, or from HEAD of the current checkout when it is null, and enters
|
||||
* its checkout; a remote-tracking `from` is fetched first. A message that
|
||||
* already waits after a failed or stopped attempt keeps waiting for
|
||||
* {@link ForgePanelController.retryWorktree}.
|
||||
* @param session - Session without a started turn.
|
||||
* @param from - local base branch, or null for HEAD.
|
||||
* @param from - full name of a local or remote-tracking base branch, or null for HEAD.
|
||||
* @param name - new branch name, or null to generate one per attempt.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable`
|
||||
* @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks
|
||||
* a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`;
|
||||
* `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable`
|
||||
* without a worktree service; `forgePanel/session-started` after a turn started or the worktree was
|
||||
* created; `forgePanel/session-busy` while the worktree is being created.
|
||||
*/
|
||||
@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise<void>
|
||||
@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Withdraw the open worktree request of a Session with its failed attempt,
|
||||
@@ -2150,13 +2207,16 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
@Remote async stopCreation(session: Session, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Make another attempt, with a new branch name, at the worktree a message
|
||||
* of the Session waits for after a failed or stopped attempt.
|
||||
* Make another attempt, on the requested branch name or a new generated
|
||||
* one, at the worktree a message of the Session waits for after a failed or
|
||||
* stopped attempt.
|
||||
* @param session - Session whose message waits.
|
||||
* @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the
|
||||
* commit last fetched.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/not-waiting` when no message waits or an attempt is running.
|
||||
*/
|
||||
@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise<void>
|
||||
@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Check out the created worktree of a Session again at its recorded
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
en: a0def5edd90e9189
|
||||
zh: 96c3f6fa48eb850d
|
||||
/git-worktrees/creation-and-retention:
|
||||
en: 1cce2f01306c7804
|
||||
zh: fe196380757b81d0
|
||||
en: d33f26f44f51da9f
|
||||
zh: 5c7577a1981b297c
|
||||
/git-worktrees/request-and-result:
|
||||
en: 5801c5909e1873a0
|
||||
zh: 5c36a4c4ea97ecad
|
||||
@@ -6,7 +6,7 @@ The experimental [`dsh-experimental-worktree`](../../packages/experimental/workt
|
||||
|
||||
## Creation and retention
|
||||
|
||||
The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. Each name must identify a new branch and an unused checkout path. The operation neither fetches missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout.
|
||||
The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. A request may instead ask to fetch a remote-tracking branch of a configured remote first, which fetches only that branch and pins the fetched commit. Each name must identify a new branch and an unused checkout path. The operation neither fetches other commits or missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout.
|
||||
|
||||
The default destination is `<current checkout root>/.agents/worktrees/<name>`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change.
|
||||
|
||||
@@ -19,12 +19,17 @@ The default destination is `<current checkout root>/.agents/worktrees/<name>`. `
|
||||
The creation request selects only the new name and local revision. The result identifies the created checkout and exact commit; it does not change the Session's original project or write permissions. An entry request names a worktree inside the pool; its result identifies the checkout, the branch checked out there, and the checkout the Session entered from. An optional callback receives each stage of the creation before it begins. A restoration checks a removed checkout out again at its recorded directory, from its branch or, when the branch is gone, from its base commit.
|
||||
|
||||
```ts type-equiv
|
||||
/** A new checkout from a locally available Git commit, branch, or tag. */
|
||||
/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */
|
||||
interface CreateWorktreeRequest {
|
||||
/** New branch name, also used as the relative checkout directory; omission generates a name. */
|
||||
name?: string
|
||||
/** Local revision to resolve before creation; omission selects HEAD. */
|
||||
from?: string
|
||||
/**
|
||||
* Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking
|
||||
* branch, `refs/remotes/<remote>/<branch>`, of a configured remote; only that branch is fetched, without tags.
|
||||
*/
|
||||
fetch?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
@@ -64,12 +69,13 @@ interface EnteredWorktree {
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* Stage of one creation or restoration, reported before it begins: `prepare`
|
||||
* Stage of one creation or restoration, reported before it begins: `fetch`
|
||||
* fetches the remote base branch of a creation that asks for it; `prepare`
|
||||
* validates the request, allocates the checkout directory, and creates the
|
||||
* branch, which a restoration creates again only when it is gone; `checkout`
|
||||
* writes the files and, for a creation, enters the checkout.
|
||||
*/
|
||||
type CreateWorktreePhase = 'prepare' | 'checkout'
|
||||
type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout'
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
@@ -135,19 +141,21 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it.
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch
|
||||
* first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit.
|
||||
* Existing branches or checkout paths fail. Uncommitted files stay in the source checkout.
|
||||
* Checkout disables configured clean, smudge, and process filters without changing Git config.
|
||||
* Repository-local replacement refs still apply; baseCommit reports the resolved object name.
|
||||
* The new checkout becomes current only after Git setup succeeds. Failures may retain newly
|
||||
* allocated Git/filesystem artifacts; no branch or checkout is removed automatically.
|
||||
* @param agent - caller whose current directory selects the source repository and file policy.
|
||||
* @param request - optional new name and local revision; defaults are generated name and HEAD.
|
||||
* @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch.
|
||||
* @param signal - cancellation of lookup, creation, and working-directory publication.
|
||||
* @param onPhase - receives each stage before it begins; it must not throw.
|
||||
* @returns canonical checkout path, branch name, pinned commit, and source repository root.
|
||||
* @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out
|
||||
* command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
* @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a
|
||||
* configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the
|
||||
* fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
*/
|
||||
async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<CreatedWorktree>
|
||||
|
||||
@@ -162,12 +170,12 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS
|
||||
* @param agent - caller whose sandbox policy confines the commands.
|
||||
* @param request - recorded directory, branch, base commit, and source repository root.
|
||||
* @param signal - cancellation of the restoration.
|
||||
* @param onPhase - receives each stage before it begins; it must not throw.
|
||||
* @param onPhase - receives each stage before it begins, never `fetch`; it must not throw.
|
||||
* @returns the directory and whether the branch was created again.
|
||||
* @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized,
|
||||
* or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
*/
|
||||
async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<RestoredWorktree>
|
||||
async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude<CreateWorktreePhase, 'fetch'>) => void, ): Promise<RestoredWorktree>
|
||||
|
||||
/**
|
||||
* Move the calling Session into an existing worktree in the pool of the checkout it works in. The
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
## 创建与保留
|
||||
|
||||
调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。每个名称必须对应新分支与未使用的检出路径。操作既不获取缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。
|
||||
调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。请求也可以要求先获取某个已配置远程的远程跟踪分支,此时只获取这一个分支,并固定获取到的提交。每个名称必须对应新分支与未使用的检出路径。操作既不获取其他提交或缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。
|
||||
|
||||
默认目标为 `<current checkout root>/.agents/worktrees/<name>`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。
|
||||
|
||||
@@ -19,12 +19,17 @@
|
||||
创建请求只选择新名称与本地版本。结果标识创建的检出目录与确切提交;它不会改变 Session 的原始项目或写权限。进入请求给出池内工作树的名称;结果标识检出目录、其中检出的分支,以及 Session 进入前所在的检出。可选的回调会在创建的每个阶段开始之前收到该阶段。恢复会在记录的目录重新检出已删除的检出目录:从它的分支检出;分支也已删除时,从它的基准提交检出。
|
||||
|
||||
```ts type-equiv
|
||||
/** A new checkout from a locally available Git commit, branch, or tag. */
|
||||
/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */
|
||||
interface CreateWorktreeRequest {
|
||||
/** New branch name, also used as the relative checkout directory; omission generates a name. */
|
||||
name?: string
|
||||
/** Local revision to resolve before creation; omission selects HEAD. */
|
||||
from?: string
|
||||
/**
|
||||
* Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking
|
||||
* branch, `refs/remotes/<remote>/<branch>`, of a configured remote; only that branch is fetched, without tags.
|
||||
*/
|
||||
fetch?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
@@ -64,12 +69,13 @@ interface EnteredWorktree {
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* Stage of one creation or restoration, reported before it begins: `prepare`
|
||||
* Stage of one creation or restoration, reported before it begins: `fetch`
|
||||
* fetches the remote base branch of a creation that asks for it; `prepare`
|
||||
* validates the request, allocates the checkout directory, and creates the
|
||||
* branch, which a restoration creates again only when it is gone; `checkout`
|
||||
* writes the files and, for a creation, enters the checkout.
|
||||
*/
|
||||
type CreateWorktreePhase = 'prepare' | 'checkout'
|
||||
type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout'
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
@@ -135,19 +141,21 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it.
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch
|
||||
* first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit.
|
||||
* Existing branches or checkout paths fail. Uncommitted files stay in the source checkout.
|
||||
* Checkout disables configured clean, smudge, and process filters without changing Git config.
|
||||
* Repository-local replacement refs still apply; baseCommit reports the resolved object name.
|
||||
* The new checkout becomes current only after Git setup succeeds. Failures may retain newly
|
||||
* allocated Git/filesystem artifacts; no branch or checkout is removed automatically.
|
||||
* @param agent - caller whose current directory selects the source repository and file policy.
|
||||
* @param request - optional new name and local revision; defaults are generated name and HEAD.
|
||||
* @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch.
|
||||
* @param signal - cancellation of lookup, creation, and working-directory publication.
|
||||
* @param onPhase - receives each stage before it begins; it must not throw.
|
||||
* @returns canonical checkout path, branch name, pinned commit, and source repository root.
|
||||
* @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out
|
||||
* command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
* @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a
|
||||
* configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the
|
||||
* fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
*/
|
||||
async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<CreatedWorktree>
|
||||
|
||||
@@ -162,12 +170,12 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS
|
||||
* @param agent - caller whose sandbox policy confines the commands.
|
||||
* @param request - recorded directory, branch, base commit, and source repository root.
|
||||
* @param signal - cancellation of the restoration.
|
||||
* @param onPhase - receives each stage before it begins; it must not throw.
|
||||
* @param onPhase - receives each stage before it begins, never `fetch`; it must not throw.
|
||||
* @returns the directory and whether the branch was created again.
|
||||
* @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized,
|
||||
* or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
*/
|
||||
async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<RestoredWorktree>
|
||||
async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude<CreateWorktreePhase, 'fetch'>) => void, ): Promise<RestoredWorktree>
|
||||
|
||||
/**
|
||||
* Move the calling Session into an existing worktree in the pool of the checkout it works in. The
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.3/cordis-loader-entry-validation/guide.md
|
||||
/:
|
||||
en: b414093b29c38765
|
||||
zh: 2a69f37a40e35a99
|
||||
/loader-validates-entry-options-and-include-parses-yaml-1-2:
|
||||
en: cf5dc11adadfd1e1
|
||||
zh: 4656ed9a0d4e9087
|
||||
/loader-validates-entry-options-and-include-parses-yaml-1-2/change:
|
||||
en: 3a403b763d8059c8
|
||||
zh: cbbdd8c71474130e
|
||||
/loader-validates-entry-options-and-include-parses-yaml-1-2/migration:
|
||||
en: ff01b0eddb91d5b1
|
||||
zh: 81478d5e1594db65
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Cordis Loader 1.0.0-rc.9 and Include 1.2.0 parse YAML 1.2, reject malformed entries, and return PatchResult from applyEntryPatches."
|
||||
---
|
||||
|
||||
# Loader validates entry options, and Include parses YAML 1.2
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
`@deepseek-ai/cordis-plugin-loader` now carries upstream Loader 1.0.0-rc.9, and `@deepseek-ai/cordis-plugin-include` carries Include 1.2.0. Hand-written `cordis.yml`, `cordis.patch.yml` and overlay files, and code that calls the Include or Loader exports, are affected:
|
||||
|
||||
- Include and `parseEntryYaml` parse YAML 1.2 under the core schema instead of the js-yaml JSON schema. A binary integer such as `0b101` now reads as the string `'0b101'`. An empty `!!js` scalar now reads as an empty expression, which evaluates to `undefined`, instead of failing to parse.
|
||||
- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` must have a `config` list, even an empty one; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and its siblings still start; `dsh` stops startup when the rejected entry is required, such as `webserver`, and warns otherwise. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted.
|
||||
- Parse, entry option and config validation errors name the file position as `file:line:column`. When an entry's own module cannot be found, the error is a `ModuleNotFoundError` without Node's `imported from` part; its `code` is still `ERR_MODULE_NOT_FOUND`.
|
||||
- A patch that replaces a group's `config` brings child entries that later patches can address, and the children it replaces can no longer be patched.
|
||||
- `applyEntryPatches(data, patches, warn)` returns `{ data, index }` instead of the entry list, and writes generated ids into the anonymous entries of a replaced group `config` in `patches`. `parseEntryYaml` throws the `YAMLError` of the `yaml` package instead of a js-yaml `YAMLException`.
|
||||
|
||||
## Migration
|
||||
|
||||
1. Write binary integers that must stay numbers in decimal or hexadecimal.
|
||||
2. Run `dsh --dump-config` for each profile. A parse error now names its line and column; fix the reported value.
|
||||
3. Add `config: []` to every `group: true` entry without `config`, such as a group whose children all come from patch `insert`. Start the profile and check the log for `invalid entry options` and `invalid config`. Correct each listed path at the position shown.
|
||||
4. Where a later patch addressed a child of a group whose `config` an earlier patch replaced, check that the child now receives the patch.
|
||||
5. In code, read `applyEntryPatches(...).data`, and pass `structuredClone(patches)` where the patch list must stay unchanged. Catch parse errors without depending on js-yaml types; `entryYamlErrorPosition(error)` still returns the position.
|
||||
6. Confirm that `dsh --dump-config` prints the expected entries and that the profile starts without those diagnostics.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、拒绝格式错误的条目,applyEntryPatches 改为返回 PatchResult。"
|
||||
---
|
||||
|
||||
# Loader 校验条目选项,Include 按 YAML 1.2 解析
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
`@deepseek-ai/cordis-plugin-loader` 现在包含上游 Loader 1.0.0-rc.9,`@deepseek-ai/cordis-plugin-include` 包含 Include 1.2.0。受影响的是手写的 `cordis.yml`、`cordis.patch.yml` 与 overlay 文件,以及调用 Include 或 Loader 导出的代码:
|
||||
|
||||
- Include 和 `parseEntryYaml` 按 YAML 1.2 core schema 解析,不再使用 js-yaml 的 JSON schema。`0b101` 这样的二进制整数现在读作字符串 `'0b101'`。空的 `!!js` 标量现在读作空表达式,求值结果为 `undefined`,不再解析失败。
|
||||
- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;`group: true` 的条目必须带有 `config` 列表,空列表也要写出;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝,同级条目仍会启动;被拒绝的条目若是 `webserver` 等必需条目,`dsh` 会终止启动,否则输出警告。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。
|
||||
- 解析错误、条目选项错误和配置校验错误都会以 `file:line:column` 指出文件位置。条目自身的模块找不到时,错误为 `ModuleNotFoundError`,不含 Node 的 `imported from` 部分;其 `code` 仍为 `ERR_MODULE_NOT_FOUND`。
|
||||
- 替换 group `config` 的 patch 带来的子条目可以被后续 patch 定位,被替换掉的子条目则不能再被 patch。
|
||||
- `applyEntryPatches(data, patches, warn)` 返回 `{ data, index }`,不再直接返回条目列表;它会把生成的 id 写入 `patches` 中被替换的 group `config` 里的匿名条目。`parseEntryYaml` 抛出 `yaml` 包的 `YAMLError`,不再抛出 js-yaml 的 `YAMLException`。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 必须保持为数字的二进制整数改写为十进制或十六进制。
|
||||
2. 对每个 profile 运行 `dsh --dump-config`。解析错误现在会给出行号和列号;按提示修正对应的值。
|
||||
3. 给每个缺少 `config` 的 `group: true` 条目加上 `config: []`,例如子条目全部来自 patch `insert` 的 group。启动 profile,检查日志中的 `invalid entry options` 和 `invalid config`,在给出的位置修正列出的每个路径。
|
||||
4. 如果后续 patch 针对的是某个 group 的子条目,而该 group 的 `config` 已被前面的 patch 替换,确认该子条目现在会应用这个 patch。
|
||||
5. 在代码中读取 `applyEntryPatches(...).data`;如果 patch 列表必须保持不变,传入 `structuredClone(patches)`。捕获解析错误时不要依赖 js-yaml 的类型;`entryYamlErrorPosition(error)` 仍会返回错误位置。
|
||||
6. 确认 `dsh --dump-config` 输出预期的条目,且 profile 启动时不再出现上述诊断。
|
||||
@@ -36,8 +36,8 @@
|
||||
en: 91d80c444ac0cfe5
|
||||
zh: e7db496043528ffb
|
||||
/deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures:
|
||||
en: 9b9e08c8638a975b
|
||||
zh: 8a3f906c4d98cb89
|
||||
en: 53a9bfee48468abe
|
||||
zh: 34d36ae0e46d8e49
|
||||
/deepseek-ai-dsh-app-boot/understand-the-implementation:
|
||||
en: f4a2695cb4c8a570
|
||||
zh: 89837235d2f376cf
|
||||
|
||||
@@ -97,7 +97,7 @@ The profile templates, installation-owned profile tuples, and retired bundle lis
|
||||
|
||||
Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Explicit enablement targets must activate even when their failure predates the operation. `recomposeProfile(ctx, patches, binName, { requiredIds, running })` runs one recomposition together with the runtime resolution: it removes the rows the generation no longer lists and waits for their disposal while their packages are still mapped, publishes the latest generation of a recomputable resolution, runs the compatibility preflight against the published packages, applies the generation, starts the `running` entries and entries whose import failed that the update left without a running fiber, and judges activation. `running` lists the entries that ran before the caller stopped some of them; each that failed afterwards counts as a new failure. A failure before the generation applies puts the removed rows back at their places, which starts them again, and starts the `running` entries again. An entry waiting for a service is reported as a warning unless it is required, so it starts once a provider appears; `reconcileProfilePatches()` judges it the same way. A publication the resolution rejects is such a failure and reports `package-moved`. `reconcileProfilePatches()`, which the Config Editor uses, applies and judges the patches without publishing the resolution or retrying failed imports. An entry whose import failed is reported with the error Loader's import returns again, so judging it evaluates the module when the import now succeeds; the state recorded before the change imports nothing, so an entry whose import failed before counts as the same failure whatever its error now is. Successful reconciliation emits `app-boot/config-reload` after lifecycle settlement and diagnostic checks, including programmatic updates without HMR. The event carries no diff or parsed config. Successful reconciliation returns after lifecycle settlement and diagnostic checks; volatile-only entry changes are committed by Loader during the update.
|
||||
|
||||
After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update.
|
||||
After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. Entry options that their group rejects count as an entry that could not activate, with the Loader's validation issues and source positions as its error. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update.
|
||||
|
||||
| Failure pattern | Optional entry at startup | Required entry at startup | Later configuration HMR |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -97,7 +97,7 @@ app-boot 应用的 profile 模板、安装方拥有的 profile 组合包元组
|
||||
|
||||
profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。显式启用的目标必须成功激活,即使它的故障早于本次操作。`recomposeProfile(ctx, patches, binName, { requiredIds, running })` 与 runtime resolution 一起执行一次重新组合:它移除新一代组合不再列出的行,并在其包仍有映射时等待这些行释放完成,发布可重新计算的 resolution 的最新一代,使兼容性预检读取已发布的包,应用新一代组合,启动更新后没有运行中 fiber 的 `running` 条目和导入失败的条目,然后判定激活结果。`running` 列出调用方停止其中部分条目之前正在运行的条目;之后每个失败的条目都计为新的故障。新一代组合应用之前的失败会把移除的行放回原位置,从而重新启动它们,并重新启动 `running` 条目。等待服务的条目报告为警告(required 条目除外),因此出现提供方后它即启动;`reconcileProfilePatches()` 以同样方式判定它。resolution 拒绝的发布属于这种失败,并报告 `package-moved`。Config Editor 使用的 `reconcileProfilePatches()` 应用并判定 patch,不发布 resolution,也不重试失败的导入。导入失败的条目以 Loader 再次导入时返回的错误报告,因此若导入现在成功,判定该条目时会对模块求值;变更前记录的激活状态不执行任何导入,因此之前导入失败的条目无论现在的错误是什么,都计为同一个故障。成功重载在生命周期结束及诊断检查通过后发出 `app-boot/config-reload`,包括未启用 HMR 时的程序化更新。事件不携带 diff 或解析后的配置。成功重载在生命周期结束及诊断检查通过后返回;仅 volatile 的条目变化由 Loader 在更新过程中提交。
|
||||
|
||||
Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。
|
||||
Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。被所在 group 拒绝的条目选项也视为无法激活的条目,其错误是 Loader 的校验问题及源码位置。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。
|
||||
|
||||
| 失败模式 | Optional 条目启动时 | Required 条目启动时 | 后续配置 HMR |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {} from './profile-resolution/service.ts'
|
||||
import type {} from './profile-context.ts'
|
||||
import { evaluatePluginCompatibility, pluginCompatibilityWarning } from './plugin-compatibility.ts'
|
||||
import { readProfileCompatibility } from './profile-compatibility.ts'
|
||||
import { includeFilename } from './include-filename.ts'
|
||||
|
||||
function readManifest(filename: string): object {
|
||||
return JSON.parse(readFileSync(filename, 'utf8')) as object
|
||||
@@ -144,7 +145,7 @@ function preflight(
|
||||
// A dynamic Include is resolved by the Include plugin itself; this walk cannot judge its rows.
|
||||
return undefined
|
||||
}
|
||||
const requested = isAbsolute(config.path) ? config.path : fileURLToPath(new URL(config.path, base))
|
||||
const requested = includeFilename(config.path, base)
|
||||
const filename = existsSync(requested) ? realpathSync(requested) : requested
|
||||
if (includes.has(filename)) return undefined
|
||||
includes.add(filename)
|
||||
@@ -156,7 +157,7 @@ function preflight(
|
||||
data = config.initial
|
||||
}
|
||||
if (!Array.isArray(data)) return undefined
|
||||
const children = applyEntryPatches(data as EntryOptions[], config.patches, patchWarning(ctx))
|
||||
const children = applyEntryPatches(data as EntryOptions[], structuredClone(config.patches), patchWarning(ctx)).data
|
||||
return check(children, pathToFileURL(filename).href)
|
||||
? `its included file ${filename} reaches an incompatible plugin, and that file is never rewritten`
|
||||
: undefined
|
||||
@@ -180,7 +181,7 @@ export function prepareProfilePatches(
|
||||
ctx: Context, patches: PatchOptions[], parentURL: string, binName = 'dsh',
|
||||
): PatchOptions[] {
|
||||
if (ctx.get('profileContext') === undefined) return patches
|
||||
const entries = applyEntryPatches([], patches, patchWarning(ctx))
|
||||
const entries = applyEntryPatches([], structuredClone(patches), patchWarning(ctx)).data
|
||||
const rows = prepareProfileEntries(ctx, entries, parentURL, binName)
|
||||
return rows.length === 0 ? [] : [{ insert: rows }]
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { readFile, realpath } from 'node:fs/promises'
|
||||
import { extname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import Loader, { EntryGroup, ModuleLoader, isJsExpr, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
|
||||
import Group from '@deepseek-ai/cordis-plugin-group'
|
||||
import Include, { applyEntryPatches, entryYamlErrorPosition, parseEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
|
||||
@@ -11,6 +11,7 @@ import { installRuntimeInterception } from '../profile-resolution/resolver.ts'
|
||||
import { buildConfigSchemaDocument } from './document.ts'
|
||||
import type { CollectedConfigEntry, ConfigSchemaDiagnostic, ConfigSchemaDump } from './types.ts'
|
||||
import { isNativeConfigSchema } from './native.ts'
|
||||
import { includeFilename } from '../include-filename.ts'
|
||||
|
||||
interface ParsedEntry {
|
||||
id?: string
|
||||
@@ -52,6 +53,10 @@ function entryList(value: unknown): unknown[] {
|
||||
return value as unknown[]
|
||||
}
|
||||
|
||||
function hasNonRecordEntry(rows: readonly unknown[]): boolean {
|
||||
return rows.some(row => !record(row) || (row.group === true && Array.isArray(row.config) && hasNonRecordEntry(row.config)))
|
||||
}
|
||||
|
||||
function includePatches(value: unknown): PatchOptions[] | undefined {
|
||||
if (value === undefined) return undefined
|
||||
if (!Array.isArray(value)) throw new Error('include patches must be a literal patch list; config expressions are not evaluated')
|
||||
@@ -125,7 +130,7 @@ export async function collectConfigSchemas(
|
||||
if (config === undefined) throw new Error('include config is missing')
|
||||
if (!record(config) || isJsExpr(config)) throw new Error('include config must be literal; config expressions are not evaluated')
|
||||
if (typeof config.path !== 'string') throw new Error('include path must be literal; config expressions are not evaluated')
|
||||
const filename = fileURLToPath(new URL(config.path, baseUrl))
|
||||
const filename = includeFilename(config.path, baseUrl)
|
||||
const extension = extname(filename)
|
||||
if (!['.json', '.yaml', '.yml'].includes(extension)) throw new Error(`include extension ${JSON.stringify(extension)} is not supported`)
|
||||
let source: unknown
|
||||
@@ -157,9 +162,11 @@ export async function collectConfigSchemas(
|
||||
}
|
||||
const patches = includePatches(config.patches)
|
||||
const rows = entryList(source)
|
||||
// Include rejects the whole file when any entry, including a group child, is not a mapping.
|
||||
if (hasNonRecordEntry(rows)) throw new Error(`include ${filename} has an entry that is not a mapping; child declarations are unavailable`)
|
||||
let children: EntryOptions[]
|
||||
try {
|
||||
children = applyEntryPatches(rows as EntryOptions[], patches, warn(path))
|
||||
children = applyEntryPatches(rows as EntryOptions[], structuredClone(patches), warn(path)).data
|
||||
} catch (error) {
|
||||
throw new Error(`include patches could not be composed for ${filename}; child declarations are unavailable`, { cause: error })
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ function metadata(): Record<string, ConfigJsonSchema> {
|
||||
id: { type: 'string', description: 'Entry id. Loader generates an id when an entry omits it; patches use the configured id.' },
|
||||
name: { type: 'string', description: 'Plugin module specifier. Inserted relative plugin paths are anchored beside their patch file.' },
|
||||
config: {},
|
||||
group: { type: ['boolean', 'null'], description: 'Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation.' },
|
||||
group: { type: ['boolean', 'null'], description: 'Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation.' },
|
||||
disabled: { anyOf: [{ type: ['boolean', 'null'] }, ref('loaderExpression')], description: 'Boolean or !!js expression. The Loader coerces other truthy values as disabled; this schema rejects them.' },
|
||||
inject: { anyOf: [{ type: 'array', items: { type: 'string' } }, { type: 'object' }, { type: 'null' }] },
|
||||
intercept: { type: ['object', 'null'] },
|
||||
@@ -129,8 +129,13 @@ export async function buildConfigSchemaDocument(
|
||||
diagnostics.push({ level: 'warning', message: `Plugin ${JSON.stringify(name)} has multiple collected schemas; entry validation accepts their union because module resolution depends on the owning tree.` })
|
||||
}
|
||||
}
|
||||
// The Loader rejects a group entry without an entry-list config, disabled or not.
|
||||
const groupRule: ConfigJsonSchema = {
|
||||
if: { properties: { group: { const: true } }, required: ['group'] },
|
||||
then: { properties: { config: ref('entryList') }, required: ['config'] },
|
||||
}
|
||||
definitions.entry = {
|
||||
type: 'object', required: ['name'], allOf: [ref('entryMetadata'), ...entryRules],
|
||||
type: 'object', required: ['name'], allOf: [ref('entryMetadata'), groupRule, ...entryRules],
|
||||
description: 'Loader entry. Unknown metadata and plugin names are accepted; plugin-specific validation is available only for the names collected in this profile. Distinct resolutions of one name use a union of their schemas.',
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Resolve an Include `path` to the file the Include plugin reads. */
|
||||
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
// A Windows drive-letter path, e.g. `C:\app\cordis.yml` or `C:/app/cordis.yml`.
|
||||
const DRIVE_LETTER = /^[A-Za-z]:[\\/]/u
|
||||
|
||||
/**
|
||||
* Resolve an Include `path` as the vendored Include does: on Windows a drive-letter path is a file path, and every
|
||||
* other path is a URL reference resolved against the owning tree's base URL.
|
||||
* @param path - literal Include `path`.
|
||||
* @param baseUrl - base URL of the tree that owns the Include entry.
|
||||
* @param platform - platform whose path rules apply to both branches; defaults to the running one.
|
||||
* @returns the absolute filename.
|
||||
* @throws when `path` resolves to a URL that is not a `file:` URL.
|
||||
*/
|
||||
export function includeFilename(path: string, baseUrl: string, platform: NodeJS.Platform = process.platform): string {
|
||||
const windows = platform === 'win32'
|
||||
if (windows && DRIVE_LETTER.test(path)) return fileURLToPath(pathToFileURL(path, { windows }), { windows })
|
||||
return fileURLToPath(new URL(path, baseUrl), { windows })
|
||||
}
|
||||
@@ -13,7 +13,9 @@ import { captureStartupComposition, type StartupCompositionDiagnostic } from './
|
||||
export type { StartupCompositionDiagnostic, StartupPluginState, StartupServiceState } from './startup-diagnostics.ts'
|
||||
import { basename, dirname, isAbsolute, resolve } from 'node:path'
|
||||
import { Context, type Fiber, type FiberState } from '@deepseek-ai/cordis'
|
||||
import Loader, { type Entry, type EntryGroup, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
|
||||
import Loader, {
|
||||
EntryTree, EntryValidationError, formatIssues, relocate, validateOptions, type Entry, type EntryGroup, type EntryOptions,
|
||||
} from '@deepseek-ai/cordis-plugin-loader'
|
||||
import Include, { applyEntryPatches, parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
|
||||
import Group from '@deepseek-ai/cordis-plugin-group'
|
||||
import { dshHomePath, dshPath, resolveDshHome } from '@deepseek-ai/dsh-home-paths'
|
||||
@@ -349,9 +351,10 @@ async function recompose(
|
||||
if (entry === undefined) throw new Error(`${binName}: profile reload requires the root Include entry`)
|
||||
// Reading the prior state imports nothing, so plugin code does not run before the next resolution publishes.
|
||||
const previousFailures = (await inactiveEntries(ctx, false)).map((failure): RecordedFailure => ({
|
||||
entry: failure.entry, fiber: failure.entry.fiber, options: JSON.stringify(failure.entry.options),
|
||||
entry: failure.entry, fiber: failure.entry?.fiber, options: JSON.stringify(failure.options),
|
||||
// An entry without a running fiber has no import error yet; the judgment after the update reads it.
|
||||
diagnostic: failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined,
|
||||
// Rejected options have no entry, and their diagnostic depends only on the options.
|
||||
diagnostic: failure.entry === undefined || failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined,
|
||||
}))
|
||||
// Removed entries leave the Loader store before their async disposers finish.
|
||||
const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [row.fiber])
|
||||
@@ -410,11 +413,11 @@ async function recompose(
|
||||
await ctx.loader.await()
|
||||
const failures = await inactiveEntries(ctx)
|
||||
const introduced = failures.filter((failure) => {
|
||||
if (requiredIds.includes(failure.entry.options.id)) return true
|
||||
if (requiredIds.includes(failure.id)) return true
|
||||
// An entry waiting for a service starts once a provider appears.
|
||||
if (failure.outcome.kind === 'pending') return false
|
||||
// An entry that ran before the caller stopped it is a new failure even when it failed the same way before.
|
||||
if (running.includes(failure.entry)) return true
|
||||
if (failure.entry !== undefined && running.includes(failure.entry)) return true
|
||||
return !previousFailures.some(previous => sameFailure(previous, failure))
|
||||
})
|
||||
if (introduced.length > 0) throw new Error(activationDiagnostic(binName, introduced, false).trimEnd())
|
||||
@@ -435,7 +438,7 @@ async function recompose(
|
||||
// A restored row is a new Loader entry with the id of the one that ran.
|
||||
const ran = new Set(running.map(row => row.options.id))
|
||||
for (const failure of await inactiveEntries(ctx)) {
|
||||
if (ran.has(failure.entry.options.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`)
|
||||
if (ran.has(failure.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`)
|
||||
}
|
||||
} catch (error) {
|
||||
// The recomposition's own failure is the outcome.
|
||||
@@ -447,7 +450,7 @@ async function recompose(
|
||||
|
||||
/** An inactive entry as a recomposition found it before changing anything. */
|
||||
interface RecordedFailure {
|
||||
entry: Entry
|
||||
entry: Entry | undefined
|
||||
fiber: Fiber | undefined
|
||||
/** The entry's options as JSON. */
|
||||
options: string
|
||||
@@ -457,8 +460,8 @@ interface RecordedFailure {
|
||||
|
||||
/** Whether an inactive entry is the failure recorded before: the same entry, fiber and options, and a matching diagnostic. */
|
||||
function sameFailure(previous: RecordedFailure, failure: InactiveEntry): boolean {
|
||||
return previous.entry === failure.entry && previous.fiber === failure.entry.fiber
|
||||
&& previous.options === JSON.stringify(failure.entry.options)
|
||||
return previous.entry === failure.entry && previous.fiber === failure.entry?.fiber
|
||||
&& previous.options === JSON.stringify(failure.options)
|
||||
&& (previous.diagnostic === undefined || previous.diagnostic === reloadDiagnostic(failure))
|
||||
}
|
||||
|
||||
@@ -480,7 +483,7 @@ function rowIds(patches: readonly PatchOptions[]): Set<string> {
|
||||
}
|
||||
}
|
||||
// Patch warnings are logged when the generation itself is prepared.
|
||||
visit(applyEntryPatches([], patches as PatchOptions[], () => {}))
|
||||
visit(applyEntryPatches([], patches as PatchOptions[], () => {}).data)
|
||||
return ids
|
||||
}
|
||||
|
||||
@@ -614,9 +617,9 @@ export interface ConfigDumpLayer {
|
||||
* Compose the configured entry list: parse the base config file with the
|
||||
* include's entry-list dialect, apply every layer's patches as ONE flattened
|
||||
* list through the include's own patch algorithm (`applyEntryPatches`) — the
|
||||
* same call `boot()` makes, so even patch-visibility corner cases (a later
|
||||
* layer targeting a group child a plain config replacement introduced, which
|
||||
* the single-pass id index never sees) compose identically — then render the
|
||||
* same call `boot()` makes, so patch-visibility cases (a later layer
|
||||
* targeting a group child that a group config replacement introduced or
|
||||
* removed) compose identically — then render the
|
||||
* result as YAML in the same dialect (`!!js` expressions print verbatim,
|
||||
* unevaluated). Row admission is a later stage: a plugin row the compatibility
|
||||
* policy denies still appears here, while a denied bundle contributes no layer.
|
||||
@@ -670,17 +673,22 @@ export function renderConfigDump(
|
||||
const base = parsed as Parameters<typeof applyEntryPatches>[0]
|
||||
// snapshot_k = ONE application of layers 1..k flattened, using the exact
|
||||
// arguments boot passes for that prefix. snapshot_N is the mounted composition.
|
||||
// The patches are cloned per call: applyEntryPatches clones entries and
|
||||
// inserted rows but assigns override values such as `config` by reference,
|
||||
// so each snapshot keeps its own copies of those values.
|
||||
const snapshot = (count: number, warnings: string[]): ReturnType<typeof applyEntryPatches> => {
|
||||
const flattened = structuredClone(layers.slice(0, count).flatMap(layer => layer.patches))
|
||||
return applyEntryPatches(base, flattened, (message: string, ...args: unknown[]) => {
|
||||
// applyEntryPatches writes the ids it generates for anonymous children of a
|
||||
// replaced group config onto those patch entries, so one full composition
|
||||
// assigns them first and every prefix reuses them. Composition holds a
|
||||
// supplied `config` array by reference and appends later inserts to it, so
|
||||
// that run reads copies of the arrays, and each snapshot composes its own clone.
|
||||
const patches = structuredClone(layers.flatMap(layer => layer.patches))
|
||||
applyEntryPatches(base, patches.map(patch => Array.isArray(patch.config) ? { ...patch, config: patch.config.slice() } : patch))
|
||||
const ends: number[] = []
|
||||
for (const layer of layers) ends.push((ends.at(-1) ?? 0) + layer.patches.length)
|
||||
const snapshot = (count: number, warnings: string[]): ReturnType<typeof applyEntryPatches>['data'] => {
|
||||
return applyEntryPatches(base, structuredClone(patches.slice(0, ends[count - 1])), (message: string, ...args: unknown[]) => {
|
||||
// The include logs through cordis's printf-style logger (`%C` = code); a
|
||||
// dump has no logger, so substitute inline for a plain line.
|
||||
let index = 0
|
||||
warnings.push(message.replace(/%C/g, () => JSON.stringify(args[index++])))
|
||||
})
|
||||
}).data
|
||||
}
|
||||
let previous = base
|
||||
let previousWarnings: string[] = []
|
||||
@@ -990,8 +998,14 @@ function formatActivationError(error: unknown, stacks = true): string {
|
||||
}
|
||||
|
||||
interface InactiveEntry {
|
||||
/** Loader entry used to identify the bootstrap Include and required ids. */
|
||||
entry: Entry
|
||||
/** Loader entry used to identify the bootstrap Include; absent for options their group rejected before creating one. */
|
||||
entry: Entry | undefined
|
||||
/** Entry id used for required ids, or `(no id)` for rejected options without a string id. */
|
||||
id: string
|
||||
/** Module specifier; for rejected options, a non-string `name` rendered as JSON. */
|
||||
name: string
|
||||
/** The options the group lists for this entry. */
|
||||
options: unknown
|
||||
/** Activation errors and missing services remain distinct for presentation. */
|
||||
outcome: { kind: 'failed'; error: unknown; phase?: string }
|
||||
| { kind: 'pending'; missing: string[] }
|
||||
@@ -1046,8 +1060,45 @@ async function importFailure(entry: Entry): Promise<unknown> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Identity fields of an inactive Loader entry. */
|
||||
function identify(entry: Entry): Pick<InactiveEntry, 'entry' | 'id' | 'name' | 'options'> {
|
||||
return { entry, id: entry.options.id, name: entry.options.name, options: entry.options }
|
||||
}
|
||||
|
||||
/** Groups whose option lists the Loader reconciled: the root group and those of active group and Include entries. */
|
||||
function activeGroups(ctx: Context): EntryGroup[] {
|
||||
const groups = [ctx.loader.root]
|
||||
for (const entry of ctx.loader.entries()) {
|
||||
if (entry.subgroup !== undefined && entry.fiber?.state === FIBER_ACTIVE) groups.push(entry.subgroup)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect Loader activation failures and disabled-expression errors. Failed
|
||||
* Options that a group lists but rejected before creating an entry, checked with the Loader's own rule.
|
||||
* The group only logs such a rejection, so each one is reported here with its source position when its tree has one.
|
||||
*/
|
||||
function rejectedOptions(ctx: Context): InactiveEntry[] {
|
||||
return activeGroups(ctx).flatMap(group => group.data.flatMap((options: unknown): InactiveEntry[] => {
|
||||
const issues = validateOptions(options, EntryTree.sep)
|
||||
if (issues.length === 0) return []
|
||||
const row: { id?: unknown; name?: unknown } = typeof options === 'object' && options !== null ? options : {}
|
||||
const id = typeof row.id === 'string' ? row.id : undefined
|
||||
const error = new EntryValidationError(issues)
|
||||
// Source positions are found by id, so options without one keep the plain message.
|
||||
if (id !== undefined) {
|
||||
const frames = group.getOuterStack(id)
|
||||
if (frames.length > 0) relocate(error, formatIssues('invalid entry options', issues, path => group.tree.getLocation(id, path)), frames)
|
||||
}
|
||||
return [{
|
||||
entry: undefined, id: id ?? '(no id)', name: typeof row.name === 'string' ? row.name : row.name === undefined ? 'undefined' : JSON.stringify(row.name),
|
||||
options, outcome: { kind: 'failed', error, phase: 'invalid entry options' },
|
||||
}]
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect Loader activation failures, disabled-expression errors and options their group rejected. Failed
|
||||
* fibers are awaited to recover their recorded rejection reason and coalesce
|
||||
* duplicate Loader notifications through the next process rejection checkpoint.
|
||||
* An entry whose import failed reports the error importing it raises now; without
|
||||
@@ -1060,14 +1111,14 @@ async function inactiveEntries(ctx: Context, importNow = true): Promise<Inactive
|
||||
try {
|
||||
if (entry.disabled) continue
|
||||
} catch (error) {
|
||||
failures.push({ entry, outcome: { kind: 'failed', error, phase: 'disabled expression failed' } })
|
||||
failures.push({ ...identify(entry), outcome: { kind: 'failed', error, phase: 'disabled expression failed' } })
|
||||
continue
|
||||
}
|
||||
const fiber = entry.fiber
|
||||
// An entry whose import failed has no fiber, or keeps the disposed fiber of its previous activation.
|
||||
if (fiber === undefined || fiber.state === FIBER_DISPOSED) {
|
||||
const error = importNow ? await importFailure(entry) : undefined
|
||||
failures.push({ entry, outcome: error === undefined
|
||||
failures.push({ ...identify(entry), outcome: error === undefined
|
||||
? { kind: 'failed', error: fiber === undefined ? 'failed to import' : `fiber state ${String(fiber.state)}` }
|
||||
: { kind: 'failed', error, phase: 'failed to import' } })
|
||||
continue
|
||||
@@ -1079,20 +1130,21 @@ async function inactiveEntries(ctx: Context, importNow = true): Promise<Inactive
|
||||
await fiber.await()
|
||||
} catch (error) {
|
||||
rejectionReasons.push(error)
|
||||
failures.push({ entry, outcome: { kind: 'failed', error } })
|
||||
failures.push({ ...identify(entry), outcome: { kind: 'failed', error } })
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (state === FIBER_PENDING) {
|
||||
const missing = Object.keys(fiber.inject).filter(service => fiber.ctx.get(service) === undefined)
|
||||
failures.push({
|
||||
entry,
|
||||
...identify(entry),
|
||||
outcome: { kind: 'pending', missing },
|
||||
})
|
||||
} else {
|
||||
failures.push({ entry, outcome: { kind: 'failed', error: `fiber state ${String(state)}` } })
|
||||
failures.push({ ...identify(entry), outcome: { kind: 'failed', error: `fiber state ${String(state)}` } })
|
||||
}
|
||||
}
|
||||
failures.push(...rejectedOptions(ctx))
|
||||
if (rejectionReasons.length > 0) await observeLoaderRejectionCheckpoint(rejectionReasons)
|
||||
return failures
|
||||
}
|
||||
@@ -1118,31 +1170,31 @@ function reloadDiagnostic(failure: InactiveEntry): string {
|
||||
}
|
||||
|
||||
/** Stable per-entry text for reload comparisons and optional warnings. */
|
||||
function inactiveDiagnostic({ entry, outcome }: InactiveEntry, stacks = true): string {
|
||||
function inactiveDiagnostic({ id, name, outcome }: InactiveEntry, stacks = true): string {
|
||||
const detail = outcome.kind === 'failed' ? failureDetail(outcome, stacks)
|
||||
: `pending (waiting for ${outcome.missing.length === 1 ? 'service' : 'services'}: ${outcome.missing.join(', ') || 'unknown'})`
|
||||
return `${entry.options.id} (${entry.options.name}): ${detail}`
|
||||
return `${id} (${name}): ${detail}`
|
||||
}
|
||||
|
||||
/** Group startup failures and pending services, marking every required entry. */
|
||||
function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], required: ReadonlySet<Entry>): string {
|
||||
function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], required: ReadonlySet<InactiveEntry>): string {
|
||||
const lines = [`${binName}: startup failed: ${String(required.size)} required ${required.size === 1 ? 'plugin' : 'plugins'} did not activate`]
|
||||
const failed = failures.flatMap(({ entry, outcome }) => outcome.kind === 'failed' ? [{ entry, outcome }] : [])
|
||||
const pending = failures.flatMap(({ entry, outcome }) => outcome.kind === 'pending' ? [{ entry, outcome }] : [])
|
||||
pending.sort((left, right) => Number(required.has(right.entry)) - Number(required.has(left.entry)))
|
||||
const label = (entry: Entry): string => `${entry.options.id}${required.has(entry) ? ' (required)' : ''}`
|
||||
const failed = failures.flatMap(failure => failure.outcome.kind === 'failed' ? [{ failure, outcome: failure.outcome }] : [])
|
||||
const pending = failures.flatMap(failure => failure.outcome.kind === 'pending' ? [{ failure, outcome: failure.outcome }] : [])
|
||||
pending.sort((left, right) => Number(required.has(right.failure)) - Number(required.has(left.failure)))
|
||||
const label = (failure: InactiveEntry): string => `${failure.id}${required.has(failure) ? ' (required)' : ''}`
|
||||
if (failed.length > 0) {
|
||||
lines.push('', `Failed plugins (${String(failed.length)}):`)
|
||||
for (const { entry, outcome } of failed) {
|
||||
lines.push(` ${label(entry)}`, ` Package: ${entry.options.name}`)
|
||||
for (const { failure, outcome } of failed) {
|
||||
lines.push(` ${label(failure)}`, ` Package: ${failure.name}`)
|
||||
lines.push(...failureDetail(outcome).split('\n').map(line => ` ${line}`))
|
||||
}
|
||||
}
|
||||
if (pending.length > 0) {
|
||||
const width = Math.max('Plugin'.length, ...pending.map(({ entry }) => label(entry).length)) + 2
|
||||
const width = Math.max('Plugin'.length, ...pending.map(({ failure }) => label(failure).length)) + 2
|
||||
lines.push('', `Plugins waiting for services (${String(pending.length)}):`, ` ${'Plugin'.padEnd(width)}Missing services`)
|
||||
for (const { entry, outcome } of pending) {
|
||||
lines.push(` ${label(entry).padEnd(width)}${outcome.missing.join(', ') || 'unknown'}`)
|
||||
for (const { failure, outcome } of pending) {
|
||||
lines.push(` ${label(failure).padEnd(width)}${outcome.missing.join(', ') || 'unknown'}`)
|
||||
}
|
||||
}
|
||||
return lines.join('\n')
|
||||
@@ -1151,7 +1203,8 @@ function startupDiagnostic(binName: string, failures: readonly InactiveEntry[],
|
||||
/**
|
||||
* Apply DSH startup policy to a settled Loader tree.
|
||||
*
|
||||
* Inactive entries from the global required list reject startup. Other
|
||||
* Inactive entries from the global required list reject startup, including
|
||||
* options that their group rejected before creating an entry. Other
|
||||
* inactive entries join that failure diagnostic, or produce one warning when
|
||||
* no required entry failed and leave successful siblings running.
|
||||
* Required ids absent from the tree, and disabled required entries, are ignored.
|
||||
@@ -1170,11 +1223,12 @@ export async function auditStartupEntries(
|
||||
warn: (line: string) => void = line => void process.stderr.write(line),
|
||||
): Promise<void> {
|
||||
const failures = await inactiveEntries(ctx)
|
||||
const required = new Set(failures.filter(({ entry }) => entry === bootstrapIncludes.get(ctx)
|
||||
|| requiredStartupEntryIds.has(entry.options.id)).map(({ entry }) => entry))
|
||||
const required = new Set(failures.filter(failure => (failure.entry !== undefined && failure.entry === bootstrapIncludes.get(ctx))
|
||||
|| requiredStartupEntryIds.has(failure.id)))
|
||||
if (required.size > 0) {
|
||||
throw new StartupError(startupDiagnostic(binName, failures, required), failures.map(({ entry, outcome }) => ({
|
||||
id: entry.options.id, module: entry.options.name, required: required.has(entry), fiberState: entry.fiber?.state, outcome,
|
||||
throw new StartupError(startupDiagnostic(binName, failures, required), failures.map(failure => ({
|
||||
id: failure.id, module: failure.name, required: required.has(failure),
|
||||
fiberState: failure.entry?.fiber?.state, outcome: failure.outcome,
|
||||
})))
|
||||
}
|
||||
if (failures.length > 0) warn(activationDiagnostic(binName, failures))
|
||||
|
||||
@@ -758,5 +758,5 @@ export function composeEntries(
|
||||
return applyEntryPatches([], structuredClone(layers.flat()), (message: string, ...args: unknown[]) => {
|
||||
let index = 0
|
||||
warn(message.replace(/%C/g, () => JSON.stringify(args[index++])))
|
||||
})
|
||||
}).data
|
||||
}
|
||||
@@ -25,6 +25,13 @@ const tmp = (): string => {
|
||||
return dir
|
||||
}
|
||||
|
||||
|
||||
/** Give a fake Loader the root group that the startup audit reads for rejected options. */
|
||||
function withRoot(ctx: Context, rows: unknown[] = []): Context {
|
||||
const root = { data: rows, getOuterStack: () => [] }
|
||||
Object.assign(ctx.loader, { root })
|
||||
return ctx
|
||||
}
|
||||
describe('resolveConfigPath', () => {
|
||||
it('resolves relative to the given cwd outside replay mode', () => {
|
||||
expect(resolveConfigPath('./cordis.yml', undefined, `${sep}base`)).toBe(resolve(`${sep}base`, 'cordis.yml'))
|
||||
@@ -484,7 +491,7 @@ describe('installFailLoud', () => {
|
||||
installFailLoud(NAME, proc)
|
||||
const error = new Error('assembled activation failure')
|
||||
const warn = vi.fn()
|
||||
const audit = auditStartupEntries({
|
||||
const audit = auditStartupEntries(withRoot({
|
||||
loader: {
|
||||
entries: () => ['broken-a', 'broken-b'].map(name => ({
|
||||
options: { id: name, name },
|
||||
@@ -496,7 +503,7 @@ describe('installFailLoud', () => {
|
||||
},
|
||||
})),
|
||||
},
|
||||
} as unknown as Context, NAME, warn)
|
||||
} as unknown as Context), NAME, warn)
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
proc.rejection(error)
|
||||
@@ -631,9 +638,9 @@ describe('auditStartupEntries', () => {
|
||||
parent?: { tree: { import(name: string): Promise<unknown> } }
|
||||
}
|
||||
|
||||
const ctxWith = (entries: FakeEntry[]): Context => ({
|
||||
const ctxWith = (entries: FakeEntry[], rows: unknown[] = []): Context => withRoot(({
|
||||
loader: { entries: () => entries.values() },
|
||||
}) as unknown as Context
|
||||
}) as unknown as Context, rows)
|
||||
|
||||
const fiber = (
|
||||
state: number,
|
||||
@@ -792,6 +799,29 @@ describe('auditStartupEntries', () => {
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails startup for required options their group rejected and lists optional ones', async () => {
|
||||
const error = await auditStartupEntries(ctxWith([], [
|
||||
{ id: 'webserver', name: './webserver.mjs', disabled: 'yes' },
|
||||
{ id: 'tool-todo', name: 7 },
|
||||
{ id: 'valid', name: './valid.mjs' },
|
||||
]), NAME, vi.fn()).catch((error: unknown) => error)
|
||||
expect(error).toBeInstanceOf(StartupError)
|
||||
const message = (error as Error).message
|
||||
expect(message).toContain(`${NAME}: startup failed: 1 required plugin did not activate`)
|
||||
expect(message).toContain(' webserver (required)\n Package: ./webserver.mjs\n invalid entry options: EntryValidationError: invalid entry options:\n - disabled must be a boolean (at disabled)')
|
||||
expect(message).toContain(' tool-todo\n Package: 7\n')
|
||||
expect(message).not.toContain('valid.mjs')
|
||||
expect((error as StartupError).entries.map(entry => [entry.id, entry.required, entry.fiberState])).toEqual([
|
||||
['webserver', true, undefined], ['tool-todo', false, undefined],
|
||||
])
|
||||
})
|
||||
|
||||
it('warns about rejected options without an id', async () => {
|
||||
const warn = vi.fn()
|
||||
await auditStartupEntries(ctxWith([], [null]), NAME, warn)
|
||||
expect(warn).toHaveBeenCalledWith(expect.stringContaining('(no id) (undefined): invalid entry options:'))
|
||||
})
|
||||
|
||||
it('omits an error cause when required plugins are only waiting for services', async () => {
|
||||
const error = await auditStartupEntries(ctxWith([
|
||||
{ fiber: fiber(0, undefined, { webStartup: {} }), options: { id: 'connection', name: './connection.mjs' } },
|
||||
@@ -887,7 +917,7 @@ describe('loadOverlayPatches', () => {
|
||||
expect(loadOverlayPatches(NAME, valid)).toEqual([{ id: 'target', config: { value: { __jsExpr: 'process.env.VALUE' } } }])
|
||||
expect(() => loadOverlayPatches(NAME, join(dir, 'missing.yml'))).toThrow(`${NAME}: failed to read overlay`)
|
||||
const malformed = join(dir, 'malformed.yml')
|
||||
writeFileSync(malformed, ': bad')
|
||||
writeFileSync(malformed, '- [bad\n')
|
||||
expect(() => loadOverlayPatches(NAME, malformed)).toThrow(`${NAME}: failed to parse overlay`)
|
||||
const mapping = join(dir, 'mapping.yml')
|
||||
writeFileSync(mapping, 'id: target\n')
|
||||
@@ -1202,7 +1232,7 @@ describe('boot', () => {
|
||||
|
||||
it.each([
|
||||
['missing', undefined, 'config file not found'],
|
||||
['malformed', 'invalid: [unclosed\n', 'unexpected end'],
|
||||
['malformed', 'invalid: [unclosed\n', 'must be sufficiently indented and end with a ] (at '],
|
||||
['non-array', 'entries: []\n', 'top-level array'],
|
||||
])('rejects a %s root configuration', async (_kind, content, message) => {
|
||||
const dir = tmp()
|
||||
|
||||
@@ -115,12 +115,9 @@ describe('renderConfigDump', () => {
|
||||
})
|
||||
|
||||
it('composes all layers as one flattened patch list, exactly like boot()', () => {
|
||||
// boot() flattens every layer into ONE applyEntryPatches call, whose id
|
||||
// index sees inserted rows but NOT children introduced by a plain group
|
||||
// `config` replacement. A per-layer composition would rebuild the index
|
||||
// between layers and let the second layer patch that child — a tree the
|
||||
// real boot never mounts. Pin the single-call semantics: the child patch
|
||||
// is skipped (with the layer-labeled warning), matching boot.
|
||||
// boot() flattens every layer into ONE applyEntryPatches call. Children
|
||||
// supplied by a group `config` replacement join the id index, so a later
|
||||
// layer can patch them, and the dump lists that layer on the group row.
|
||||
const dir = tmp()
|
||||
const base = join(dir, 'base.yml')
|
||||
writeFileSync(base, [
|
||||
@@ -138,14 +135,50 @@ describe('renderConfigDump', () => {
|
||||
},
|
||||
{ label: 'b.yml', patches: [{ id: 'child', config: { v: 2 } }] },
|
||||
], line => void warnings.push(line))
|
||||
expect(warnings).toEqual([`${NAME}: [b.yml] patch: entry "child" not found`])
|
||||
expect(warnings).toEqual([])
|
||||
const parsed = parseEntryYaml(dump) as {
|
||||
config?: { config?: { v?: number } }[]
|
||||
}[]
|
||||
expect(parsed[0]?.config?.[0]?.config?.v).toBe(1)
|
||||
// The skipped layer did not change the row, so the comment does not list it.
|
||||
expect(parsed[0]?.config?.[0]?.config?.v).toBe(2)
|
||||
expect(dump).toContain('# == base.yml, patched by a.yml, b.yml\n- id: g')
|
||||
})
|
||||
|
||||
it('keeps generated ids of anonymous replaced group children across layers', () => {
|
||||
const dir = tmp()
|
||||
const base = join(dir, 'base.yml')
|
||||
writeFileSync(base, '- id: g\n name: ./group.mjs\n group: true\n config: []\n- id: other\n name: ./noop.mjs\n')
|
||||
const patches = [{ id: 'g', config: [{ name: './noop.mjs' }] }]
|
||||
const dump = renderConfigDump(NAME, base, [
|
||||
{ label: 'a.yml', patches },
|
||||
{ label: 'b.yml', patches: [{ id: 'other', disabled: true }] },
|
||||
], () => {})
|
||||
expect(dump).toContain('# == base.yml, patched by a.yml\n- id: g')
|
||||
expect(dump).not.toContain('b.yml\n- id: g')
|
||||
expect(dump).toContain('# == base.yml, patched by b.yml\n- id: other')
|
||||
expect(patches).toEqual([{ id: 'g', config: [{ name: './noop.mjs' }] }])
|
||||
})
|
||||
|
||||
it('keeps each layer\'s snapshot when a later layer inserts into a config array an earlier layer supplied', () => {
|
||||
const dir = tmp()
|
||||
const base = join(dir, 'base.yml')
|
||||
writeFileSync(base, '- id: x\n name: ./group.mjs\n')
|
||||
const dump = renderConfigDump(NAME, base, [
|
||||
{ label: 'a.yml', patches: [{ id: 'x', config: [] }] },
|
||||
{ label: 'b.yml', patches: [{ id: 'x', group: true }] },
|
||||
{ label: 'c.yml', patches: [{ id: 'x', insert: [{ id: 'child', name: './noop.mjs' }] }] },
|
||||
], () => {})
|
||||
expect((parseEntryYaml(dump) as { config: unknown[] }[])[0]!.config).toEqual([{ id: 'child', name: './noop.mjs' }])
|
||||
expect(dump).toContain('# == base.yml, patched by a.yml, b.yml, c.yml\n- id: x')
|
||||
})
|
||||
|
||||
it('drops the children of a replaced group config from the patch index', () => {
|
||||
const dir = tmp()
|
||||
const base = join(dir, 'base.yml')
|
||||
writeFileSync(base, '- id: g\n name: ./group.mjs\n group: true\n config:\n - id: child\n name: ./noop.mjs\n')
|
||||
const warnings: string[] = []
|
||||
renderConfigDump(NAME, base, [
|
||||
{ label: 'a.yml', patches: [{ id: 'g', config: [] }, { id: 'child', disabled: true }] },
|
||||
], line => void warnings.push(line))
|
||||
expect(warnings).toEqual([`${NAME}: [a.yml] patch: entry "child" not found`])
|
||||
})
|
||||
|
||||
it('reports a patch whose target row is absent through warn with its layer label and keeps composing', () => {
|
||||
|
||||
@@ -418,15 +418,18 @@ describe('collectConfigSchemas', () => {
|
||||
expect(validates(result, [{ name: 'good', config: 3 }])).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps healthy group and include siblings after malformed child rows', async () => {
|
||||
it('keeps healthy group siblings after a malformed child row and rejects an include with a non-mapping entry', async () => {
|
||||
modules.set('good', { Config: Schema.string() })
|
||||
const result = await collectConfigSchemas(profile, [
|
||||
row('cordis:group', [{ name: false }, row('good')]),
|
||||
row('cordis:include', { path: './missing.yml', initial: [null, row('good')] }),
|
||||
row('cordis:include', { path: './missing.yml', initial: [row('good'), { ...row('cordis:group', [null]), group: true }] }),
|
||||
], resolution)
|
||||
expect(result['x-cordis'].diagnostics.map(item => item.path)).toEqual(['/0/config/0', '/1/include/0'])
|
||||
expect(result['x-cordis'].diagnostics.map(item => [item.path, item.message])).toEqual([
|
||||
['/0/config/0', expect.any(String)],
|
||||
['/1', expect.stringContaining('has an entry that is not a mapping')],
|
||||
])
|
||||
expect(result['x-cordis'].entries.filter(entry => entry.status === 'schema').map(entry => entry.path))
|
||||
.toEqual(['/0/config/1', '/1/include/1'])
|
||||
.toEqual(['/0/config/1'])
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -442,6 +445,29 @@ describe('collectConfigSchemas', () => {
|
||||
expect(result['x-cordis'].complete).toBe(false)
|
||||
})
|
||||
|
||||
it('resolves a drive-letter include path on Windows as Include does', async () => {
|
||||
modules.set('good', { Config: Schema.string() })
|
||||
const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
|
||||
Object.defineProperty(process, 'platform', { ...platform, value: 'win32' })
|
||||
try {
|
||||
const result = await collectConfigSchemas(profile, [
|
||||
row('cordis:include', { path: 'C:/dsh-missing/extra.yml', initial: [row('good')] }),
|
||||
], resolution)
|
||||
expect(result['x-cordis'].diagnostics).toEqual([])
|
||||
expect(result['x-cordis'].entries.map(entry => [entry.path, entry.status])).toEqual([['/0', 'absent'], ['/0/include/0', 'schema']])
|
||||
} finally {
|
||||
Object.defineProperty(process, 'platform', platform)
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves the caller\'s include patches unchanged when a patch replaces a group config', async () => {
|
||||
const patches = [{ id: 'group', config: [{ name: 'noop' }] }]
|
||||
await collectConfigSchemas(profile, [row('cordis:include', {
|
||||
path: './missing.yml', initial: [{ ...row('cordis:group', []), id: 'group', group: true }], patches,
|
||||
})], resolution)
|
||||
expect(patches).toEqual([{ id: 'group', config: [{ name: 'noop' }] }])
|
||||
})
|
||||
|
||||
it('does not validate contents of an insertion that Loader skips', async () => {
|
||||
const result = await collectConfigSchemas(profile, [row('cordis:include', {
|
||||
path: './missing.yml', initial: [row('noop')], patches: [{ id: 'missing', insert: [null] }, { config: {} }],
|
||||
@@ -456,6 +482,16 @@ describe('collectConfigSchemas', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('requires an entry-list config on every group: true entry, as the Loader does', async () => {
|
||||
const result = await collectConfigSchemas(profile, [row('noop')], resolution)
|
||||
expect(validates(result, [{ name: 'noop', group: true, config: [] }])).toBe(true)
|
||||
expect(validates(result, [{ name: 'noop', group: false }])).toBe(true)
|
||||
for (const value of [{ name: 'noop', group: true }, { name: 'noop', group: true, config: {} }, { name: 'noop', group: true, disabled: true }]) {
|
||||
expect(validates(result, [value])).toBe(false)
|
||||
}
|
||||
expect(validates(result, [{ id: 'g', config: [] }], 'patchList')).toBe(true)
|
||||
})
|
||||
|
||||
it('allows disabled config omission without disabling group:true or supplied-config validation', async () => {
|
||||
modules.set('required', { Config: Schema.string().required() })
|
||||
const result = await collectConfigSchemas(profile, [row('required')], resolution)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Include `path` resolution shared by the schema collector and compatibility preflight. */
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { includeFilename } from '../src/include-filename.ts'
|
||||
|
||||
describe('includeFilename', () => {
|
||||
it('reads a drive-letter path as a Windows file path on Windows', () => {
|
||||
expect(includeFilename('C:/config/extra.yml', 'file:///D:/app/', 'win32')).toBe('C:\\config\\extra.yml')
|
||||
expect(includeFilename('c:\\config\\extra.yml', 'file:///D:/app/', 'win32')).toBe('c:\\config\\extra.yml')
|
||||
})
|
||||
|
||||
it('resolves other paths against the tree base URL', () => {
|
||||
expect(includeFilename('./extra.yml', 'file:///app/cordis.yml', 'linux')).toBe('/app/extra.yml')
|
||||
expect(includeFilename('file:///etc/extra.yml', 'file:///app/', 'linux')).toBe('/etc/extra.yml')
|
||||
// Off Windows, Include reads `C:` as a URL scheme too.
|
||||
expect(() => includeFilename('C:/config/extra.yml', 'file:///app/', 'linux')).toThrow()
|
||||
expect(includeFilename('./extra.yml', 'file:///D:/app/cordis.yml', 'win32')).toBe('D:\\app\\extra.yml')
|
||||
})
|
||||
})
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
loadOverlayPatches,
|
||||
PROFILE_PATCH_FILENAME,
|
||||
reconcileProfilePatches,
|
||||
StartupError,
|
||||
} from '../src/index.ts'
|
||||
|
||||
const NAME = 'dsh-test-bin'
|
||||
@@ -132,12 +133,12 @@ describe('loadOptionalPatches', () => {
|
||||
.toThrow(new RegExp(`^${NAME}: failed to read patches `))
|
||||
})
|
||||
|
||||
it('fails loud on unparsable YAML and on a !!js tag with no expression body', () => {
|
||||
it('fails loud on unparsable YAML and on an unknown tag', () => {
|
||||
const dir = tmp()
|
||||
writeFileSync(join(dir, PROFILE_PATCH_FILENAME), 'invalid: [unclosed\n')
|
||||
expect(() => loadOptionalPatches(NAME, join(dir, PROFILE_PATCH_FILENAME)))
|
||||
.toThrow(new RegExp(`^${NAME}: failed to parse patches `))
|
||||
writeFileSync(join(dir, PROFILE_PATCH_FILENAME), '- id: x\n config:\n a: !!js\n')
|
||||
writeFileSync(join(dir, PROFILE_PATCH_FILENAME), '- id: x\n config:\n a: !js process.env.A\n')
|
||||
expect(() => loadOptionalPatches(NAME, join(dir, PROFILE_PATCH_FILENAME)))
|
||||
.toThrow(new RegExp(`^${NAME}: failed to parse patches `))
|
||||
})
|
||||
@@ -343,11 +344,30 @@ describe('profile reconciliation settlement', () => {
|
||||
const ctx = await boot(NAME, join(dir, 'cordis.yml'), patches)
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
// Reload diagnostics carry the import error's message without stack frames.
|
||||
const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: Error \\[ERR_MODULE_NOT_FOUND\\]'
|
||||
const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs' imported from [^\\n]*$`, 'u')
|
||||
const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: ModuleNotFoundError'
|
||||
const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs'$`, 'u')
|
||||
expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual([expect.stringMatching(diagnostic)])
|
||||
})
|
||||
|
||||
it('fails startup for a required row whose options the Loader rejects, at its source position', async () => {
|
||||
const dir = tmp()
|
||||
writeFileSync(join(dir, 'cordis.yml'), '- id: webserver\n name: ./webserver.mjs\n disabled: maybe\n')
|
||||
const error = await boot(NAME, join(dir, 'cordis.yml')).catch((caught: unknown) => caught)
|
||||
expect(error).toBeInstanceOf(StartupError)
|
||||
expect((error as Error).message).toContain(' webserver (required)\n Package: ./webserver.mjs')
|
||||
expect((error as Error).message).toContain(`disabled must be a boolean (at disabled, ${join(dir, 'cordis.yml')}:3:13)`)
|
||||
})
|
||||
|
||||
it('rejects a recomposition that introduces rows the Loader rejects', async () => {
|
||||
const dir = tmp()
|
||||
writeFileSync(join(dir, 'cordis.yml'), '[]\n')
|
||||
const ctx = await boot(NAME, join(dir, 'cordis.yml'))
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const patches = [{ insert: [{ id: 'bad-group', name: 'cordis:group', group: true }] }]
|
||||
await expect(reconcileProfilePatches(ctx, patches, NAME)).rejects
|
||||
.toThrow('bad-group (cordis:group): invalid entry options: EntryValidationError: invalid entry options:\n - config is required (at config)')
|
||||
})
|
||||
|
||||
it('rejects a context without the launcher root Include', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
|
||||
@@ -86,7 +86,7 @@ it('updates the last matching named override and leaves mismatched names untouch
|
||||
{ id: 'tool', name: 'package', config: { value: { __jsExpr: 'process.platform' } }, disabled: false },
|
||||
{ id: 'tool', name: 'another-package', disabled: true },
|
||||
])
|
||||
expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {}))
|
||||
expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {}).data)
|
||||
.toMatchObject([{ id: 'tool', name: 'package', disabled: false }])
|
||||
expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(false)
|
||||
expect(await readFile(profile.patchPath, 'utf8')).toBe(text)
|
||||
|
||||
@@ -20,7 +20,7 @@ it.each([
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]!.name).toBe('@deepseek-ai/dsh-client-ui-sidebar-browser')
|
||||
const configured = applyEntryPatches(rows, override === undefined ? [] : [{ id: 'ui-sidebar-browser', disabled: override }],
|
||||
(message) => { throw new Error(message) })
|
||||
(message) => { throw new Error(message) }).data
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
if (profile !== undefined) {
|
||||
|
||||
@@ -28,7 +28,7 @@ it('loads one shared conversion row and retains caller-owned PDFs after disposal
|
||||
.filter(row => row.name === '@deepseek-ai/dsh-office-kit')
|
||||
expect(rows.map(row => row.id)).toEqual(['office-kit'])
|
||||
const configured = applyEntryPatches(rows, [{ id: 'office-kit', config: { maxConcurrentConversions: 1, outputDirectory } }],
|
||||
(message) => { throw new Error(message) })
|
||||
(message) => { throw new Error(message) }).data
|
||||
const configPath = join(directory, 'cordis.yml')
|
||||
await writeFile(configPath, JSON.stringify(configured))
|
||||
ctx.baseUrl = pathToFileURL(directory).href + '/'
|
||||
|
||||
@@ -52,7 +52,7 @@ it('loads the shipped Office rows with separately patched settings and authorize
|
||||
const configured = applyEntryPatches(rows, [
|
||||
{ id: 'office-kit', config: providerConfig },
|
||||
{ id: 'ui-sidebar-documentpreview', config: clientConfig },
|
||||
], (message) => { throw new Error(message) })
|
||||
], (message) => { throw new Error(message) }).data
|
||||
expect(configured.find(row => row.id === 'ui-sidebar-documentpreview')!.config).toEqual(clientConfig)
|
||||
await writeFile(configPath, JSON.stringify([
|
||||
{ name: '@deepseek-ai/dsh-session' },
|
||||
|
||||
@@ -17,7 +17,7 @@ async function setup(options: { origin?: string; ssh?: 'SSH_CONNECTION' | 'SSH_T
|
||||
{ source: 'process', values: options.ssh === undefined ? {} : { [options.ssh]: 'remote-launch' } },
|
||||
{ source: 'project-env', path: '/project/.env', values: { SSH_TTY: 'project-setting' } },
|
||||
]))
|
||||
if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [] } as never)
|
||||
if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [], root: { data: [] } } as never)
|
||||
const server: Pick<WebServer, 'host' | 'protocol' | 'registerFallback'> = {
|
||||
host: '127.0.0.1', protocol: 'http:', registerFallback: () => () => {},
|
||||
}
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: 91e5f113f2e5c739
|
||||
zh: 52eefce9ed4a1239
|
||||
en: 8046882569b4ae52
|
||||
zh: 2e5e675422b6b043
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: b98cb51f33ed09ec
|
||||
zh: 2950d24bfd887d69
|
||||
en: fd849091afb60a72
|
||||
zh: c0d4aa524745d28a
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 2bc25a99e17789c4
|
||||
zh: 4bec723fbf249d28
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work:
|
||||
en: 8801648dd9433da6
|
||||
zh: be520fb644ea8895
|
||||
en: 49fd22a6073c1680
|
||||
zh: a2ca41e361799b19
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -29,17 +29,17 @@ Enable the [forge bundle](../forge-bundle/README.md) on the Plugins page; it com
|
||||
|
||||
Panel text follows the application language: Chinese, English, Japanese, Spanish, French, German, Russian, or Portuguese.
|
||||
|
||||
- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh-<first 8 hexadecimal digits of the Session id>-<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists.
|
||||
- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector. The selector's searchable menu lists, most recently committed first, the current branch, then each remote's default branch, then local branches, then one group per remote headed by its name and its repository, `owner/name` for a recognized code host or else its fetch URL without the user name and password a URL can carry; typing filters the rows at once and lists the branches whose names contain the text after a short pause, and Enter chooses the first row. A remote branch is fetched, only that branch and without tags, when the worktree is created. The menu's last row, Name the new branch, opens a dialog whose field starts with the `worktreePrefix` and checks Git's branch-name rules while the name is typed; Save asks the Host, which also refuses a name the checkout already uses as a branch, and keeps the dialog open with the reason. With a chosen name, the selector shows the name before the base, and the dialog offers to use a generated name again. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the chosen branch, or else `dsh-<first 8 hexadecimal digits of the Session id>-<4 random hexadecimal digits>`, is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists.
|
||||
- **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `enter_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. The bundle's worktree row on the Plugins page offers Keep worktrees when archiving: once saved, archiving keeps every worktree and shows the ordinary archive notice; the switch is read at each archive, so it does not affect a cleanup already scheduled.
|
||||
- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its two steps, creating the branch and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again with a new branch name, and Continue without a worktree withdraws the request so the message goes on in the current checkout.
|
||||
- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again.
|
||||
- **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph.
|
||||
- **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden.
|
||||
- **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. 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 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.
|
||||
- **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. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the viewLine truncated
|
||||
- **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
|
||||
|
||||
- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; when the counts do not fit the tree's width, it shows the layer names alone and each count in the hover text of its layer. Where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. The file tree draws a viewed file subdued, and a directory once every file in it is viewed, so the files left to review stand out; a file changed since it was viewed draws as unviewed, and assistive technology reads the state as each row's description. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits.
|
||||
- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none.
|
||||
@@ -63,9 +63,9 @@ All files opens a searchable directory tree with the selected file scrolled to i
|
||||
|
||||
`ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later.
|
||||
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=<maxBranches>`; `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.
|
||||
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 `workspace-root/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. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, and with `forgePanel/invalid-branch` for an empty branch; `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 with a new branch name, publishing 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, failed step, and reason stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, refused with `forgePanel/not-waiting` while none waits or one runs, 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 `workspace-root/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.
|
||||
|
||||
|
||||
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.
|
||||
@@ -85,6 +85,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
|
||||
| [`src/index.ts`](src/index.ts) | `forgePanel` Remote and per-Session panels |
|
||||
| [`src/panel.ts`](src/panel.ts) | Panel state, inspection scheduling, and sign-in probes |
|
||||
| [`src/worktree.ts`](src/worktree.ts) | Worktree record, projection, waiting messages, and creation at the first step |
|
||||
| [`src/branch-name.ts`](src/branch-name.ts) | Branch-name rules and branch labels for the Host and the Client |
|
||||
| [`src/states.ts`](src/states.ts) | Change request states for the Session list |
|
||||
| [`src/git.ts`](src/git.ts) | Git queries under Session permissions |
|
||||
| [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order |
|
||||
@@ -114,7 +115,10 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
|
||||
| [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | Viewed marks the code host keeps, with marks being saved |
|
||||
| [`src/client/menu-search.ts`](src/client/menu-search.ts) | Keys of the search field at the top of a menu |
|
||||
| [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory |
|
||||
| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option |
|
||||
| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option and its base menu |
|
||||
| [`src/client/WorktreeNameDialog.tsx`](src/client/WorktreeNameDialog.tsx) | Naming dialog of a worktree branch |
|
||||
| [`src/client/branch-search.tsx`](src/client/branch-search.tsx) | Search state and status rows of the branch menus |
|
||||
| [`src/client/ChangesLoading.tsx`](src/client/ChangesLoading.tsx) | Changes view while it reads |
|
||||
| [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card |
|
||||
| [`src/client/SessionRowForge.tsx`](src/client/SessionRowForge.tsx) | Session row icons |
|
||||
| [`src/client/SessionHoverForge.tsx`](src/client/SessionHoverForge.tsx) | Session row hover card section |
|
||||
@@ -149,7 +153,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi
|
||||
- **Polling while shown** — status is polled only while a Session list row or an active panel surface for the Session subscribes; retained hidden changes bodies do not subscribe; there are no notifications for checks that finish meanwhile.
|
||||
- **Unopened Sessions in the list** — the Session list reads the worktree and bindings of a Session that is not loaded from its cached summary: a Session without one shows neither, and one last used before this version shows its worktree only after it is opened.
|
||||
- **Inspection triggers** — the checkout is inspected after Session tool results and directory changes; a change made outside the Session appears when the Session panel opens or the window regains focus, at most once every 10 seconds, or after the next tool result.
|
||||
- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Branch names come from the Session id and random digits, not from the Session title, which does not exist yet.
|
||||
- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Generated branch names come from the Session id and random digits, not from the Session title, which does not exist yet; a name chosen in the naming dialog replaces them.
|
||||
- **Messages during a turn** — a message that enters while the Agent runs a turn or other maintenance gets no hold: a requested worktree is then created at the first step, where a failure ends the turn without the message, and a removed worktree is not checked, so the working-directory service moves the Session back to the project directory.
|
||||
- **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well.
|
||||
- **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project.
|
||||
|
||||
@@ -29,17 +29,17 @@ kind: "package-reference"
|
||||
|
||||
面板文案跟随应用语言,支持中文、英文、日语、西班牙语、法语、德语、俄语和葡萄牙语。
|
||||
|
||||
- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh-<Session id 前 8 位十六进制数>-<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。
|
||||
- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器。选择器的菜单可搜索,按最近提交排序依次列出:当前分支、每个远程的默认分支、本地分支,然后每个远程一组,组名旁显示该远程对应的仓库(识别出代码托管仓库时为 `owner/name`,否则为去掉用户名和密码后的获取地址);输入时已列出的行立即过滤,短暂停顿后列出名称包含所输入文字的分支,按 Enter 选择第一行。远程分支在创建 worktree 时获取,只获取这一个分支,不获取标签。菜单最后一行“指定新分支名称…”打开对话框:输入框以 `worktreePrefix` 开头,输入时检查 Git 的分支名规则;“确定”交给 Host,Host 还会拒绝检出中已有的分支名,拒绝时对话框保持打开并显示原因。指定名称后,选择器在基准前显示该名称,对话框也提供“改回自动命名”。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建指定的分支,未指定时为 `dsh-<Session id 前 8 位十六进制数>-<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。
|
||||
- **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `enter_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。插件页上该套件的 worktree 行提供“归档时不删除工作树”开关:保存后,归档会保留所有工作树并显示普通归档提示;开关在每次归档时读取,不影响已排队的清理。
|
||||
- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支以及“创建分支”“检出文件”两个步骤;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”换一个新分支名再试;“不使用工作树”撤回请求,消息在当前检出中继续发送。
|
||||
- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。
|
||||
- **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。
|
||||
- **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。
|
||||
- **检出行**——显示当前检出的分支(分离 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 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。这些内容只占一行:含失败检查的一行放不下时,失败检查改用不带数量的短文案;仍放不下的一行末尾显示省略号,并随标题一起滚动显示。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。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 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间Line truncated
|
||||
- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 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
|
||||
|
||||
- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;文件树宽度放不下数量时,只显示各层名称,数量在悬停提示里。不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。文件树把已审阅的文件置灰,目录下的文件全部已审阅时目录也置灰,以便看出还没审阅的文件;有新改动的文件按未审阅显示,辅助技术把这一状态读作每行的描述。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。
|
||||
- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。
|
||||
@@ -63,9 +63,9 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后
|
||||
|
||||
`ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。
|
||||
|
||||
检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=<maxBranches>`;`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 沙箱策略的规范工作区根内时才可用。
|
||||
检查运行 `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 头部与每个 `workspace-root/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;分支名为空时以 `forgePanel/invalid-branch` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留使用新分支名进行一次尝试,在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、失败步骤与原因以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;撤回请求则让消息在当前检出中继续。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 头部与每个 `workspace-root/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 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。
|
||||
@@ -85,6 +85,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
| [`src/index.ts`](src/index.ts) | `forgePanel` Remote 与按 Session 的面板 |
|
||||
| [`src/panel.ts`](src/panel.ts) | 面板状态、检查调度与登录检查 |
|
||||
| [`src/worktree.ts`](src/worktree.ts) | worktree 记录、投影、等待中的消息,以及在第一步创建 worktree |
|
||||
| [`src/branch-name.ts`](src/branch-name.ts) | Host 与 Client 共用的分支名规则与分支显示名 |
|
||||
| [`src/states.ts`](src/states.ts) | 会话列表用的变更请求状态 |
|
||||
| [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 |
|
||||
| [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 |
|
||||
@@ -114,7 +115,10 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
| [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | 代码托管平台保存的已审阅标记,以及正在保存的标记 |
|
||||
| [`src/client/menu-search.ts`](src/client/menu-search.ts) | 菜单顶部搜索框的按键处理 |
|
||||
| [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 |
|
||||
| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 |
|
||||
| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项及其基准菜单 |
|
||||
| [`src/client/WorktreeNameDialog.tsx`](src/client/WorktreeNameDialog.tsx) | worktree 分支的命名对话框 |
|
||||
| [`src/client/branch-search.tsx`](src/client/branch-search.tsx) | 分支菜单的搜索状态与状态行 |
|
||||
| [`src/client/ChangesLoading.tsx`](src/client/ChangesLoading.tsx) | 读取中的变更视图 |
|
||||
| [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 |
|
||||
| [`src/client/SessionRowForge.tsx`](src/client/SessionRowForge.tsx) | 会话行图标 |
|
||||
| [`src/client/SessionHoverForge.tsx`](src/client/SessionHoverForge.tsx) | 会话行悬浮卡片中的部分 |
|
||||
@@ -149,7 +153,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
- **只在显示时轮询**——只有会话列表的某一行或该 Session 的活动面板界面订阅时才会轮询状态,保活但隐藏的变更正文不订阅;其间检查结束不会有通知。
|
||||
- **会话列表中未打开的 Session**——会话列表从缓存的摘要中读取未加载 Session 的 worktree 与绑定:没有缓存摘要的 Session 两者都不显示;此版本之前最后使用的 Session 要打开之后才显示其 worktree。
|
||||
- **检查触发时机**——检出只在 Session 的工具结果与目录变化之后检查;Session 之外的改动在会话面板打开或窗口重新获得焦点时出现(每 10 秒最多一次),否则要等到下一个工具结果。
|
||||
- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在。
|
||||
- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。自动生成的分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在;在命名对话框中指定的名称会取代它。
|
||||
- **一轮进行中的消息**——Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留:所请求的 worktree 改为在第一步创建,失败时这一轮结束且不带这条消息;已删除的 worktree 不会被检查,工作目录服务会把 Session 移回项目目录。
|
||||
- **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。
|
||||
- **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/** Branch-name rules and branch labels shared by the Host and the Client; free of Node imports. */
|
||||
|
||||
/** Prefix of the full names of local branches. */
|
||||
export const LOCAL_REF_PREFIX = 'refs/heads/'
|
||||
|
||||
/** Prefix of the full names of remote-tracking branches. */
|
||||
export const REMOTE_REF_PREFIX = 'refs/remotes/'
|
||||
|
||||
/**
|
||||
* Why a name cannot be a new branch name: Git's rules for `refs/heads/<name>`, plus the worktree service's
|
||||
* refusal of a leading `-`.
|
||||
*/
|
||||
export type BranchNameProblem =
|
||||
| 'empty'
|
||||
| 'space'
|
||||
| 'character'
|
||||
| 'leading-dash'
|
||||
| 'leading-slash'
|
||||
| 'trailing-slash'
|
||||
| 'double-slash'
|
||||
| 'double-dot'
|
||||
| 'trailing-dot'
|
||||
| 'at'
|
||||
| 'at-brace'
|
||||
| 'dot-segment'
|
||||
| 'lock-segment'
|
||||
|
||||
/** Characters Git refuses anywhere in a ref name: ASCII controls, `~ ^ : ? * [`, and the backslash. */
|
||||
const FORBIDDEN = /[\u0000-\u001f\u007f~^:?*[\\]/
|
||||
|
||||
/**
|
||||
* Find the first rule a new branch name breaks. `git check-ref-format` stays the final check on the Host.
|
||||
* @param name - candidate branch name.
|
||||
* @returns the broken rule, or null when the name passes every rule.
|
||||
*/
|
||||
export function branchNameProblem(name: string): BranchNameProblem | null {
|
||||
if (name.length === 0) return 'empty'
|
||||
if (/\s/.test(name)) return 'space'
|
||||
if (FORBIDDEN.test(name)) return 'character'
|
||||
if (name.startsWith('-')) return 'leading-dash'
|
||||
if (name.startsWith('/')) return 'leading-slash'
|
||||
if (name.endsWith('/')) return 'trailing-slash'
|
||||
if (name.includes('//')) return 'double-slash'
|
||||
if (name.includes('..')) return 'double-dot'
|
||||
if (name.endsWith('.')) return 'trailing-dot'
|
||||
if (name === '@') return 'at'
|
||||
if (name.includes('@{')) return 'at-brace'
|
||||
const segments = name.split('/')
|
||||
if (segments.some(segment => segment.startsWith('.'))) return 'dot-segment'
|
||||
if (segments.some(segment => segment.endsWith('.lock'))) return 'lock-segment'
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The name a branch shows: a full local or remote-tracking branch name without its `refs/heads/` or
|
||||
* `refs/remotes/` prefix; any other revision, such as a short name an earlier panel recorded, as it is.
|
||||
* @param ref - branch or revision.
|
||||
* @returns the shown name.
|
||||
*/
|
||||
export function branchLabel(ref: string): string {
|
||||
for (const prefix of [LOCAL_REF_PREFIX, REMOTE_REF_PREFIX]) {
|
||||
if (ref.startsWith(prefix) && ref.length > prefix.length) return ref.slice(prefix.length)
|
||||
}
|
||||
return ref
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a revision is the full name of a remote-tracking branch, which a worktree creation fetches first.
|
||||
* @param ref - branch or revision, or null for HEAD.
|
||||
* @returns whether `ref` lies under `refs/remotes/`.
|
||||
*/
|
||||
export function isRemoteRef(ref: string | null): boolean {
|
||||
return ref !== null && ref.startsWith(REMOTE_REF_PREFIX) && ref.length > REMOTE_REF_PREFIX.length
|
||||
}
|
||||
@@ -1,21 +1,19 @@
|
||||
/** Base branch picker of the local changes view's `branch` scope: the automatic fork point, then remote-tracking and local branches. */
|
||||
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular,
|
||||
IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, StateDot, Tooltip,
|
||||
IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular,
|
||||
IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts'
|
||||
import { branchSearchStatus, useBranchSearch } from './branch-search.tsx'
|
||||
import type { NS } from './locales.ts'
|
||||
import { searchFieldKeyDown } from './menu-search.ts'
|
||||
import css from './BaseMenu.module.css'
|
||||
|
||||
/** Milliseconds between the last keystroke of a search and the listing it reads. */
|
||||
const SEARCH_DELAY_MS = 150
|
||||
|
||||
/** Props of the base branch picker. */
|
||||
export interface BaseMenuProps extends PropsLocale<typeof NS> {
|
||||
/** Chosen branch, or null for the automatic fork point. */
|
||||
@@ -49,32 +47,11 @@ interface BaseOption {
|
||||
*/
|
||||
export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: BaseMenuProps): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [listing, setListing] = useState<RemoteResult<ForgeBaseBranches> | null>(null)
|
||||
const search = useRef<HTMLInputElement>(null)
|
||||
const shown = visible && open
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => {
|
||||
void list(query, controller.signal).then((result) => { if (!controller.signal.aborted) setListing(result) })
|
||||
}, query === '' ? 0 : SEARCH_DELAY_MS)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [shown, query, attempt, list])
|
||||
// The portalled menu measures itself hidden before its first frame, and a hidden field cannot take the keyboard.
|
||||
// A touch screen keeps its on-screen keyboard closed until the field is tapped.
|
||||
useEffect(() => {
|
||||
if (!shown || (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)) return
|
||||
const frame = requestAnimationFrame(() => { search.current?.focus() })
|
||||
return () => { cancelAnimationFrame(frame) }
|
||||
}, [shown])
|
||||
const { query, setQuery, listing, retry, reset, field } = useBranchSearch(shown, list)
|
||||
const close = (): void => {
|
||||
setOpen(false)
|
||||
setQuery('')
|
||||
reset()
|
||||
}
|
||||
const pick = (base: ForgeBaseBranch | null): void => {
|
||||
close()
|
||||
@@ -110,20 +87,8 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B
|
||||
].filter(group => group.options.length > 0)
|
||||
const first = groups[0]?.options[0]
|
||||
|
||||
let body: ReactNode
|
||||
if (listing === null) {
|
||||
body = <div className={css.status} role="status"><StateDot state="ongoing" />{t('diff.base.loading')}</div>
|
||||
} else if (!listing.ok) {
|
||||
body = (
|
||||
<div className={css.status} role="status">
|
||||
<span>{t('toast.branchesFailed')}</span>
|
||||
<Button size="sm" variant="outline" onClick={() => { setAttempt(count => count + 1) }}>{t('retry')}</Button>
|
||||
</div>
|
||||
)
|
||||
} else if (groups.length === 0) {
|
||||
body = <div className={css.status}>{t('diff.base.empty')}</div>
|
||||
} else {
|
||||
body = groups.map(group => (
|
||||
const body: ReactNode = branchSearchStatus({ listing, empty: groups.length === 0, retry, className: css.status, t })
|
||||
?? groups.map(group => (
|
||||
<div key={group.id} role="group" aria-label={group.label}>
|
||||
{/* The automatic row's tag names it, so its group shows no heading. */}
|
||||
{group.id !== 'automatic' && <div className={css.label} role="presentation">{group.label}</div>}
|
||||
@@ -142,7 +107,6 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
}
|
||||
|
||||
return (
|
||||
<Menu
|
||||
@@ -167,7 +131,7 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B
|
||||
>
|
||||
<div className={css.root} data-forge-base-menu="">
|
||||
<div className={css.search}>
|
||||
<Input ref={search} className={clsx(css.searchInput)} icon={<IconSearchOutlineRegular size={14} />} value={query}
|
||||
<Input ref={field} className={clsx(css.searchInput)} icon={<IconSearchOutlineRegular size={14} />} value={query}
|
||||
aria-label={t('diff.base.search')} placeholder={t('diff.base.search')}
|
||||
onChange={(event) => { setQuery(event.target.value) }}
|
||||
onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.base) }) }} />
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
/**
|
||||
* 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, 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.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import { useId, useRef, useState, type ReactNode } from 'react'
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, type RefObject } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular,
|
||||
@@ -170,10 +172,14 @@ function finished(snapshot: ChangeRequestSnapshot, now: number, t: Translate): s
|
||||
return ago === undefined ? state : t('time.finished', { state, time: ago })
|
||||
}
|
||||
|
||||
/** Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress. */
|
||||
function Summary({ snapshot, now, t }: {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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} />
|
||||
@@ -187,7 +193,7 @@ function Summary({ snapshot, now, t }: {
|
||||
<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 ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted')
|
||||
? 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>}
|
||||
@@ -195,6 +201,61 @@ function Summary({ snapshot, now, t }: {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param snapshot - change request status.
|
||||
* @param t - copy.
|
||||
* @returns the line's full text after the number, or null.
|
||||
*/
|
||||
function shortenable(snapshot: ChangeRequestSnapshot | null, t: Translate): string | null {
|
||||
if (snapshot?.state !== 'open') return null
|
||||
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 flag = flagOf(snapshot)
|
||||
return flag === undefined ? full : `${full} ${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
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
@@ -432,11 +493,32 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc
|
||||
const tone = toneOf(snapshot)
|
||||
const name = number === null ? snapshot?.title ?? url : t('change.number', { number })
|
||||
const titleRef = useRef<HTMLSpanElement>(null)
|
||||
const marquee = useHoverMarquee(titleRef)
|
||||
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} t={t} /> : null
|
||||
: 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}>
|
||||
@@ -456,9 +538,7 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc
|
||||
</a>
|
||||
{(number !== null || meta !== null) && (
|
||||
<div className={css.meta}>
|
||||
{number !== null && <span>{t('change.number', { number })}</span>}
|
||||
{number !== null && meta !== null && <span aria-hidden="true">·</span>}
|
||||
{meta}
|
||||
{expanded ? parts : <MarqueeText ref={lineRef} className={css.statusLine}>{parts}</MarqueeText>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -160,15 +160,19 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode {
|
||||
|
||||
/**
|
||||
* Open directory navigation through the existing files toolbar entry.
|
||||
* @param props - navigator data and whether its owning tab is visible.
|
||||
* @param props - navigator data, whether its owning tab is visible, and whether the files are still being read, when
|
||||
* the entry names no count.
|
||||
* @returns the toolbar entry and its portalled menu.
|
||||
*/
|
||||
export function ChangedFilesMenu({ visible, ...props }: ChangedFilesProps & { readonly visible: boolean }): ReactNode {
|
||||
export function ChangedFilesMenu({ visible, loading = false, ...props }: ChangedFilesProps & {
|
||||
readonly visible: boolean
|
||||
readonly loading?: boolean
|
||||
}): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
return <Menu open={visible && open} portal dense align="start" className={css.anchor} listClassName={css.menu} onClose={() => { setOpen(false) }}
|
||||
anchor={<button type="button" className={css.trigger} aria-haspopup="menu" aria-expanded={visible && open} disabled={props.files.length === 0}
|
||||
onClick={() => { setOpen(value => !value) }}>
|
||||
<span className={css.triggerLabel}>{props.t('diff.allFiles', { count: props.files.length })}</span>
|
||||
<span className={css.triggerLabel}>{loading ? props.t('diff.allFilesLoading') : props.t('diff.allFiles', { count: props.files.length })}</span>
|
||||
<IconChevronDownOutlineRegular size={12} className={css.triggerChevron} />
|
||||
</button>}>
|
||||
<ChangedFiles {...props} menu jump={(path) => { setOpen(false); props.jump(path) }} />
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/* The changes view while it reads: one status line, then file cards drawn as skeletons. The cards copy `.file` and
|
||||
`.fileHeader` of ChangesTab.module.css; the fill and pulse copy the Plugins page skeleton. */
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 20px;
|
||||
margin: 0 0 10px;
|
||||
padding: 0 4px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: var(--dsh-content-font-size-secondary, 13px);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.fill {
|
||||
border-radius: var(--dsw-radius-xs);
|
||||
background: var(--dsw-alias-bg-skeleton);
|
||||
animation: forge-skeleton-pulse 2s cubic-bezier(0.36, 0, 0.64, 1) infinite;
|
||||
}
|
||||
|
||||
@keyframes forge-skeleton-pulse {
|
||||
0% { opacity: 1; }
|
||||
40% { opacity: 0.6; }
|
||||
80%, 100% { opacity: 1; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.fill { animation: none; }
|
||||
}
|
||||
|
||||
.file {
|
||||
overflow: clip;
|
||||
border: 0.5px solid var(--dsw-alias-border-l4);
|
||||
border-radius: var(--dsw-radius-lg);
|
||||
background: var(--forge-changes-bg);
|
||||
}
|
||||
|
||||
.file + .file {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
@container forge-changes (max-width: 380px) {
|
||||
.file + .file {
|
||||
margin-top: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
box-sizing: border-box;
|
||||
min-height: 36px;
|
||||
padding: 0 10px 0 12px;
|
||||
border-bottom: 0.5px solid var(--dsw-alias-border-l3);
|
||||
background: linear-gradient(var(--dsw-alias-interactive-bg-hover), var(--dsw-alias-interactive-bg-hover)), var(--forge-changes-bg);
|
||||
}
|
||||
|
||||
.folded .header {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.icon,
|
||||
.box {
|
||||
flex: none;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.path {
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
.counts {
|
||||
flex: none;
|
||||
width: 52px;
|
||||
height: 10px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.lines {
|
||||
display: grid;
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.split {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.column + .column {
|
||||
border-left: 0.5px solid var(--dsw-alias-border-l3);
|
||||
}
|
||||
|
||||
.line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
height: 18px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.number {
|
||||
flex: none;
|
||||
width: 20px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.code {
|
||||
height: 8px;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/** The changes view's body while it reads: a status line above file cards drawn as skeletons. */
|
||||
|
||||
import clsx from 'clsx'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { NS } from './locales.ts'
|
||||
import css from './ChangesLoading.module.css'
|
||||
|
||||
/** Widths, in percent of a line, that the skeleton's code bars cycle through. */
|
||||
const CODE_WIDTHS = [62, 48, 74, 35, 81, 56, 44, 69, 28, 52, 77, 39] as const
|
||||
|
||||
/**
|
||||
* The skeleton cards: a changed file shown in two columns when the view splits sides, an added file, and two
|
||||
* collapsed files. `path` is the path bar's width in percent of the header.
|
||||
*/
|
||||
const FILES = [
|
||||
{ path: 46, lines: 7, sides: 2 },
|
||||
{ path: 34, lines: 4, sides: 1 },
|
||||
{ path: 52, lines: 0, sides: 1 },
|
||||
{ path: 28, lines: 0, sides: 1 },
|
||||
] as const
|
||||
|
||||
function Column({ lines, offset }: { readonly lines: number; readonly offset: number }): ReactNode {
|
||||
return (
|
||||
<div className={css.column}>
|
||||
{Array.from({ length: lines }, (_, index) => (
|
||||
<div key={index} className={css.line}>
|
||||
<span className={clsx(css.fill, css.number)} />
|
||||
<span className={clsx(css.fill, css.code)} style={{ width: `${CODE_WIDTHS[(index + offset) % CODE_WIDTHS.length]}%` }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the reading state of the changes view. The status line is the only text and announces itself politely;
|
||||
* the cards are hidden from assistive technology.
|
||||
* @param props - whether changed files show their sides in two columns, and copy.
|
||||
* @returns the status line and the skeleton cards.
|
||||
*/
|
||||
export function ChangesLoading({ split, t }: { readonly split: boolean } & PropsLocale<typeof NS>): ReactNode {
|
||||
return (
|
||||
<>
|
||||
<div className={css.status} role="status">{t('diff.loading')}</div>
|
||||
<div aria-hidden="true" data-forge-changes-skeleton="">
|
||||
{FILES.map((file, index) => {
|
||||
const columns = split && file.sides === 2
|
||||
return (
|
||||
<div key={index} className={clsx(css.file, file.lines === 0 && css.folded)}>
|
||||
<div className={css.header}>
|
||||
<span className={clsx(css.fill, css.icon)} />
|
||||
<span className={clsx(css.fill, css.path)} style={{ width: `${file.path}%` }} />
|
||||
<span className={clsx(css.fill, css.counts)} />
|
||||
<span className={clsx(css.fill, css.box)} />
|
||||
</div>
|
||||
{file.lines > 0 && (
|
||||
<div className={clsx(css.lines, columns && css.split)}>
|
||||
<Column lines={file.lines} offset={index * 5} />
|
||||
{columns && <Column lines={file.lines} offset={index * 5 + 4} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular,
|
||||
IconInfoOutlineRegular, IconFilesDiffOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular,
|
||||
IconWrapFillRegular,
|
||||
Menu, StateDot, Tooltip,
|
||||
Menu, Tooltip,
|
||||
type MenuEntry,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
@@ -53,6 +53,7 @@ import { SectionReach } from './section-reach.ts'
|
||||
import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx'
|
||||
import { changedFileTree, filesInTreeOrder } from './file-tree.ts'
|
||||
import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx'
|
||||
import { ChangesLoading } from './ChangesLoading.tsx'
|
||||
import { drawnLines, matchesHunks, revealGap, textLines, type GapExpansion, type GapReveal } from './diff-rows.ts'
|
||||
import { ChangeRequestGlyph } from './glyphs.tsx'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
@@ -1218,7 +1219,7 @@ export function ChangesTab({
|
||||
</div>
|
||||
)
|
||||
} else if (failed === null) {
|
||||
body = <div className={css.centered}><StateDot state="ongoing" /></div>
|
||||
body = <div className={css.files} aria-busy="true"><ChangesLoading split={split} t={t} /></div>
|
||||
} else {
|
||||
body = (
|
||||
<div className={css.centered} role="status">
|
||||
@@ -1332,7 +1333,9 @@ export function ChangesTab({
|
||||
{treeShown && <div className={css.lensCell}><LensControl {...lensProps} need={setLensWidth} /></div>}
|
||||
<div ref={toolbarRow} className={css.toolbarMain}>
|
||||
{tab.visible && source.kind === 'local' && <ScopeMenu scope={scope} choose={(next) => { actions.scoped(tab.id, next) }} t={t} />}
|
||||
{tab.visible && <span className={css.filesSlot}><ChangedFilesMenu {...navigator} visible /></span>}
|
||||
{tab.visible && (
|
||||
<span className={css.filesSlot}><ChangedFilesMenu {...navigator} loading={data === null && failed === null} visible /></span>
|
||||
)}
|
||||
{tab.visible && allFiles.length > 0 && (
|
||||
<span className={css.lensMenu}><LensMenu {...lensProps} visible /></span>
|
||||
)}
|
||||
|
||||
@@ -217,12 +217,35 @@
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* Only the branch names shorten; the number, checks, and flags keep whole words on one line. */
|
||||
.meta > :not(.ellipsis) {
|
||||
/* 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);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { IconBranchOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
// Type-only: pulls the ui-workspace SlotMap merge (the Session row seats).
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import { branchLabel } from '../branch-name.ts'
|
||||
import { ChangeRequestGlyph } from './glyphs.tsx'
|
||||
import type { NS } from './locales.ts'
|
||||
import { useSessionForgeFacts, type SessionListInjected } from './session-list.ts'
|
||||
@@ -41,7 +42,7 @@ export function SessionHoverForge({ sessionId, useSessions, useStates, t }: Sess
|
||||
<span className={css.hoverIcon} aria-hidden="true"><IconBranchOutlineRegular size={12} /></span>
|
||||
<span className={css.hoverBody}>
|
||||
<span className={css.hoverBranch}>{worktree.branch}</span>
|
||||
<span className={css.hoverNote}>{t('checkout.worktreeFrom', { base: worktree.from ?? worktree.baseCommit.slice(0, 7) })}</span>
|
||||
<span className={css.hoverNote}>{t('checkout.worktreeFrom', { base: worktree.from === null ? worktree.baseCommit.slice(0, 7) : branchLabel(worktree.from) })}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/* Naming dialog of a worktree branch: the Modal body's field, its message line, and the footer's left action. */
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.field {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field input {
|
||||
font-family: var(--ds-font-family-code);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.field.invalid,
|
||||
.field.invalid:focus-within {
|
||||
border-color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
/* Reserves two lines, so a longer reason replacing the hint does not move the footer. */
|
||||
.message {
|
||||
min-height: 36px;
|
||||
margin: 0;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.auto {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
@media (pointer: coarse) {
|
||||
.field input {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/** Dialog that names the new branch of a requested worktree, from the New Session option or after a failed attempt. */
|
||||
|
||||
import { useId, useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { Button, Input, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { branchLabel, branchNameProblem } from '../branch-name.ts'
|
||||
import type { NS } from './locales.ts'
|
||||
import css from './WorktreeNameDialog.module.css'
|
||||
|
||||
/**
|
||||
* Outcome of a worktree request: accepted; refused for its branch name, which the dialog shows; or failed otherwise,
|
||||
* which the request reports itself.
|
||||
*/
|
||||
export type WorktreeRequestResult = 'accepted' | 'invalid-name' | 'branch-exists' | 'failed'
|
||||
|
||||
/** Props of the naming dialog. */
|
||||
export interface WorktreeNameDialogProps extends PropsLocale<typeof NS> {
|
||||
/** `name` names the branch of the open request; `retry` renames it after a failed attempt, then tries again. */
|
||||
readonly mode: 'name' | 'retry'
|
||||
/** Text the field starts with: the chosen name, or the prefix of generated names. */
|
||||
readonly initial: string
|
||||
/** Prefix of generated names; a field that holds only the prefix names no branch yet. */
|
||||
readonly prefix: string
|
||||
/** Base of the request, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the request already names its branch, which offers a return to generated names. */
|
||||
readonly named: boolean
|
||||
/**
|
||||
* Request the worktree on `name`, or on generated names for null; in `retry` mode the caller also tries again
|
||||
* once the request is accepted.
|
||||
*/
|
||||
readonly submit: (name: string | null) => Promise<WorktreeRequestResult>
|
||||
/** Close the dialog without a request. */
|
||||
readonly close: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the dialog: one branch name field checked against Git's branch-name rules while it is typed, and checked by
|
||||
* the Host when it is confirmed. A refused name keeps the dialog open with the reason under the field; an accepted
|
||||
* request closes it.
|
||||
* @param props - mode, starting text, prefix, base, the request, and copy.
|
||||
* @returns the dialog.
|
||||
*/
|
||||
export function WorktreeNameDialog({ mode, initial, prefix, from, named, submit, close, t }: WorktreeNameDialogProps): ReactNode {
|
||||
const [value, setValue] = useState(initial)
|
||||
const [refusal, setRefusal] = useState<{ readonly name: string; readonly text: string } | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const fieldId = useId()
|
||||
const messageId = useId()
|
||||
// The starting prefix names no branch yet, so it gets the hint rather than a rule it breaks, such as a trailing `/`.
|
||||
const blank = value === prefix
|
||||
const problem = blank ? null : branchNameProblem(value)
|
||||
const error = problem !== null ? t(`branchName.${problem}`) : refusal?.name === value ? refusal.text : null
|
||||
const retry = mode === 'retry'
|
||||
const send = (name: string | null): void => {
|
||||
setBusy(true)
|
||||
void submit(name).then((result) => {
|
||||
setBusy(false)
|
||||
if (result === 'accepted') close()
|
||||
else if (name !== null && result === 'branch-exists') setRefusal({ name, text: t('branchName.exists', { name }) })
|
||||
else if (name !== null && result === 'invalid-name') setRefusal({ name, text: t('branchName.invalid') })
|
||||
})
|
||||
}
|
||||
const confirmable = !busy && error === null && !blank
|
||||
const base = from === null ? null : branchLabel(from)
|
||||
const hint = blank && prefix !== '' ? t('nameDialog.prefixOnly') : base === null ? t('nameDialog.hintHead') : t('nameDialog.hint', { branch: base })
|
||||
return (
|
||||
<Modal open onClose={close} title={t(retry ? 'nameDialog.retryTitle' : 'nameDialog.title')} closeLabel={t('nameDialog.close')}
|
||||
footer={<>
|
||||
{named && !retry && (
|
||||
<Button variant="outline" className={css.auto} disabled={busy} onClick={() => { send(null) }}>{t('nameDialog.auto')}</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={close}>{t('nameDialog.cancel')}</Button>
|
||||
<Button variant="primary" disabled={!confirmable} onClick={() => { send(value) }}>
|
||||
{t(retry ? 'nameDialog.retry' : 'nameDialog.confirm')}
|
||||
</Button>
|
||||
</>}>
|
||||
<div className={css.form} data-forge-worktree-name="">
|
||||
<label className={css.label} htmlFor={fieldId}>{t('nameDialog.field')}</label>
|
||||
<Input id={fieldId} data-modal-autofocus className={clsx(css.field, error !== null && css.invalid)} value={value}
|
||||
spellCheck={false} autoCapitalize="off" autoComplete="off" aria-invalid={error !== null} aria-describedby={messageId}
|
||||
onChange={(event) => { setValue(event.target.value) }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' || event.nativeEvent.isComposing) return
|
||||
event.preventDefault()
|
||||
if (confirmable) send(value)
|
||||
}} />
|
||||
<p id={messageId} className={clsx(css.message, error !== null && css.error)} role={error === null ? undefined : 'alert'}>{error ?? hint}</p>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -11,9 +11,11 @@ import {
|
||||
import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { branchLabel } from '../branch-name.ts'
|
||||
import type { ForgeMissingWorktree, ForgePanelWorktree, ForgeSessionWorktree, ForgeWorktreeRestoration } from '../types.ts'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
import type { PanelSnapshot } from './source.ts'
|
||||
import { WorktreeNameDialog, type WorktreeRequestResult } from './WorktreeNameDialog.tsx'
|
||||
import css from './WorktreeProgress.module.css'
|
||||
|
||||
/** Business face of the card. */
|
||||
@@ -22,8 +24,18 @@ export interface WorktreeProgressInjected {
|
||||
readonly hooks: { readonly panel: HostObservable<PanelSnapshot> }
|
||||
/** Stop the running attempt a message waits for; the message keeps waiting. */
|
||||
readonly stop: () => void
|
||||
/** Make another attempt at the worktree a message waits for. */
|
||||
readonly retry: () => void
|
||||
/**
|
||||
* Make another attempt at the worktree a message waits for.
|
||||
* @param fetch - false starts from the remote base branch as last fetched, without fetching it.
|
||||
*/
|
||||
readonly retry: (fetch: boolean) => void
|
||||
/**
|
||||
* Request the worktree again from the same base on another branch name, before another attempt.
|
||||
* @param from - base of the open request, or null for HEAD.
|
||||
* @param name - new branch name.
|
||||
* @returns the outcome; a failure other than a refused name is already reported.
|
||||
*/
|
||||
readonly request: (from: string | null, name: string | null) => Promise<WorktreeRequestResult>
|
||||
/** Withdraw the worktree request, so the waiting message goes on without a worktree. */
|
||||
readonly withdraw: () => void
|
||||
/**
|
||||
@@ -42,43 +54,57 @@ type Translate = WorktreeProgressProps['t']
|
||||
|
||||
type StepState = 'done' | 'running' | 'waiting' | 'failed'
|
||||
|
||||
type Phase = 'prepare' | 'checkout'
|
||||
type Phase = 'fetch' | 'prepare' | 'checkout'
|
||||
|
||||
type StepList = readonly { readonly phase: Phase; readonly label: ForgePanelKey }[]
|
||||
/** Steps in the order they run, each with its label. */
|
||||
type StepList = readonly { readonly phase: Phase; readonly label: ReactNode }[]
|
||||
|
||||
const CREATION_STEPS: StepList = [
|
||||
{ phase: 'prepare', label: 'creation.prepare' },
|
||||
{ phase: 'checkout', label: 'creation.checkout' },
|
||||
]
|
||||
|
||||
const RESTORATION_STEPS: StepList = [
|
||||
{ phase: 'prepare', label: 'restoration.prepare' },
|
||||
{ phase: 'checkout', label: 'creation.checkout' },
|
||||
]
|
||||
|
||||
function stepState(current: 'prepare' | 'checkout', failed: boolean, phase: 'prepare' | 'checkout'): StepState {
|
||||
if (phase === current) return failed ? 'failed' : 'running'
|
||||
return phase === 'prepare' ? 'done' : 'waiting'
|
||||
function stepState(steps: StepList, current: Phase, failed: boolean, phase: Phase): StepState {
|
||||
const at = steps.findIndex(step => step.phase === current)
|
||||
const index = steps.findIndex(step => step.phase === phase)
|
||||
if (index === at) return failed ? 'failed' : 'running'
|
||||
return index < at ? 'done' : 'waiting'
|
||||
}
|
||||
|
||||
function Steps({ steps, phase, failed, t }: {
|
||||
function Steps({ steps, phase, failed }: {
|
||||
readonly steps: StepList
|
||||
readonly phase: Phase
|
||||
readonly failed: boolean
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
return (
|
||||
<ul className={css.steps}>
|
||||
{steps.map(step => (
|
||||
<li key={step.phase} className={css.step} data-state={stepState(phase, failed, step.phase)}>
|
||||
<StepIcon state={stepState(phase, failed, step.phase)} />
|
||||
<span>{t(step.label)}</span>
|
||||
</li>
|
||||
))}
|
||||
{steps.map((step) => {
|
||||
const state = stepState(steps, phase, failed, step.phase)
|
||||
return (
|
||||
<li key={step.phase} className={css.step} data-state={state} data-forge-step={step.phase}>
|
||||
<StepIcon state={state} />
|
||||
<span>{step.label}</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** The steps of a creation, which fetches a remote base branch first when it asks to. */
|
||||
function creationSteps(creation: CreationView, t: Translate): StepList {
|
||||
const from = creation.from === null ? null : branchLabel(creation.from)
|
||||
return [
|
||||
...creation.fetch && from !== null
|
||||
? [{ phase: 'fetch' as const, label: t('creation.fetch', { branch: from }) }]
|
||||
: [],
|
||||
{ phase: 'prepare', label: t('creation.prepare') },
|
||||
{ phase: 'checkout', label: t('creation.checkout') },
|
||||
]
|
||||
}
|
||||
|
||||
function restorationSteps(t: Translate): StepList {
|
||||
return [
|
||||
{ phase: 'prepare', label: t('restoration.prepare') },
|
||||
{ phase: 'checkout', label: t('creation.checkout') },
|
||||
]
|
||||
}
|
||||
|
||||
function StepIcon({ state }: { readonly state: StepState }): ReactNode {
|
||||
switch (state) {
|
||||
case 'done': return <IconCheckOutlineRegular size={14} className={css.done} />
|
||||
@@ -93,11 +119,15 @@ function StepIcon({ state }: { readonly state: StepState }): ReactNode {
|
||||
/** One creation as the card shows it: the running attempt, or the failed or stopped one a message waits after. */
|
||||
interface CreationView {
|
||||
readonly state: 'running' | 'failed' | 'stopped'
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
readonly phase: Phase
|
||||
readonly branch: string | null
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetches its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/** Failure text, or null unless the attempt failed. */
|
||||
readonly message: string | null
|
||||
/** Whether the failed attempt found its branch or checkout directory taken. */
|
||||
readonly exists: boolean
|
||||
/** Whether a message waits for the running attempt, which can then be stopped. */
|
||||
readonly held: boolean
|
||||
}
|
||||
@@ -105,10 +135,12 @@ interface CreationView {
|
||||
/** The running attempt, else the failed or stopped one a message waits after, or undefined without either. */
|
||||
function creationOf(worktree: ForgePanelWorktree): CreationView | undefined {
|
||||
const { creation, failure, waiting } = worktree
|
||||
if (creation !== null) return { ...creation, state: 'running', message: null }
|
||||
if (creation !== null) return { ...creation, state: 'running', message: null, exists: false }
|
||||
if (waiting !== 'creation') return undefined
|
||||
if (failure !== null) return { ...failure, state: 'failed', held: false }
|
||||
return { state: 'stopped', phase: 'prepare', branch: null, from: worktree.request?.from ?? null, message: null, held: false }
|
||||
return {
|
||||
state: 'stopped', phase: 'prepare', branch: null, from: worktree.request?.from ?? null, fetch: false, message: null, exists: false, held: false,
|
||||
}
|
||||
}
|
||||
|
||||
function Details({ creation, t }: { readonly creation: CreationView; readonly t: Translate }): ReactNode {
|
||||
@@ -121,7 +153,7 @@ function Details({ creation, t }: { readonly creation: CreationView; readonly t:
|
||||
</>
|
||||
)}
|
||||
<dt>{t('creation.base')}</dt>
|
||||
<dd className={css.code}>{creation.from ?? t('creation.head')}</dd>
|
||||
<dd className={css.code}>{creation.from === null ? t('creation.head') : branchLabel(creation.from)}</dd>
|
||||
{creation.message !== null && (
|
||||
<>
|
||||
<dt>{t('creation.error')}</dt>
|
||||
@@ -138,17 +170,38 @@ const CREATION_TITLE: Record<CreationView['state'], ForgePanelKey> = {
|
||||
stopped: 'creation.stopped',
|
||||
}
|
||||
|
||||
function CreationCard({ creation, stop, retry, withdraw, t }: {
|
||||
/** The buttons of a failed or stopped attempt before withdrawing; the first one is the primary action. */
|
||||
function waitingActions(creation: CreationView, named: boolean, retry: WorktreeProgressInjected['retry'], rename: () => void, t: Translate): ReactNode {
|
||||
const again = { key: 'retry', label: t('creation.retry'), act: () => { retry(true) } }
|
||||
const actions = creation.state === 'failed' && creation.phase === 'fetch'
|
||||
? [again, { key: 'fetched', label: t('creation.useFetched'), act: () => { retry(false) } }]
|
||||
: creation.state === 'failed' && creation.exists && named
|
||||
? [{ key: 'rename', label: t('creation.rename'), act: rename }, again]
|
||||
: [again]
|
||||
return actions.map((action, index) => (
|
||||
<Button key={action.key} size="sm" variant={index === 0 ? 'primary' : 'ghost'} onClick={action.act}>{action.label}</Button>
|
||||
))
|
||||
}
|
||||
|
||||
function CreationCard({ creation, open: openRequest, prefix, stop, retry, withdraw, request, t }: {
|
||||
readonly creation: CreationView
|
||||
/** The open request, whose base a rename keeps and whose branch name it replaces. */
|
||||
readonly open: ForgePanelWorktree['request']
|
||||
/** Prefix of generated branch names. */
|
||||
readonly prefix: string
|
||||
readonly stop: WorktreeProgressInjected['stop']
|
||||
readonly retry: WorktreeProgressInjected['retry']
|
||||
readonly withdraw: WorktreeProgressInjected['withdraw']
|
||||
readonly request: WorktreeProgressInjected['request']
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [renaming, setRenaming] = useState(false)
|
||||
const running = creation.state === 'running'
|
||||
const failed = creation.state === 'failed'
|
||||
const title = t(CREATION_TITLE[creation.state])
|
||||
const name = openRequest?.name ?? null
|
||||
const from = openRequest?.from ?? null
|
||||
return (
|
||||
<div className={css.dock} data-forge-creation={running ? creation.phase : creation.state}>
|
||||
<section className={css.card} aria-label={title} aria-busy={running}>
|
||||
@@ -157,7 +210,7 @@ function CreationCard({ creation, stop, retry, withdraw, t }: {
|
||||
<span className={css.title}>{title}</span>
|
||||
{creation.branch !== null && <span className={css.branch}>{creation.branch}</span>}
|
||||
</div>
|
||||
{creation.state !== 'stopped' && <Steps steps={CREATION_STEPS} phase={creation.phase} failed={failed} t={t} />}
|
||||
{creation.state !== 'stopped' && <Steps steps={creationSteps(creation, t)} phase={creation.phase} failed={failed} />}
|
||||
{(open || failed) && <Details creation={creation} t={t} />}
|
||||
{!running && <p className={css.note}>{t('creation.waiting')}</p>}
|
||||
<div className={css.footer}>
|
||||
@@ -169,7 +222,7 @@ function CreationCard({ creation, stop, retry, withdraw, t }: {
|
||||
)}
|
||||
{!running && (
|
||||
<span className={css.actions}>
|
||||
<Button size="sm" variant="primary" onClick={retry}>{t('creation.retry')}</Button>
|
||||
{waitingActions(creation, name !== null, retry, () => { setRenaming(true) }, t)}
|
||||
<Button size="sm" variant="ghost" onClick={withdraw}>{t('creation.skip')}</Button>
|
||||
</span>
|
||||
)}
|
||||
@@ -180,6 +233,15 @@ function CreationCard({ creation, stop, retry, withdraw, t }: {
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
{renaming && name !== null && (
|
||||
<WorktreeNameDialog mode="retry" initial={name} prefix={prefix} from={from} named
|
||||
submit={async (next) => {
|
||||
const result = await request(from, next)
|
||||
if (result === 'accepted') retry(true)
|
||||
return result
|
||||
}}
|
||||
close={() => { setRenaming(false) }} t={t} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -222,7 +284,7 @@ function MissingCard({ created, missing, restoration, waiting, restore, leave, t
|
||||
<span className={css.title}>{t('restoration.title')}</span>
|
||||
<span className={css.branch}>{created.branch}</span>
|
||||
</div>
|
||||
<Steps steps={RESTORATION_STEPS} phase={phase} failed={false} t={t} />
|
||||
<Steps steps={restorationSteps(t)} phase={phase} failed={false} />
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
@@ -260,11 +322,14 @@ function MissingCard({ created, missing, restoration, waiting, restore, leave, t
|
||||
* @param props - panel hook, actions, and copy.
|
||||
* @returns the card, or nothing while no attempt runs, no message waits, and the worktree exists.
|
||||
*/
|
||||
export function WorktreeProgress({ usePanel, stop, retry, withdraw, restore, leave, t }: WorktreeProgressProps): ReactNode {
|
||||
export function WorktreeProgress({ usePanel, stop, retry, withdraw, request, restore, leave, t }: WorktreeProgressProps): ReactNode {
|
||||
const worktree = usePanel(snapshot => snapshot.state?.worktree ?? null)
|
||||
if (worktree === null) return null
|
||||
const creation = creationOf(worktree)
|
||||
if (creation !== undefined) return <CreationCard creation={creation} stop={stop} retry={retry} withdraw={withdraw} t={t} />
|
||||
if (creation !== undefined) {
|
||||
return <CreationCard creation={creation} open={worktree.request} prefix={worktree.namePrefix} stop={stop} retry={retry}
|
||||
withdraw={withdraw} request={request} t={t} />
|
||||
}
|
||||
if (worktree.missing === null || worktree.created === null) return null
|
||||
return (
|
||||
<MissingCard
|
||||
|
||||
@@ -46,6 +46,27 @@
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
/* A chosen name leads; the base after it gives way first. */
|
||||
.named {
|
||||
max-width: 280px;
|
||||
}
|
||||
|
||||
.nameLabel {
|
||||
flex: 0 1 auto;
|
||||
min-width: 4em;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.fromLabel {
|
||||
flex: 0 100 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.current {
|
||||
box-sizing: content-box;
|
||||
max-width: 200px;
|
||||
@@ -96,26 +117,144 @@
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.option {
|
||||
display: inline-flex;
|
||||
/* The base menu: the changes view's BaseMenu search, rows, and labels, with a footer row that names the branch. */
|
||||
.anchor {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.menu {
|
||||
width: min(360px, calc(100vw - 24px));
|
||||
}
|
||||
|
||||
.menuRoot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.search {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.searchInput {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.searchInput input::placeholder {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.rows {
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
padding: 0 0 2px;
|
||||
}
|
||||
|
||||
.groupLabel {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
padding: 6px 8px 4px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 11px;
|
||||
line-height: 15px;
|
||||
}
|
||||
|
||||
.groupName {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.groupRepository {
|
||||
min-width: 0;
|
||||
margin-left: auto;
|
||||
overflow: hidden;
|
||||
font-family: var(--ds-font-family-code);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.optionName {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-family: var(--ds-font-family-code);
|
||||
font-size: 12px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.optionNote {
|
||||
flex: none;
|
||||
.remotePrefix {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.tag {
|
||||
flex: none;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--dsw-radius-xs);
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.check {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 8px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: 3px;
|
||||
padding-top: 3px;
|
||||
border-top: 0.5px solid var(--dsw-alias-border-l2);
|
||||
}
|
||||
|
||||
.footerLabel {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.footerValue {
|
||||
min-width: 0;
|
||||
margin-left: auto;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.footerName {
|
||||
font-family: var(--ds-font-family-code);
|
||||
}
|
||||
|
||||
@media (pointer: coarse) {
|
||||
.search input {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
@@ -126,7 +265,12 @@
|
||||
}
|
||||
|
||||
.base,
|
||||
.named,
|
||||
.current {
|
||||
max-width: 120px;
|
||||
}
|
||||
|
||||
.fromLabel {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,21 @@
|
||||
/** New Session option: start the Session in a new worktree, from a chosen local branch. */
|
||||
/** New Session option: start the Session in a new worktree, on a chosen or generated branch, from a local or remote branch. */
|
||||
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { IconBranchOutlineRegular, IconChevronDownOutlineRegular, Menu, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import {
|
||||
IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconEditOutlineRegular, IconPlusOutlineRegular,
|
||||
IconSearchOutlineRegular, Input, Menu, MenuItemButton, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ForgeBranches, ForgePanelState, ForgeWorktreeBlocker } from '../types.ts'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { branchLabel, LOCAL_REF_PREFIX, REMOTE_REF_PREFIX } from '../branch-name.ts'
|
||||
import type { ForgeBaseBranch, ForgePanelState, ForgeWorktreeBases, ForgeWorktreeBlocker } from '../types.ts'
|
||||
import { branchSearchStatus, useBranchSearch } from './branch-search.tsx'
|
||||
import type { NS } from './locales.ts'
|
||||
import { searchFieldKeyDown } from './menu-search.ts'
|
||||
import type { PanelSnapshot } from './source.ts'
|
||||
import { WorktreeNameDialog, type WorktreeRequestResult } from './WorktreeNameDialog.tsx'
|
||||
import css from './WorktreeToggle.module.css'
|
||||
|
||||
/** Business face of the New Session option. */
|
||||
@@ -16,21 +23,24 @@ export interface WorktreeToggleInjected {
|
||||
/** Panel snapshot of the Session; the renderer binds it as `usePanel`. */
|
||||
readonly hooks: { readonly panel: HostObservable<PanelSnapshot> }
|
||||
/**
|
||||
* Request a worktree from a base branch, replacing an open request.
|
||||
* @param from - base branch, or null for HEAD.
|
||||
* @returns whether the Host accepted it.
|
||||
* Request a worktree from a base on a branch name, replacing an open request.
|
||||
* @param from - full name of a local or remote-tracking base branch, or null for HEAD.
|
||||
* @param name - new branch name, or null for a generated one.
|
||||
* @returns the outcome; a failure other than a refused name is already reported.
|
||||
*/
|
||||
readonly request: (from: string | null) => Promise<boolean>
|
||||
readonly request: (from: string | null, name: string | null) => Promise<WorktreeRequestResult>
|
||||
/**
|
||||
* Withdraw the open request.
|
||||
* @returns whether the Host accepted it.
|
||||
*/
|
||||
readonly cancel: () => Promise<boolean>
|
||||
/**
|
||||
* List the local branches of the Session's checkout.
|
||||
* @returns the branches, or undefined when they could not be read.
|
||||
* List the branches a worktree of the Session's checkout can start from whose names contain `query`.
|
||||
* @param query - search text; empty for every branch.
|
||||
* @param signal - aborts the read.
|
||||
* @returns the branches, or the failure the menu shows.
|
||||
*/
|
||||
readonly branches: () => Promise<ForgeBranches | undefined>
|
||||
readonly bases: (query: string, signal: AbortSignal) => Promise<RemoteResult<ForgeWorktreeBases>>
|
||||
}
|
||||
|
||||
/** Full props of the New Session option. */
|
||||
@@ -38,59 +48,156 @@ export type WorktreeToggleProps = InjectFace<WorktreeToggleInjected> & PropsLoca
|
||||
|
||||
type Translate = WorktreeToggleProps['t']
|
||||
|
||||
function BaseMenu({ base, held, branches, request, t }: {
|
||||
readonly base: string | null
|
||||
/** Whether the worktree is being created, which freezes the base. */
|
||||
/** One selectable branch row: the branch, the remote it belongs to, and the tag that names a pinned row. */
|
||||
interface BaseRow {
|
||||
readonly branch: ForgeBaseBranch
|
||||
readonly remote?: string
|
||||
readonly tag?: string
|
||||
}
|
||||
|
||||
/** What the option says about a request's base. */
|
||||
function baseTextOf(from: string | null, t: Translate): string {
|
||||
return from === null ? t('worktree.baseHead') : t('worktree.base', { branch: branchLabel(from) })
|
||||
}
|
||||
|
||||
/** What the option says about a request that names its branch. */
|
||||
function namedTipOf(name: string, from: string | null, t: Translate): string {
|
||||
return from === null ? t('worktree.namedTipHead', { name }) : t('worktree.namedTip', { name, branch: branchLabel(from) })
|
||||
}
|
||||
|
||||
/** The full name of a request's base; earlier panels recorded local branches by their short names. */
|
||||
function refOf(from: string | null): string | null {
|
||||
return from === null || from.startsWith('refs/') ? from : `${LOCAL_REF_PREFIX}${from}`
|
||||
}
|
||||
|
||||
/** A branch name split into a remote's prefix and the rest; local branches have no prefix. */
|
||||
function nameParts(branch: ForgeBaseBranch, remote: string | undefined): { readonly prefix: string; readonly rest: string } {
|
||||
return remote !== undefined && branch.ref.startsWith(REMOTE_REF_PREFIX)
|
||||
? { prefix: `${remote}/`, rest: branch.name.slice(remote.length + 1) }
|
||||
: { prefix: '', rest: branch.name }
|
||||
}
|
||||
|
||||
function BranchRows({ rows, chosen, pick }: {
|
||||
readonly rows: readonly BaseRow[]
|
||||
readonly chosen: string | null
|
||||
readonly pick: (ref: string) => void
|
||||
}): ReactNode {
|
||||
return rows.map(({ branch, remote, tag }) => {
|
||||
const selected = branch.ref === chosen
|
||||
const parts = nameParts(branch, remote)
|
||||
return (
|
||||
<MenuItemButton key={branch.ref} icon={<IconBranchOutlineRegular size={14} />} current={selected}
|
||||
onSelect={() => { pick(branch.ref) }}>
|
||||
<span className={css.option} data-forge-worktree-base={branch.ref}>
|
||||
<span className={css.optionName}>
|
||||
{parts.prefix !== '' && <span className={css.remotePrefix}>{parts.prefix}</span>}
|
||||
{parts.rest}
|
||||
</span>
|
||||
{tag !== undefined && <span className={css.tag}>{tag}</span>}
|
||||
{selected && <IconCheckOutlineRegular size={14} className={css.check} />}
|
||||
</span>
|
||||
</MenuItemButton>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function WorktreeMenu({ from, name, held, bases, choose, nameBranch, t }: {
|
||||
readonly from: string | null
|
||||
readonly name: string | null
|
||||
/** Whether the worktree is being created, which freezes the request. */
|
||||
readonly held: boolean
|
||||
readonly branches: WorktreeToggleInjected['branches']
|
||||
readonly request: WorktreeToggleInjected['request']
|
||||
readonly bases: WorktreeToggleInjected['bases']
|
||||
readonly choose: (ref: string) => void
|
||||
readonly nameBranch: () => void
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const [listed, setListed] = useState<ForgeBranches | null>(null)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const show = (): void => {
|
||||
if (open) {
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
void branches().then((result) => {
|
||||
setLoading(false)
|
||||
if (result === undefined) return
|
||||
setListed(result)
|
||||
setOpen(true)
|
||||
})
|
||||
const { query, setQuery, listing, retry, reset, field } = useBranchSearch(open, bases)
|
||||
const chosen = refOf(from)
|
||||
const close = (): void => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}
|
||||
const items: MenuEntry[] = [
|
||||
{ type: 'label', id: 'title', text: t('worktree.baseMenu') },
|
||||
...(listed?.branches ?? []).map(name => ({
|
||||
id: name,
|
||||
label: name === listed?.current
|
||||
? <span className={css.option}><span className={css.optionName}>{name}</span><span className={css.optionNote}>{t('worktree.currentBranch')}</span></span>
|
||||
: <span className={css.optionName}>{name}</span>,
|
||||
})),
|
||||
]
|
||||
const pick = (ref: string): void => {
|
||||
close()
|
||||
if (ref !== chosen) choose(ref)
|
||||
}
|
||||
const value = listing?.ok === true ? listing.value : null
|
||||
const needle = query.trim().toLowerCase()
|
||||
const matches = (branch: ForgeBaseBranch): boolean => branch.name.toLowerCase().includes(needle)
|
||||
const pinned: BaseRow[] = value === null ? [] : [
|
||||
...value.current === null ? [] : [{ branch: value.current, tag: t('worktree.currentBranch') }],
|
||||
...value.defaults.map(({ remote, ...branch }) => ({ branch, remote, tag: t('worktree.remoteDefault') })),
|
||||
].filter(row => matches(row.branch))
|
||||
const local = (value?.local ?? []).filter(matches).map(branch => ({ branch }))
|
||||
const remotes = (value?.remotes ?? []).map(remote => ({
|
||||
...remote, rows: remote.branches.filter(matches).map(branch => ({ branch, remote: remote.name })),
|
||||
}))
|
||||
.filter(remote => remote.rows.length > 0)
|
||||
const first = pinned[0] ?? local[0] ?? remotes[0]?.rows[0]
|
||||
|
||||
const body: ReactNode = branchSearchStatus({ listing, empty: first === undefined, retry, className: css.status, t }) ?? <>
|
||||
{pinned.length > 0 && <div role="group" aria-label={t('worktree.pinned')}><BranchRows rows={pinned} chosen={chosen} pick={pick} /></div>}
|
||||
{local.length > 0 && (
|
||||
<div role="group" aria-label={t('diff.base.local')}>
|
||||
<div className={css.groupLabel} role="presentation">{t('diff.base.local')}</div>
|
||||
<BranchRows rows={local} chosen={chosen} pick={pick} />
|
||||
</div>
|
||||
)}
|
||||
{remotes.map(remote => (
|
||||
<div key={remote.name} role="group" aria-label={t('worktree.remoteGroup', { remote: remote.name })}>
|
||||
<div className={css.groupLabel} role="presentation">
|
||||
<span className={css.groupName}>{t('worktree.remoteGroup', { remote: remote.name })}</span>
|
||||
{remote.repository !== null && <span className={css.groupRepository}>{remote.repository}</span>}
|
||||
</div>
|
||||
<BranchRows rows={remote.rows} chosen={chosen} pick={pick} />
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
|
||||
const baseText = baseTextOf(from, t)
|
||||
const label = name === null ? baseText : namedTipOf(name, from, t)
|
||||
return (
|
||||
<Menu
|
||||
open={open}
|
||||
items={items}
|
||||
selectedId={base ?? undefined}
|
||||
onSelect={(id) => {
|
||||
setOpen(false)
|
||||
if (id !== base) void request(id)
|
||||
}}
|
||||
onClose={() => { setOpen(false) }}
|
||||
side="bottom"
|
||||
align="end"
|
||||
portal
|
||||
dense
|
||||
className={css.anchor}
|
||||
listClassName={css.menu}
|
||||
onClose={close}
|
||||
anchor={
|
||||
<button type="button" className={css.base} aria-haspopup="menu" aria-expanded={open} disabled={loading || held} onClick={show}>
|
||||
<span className={css.baseLabel}>{base === null ? t('worktree.baseHead') : t('worktree.base', { branch: base })}</span>
|
||||
<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, open && css.chevronOpen)} />
|
||||
</button>
|
||||
<Tooltip label={label} side="bottom" portal delayMs={500}>
|
||||
<button type="button" className={clsx(css.base, name !== null && css.named)} aria-haspopup="menu" aria-expanded={open} aria-label={label}
|
||||
data-forge-base-branch="" disabled={held} onClick={() => { if (open) close(); else setOpen(true) }}>
|
||||
{name === null
|
||||
? <span className={css.baseLabel}>{baseText}</span>
|
||||
: <><span className={css.nameLabel}>{name}</span><span className={css.fromLabel}>{` · ${baseText}`}</span></>}
|
||||
<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, open && css.chevronOpen)} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
}
|
||||
/>
|
||||
>
|
||||
<div className={css.menuRoot} data-forge-worktree-menu="">
|
||||
<div className={css.search}>
|
||||
<Input ref={field} className={clsx(css.searchInput)} icon={<IconSearchOutlineRegular size={14} />} value={query}
|
||||
aria-label={t('diff.base.search')} placeholder={t('diff.base.search')}
|
||||
onChange={(event) => { setQuery(event.target.value) }}
|
||||
onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.branch.ref) }) }} />
|
||||
</div>
|
||||
<div className={css.rows}>{body}</div>
|
||||
<div className={css.footer}>
|
||||
<MenuItemButton icon={name === null ? <IconPlusOutlineRegular size={14} /> : <IconEditOutlineRegular size={14} />}
|
||||
onSelect={() => { close(); nameBranch() }}>
|
||||
<span className={css.option} data-forge-worktree-name-entry="">
|
||||
<span className={css.footerLabel}>{t(name === null ? 'worktree.name.add' : 'worktree.name.label')}</span>
|
||||
<span className={clsx(css.footerValue, name !== null && css.footerName)}>{name ?? t('worktree.name.auto')}</span>
|
||||
</span>
|
||||
</MenuItemButton>
|
||||
</div>
|
||||
</div>
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -110,35 +217,42 @@ function optionOf(state: ForgePanelState | null): {
|
||||
|
||||
/**
|
||||
* Render the worktree option while the Session can still start in a worktree:
|
||||
* the current branch, or the base branch menu once requested, then the checkbox.
|
||||
* A blocked request keeps its selected base visible without a menu; the checkbox
|
||||
* only withdraws it. Branch details support pointer, touch, and keyboard access.
|
||||
* The request stays fixed while the worktree is being created.
|
||||
* @param props - panel snapshot hook, request actions, and copy.
|
||||
* the current branch, or the base and branch name menu once requested, then the
|
||||
* checkbox. The menu searches local branches and each remote's branches and
|
||||
* opens the naming dialog. A blocked request keeps its selected base visible
|
||||
* without a menu; the checkbox only withdraws it. Branch details support
|
||||
* pointer, touch, and keyboard access. The request stays fixed while the
|
||||
* worktree is being created.
|
||||
* @param props - panel snapshot hook, request actions, the base listing, and copy.
|
||||
* @returns the option, or nothing outside a known Git checkout, once a turn started,
|
||||
* the request settled, or no worktree service is mounted.
|
||||
*/
|
||||
export function WorktreeToggle({ usePanel, request, cancel, branches, t }: WorktreeToggleProps): ReactNode {
|
||||
export function WorktreeToggle({ usePanel, request, cancel, bases, t }: WorktreeToggleProps): ReactNode {
|
||||
const state = usePanel(snapshot => snapshot.state)
|
||||
const [pending, setPending] = useState<boolean | null>(null)
|
||||
const [naming, setNaming] = useState(false)
|
||||
const option = optionOf(state)
|
||||
if (state === null || option === undefined) return null
|
||||
const held = state.worktree.creation !== null
|
||||
const requested = pending ?? state.worktree.request !== null
|
||||
const usable = option.blocker === null
|
||||
const disabled = held || pending !== null || (!usable && !requested)
|
||||
const currentRef = option.current === null ? null : `${LOCAL_REF_PREFIX}${option.current}`
|
||||
const current = option.current ?? (option.commit === null ? t('checkout.detached') : t('worktree.detachedTip', { commit: option.commit }))
|
||||
const base = state.worktree.request === null ? option.current : state.worktree.request.from
|
||||
const branchText = requested ? base === null ? t('worktree.baseHead') : t('worktree.base', { branch: base }) : current
|
||||
const from = state.worktree.request === null ? currentRef : state.worktree.request.from
|
||||
const name = state.worktree.request?.name ?? null
|
||||
const requestedText = name === null ? baseTextOf(from, t) : namedTipOf(name, from, t)
|
||||
const branchText = requested ? requestedText : current
|
||||
const branchTip = requested || option.current === null ? branchText : t('worktree.currentBranchTip', { branch: option.current })
|
||||
const change = (checked: boolean): void => {
|
||||
setPending(checked)
|
||||
void (checked ? request(option.current) : cancel()).then(() => { setPending(null) })
|
||||
void (checked ? request(currentRef, null) : cancel()).then(() => { setPending(null) })
|
||||
}
|
||||
return (
|
||||
<span className={css.root} data-forge-worktree="">
|
||||
{requested && usable ? (
|
||||
<BaseMenu base={state.worktree.request?.from ?? option.current} held={held} branches={branches} request={request} t={t} />
|
||||
<WorktreeMenu from={from} name={name} held={held} bases={bases} t={t}
|
||||
choose={(ref) => { void request(ref, name) }} nameBranch={() => { setNaming(true) }} />
|
||||
) : (
|
||||
<Tooltip label={branchTip} side="bottom" portal openOnClick>
|
||||
<button type="button" className={css.current} aria-label={branchTip}
|
||||
@@ -160,6 +274,10 @@ export function WorktreeToggle({ usePanel, request, cancel, branches, t }: Workt
|
||||
{t('worktree.label')}
|
||||
</label>
|
||||
</Tooltip>
|
||||
{naming && requested && (
|
||||
<WorktreeNameDialog mode="name" initial={name ?? state.worktree.namePrefix} prefix={state.worktree.namePrefix} from={from}
|
||||
named={name !== null} submit={next => request(from, next)} close={() => { setNaming(false) }} t={t} />
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* The search shared by the branch pickers: the query, the listing it read, the search field's focus, and the status a
|
||||
* menu shows instead of rows.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode, type RefObject } from 'react'
|
||||
import { Button, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { NS } from './locales.ts'
|
||||
|
||||
/** Milliseconds between the last keystroke of a search and the listing it reads. */
|
||||
const SEARCH_DELAY_MS = 150
|
||||
|
||||
/** A branch picker's search while its menu is shown. */
|
||||
export interface BranchSearch<T> {
|
||||
/** Text in the search field. */
|
||||
readonly query: string
|
||||
/** Change the search text; the listing is read again after a short pause. */
|
||||
readonly setQuery: (query: string) => void
|
||||
/** The last listing that arrived, or null before the first one. */
|
||||
readonly listing: RemoteResult<T> | null
|
||||
/** Read the listing again, as after a failed read. */
|
||||
readonly retry: () => void
|
||||
/** Clear the search text, as when the menu closes. */
|
||||
readonly reset: () => void
|
||||
/** The search field, which takes the keyboard once the menu shows unless the pointer is coarse. */
|
||||
readonly field: RefObject<HTMLInputElement>
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the branches of a picker while its menu is shown: at once on opening and on a retry, and after a pause while
|
||||
* the search text changes. Each new read cancels the one before; the last listing stays until the next arrives.
|
||||
* @param shown - whether the menu is shown.
|
||||
* @param list - reads the branches whose names contain the query; the signal aborts the read.
|
||||
* @returns the search state.
|
||||
*/
|
||||
export function useBranchSearch<T>(
|
||||
shown: boolean,
|
||||
list: (query: string, signal: AbortSignal) => Promise<RemoteResult<T>>,
|
||||
): BranchSearch<T> {
|
||||
const [query, setQuery] = useState('')
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [listing, setListing] = useState<RemoteResult<T> | null>(null)
|
||||
const field = useRef<HTMLInputElement>(null)
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => {
|
||||
void list(query, controller.signal).then((result) => { if (!controller.signal.aborted) setListing(result) })
|
||||
}, query === '' ? 0 : SEARCH_DELAY_MS)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [shown, query, attempt, list])
|
||||
// The portalled menu measures itself hidden before its first frame, and a hidden field cannot take the keyboard.
|
||||
// A touch screen keeps its on-screen keyboard closed until the field is tapped.
|
||||
useEffect(() => {
|
||||
if (!shown || (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)) return
|
||||
const frame = requestAnimationFrame(() => { field.current?.focus() })
|
||||
return () => { cancelAnimationFrame(frame) }
|
||||
}, [shown])
|
||||
const retry = useCallback(() => { setAttempt(count => count + 1) }, [])
|
||||
const reset = useCallback(() => { setQuery('') }, [])
|
||||
return { query, setQuery, listing, retry, reset, field }
|
||||
}
|
||||
|
||||
/**
|
||||
* The status a branch menu shows instead of its rows: reading, a failed read with a retry, or no matching branch.
|
||||
* @param props - the listing, whether no row matches, the retry, the status row's class, and copy.
|
||||
* @returns the status row, or null while the menu shows rows.
|
||||
*/
|
||||
export function branchSearchStatus({ listing, empty, retry, className, t }: {
|
||||
readonly listing: RemoteResult<unknown> | null
|
||||
readonly empty: boolean
|
||||
readonly retry: () => void
|
||||
readonly className: string | undefined
|
||||
} & PropsLocale<typeof NS>): ReactNode {
|
||||
if (listing === null) return <div className={className} role="status"><StateDot state="ongoing" />{t('diff.base.loading')}</div>
|
||||
if (!listing.ok) {
|
||||
return (
|
||||
<div className={className} role="status">
|
||||
<span>{t('toast.branchesFailed')}</span>
|
||||
<Button size="sm" variant="outline" onClick={retry}>{t('retry')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return empty ? <div className={className}>{t('diff.base.empty')}</div> : null
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import { branchLabel } from '../branch-name.ts'
|
||||
import type { ForgePanelState } from '../types.ts'
|
||||
import type { NS } from './locales.ts'
|
||||
|
||||
@@ -52,7 +53,7 @@ export function checkoutLabel(state: ForgePanelState, home: string | undefined,
|
||||
const { root, branch, linked, commit } = state.checkout.checkout
|
||||
const path = abbreviateHomePath(root, home)
|
||||
if (created !== null && created.path === root) {
|
||||
const base = created.from ?? created.baseCommit.slice(0, 7)
|
||||
const base = created.from === null ? created.baseCommit.slice(0, 7) : branchLabel(created.from)
|
||||
return {
|
||||
name: branch ?? commit,
|
||||
detached: branch === null,
|
||||
|
||||
@@ -330,7 +330,6 @@ export const zh = {
|
||||
'worktree.blocked.read-only': '只读模式下无法使用工作树',
|
||||
'worktree.base': '基于 {branch}',
|
||||
'worktree.baseHead': '基于当前 HEAD',
|
||||
'worktree.baseMenu': '选择基准分支',
|
||||
'worktree.currentBranch': '当前分支',
|
||||
'worktree.currentBranchTip': '当前分支:{branch}',
|
||||
'worktree.detachedTip': '未在分支上 · {commit}',
|
||||
@@ -347,6 +346,45 @@ export const zh = {
|
||||
'creation.cancel': '取消',
|
||||
'creation.stopped': '已停止创建工作树',
|
||||
'creation.retry': '重试',
|
||||
'diff.loading': '正在读取变更…',
|
||||
'diff.allFilesLoading': '全部文件',
|
||||
'worktree.pinned': '当前分支与远程默认分支',
|
||||
'worktree.remoteDefault': '远程默认',
|
||||
'worktree.remoteGroup': '远程 · {remote}',
|
||||
'worktree.namedTip': '新分支 {name},基于 {branch}',
|
||||
'worktree.namedTipHead': '新分支 {name},基于当前 HEAD',
|
||||
'worktree.name.add': '指定新分支名称…',
|
||||
'worktree.name.label': '新分支名称',
|
||||
'worktree.name.auto': '自动命名',
|
||||
'nameDialog.title': '命名新分支',
|
||||
'nameDialog.retryTitle': '更改分支名称',
|
||||
'nameDialog.field': '分支名称',
|
||||
'nameDialog.hint': '发送第一条消息时基于 {branch} 新建此分支,工作树目录与分支同名',
|
||||
'nameDialog.hintHead': '发送第一条消息时基于当前 HEAD 新建此分支,工作树目录与分支同名',
|
||||
'nameDialog.prefixOnly': '在前缀后输入名称',
|
||||
'nameDialog.auto': '改回自动命名',
|
||||
'nameDialog.cancel': '取消',
|
||||
'nameDialog.confirm': '确定',
|
||||
'nameDialog.retry': '重试',
|
||||
'nameDialog.close': '关闭',
|
||||
'branchName.empty': '输入分支名称',
|
||||
'branchName.space': '分支名不能包含空格',
|
||||
'branchName.character': '分支名不能包含 ~ ^ : ? * [ \\ 这些字符',
|
||||
'branchName.leading-dash': '分支名不能以“-”开头',
|
||||
'branchName.leading-slash': '分支名不能以“/”开头',
|
||||
'branchName.trailing-slash': '分支名不能以“/”结尾',
|
||||
'branchName.double-slash': '分支名不能包含连续的“/”',
|
||||
'branchName.double-dot': '分支名不能包含“..”',
|
||||
'branchName.trailing-dot': '分支名不能以“.”结尾',
|
||||
'branchName.at': '分支名不能是“@”',
|
||||
'branchName.at-brace': '分支名不能包含“@{”',
|
||||
'branchName.dot-segment': '“/”分隔的每一段都不能以“.”开头',
|
||||
'branchName.lock-segment': '“/”分隔的每一段都不能以“.lock”结尾',
|
||||
'branchName.exists': '分支 {name} 已存在',
|
||||
'branchName.invalid': 'Git 不接受这个分支名',
|
||||
'creation.fetch': '获取 {branch}',
|
||||
'creation.useFetched': '使用上次获取的版本',
|
||||
'creation.rename': '更改名称',
|
||||
'creation.waiting': '消息会在工作树建好后发送',
|
||||
'missing.title': '工作树不可用',
|
||||
'missing.unknown': '工作树恢复尚未完成,暂时无法确认分支 {branch} 的状态。请排除恢复错误后重试,或在项目目录继续',
|
||||
@@ -780,7 +818,6 @@ export const en: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': 'A read-only Session cannot use a worktree',
|
||||
'worktree.base': 'From {branch}',
|
||||
'worktree.baseHead': 'From the current HEAD',
|
||||
'worktree.baseMenu': 'Base branch',
|
||||
'worktree.currentBranch': 'Current',
|
||||
'worktree.currentBranchTip': 'Current branch: {branch}',
|
||||
'worktree.detachedTip': 'Not on a branch · {commit}',
|
||||
@@ -797,6 +834,45 @@ export const en: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'Cancel',
|
||||
'creation.stopped': 'Worktree creation stopped',
|
||||
'creation.retry': 'Retry',
|
||||
'diff.loading': 'Reading changes…',
|
||||
'diff.allFilesLoading': 'All files',
|
||||
'worktree.pinned': 'Current and remote default branches',
|
||||
'worktree.remoteDefault': 'Remote default',
|
||||
'worktree.remoteGroup': 'Remote · {remote}',
|
||||
'worktree.namedTip': 'New branch {name} from {branch}',
|
||||
'worktree.namedTipHead': 'New branch {name} from the current HEAD',
|
||||
'worktree.name.add': 'Name the new branch…',
|
||||
'worktree.name.label': 'New branch name',
|
||||
'worktree.name.auto': 'Generated',
|
||||
'nameDialog.title': 'Name the new branch',
|
||||
'nameDialog.retryTitle': 'Rename the branch',
|
||||
'nameDialog.field': 'Branch name',
|
||||
'nameDialog.hint': 'The first message creates this branch from {branch}; the worktree directory takes its name',
|
||||
'nameDialog.hintHead': 'The first message creates this branch from the current HEAD; the worktree directory takes its name',
|
||||
'nameDialog.prefixOnly': 'Type a name after the prefix',
|
||||
'nameDialog.auto': 'Use a generated name',
|
||||
'nameDialog.cancel': 'Cancel',
|
||||
'nameDialog.confirm': 'Save',
|
||||
'nameDialog.retry': 'Retry',
|
||||
'nameDialog.close': 'Close',
|
||||
'branchName.empty': 'Enter a branch name',
|
||||
'branchName.space': 'Branch names cannot contain spaces',
|
||||
'branchName.character': 'Branch names cannot contain ~ ^ : ? * [ or \\',
|
||||
'branchName.leading-dash': 'Branch names cannot start with “-”',
|
||||
'branchName.leading-slash': 'Branch names cannot start with “/”',
|
||||
'branchName.trailing-slash': 'Branch names cannot end with “/”',
|
||||
'branchName.double-slash': 'Branch names cannot contain “//”',
|
||||
'branchName.double-dot': 'Branch names cannot contain “..”',
|
||||
'branchName.trailing-dot': 'Branch names cannot end with “.”',
|
||||
'branchName.at': 'A branch cannot be named “@”',
|
||||
'branchName.at-brace': 'Branch names cannot contain “@{”',
|
||||
'branchName.dot-segment': 'No part between slashes can start with “.”',
|
||||
'branchName.lock-segment': 'No part between slashes can end with “.lock”',
|
||||
'branchName.exists': 'A branch named {name} already exists',
|
||||
'branchName.invalid': 'Git does not accept this branch name',
|
||||
'creation.fetch': 'Fetch {branch}',
|
||||
'creation.useFetched': 'Use the last fetched version',
|
||||
'creation.rename': 'Rename',
|
||||
'creation.waiting': 'The message is sent once the worktree exists',
|
||||
'missing.title': 'The worktree is unavailable',
|
||||
'missing.unknown': 'Worktree restoration is incomplete and branch {branch} cannot be inspected. Resolve the restoration error and retry, or continue in the project.',
|
||||
@@ -1234,7 +1310,6 @@ export const ja: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': '読み取り専用のセッションではワークツリーを使用できません',
|
||||
'worktree.base': '基点 {branch}',
|
||||
'worktree.baseHead': '現在の HEAD を基点にする',
|
||||
'worktree.baseMenu': '基準ブランチ',
|
||||
'worktree.currentBranch': '現在',
|
||||
'worktree.currentBranchTip': '現在のブランチ:{branch}',
|
||||
'worktree.detachedTip': 'ブランチ上にありません · {commit}',
|
||||
@@ -1251,6 +1326,45 @@ export const ja: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'キャンセル',
|
||||
'creation.stopped': 'ワークツリーの作成を停止しました',
|
||||
'creation.retry': '再試行',
|
||||
'diff.loading': '変更を読み取り中…',
|
||||
'diff.allFilesLoading': 'すべてのファイル',
|
||||
'worktree.pinned': '現在のブランチとリモートのデフォルト',
|
||||
'worktree.remoteDefault': 'リモートのデフォルト',
|
||||
'worktree.remoteGroup': 'リモート · {remote}',
|
||||
'worktree.namedTip': '新しいブランチ {name}、基点 {branch}',
|
||||
'worktree.namedTipHead': '新しいブランチ {name}、基点は現在の HEAD',
|
||||
'worktree.name.add': '新しいブランチに名前を付ける…',
|
||||
'worktree.name.label': '新しいブランチ名',
|
||||
'worktree.name.auto': '自動生成',
|
||||
'nameDialog.title': '新しいブランチに名前を付ける',
|
||||
'nameDialog.retryTitle': 'ブランチ名を変更',
|
||||
'nameDialog.field': 'ブランチ名',
|
||||
'nameDialog.hint': '最初のメッセージの送信時に {branch} からこのブランチを作成し、ワークツリーのディレクトリも同じ名前になります',
|
||||
'nameDialog.hintHead': '最初のメッセージの送信時に現在の HEAD からこのブランチを作成し、ワークツリーのディレクトリも同じ名前になります',
|
||||
'nameDialog.prefixOnly': 'プレフィックスの後に名前を入力してください',
|
||||
'nameDialog.auto': '自動生成の名前に戻す',
|
||||
'nameDialog.cancel': 'キャンセル',
|
||||
'nameDialog.confirm': '保存',
|
||||
'nameDialog.retry': '再試行',
|
||||
'nameDialog.close': '閉じる',
|
||||
'branchName.empty': 'ブランチ名を入力してください',
|
||||
'branchName.space': 'ブランチ名に空白は使えません',
|
||||
'branchName.character': 'ブランチ名に ~ ^ : ? * [ \\ は使えません',
|
||||
'branchName.leading-dash': 'ブランチ名を「-」で始めることはできません',
|
||||
'branchName.leading-slash': 'ブランチ名を「/」で始めることはできません',
|
||||
'branchName.trailing-slash': 'ブランチ名を「/」で終えることはできません',
|
||||
'branchName.double-slash': 'ブランチ名に「//」は使えません',
|
||||
'branchName.double-dot': 'ブランチ名に「..」は使えません',
|
||||
'branchName.trailing-dot': 'ブランチ名を「.」で終えることはできません',
|
||||
'branchName.at': 'ブランチ名を「@」にすることはできません',
|
||||
'branchName.at-brace': 'ブランチ名に「@{」は使えません',
|
||||
'branchName.dot-segment': '「/」で区切った各部分を「.」で始めることはできません',
|
||||
'branchName.lock-segment': '「/」で区切った各部分を「.lock」で終えることはできません',
|
||||
'branchName.exists': 'ブランチ {name} はすでに存在します',
|
||||
'branchName.invalid': 'Git がこのブランチ名を受け付けません',
|
||||
'creation.fetch': '{branch} を取得',
|
||||
'creation.useFetched': '前回取得したバージョンを使う',
|
||||
'creation.rename': '名前を変更',
|
||||
'creation.waiting': 'ワークツリーの作成後にメッセージを送信します',
|
||||
'missing.title': 'ワークツリーを利用できません',
|
||||
'missing.unknown': 'ワークツリーの復元が未完了のため、ブランチ {branch} を確認できません。復元エラーを解消して再試行するか、プロジェクトで続行してください',
|
||||
@@ -1681,7 +1795,6 @@ export const es: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': 'Una sesión de solo lectura no puede usar un árbol de trabajo',
|
||||
'worktree.base': 'Desde {branch}',
|
||||
'worktree.baseHead': 'Desde el HEAD actual',
|
||||
'worktree.baseMenu': 'Rama base',
|
||||
'worktree.currentBranch': 'Actual',
|
||||
'worktree.currentBranchTip': 'Rama actual: {branch}',
|
||||
'worktree.detachedTip': 'Sin rama activa · {commit}',
|
||||
@@ -1698,6 +1811,45 @@ export const es: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'Cancelar',
|
||||
'creation.stopped': 'Creación del árbol de trabajo detenida',
|
||||
'creation.retry': 'Reintentar',
|
||||
'diff.loading': 'Leyendo los cambios…',
|
||||
'diff.allFilesLoading': 'Todos los archivos',
|
||||
'worktree.pinned': 'Rama actual y ramas predeterminadas remotas',
|
||||
'worktree.remoteDefault': 'Predeterminada remota',
|
||||
'worktree.remoteGroup': 'Remoto · {remote}',
|
||||
'worktree.namedTip': 'Rama nueva {name} desde {branch}',
|
||||
'worktree.namedTipHead': 'Rama nueva {name} desde el HEAD actual',
|
||||
'worktree.name.add': 'Poner nombre a la rama nueva…',
|
||||
'worktree.name.label': 'Nombre de la rama nueva',
|
||||
'worktree.name.auto': 'Generado',
|
||||
'nameDialog.title': 'Poner nombre a la rama nueva',
|
||||
'nameDialog.retryTitle': 'Cambiar el nombre de la rama',
|
||||
'nameDialog.field': 'Nombre de la rama',
|
||||
'nameDialog.hint': 'El primer mensaje crea esta rama desde {branch}; el directorio del árbol de trabajo toma su nombre',
|
||||
'nameDialog.hintHead': 'El primer mensaje crea esta rama desde el HEAD actual; el directorio del árbol de trabajo toma su nombre',
|
||||
'nameDialog.prefixOnly': 'Escribe un nombre después del prefijo',
|
||||
'nameDialog.auto': 'Usar un nombre generado',
|
||||
'nameDialog.cancel': 'Cancelar',
|
||||
'nameDialog.confirm': 'Guardar',
|
||||
'nameDialog.retry': 'Reintentar',
|
||||
'nameDialog.close': 'Cerrar',
|
||||
'branchName.empty': 'Escribe un nombre de rama',
|
||||
'branchName.space': 'El nombre de una rama no puede contener espacios',
|
||||
'branchName.character': 'El nombre de una rama no puede contener ~ ^ : ? * [ ni \\',
|
||||
'branchName.leading-dash': 'El nombre de una rama no puede empezar por «-»',
|
||||
'branchName.leading-slash': 'El nombre de una rama no puede empezar por «/»',
|
||||
'branchName.trailing-slash': 'El nombre de una rama no puede terminar en «/»',
|
||||
'branchName.double-slash': 'El nombre de una rama no puede contener «//»',
|
||||
'branchName.double-dot': 'El nombre de una rama no puede contener «..»',
|
||||
'branchName.trailing-dot': 'El nombre de una rama no puede terminar en «.»',
|
||||
'branchName.at': 'Una rama no puede llamarse «@»',
|
||||
'branchName.at-brace': 'El nombre de una rama no puede contener «@{»',
|
||||
'branchName.dot-segment': 'Ninguna parte entre barras puede empezar por «.»',
|
||||
'branchName.lock-segment': 'Ninguna parte entre barras puede terminar en «.lock»',
|
||||
'branchName.exists': 'Ya existe una rama llamada {name}',
|
||||
'branchName.invalid': 'Git no acepta este nombre de rama',
|
||||
'creation.fetch': 'Obtener {branch}',
|
||||
'creation.useFetched': 'Usar la última versión obtenida',
|
||||
'creation.rename': 'Cambiar nombre',
|
||||
'creation.waiting': 'El mensaje se enviará cuando exista el árbol de trabajo',
|
||||
'missing.title': 'El árbol de trabajo no está disponible',
|
||||
'missing.unknown': 'La restauración está incompleta y no se puede consultar la rama {branch}. Resuelve el error y reintenta, o continúa en el proyecto',
|
||||
@@ -2128,7 +2280,6 @@ export const fr: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': 'Une session en lecture seule ne peut pas utiliser d’arbre de travail',
|
||||
'worktree.base': 'Depuis {branch}',
|
||||
'worktree.baseHead': 'Depuis le HEAD actuel',
|
||||
'worktree.baseMenu': 'Branche de base',
|
||||
'worktree.currentBranch': 'Actuelle',
|
||||
'worktree.currentBranchTip': 'Branche actuelle : {branch}',
|
||||
'worktree.detachedTip': 'Aucune branche active · {commit}',
|
||||
@@ -2145,6 +2296,45 @@ export const fr: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'Annuler',
|
||||
'creation.stopped': 'Création de l’arbre de travail arrêtée',
|
||||
'creation.retry': 'Réessayer',
|
||||
'diff.loading': 'Lecture des modifications…',
|
||||
'diff.allFilesLoading': 'Tous les fichiers',
|
||||
'worktree.pinned': 'Branche actuelle et branches par défaut des dépôts distants',
|
||||
'worktree.remoteDefault': 'Par défaut distante',
|
||||
'worktree.remoteGroup': 'Distant · {remote}',
|
||||
'worktree.namedTip': 'Nouvelle branche {name} depuis {branch}',
|
||||
'worktree.namedTipHead': 'Nouvelle branche {name} depuis le HEAD actuel',
|
||||
'worktree.name.add': 'Nommer la nouvelle branche…',
|
||||
'worktree.name.label': 'Nom de la nouvelle branche',
|
||||
'worktree.name.auto': 'Généré',
|
||||
'nameDialog.title': 'Nommer la nouvelle branche',
|
||||
'nameDialog.retryTitle': 'Renommer la branche',
|
||||
'nameDialog.field': 'Nom de la branche',
|
||||
'nameDialog.hint': 'Le premier message crée cette branche depuis {branch} ; le répertoire de l’arbre de travail prend son nom',
|
||||
'nameDialog.hintHead': 'Le premier message crée cette branche depuis le HEAD actuel ; le répertoire de l’arbre de travail prend son nom',
|
||||
'nameDialog.prefixOnly': 'Saisissez un nom après le préfixe',
|
||||
'nameDialog.auto': 'Utiliser un nom généré',
|
||||
'nameDialog.cancel': 'Annuler',
|
||||
'nameDialog.confirm': 'Enregistrer',
|
||||
'nameDialog.retry': 'Réessayer',
|
||||
'nameDialog.close': 'Fermer',
|
||||
'branchName.empty': 'Saisissez un nom de branche',
|
||||
'branchName.space': 'Un nom de branche ne peut pas contenir d’espaces',
|
||||
'branchName.character': 'Un nom de branche ne peut pas contenir ~ ^ : ? * [ ni \\',
|
||||
'branchName.leading-dash': 'Un nom de branche ne peut pas commencer par « - »',
|
||||
'branchName.leading-slash': 'Un nom de branche ne peut pas commencer par « / »',
|
||||
'branchName.trailing-slash': 'Un nom de branche ne peut pas finir par « / »',
|
||||
'branchName.double-slash': 'Un nom de branche ne peut pas contenir « // »',
|
||||
'branchName.double-dot': 'Un nom de branche ne peut pas contenir « .. »',
|
||||
'branchName.trailing-dot': 'Un nom de branche ne peut pas finir par « . »',
|
||||
'branchName.at': 'Une branche ne peut pas s’appeler « @ »',
|
||||
'branchName.at-brace': 'Un nom de branche ne peut pas contenir « @{ »',
|
||||
'branchName.dot-segment': 'Aucune partie entre barres obliques ne peut commencer par « . »',
|
||||
'branchName.lock-segment': 'Aucune partie entre barres obliques ne peut finir par « .lock »',
|
||||
'branchName.exists': 'Une branche nommée {name} existe déjà',
|
||||
'branchName.invalid': 'Git refuse ce nom de branche',
|
||||
'creation.fetch': 'Récupérer {branch}',
|
||||
'creation.useFetched': 'Utiliser la dernière version récupérée',
|
||||
'creation.rename': 'Renommer',
|
||||
'creation.waiting': 'Le message sera envoyé après la création de l’arbre de travail',
|
||||
'missing.title': 'L’arbre de travail est indisponible',
|
||||
'missing.unknown': 'La restauration est incomplète et la branche {branch} ne peut pas être inspectée. Corrigez l’erreur puis réessayez, ou continuez dans le projet',
|
||||
@@ -2575,7 +2765,6 @@ export const de: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': 'Eine schreibgeschützte Sitzung kann keinen Arbeitsbaum verwenden',
|
||||
'worktree.base': 'Aus {branch}',
|
||||
'worktree.baseHead': 'Aus dem aktuellen HEAD',
|
||||
'worktree.baseMenu': 'Basis-Branch',
|
||||
'worktree.currentBranch': 'Aktuell',
|
||||
'worktree.currentBranchTip': 'Aktueller Branch: {branch}',
|
||||
'worktree.detachedTip': 'Auf keinem Branch · {commit}',
|
||||
@@ -2592,6 +2781,45 @@ export const de: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'Abbrechen',
|
||||
'creation.stopped': 'Erstellung des Arbeitsbaums angehalten',
|
||||
'creation.retry': 'Erneut versuchen',
|
||||
'diff.loading': 'Änderungen werden gelesen…',
|
||||
'diff.allFilesLoading': 'Alle Dateien',
|
||||
'worktree.pinned': 'Aktueller Branch und Standard-Branches der Remotes',
|
||||
'worktree.remoteDefault': 'Remote-Standard',
|
||||
'worktree.remoteGroup': 'Remote · {remote}',
|
||||
'worktree.namedTip': 'Neuer Branch {name} aus {branch}',
|
||||
'worktree.namedTipHead': 'Neuer Branch {name} aus dem aktuellen HEAD',
|
||||
'worktree.name.add': 'Neuen Branch benennen…',
|
||||
'worktree.name.label': 'Name des neuen Branches',
|
||||
'worktree.name.auto': 'Generiert',
|
||||
'nameDialog.title': 'Neuen Branch benennen',
|
||||
'nameDialog.retryTitle': 'Branch umbenennen',
|
||||
'nameDialog.field': 'Branch-Name',
|
||||
'nameDialog.hint': 'Die erste Nachricht erstellt diesen Branch aus {branch}; das Arbeitsbaumverzeichnis erhält denselben Namen',
|
||||
'nameDialog.hintHead': 'Die erste Nachricht erstellt diesen Branch aus dem aktuellen HEAD; das Arbeitsbaumverzeichnis erhält denselben Namen',
|
||||
'nameDialog.prefixOnly': 'Namen nach dem Präfix eingeben',
|
||||
'nameDialog.auto': 'Generierten Namen verwenden',
|
||||
'nameDialog.cancel': 'Abbrechen',
|
||||
'nameDialog.confirm': 'Speichern',
|
||||
'nameDialog.retry': 'Erneut versuchen',
|
||||
'nameDialog.close': 'Schließen',
|
||||
'branchName.empty': 'Branch-Namen eingeben',
|
||||
'branchName.space': 'Branch-Namen dürfen keine Leerzeichen enthalten',
|
||||
'branchName.character': 'Branch-Namen dürfen ~ ^ : ? * [ und \\ nicht enthalten',
|
||||
'branchName.leading-dash': 'Branch-Namen dürfen nicht mit „-“ beginnen',
|
||||
'branchName.leading-slash': 'Branch-Namen dürfen nicht mit „/“ beginnen',
|
||||
'branchName.trailing-slash': 'Branch-Namen dürfen nicht auf „/“ enden',
|
||||
'branchName.double-slash': 'Branch-Namen dürfen „//“ nicht enthalten',
|
||||
'branchName.double-dot': 'Branch-Namen dürfen „..“ nicht enthalten',
|
||||
'branchName.trailing-dot': 'Branch-Namen dürfen nicht auf „.“ enden',
|
||||
'branchName.at': 'Ein Branch darf nicht „@“ heißen',
|
||||
'branchName.at-brace': 'Branch-Namen dürfen „@{“ nicht enthalten',
|
||||
'branchName.dot-segment': 'Kein Teil zwischen Schrägstrichen darf mit „.“ beginnen',
|
||||
'branchName.lock-segment': 'Kein Teil zwischen Schrägstrichen darf auf „.lock“ enden',
|
||||
'branchName.exists': 'Ein Branch namens {name} existiert bereits',
|
||||
'branchName.invalid': 'Git akzeptiert diesen Branch-Namen nicht',
|
||||
'creation.fetch': '{branch} abrufen',
|
||||
'creation.useFetched': 'Zuletzt abgerufene Version verwenden',
|
||||
'creation.rename': 'Umbenennen',
|
||||
'creation.waiting': 'Die Nachricht wird gesendet, sobald der Arbeitsbaum erstellt ist',
|
||||
'missing.title': 'Arbeitsbaum nicht verfügbar',
|
||||
'missing.unknown': 'Die Wiederherstellung ist unvollständig und Branch {branch} kann nicht geprüft werden. Den Fehler beheben und erneut versuchen oder im Projekt fortfahren',
|
||||
@@ -3022,7 +3250,6 @@ export const ru: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': 'Сеанс только для чтения не может использовать рабочее дерево',
|
||||
'worktree.base': 'На основе {branch}',
|
||||
'worktree.baseHead': 'На основе текущего HEAD',
|
||||
'worktree.baseMenu': 'Базовая ветка',
|
||||
'worktree.currentBranch': 'Текущая',
|
||||
'worktree.currentBranchTip': 'Текущая ветка: {branch}',
|
||||
'worktree.detachedTip': 'Вне ветки · {commit}',
|
||||
@@ -3039,6 +3266,45 @@ export const ru: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'Отмена',
|
||||
'creation.stopped': 'Создание рабочего дерева остановлено',
|
||||
'creation.retry': 'Повторить',
|
||||
'diff.loading': 'Чтение изменений…',
|
||||
'diff.allFilesLoading': 'Все файлы',
|
||||
'worktree.pinned': 'Текущая ветка и ветки по умолчанию удалённых репозиториев',
|
||||
'worktree.remoteDefault': 'По умолчанию на удалённом',
|
||||
'worktree.remoteGroup': 'Удалённый · {remote}',
|
||||
'worktree.namedTip': 'Новая ветка {name} от {branch}',
|
||||
'worktree.namedTipHead': 'Новая ветка {name} от текущего HEAD',
|
||||
'worktree.name.add': 'Назвать новую ветку…',
|
||||
'worktree.name.label': 'Имя новой ветки',
|
||||
'worktree.name.auto': 'Создаётся автоматически',
|
||||
'nameDialog.title': 'Назвать новую ветку',
|
||||
'nameDialog.retryTitle': 'Переименовать ветку',
|
||||
'nameDialog.field': 'Имя ветки',
|
||||
'nameDialog.hint': 'Первое сообщение создаст эту ветку от {branch}; каталог рабочего дерева получит то же имя',
|
||||
'nameDialog.hintHead': 'Первое сообщение создаст эту ветку от текущего HEAD; каталог рабочего дерева получит то же имя',
|
||||
'nameDialog.prefixOnly': 'Введите имя после префикса',
|
||||
'nameDialog.auto': 'Использовать созданное имя',
|
||||
'nameDialog.cancel': 'Отмена',
|
||||
'nameDialog.confirm': 'Сохранить',
|
||||
'nameDialog.retry': 'Повторить',
|
||||
'nameDialog.close': 'Закрыть',
|
||||
'branchName.empty': 'Введите имя ветки',
|
||||
'branchName.space': 'Имя ветки не может содержать пробелы',
|
||||
'branchName.character': 'Имя ветки не может содержать ~ ^ : ? * [ и \\',
|
||||
'branchName.leading-dash': 'Имя ветки не может начинаться с «-»',
|
||||
'branchName.leading-slash': 'Имя ветки не может начинаться с «/»',
|
||||
'branchName.trailing-slash': 'Имя ветки не может заканчиваться на «/»',
|
||||
'branchName.double-slash': 'Имя ветки не может содержать «//»',
|
||||
'branchName.double-dot': 'Имя ветки не может содержать «..»',
|
||||
'branchName.trailing-dot': 'Имя ветки не может заканчиваться на «.»',
|
||||
'branchName.at': 'Ветка не может называться «@»',
|
||||
'branchName.at-brace': 'Имя ветки не может содержать «@{»',
|
||||
'branchName.dot-segment': 'Ни одна часть между косыми чертами не может начинаться с «.»',
|
||||
'branchName.lock-segment': 'Ни одна часть между косыми чертами не может заканчиваться на «.lock»',
|
||||
'branchName.exists': 'Ветка {name} уже существует',
|
||||
'branchName.invalid': 'Git не принимает это имя ветки',
|
||||
'creation.fetch': 'Получение {branch}',
|
||||
'creation.useFetched': 'Использовать последнюю полученную версию',
|
||||
'creation.rename': 'Переименовать',
|
||||
'creation.waiting': 'Сообщение будет отправлено после создания рабочего дерева',
|
||||
'missing.title': 'Рабочее дерево недоступно',
|
||||
'missing.unknown': 'Восстановление не завершено, ветка {branch} недоступна для проверки. Устраните ошибку и повторите попытку или продолжите в проекте',
|
||||
@@ -3469,7 +3735,6 @@ export const pt: Record<ForgePanelKey, string> = {
|
||||
'worktree.blocked.read-only': 'Uma sessão somente leitura não pode usar uma árvore de trabalho',
|
||||
'worktree.base': 'A partir de {branch}',
|
||||
'worktree.baseHead': 'A partir do HEAD atual',
|
||||
'worktree.baseMenu': 'Branch base',
|
||||
'worktree.currentBranch': 'Atual',
|
||||
'worktree.currentBranchTip': 'Branch atual: {branch}',
|
||||
'worktree.detachedTip': 'Fora de uma branch · {commit}',
|
||||
@@ -3486,6 +3751,45 @@ export const pt: Record<ForgePanelKey, string> = {
|
||||
'creation.cancel': 'Cancelar',
|
||||
'creation.stopped': 'Criação da árvore de trabalho interrompida',
|
||||
'creation.retry': 'Tentar novamente',
|
||||
'diff.loading': 'Lendo as alterações…',
|
||||
'diff.allFilesLoading': 'Todos os arquivos',
|
||||
'worktree.pinned': 'Branch atual e branches padrão remotos',
|
||||
'worktree.remoteDefault': 'Padrão remoto',
|
||||
'worktree.remoteGroup': 'Remoto · {remote}',
|
||||
'worktree.namedTip': 'Branch novo {name} a partir de {branch}',
|
||||
'worktree.namedTipHead': 'Branch novo {name} a partir do HEAD atual',
|
||||
'worktree.name.add': 'Dar nome ao branch novo…',
|
||||
'worktree.name.label': 'Nome do branch novo',
|
||||
'worktree.name.auto': 'Gerado',
|
||||
'nameDialog.title': 'Dar nome ao branch novo',
|
||||
'nameDialog.retryTitle': 'Renomear o branch',
|
||||
'nameDialog.field': 'Nome do branch',
|
||||
'nameDialog.hint': 'A primeira mensagem cria este branch a partir de {branch}; o diretório da árvore de trabalho recebe o mesmo nome',
|
||||
'nameDialog.hintHead': 'A primeira mensagem cria este branch a partir do HEAD atual; o diretório da árvore de trabalho recebe o mesmo nome',
|
||||
'nameDialog.prefixOnly': 'Digite um nome depois do prefixo',
|
||||
'nameDialog.auto': 'Usar um nome gerado',
|
||||
'nameDialog.cancel': 'Cancelar',
|
||||
'nameDialog.confirm': 'Salvar',
|
||||
'nameDialog.retry': 'Tentar novamente',
|
||||
'nameDialog.close': 'Fechar',
|
||||
'branchName.empty': 'Digite um nome de branch',
|
||||
'branchName.space': 'Nomes de branch não podem conter espaços',
|
||||
'branchName.character': 'Nomes de branch não podem conter ~ ^ : ? * [ nem \\',
|
||||
'branchName.leading-dash': 'Nomes de branch não podem começar com “-”',
|
||||
'branchName.leading-slash': 'Nomes de branch não podem começar com “/”',
|
||||
'branchName.trailing-slash': 'Nomes de branch não podem terminar com “/”',
|
||||
'branchName.double-slash': 'Nomes de branch não podem conter “//”',
|
||||
'branchName.double-dot': 'Nomes de branch não podem conter “..”',
|
||||
'branchName.trailing-dot': 'Nomes de branch não podem terminar com “.”',
|
||||
'branchName.at': 'Um branch não pode se chamar “@”',
|
||||
'branchName.at-brace': 'Nomes de branch não podem conter “@{”',
|
||||
'branchName.dot-segment': 'Nenhuma parte entre barras pode começar com “.”',
|
||||
'branchName.lock-segment': 'Nenhuma parte entre barras pode terminar com “.lock”',
|
||||
'branchName.exists': 'Já existe um branch chamado {name}',
|
||||
'branchName.invalid': 'O Git não aceita este nome de branch',
|
||||
'creation.fetch': 'Obter {branch}',
|
||||
'creation.useFetched': 'Usar a última versão obtida',
|
||||
'creation.rename': 'Renomear',
|
||||
'creation.waiting': 'A mensagem será enviada após a criação da árvore de trabalho',
|
||||
'missing.title': 'A árvore de trabalho está indisponível',
|
||||
'missing.unknown': 'A restauração está incompleta e não é possível inspecionar a branch {branch}. Corrija o erro e tente novamente ou continue no projeto',
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
createNoticeSource, createPanelSource, createStreamSource, foldStates, type PanelSource,
|
||||
} from './source.ts'
|
||||
import { numberOf } from './status.ts'
|
||||
import type { WorktreeRequestResult } from './WorktreeNameDialog.tsx'
|
||||
import { WorktreeProgress, type WorktreeProgressInjected } from './WorktreeProgress.tsx'
|
||||
import { WorktreeSettings } from './WorktreeSettings.tsx'
|
||||
import { WorktreeSettingsForm, type WorktreeSettings as WorktreeSettingsFields } from './worktree-settings-form.ts'
|
||||
@@ -388,6 +389,15 @@ function registerUi(ctx: Context): void {
|
||||
},
|
||||
}
|
||||
}
|
||||
/** Request a worktree; a refused branch name goes back to the naming dialog, any other failure to a toast. */
|
||||
const requestWorktree = async (sessionId: SessionId, from: string | null, name: string | null): Promise<WorktreeRequestResult> => {
|
||||
const result = await ctx.remote.forgePanel.requestWorktree(sessionId, from, name)
|
||||
if (result.ok) return 'accepted'
|
||||
if (result.error.code === 'forgePanel/branch-exists') return 'branch-exists'
|
||||
if (result.error.code === 'forgePanel/invalid-name') return 'invalid-name'
|
||||
settled(result, 'toast.worktreeFailed', { 'forgePanel/session-started': 'toast.worktreeStarted' })
|
||||
return 'failed'
|
||||
}
|
||||
const progressFace = (sessionId: SessionId): WorktreeProgressInjected => {
|
||||
const store = storesOf(sessionId)
|
||||
return {
|
||||
@@ -395,9 +405,10 @@ function registerUi(ctx: Context): void {
|
||||
stop: () => {
|
||||
void ctx.remote.forgePanel.stopCreation(sessionId).then(result => settled(result, 'toast.worktreeFailed'))
|
||||
},
|
||||
retry: () => {
|
||||
void ctx.remote.forgePanel.retryWorktree(sessionId).then(result => settled(result, 'toast.worktreeFailed'))
|
||||
retry: (fetch) => {
|
||||
void ctx.remote.forgePanel.retryWorktree(sessionId, fetch).then(result => settled(result, 'toast.worktreeFailed'))
|
||||
},
|
||||
request: async (from, name) => await requestWorktree(sessionId, from, name),
|
||||
withdraw: () => {
|
||||
void ctx.remote.forgePanel.cancelWorktree(sessionId).then(result => settled(result, 'toast.worktreeFailed'))
|
||||
},
|
||||
@@ -408,16 +419,13 @@ function registerUi(ctx: Context): void {
|
||||
}
|
||||
}
|
||||
const worktreeFace = (sessionId: SessionId): WorktreeToggleInjected => {
|
||||
const worktreeCodes: Partial<Record<string, ForgePanelKey>> = { 'forgePanel/session-started': 'toast.worktreeStarted' }
|
||||
const store = storesOf(sessionId)
|
||||
return {
|
||||
hooks: { panel: store.panel.hooks.panel },
|
||||
request: async from => settled(await ctx.remote.forgePanel.requestWorktree(sessionId, from), 'toast.worktreeFailed', worktreeCodes),
|
||||
cancel: async () => settled(await ctx.remote.forgePanel.cancelWorktree(sessionId), 'toast.worktreeFailed', worktreeCodes),
|
||||
branches: async () => {
|
||||
const result = await ctx.remote.forgePanel.branches(sessionId)
|
||||
return settled(result, 'toast.branchesFailed') && result.ok ? result.value : undefined
|
||||
},
|
||||
request: async (from, name) => await requestWorktree(sessionId, from, name),
|
||||
cancel: async () => settled(await ctx.remote.forgePanel.cancelWorktree(sessionId), 'toast.worktreeFailed',
|
||||
{ 'forgePanel/session-started': 'toast.worktreeStarted' }),
|
||||
bases: (query, signal) => ctx.remote.forgePanel.worktreeBases(sessionId, query, signal),
|
||||
}
|
||||
}
|
||||
ctx.slots.inject('conversation.session.panel.section', function* () {
|
||||
|
||||
@@ -7,9 +7,10 @@ import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import type { SubprocessCollectedOutputs } from '@deepseek-ai/dsh-subprocess'
|
||||
import { deadline } from '@deepseek-ai/dsh-timeout'
|
||||
import { baseBranches, parseName, parseRemotes, parseTopLevel } from './parse.ts'
|
||||
import { LOCAL_REF_PREFIX } from './branch-name.ts'
|
||||
import { parseName, parseRemotes, parseTopLevel } from './parse.ts'
|
||||
import type { GitRemote } from './parse.ts'
|
||||
import type { ForgeBranches, ForgeCheckout } from './types.ts'
|
||||
import type { ForgeCheckout } from './types.ts'
|
||||
|
||||
/** Resolved Git executable and process limits. */
|
||||
export interface GitConfig {
|
||||
@@ -128,36 +129,6 @@ export async function inspectCheckout(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List the local branches that can start a worktree of the checkout containing
|
||||
* `directory`, using the Session's permissions as in {@link inspectCheckout}.
|
||||
* @param ctx - context that provides `subprocess`, `sandbox`, and `sandboxPolicy`.
|
||||
* @param config - executable and process limits.
|
||||
* @param session - Session whose sandbox policy and execution world apply.
|
||||
* @param directory - absolute directory inside the checkout.
|
||||
* @param limit - most branch names to return.
|
||||
* @param signal - cancellation of every command.
|
||||
* @returns the checked-out branch and local branches, the checked-out one first and then most recently committed first.
|
||||
* @throws when `directory` is not inside a checkout, or Git cannot run, fails, times out, or prints more than `maxOutputBytes`.
|
||||
*/
|
||||
export async function listBranches(
|
||||
ctx: Context,
|
||||
config: GitConfig,
|
||||
session: Session,
|
||||
directory: string,
|
||||
limit: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ForgeBranches> {
|
||||
const [current, refs] = await together(signal, (signal) => {
|
||||
const git = gitIn(ctx, config, session, directory, signal)
|
||||
return [
|
||||
currentBranch(git),
|
||||
git('for-each-ref', ['for-each-ref', '--sort=-committerdate', `--count=${limit}`, '--format=%(refname:lstrip=2)', 'refs/heads/']),
|
||||
] as const
|
||||
})
|
||||
return { current, branches: baseBranches(current, refs.stdout, limit) }
|
||||
}
|
||||
|
||||
/** A failed read cancels its siblings and returns only after every read has finished cleanup. */
|
||||
async function together<T extends readonly Promise<unknown>[]>(
|
||||
signal: AbortSignal,
|
||||
@@ -215,10 +186,14 @@ export function gitIn(ctx: Context, config: GitConfig, session: Session, directo
|
||||
runGit(ctx, config, policy, directory, name, args, signal, allowedExitCodes, configOverrides)
|
||||
}
|
||||
|
||||
/** Read the checked-out branch, including an unborn one; null when HEAD is detached. */
|
||||
/**
|
||||
* Read the checked-out local branch, including an unborn one; null when HEAD is detached or names a ref outside
|
||||
* `refs/heads/`. The full ref is read because the short form turns `main` into `heads/main` while a tag shares the name.
|
||||
*/
|
||||
async function currentBranch(git: Git): Promise<string | null> {
|
||||
const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', '--short', 'HEAD'], [0, 1])
|
||||
return head.exitCode === 0 ? parseName(head.stdout) : null
|
||||
const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', 'HEAD'], [0, 1])
|
||||
const ref = head.exitCode === 0 ? parseName(head.stdout) : null
|
||||
return ref !== null && ref.startsWith(LOCAL_REF_PREFIX) ? ref.slice(LOCAL_REF_PREFIX.length) : null
|
||||
}
|
||||
|
||||
/** Read the abbreviated commit HEAD names; null while the checked-out branch has no commit. */
|
||||
|
||||
@@ -21,8 +21,9 @@ import type {} from '@deepseek-ai/dsh-session-query'
|
||||
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { gitIn, inspectCheckout, listBranches } from './git.ts'
|
||||
import { gitIn, hasBranch, inspectCheckout } from './git.ts'
|
||||
import type { Inspection } from './git.ts'
|
||||
import { branchNameProblem } from './branch-name.ts'
|
||||
import { parseDiff } from './diff.ts'
|
||||
import {
|
||||
aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint,
|
||||
@@ -35,14 +36,15 @@ import { lensVersion } from './lens-version.ts'
|
||||
import { rangeStart } from './commit-range.ts'
|
||||
import { ATTRIBUTES_PATH, FileLayers } from './layers.ts'
|
||||
import { missingWorktree, SessionPanel } from './panel.ts'
|
||||
import { BASE_REF_PREFIXES, parseWorktreeBases, remoteOrder, remoteRepository } from './parse.ts'
|
||||
import { PatchCache } from './patch-cache.ts'
|
||||
import { ReviewCache } from './review-cache.ts'
|
||||
import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts'
|
||||
import type { PanelConfig } from './panel.ts'
|
||||
import type {
|
||||
Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile,
|
||||
Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile,
|
||||
ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState,
|
||||
} from './types.ts'
|
||||
import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts'
|
||||
import type { HeldWork } from './worktree.ts'
|
||||
@@ -56,11 +58,10 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
}
|
||||
|
||||
/** Panel limits plus the branch and commit listing limits, the worktree branch prefix, and the lens and annotation limits. */
|
||||
/** Panel limits and worktree branch prefix plus the branch and commit listing limits and the lens and annotation limits. */
|
||||
type ControllerConfig = PanelConfig & {
|
||||
readonly maxBranches: number
|
||||
readonly maxCommits: number
|
||||
readonly worktreePrefix: string
|
||||
readonly lensTimeoutMs: number
|
||||
readonly maxLensReadBytes: number
|
||||
readonly maxCachedLensBytes: number
|
||||
@@ -141,7 +142,8 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
] as const) {
|
||||
if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`)
|
||||
}
|
||||
if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name')
|
||||
// Generated names append hexadecimal digits, so the prefix followed by one digit must be a valid branch name.
|
||||
if (branchNameProblem(`${resolved.worktreePrefix}0`) !== null) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name')
|
||||
for (const key of ['testPaths', 'interfacePaths'] as const) {
|
||||
if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`)
|
||||
}
|
||||
@@ -241,15 +243,24 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* List the local branches that can start a worktree of the Session's current checkout.
|
||||
* @param session - Session whose current directory is listed.
|
||||
* List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each
|
||||
* remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the
|
||||
* order the panel recognizes code hosts.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first.
|
||||
* @throws when the current directory is not inside a checkout or Git fails.
|
||||
* @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
*/
|
||||
@Remote
|
||||
async branches(session: Session, signal: AbortSignal): Promise<ForgeBranches> {
|
||||
return await listBranches(this.home, this.config, session, this.home.workingDirectory.get(session), this.config.maxBranches, signal)
|
||||
async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases> {
|
||||
signal.throwIfAborted()
|
||||
const inspection = await this.checkoutOf(session, signal)
|
||||
// A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output.
|
||||
const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal)
|
||||
const refs = await git('worktree-bases', ['for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES])
|
||||
return parseWorktreeBases(refs.stdout, inspection.checkout.branch, remoteOrder(inspection.upstream, inspection.remotes), query,
|
||||
this.config.maxBranches, remote => remoteRepository(remote, url => this.home.forge.repositoryFromRemote(url)))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -820,24 +831,34 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
/**
|
||||
* Ask for a new worktree before the Session's first turn, replacing an open
|
||||
* request and forgetting a failed attempt. While the next message waits in
|
||||
* the inbox, or else at the first step proposal, the panel creates a branch
|
||||
* from `from`, or from HEAD of the current checkout when it is null, and
|
||||
* enters its checkout. A message that already waits after a failed or
|
||||
* stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}.
|
||||
* the inbox, or else at the first step proposal, the panel creates the
|
||||
* branch `name`, or a generated branch per attempt when it is null, from
|
||||
* `from`, or from HEAD of the current checkout when it is null, and enters
|
||||
* its checkout; a remote-tracking `from` is fetched first. A message that
|
||||
* already waits after a failed or stopped attempt keeps waiting for
|
||||
* {@link ForgePanelController.retryWorktree}.
|
||||
* @param session - Session without a started turn.
|
||||
* @param from - local base branch, or null for HEAD.
|
||||
* @param from - full name of a local or remote-tracking base branch, or null for HEAD.
|
||||
* @param name - new branch name, or null to generate one per attempt.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable`
|
||||
* @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks
|
||||
* a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`;
|
||||
* `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable`
|
||||
* without a worktree service; `forgePanel/session-started` after a turn started or the worktree was
|
||||
* created; `forgePanel/session-busy` while the worktree is being created.
|
||||
*/
|
||||
@Remote
|
||||
async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise<void> {
|
||||
async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted()
|
||||
if (from?.length === 0) throw new RemoteError('forgePanel/invalid-branch', 'The base branch name is empty', {})
|
||||
this.editableWorktree(session)
|
||||
if (name !== null) {
|
||||
await this.checkBranchName(session, name, signal)
|
||||
// The Session may have started or begun a creation while Git answered.
|
||||
this.editableWorktree(session)
|
||||
}
|
||||
this.creations.forget(session)
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from })
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from, ...name === null ? {} : { name } })
|
||||
this.creations.recheck(session)
|
||||
}
|
||||
|
||||
@@ -873,16 +894,19 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Make another attempt, with a new branch name, at the worktree a message
|
||||
* of the Session waits for after a failed or stopped attempt.
|
||||
* Make another attempt, on the requested branch name or a new generated
|
||||
* one, at the worktree a message of the Session waits for after a failed or
|
||||
* stopped attempt.
|
||||
* @param session - Session whose message waits.
|
||||
* @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the
|
||||
* commit last fetched.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/not-waiting` when no message waits or an attempt is running.
|
||||
*/
|
||||
@Remote
|
||||
async retryWorktree(session: Session, signal: AbortSignal): Promise<void> {
|
||||
async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted()
|
||||
if (!this.creations.retry(session)) {
|
||||
if (!this.creations.retry(session, fetch)) {
|
||||
throw new RemoteError('forgePanel/not-waiting', 'No message waits for another attempt at the worktree', {})
|
||||
}
|
||||
}
|
||||
@@ -1060,6 +1084,18 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
return this.worktreeStates.stateOf(session)
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a new branch name that breaks a branch-name rule or names a local branch of the Session's checkout. The
|
||||
* rules cover every name `git check-ref-format` refuses, which the worktree service runs again at creation.
|
||||
*/
|
||||
private async checkBranchName(session: Session, name: string, signal: AbortSignal): Promise<void> {
|
||||
if (branchNameProblem(name) !== null) throw new RemoteError('forgePanel/invalid-name', 'The new branch name is invalid', {})
|
||||
const root = (await this.checkoutOf(session, signal)).checkout.root
|
||||
if (await hasBranch(this.home, this.config, session, root, name, signal)) {
|
||||
throw new RemoteError('forgePanel/branch-exists', `A local branch named ${name} exists`, {})
|
||||
}
|
||||
}
|
||||
|
||||
private editableWorktree(session: Session): ForgeWorktreeState {
|
||||
if (this.home.get('worktrees') === undefined) {
|
||||
throw new RemoteError('forgePanel/worktrees-unavailable', 'No worktree service is mounted', {})
|
||||
@@ -1346,21 +1382,4 @@ function actionError(failure: ForgeActionFailure): RemoteError {
|
||||
return new RemoteError(code, failure.message, {})
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `prefix` followed by hexadecimal digits is a branch name that Git
|
||||
* accepts: no leading `-` or `/`, no empty component, no component that
|
||||
* starts with `.` or ends with `.lock`, and none of `..`, `@{`, whitespace,
|
||||
* control characters, `~`, `^`, `:`, `?`, `*`, `[`, or `\`.
|
||||
* @param prefix - configured worktree branch prefix.
|
||||
* @returns whether every generated name passes `git check-ref-format --branch`.
|
||||
*/
|
||||
function branchPrefix(prefix: string): boolean {
|
||||
const name = `${prefix}0`
|
||||
if (name.startsWith('-') || name.includes('..') || name.includes('@{')) return false
|
||||
for (const char of name) {
|
||||
if (char <= ' ' || char === '\x7f' || '~^:?*[\\'.includes(char)) return false
|
||||
}
|
||||
return name.split('/').every(part => part.length > 0 && !part.startsWith('.') && !part.endsWith('.lock'))
|
||||
}
|
||||
|
||||
export default ForgePanelController
|
||||
@@ -17,6 +17,7 @@ import { gitIn, GitOutputTooLarge } from './git.ts'
|
||||
import type { Git, GitConfig, GitOutput, Inspection } from './git.ts'
|
||||
import { ATTRIBUTES_PATH } from './layers.ts'
|
||||
import type { FileLayers } from './layers.ts'
|
||||
import { branchLabel } from './branch-name.ts'
|
||||
import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts'
|
||||
import type {
|
||||
ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree,
|
||||
@@ -114,7 +115,8 @@ const BINARY_PROBE = 8000
|
||||
*/
|
||||
export async function forkPoint(git: Git, inspection: Inspection, created: ForgeSessionWorktree | null): Promise<ForkPoint | null> {
|
||||
if (created !== null && created.path === inspection.checkout.root) {
|
||||
return { commit: created.baseCommit, label: created.from ?? created.baseCommit.slice(0, 7), worktree: true }
|
||||
const label = created.from === null ? created.baseCommit.slice(0, 7) : branchLabel(created.from)
|
||||
return { commit: created.baseCommit, label, worktree: true }
|
||||
}
|
||||
for (const remote of remoteOrder(inspection.upstream, inspection.remotes)) {
|
||||
const head = await git('remote-head', ['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote.name}/HEAD`], [0, 1, 128])
|
||||
|
||||
@@ -27,6 +27,8 @@ import type { WorktreeCreations } from './worktree.ts'
|
||||
export interface PanelConfig extends DiffConfig {
|
||||
/** Deadline in milliseconds for one provider sign-in probe. */
|
||||
readonly readinessTimeoutMs: number
|
||||
/** Prefix of generated worktree branch names, which a name the user types starts from. */
|
||||
readonly worktreePrefix: string
|
||||
}
|
||||
|
||||
/** The checkout's upstream branch and the remote URL its change requests are looked up at. */
|
||||
@@ -70,7 +72,7 @@ export class SessionPanel {
|
||||
|
||||
/**
|
||||
* @param ctx - service context that provides the forge, Session, directory, and process services.
|
||||
* @param config - Git limits and the sign-in probe deadline.
|
||||
* @param config - Git limits, the sign-in probe deadline, and the worktree branch name prefix.
|
||||
* @param session - Session the panel describes.
|
||||
* @param worktreeStates - reads the `forgeWorktree` projection of the Session.
|
||||
* @param creations - reads the running creation and restoration, the last failed creation, and what a message of the
|
||||
@@ -229,6 +231,7 @@ export class SessionPanel {
|
||||
return {
|
||||
editable: this.ctx.get('worktrees') !== undefined && !state.locked && state.created === null,
|
||||
blocker: this.blocker,
|
||||
namePrefix: this.config.worktreePrefix,
|
||||
request: state.request,
|
||||
created: state.created,
|
||||
creation: this.creations.of(this.session),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Parsers for the porcelain output of the read-only Git commands the panel runs. */
|
||||
|
||||
import type { ForgeBaseBranch } from './types.ts'
|
||||
import type { ForgeBaseBranch, ForgeRemoteDefault, ForgeWorktreeBases } from './types.ts'
|
||||
|
||||
/** One remote with the URLs `git remote -v` prints for it. */
|
||||
export interface GitRemote {
|
||||
@@ -23,7 +23,7 @@ export function parseTopLevel(output: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the first line of a one-name output such as `git symbolic-ref --short HEAD`.
|
||||
* Read the first line of a one-name output such as `git symbolic-ref --quiet HEAD`.
|
||||
* @param output - stdout of the command.
|
||||
* @returns the name, or null when the command printed none.
|
||||
*/
|
||||
@@ -67,16 +67,73 @@ export function parseBaseBranches(
|
||||
}
|
||||
|
||||
/**
|
||||
* Order worktree base branches: the checked-out branch first, then the other
|
||||
* listed branches in listed order.
|
||||
* Select the branches a new worktree can start from out of `git for-each-ref` output, keeping its order within
|
||||
* each group: the checked-out branch, each remote's default branch, the other local branches, and the other
|
||||
* remote-tracking branches of each remote. A remote's default branch is the branch its `refs/remotes/<remote>/HEAD`
|
||||
* names; remote-tracking branches of unconfigured remotes and other symbolic refs are left out.
|
||||
* @param output - stdout of `git for-each-ref --format=%(refname)%00%(symref)` over {@link BASE_REF_PREFIXES}.
|
||||
* @param current - checked-out branch, or null when HEAD is detached.
|
||||
* @param output - stdout of `git for-each-ref --format=%(refname:lstrip=2) refs/heads/`.
|
||||
* @param limit - most names to return.
|
||||
* @returns distinct branch names, at most `limit`.
|
||||
* @param remotes - configured remotes in the order their groups take.
|
||||
* @param query - text the names must contain, ignoring case; empty or blank for every branch.
|
||||
* @param limit - most branches in the local group and in each remote's group.
|
||||
* @param repositoryOf - the repository a remote's group names.
|
||||
* @returns the branches, with remotes that have no listed branch left out.
|
||||
*/
|
||||
export function baseBranches(current: string | null, output: string, limit: number): string[] {
|
||||
const listed = output.split(/\r?\n/).filter(name => name.length > 0 && name !== current)
|
||||
return (current === null ? listed : [current, ...listed]).slice(0, limit)
|
||||
export function parseWorktreeBases(
|
||||
output: string,
|
||||
current: string | null,
|
||||
remotes: readonly GitRemote[],
|
||||
query: string,
|
||||
limit: number,
|
||||
repositoryOf: (remote: GitRemote) => string | null,
|
||||
): ForgeWorktreeBases {
|
||||
const [heads, tracking] = BASE_REF_PREFIXES
|
||||
const needle = query.trim().toLowerCase()
|
||||
const matches = (name: string): boolean => name.toLowerCase().includes(needle)
|
||||
const listed: string[] = []
|
||||
const remoteHeads = new Map<string, string>()
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
const [ref = '', symref = ''] = line.split('\0')
|
||||
if (ref.length === 0) continue
|
||||
if (symref.length === 0) {
|
||||
listed.push(ref)
|
||||
continue
|
||||
}
|
||||
const owner = ref.startsWith(tracking) ? upstreamBranch(ref.slice(tracking.length), remotes) : undefined
|
||||
if (owner?.branch === 'HEAD') remoteHeads.set(owner.remote.name, symref)
|
||||
}
|
||||
const present = new Set(listed)
|
||||
const defaultRefs = new Set<string>()
|
||||
const defaults: ForgeRemoteDefault[] = []
|
||||
for (const remote of remotes) {
|
||||
const target = remoteHeads.get(remote.name)
|
||||
if (target === undefined || !present.has(target) || !target.startsWith(`${tracking}${remote.name}/`)) continue
|
||||
defaultRefs.add(target)
|
||||
const name = target.slice(tracking.length)
|
||||
if (matches(name)) defaults.push({ ref: target, name, remote: remote.name })
|
||||
}
|
||||
const local: ForgeBaseBranch[] = []
|
||||
const groups = remotes.map(remote => ({ remote, branches: [] as ForgeBaseBranch[] }))
|
||||
for (const ref of listed) {
|
||||
if (ref.startsWith(heads)) {
|
||||
const name = ref.slice(heads.length)
|
||||
if (name !== current && local.length < limit && matches(name)) local.push({ ref, name })
|
||||
continue
|
||||
}
|
||||
if (!ref.startsWith(tracking) || defaultRefs.has(ref)) continue
|
||||
const name = ref.slice(tracking.length)
|
||||
const owner = upstreamBranch(name, remotes)?.remote
|
||||
const group = groups.find(candidate => candidate.remote === owner)
|
||||
if (group !== undefined && group.branches.length < limit && matches(name)) group.branches.push({ ref, name })
|
||||
}
|
||||
const currentRef = `${heads}${current ?? ''}`
|
||||
return {
|
||||
current: current !== null && present.has(currentRef) && matches(current) ? { ref: currentRef, name: current } : null,
|
||||
defaults,
|
||||
local,
|
||||
remotes: groups.filter(group => group.branches.length > 0)
|
||||
.map(({ remote, branches }) => ({ name: remote.name, repository: repositoryOf(remote), branches })),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,6 +180,25 @@ export function upstreamBranch(
|
||||
return remote === undefined ? undefined : { remote, branch: upstream.slice(remote.name.length + 1) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Name the repository a remote's group shows: `owner/name` of the first URL a provider recognizes, else the first URL
|
||||
* without the user name and password a URL can carry as a token, since the name reaches the browser.
|
||||
* @param remote - remote with its URLs, fetch URL first.
|
||||
* @param recognize - the repository a provider recognizes from a URL, or undefined.
|
||||
* @returns the name, or null for a remote without a URL.
|
||||
*/
|
||||
export function remoteRepository(
|
||||
remote: GitRemote,
|
||||
recognize: (url: string) => { readonly owner: string; readonly name: string } | undefined,
|
||||
): string | null {
|
||||
for (const url of remote.urls) {
|
||||
const repository = recognize(url)
|
||||
if (repository !== undefined) return `${repository.owner}/${repository.name}`
|
||||
}
|
||||
// A URL's user information ends at the last `@` before its path, query, or fragment.
|
||||
return remote.urls[0]?.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/?#]*@/, '$1') ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Order remotes for code host recognition: the upstream's remote first, then
|
||||
* `origin`, then the rest in listed order.
|
||||
|
||||
@@ -34,7 +34,10 @@ export interface ForgeSessionWorktree {
|
||||
readonly path: string
|
||||
/** Branch created for the checkout. */
|
||||
readonly branch: string
|
||||
/** Requested base branch, or null when the checkout started from HEAD of the source checkout. */
|
||||
/**
|
||||
* Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels
|
||||
* recorded, or null when the checkout started from HEAD of the source checkout.
|
||||
*/
|
||||
readonly from: string | null
|
||||
/** Commit object name the branch started from. */
|
||||
readonly baseCommit: string
|
||||
@@ -44,8 +47,11 @@ export interface ForgeSessionWorktree {
|
||||
|
||||
/** Payload of the `plugin:client-ui-forge/worktree` record. */
|
||||
export type WorktreeRecord =
|
||||
/** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */
|
||||
| { readonly action: 'request'; readonly from: string | null }
|
||||
/**
|
||||
* Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the
|
||||
* branch `name`, or on a generated branch name when `name` is absent.
|
||||
*/
|
||||
| { readonly action: 'request'; readonly from: string | null; readonly name?: string }
|
||||
/** Withdraw the open request. */
|
||||
| { readonly action: 'cancel' }
|
||||
/** The requested worktree was created and became the Session's working directory. */
|
||||
@@ -57,8 +63,13 @@ export type WorktreeRecord =
|
||||
|
||||
/** One open worktree request. */
|
||||
export interface ForgeWorktreeRequest {
|
||||
/** Base branch, or null for HEAD of the source checkout. */
|
||||
/**
|
||||
* Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or
|
||||
* null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it.
|
||||
*/
|
||||
readonly from: string | null
|
||||
/** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */
|
||||
readonly name: string | null
|
||||
}
|
||||
|
||||
/** Host-only state of the `forgeWorktree` projection. */
|
||||
@@ -88,12 +99,17 @@ export type ForgeWorktreeBlocker =
|
||||
|
||||
/** One running worktree creation. */
|
||||
export interface ForgeWorktreeCreation {
|
||||
/** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
/**
|
||||
* Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then
|
||||
* `checkout` writes the files.
|
||||
*/
|
||||
readonly phase: 'fetch' | 'prepare' | 'checkout'
|
||||
/** Branch the attempt creates. */
|
||||
readonly branch: string
|
||||
/** Base branch, or null for HEAD. */
|
||||
/** Base as the request names it, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetches its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/**
|
||||
* Whether a message waits for the creation before its turn starts. Only
|
||||
* such a creation can be stopped, after which the message keeps waiting; a
|
||||
@@ -112,12 +128,16 @@ export interface ForgeWorktreeRestoration {
|
||||
export interface ForgeWorktreeFailure {
|
||||
/** Branch the attempt created, or null when it failed before naming one. */
|
||||
readonly branch: string | null
|
||||
/** Base branch of the attempt, or null for HEAD. */
|
||||
/** Base of the attempt as the request names it, or null for HEAD. */
|
||||
readonly from: string | null
|
||||
/** Whether the attempt fetched, or tried to fetch, its remote base branch first. */
|
||||
readonly fetch: boolean
|
||||
/** Step that failed. */
|
||||
readonly phase: 'prepare' | 'checkout'
|
||||
readonly phase: 'fetch' | 'prepare' | 'checkout'
|
||||
/** Failure text. */
|
||||
readonly message: string
|
||||
/** Whether the branch or the checkout directory of that name already existed, which another name avoids. */
|
||||
readonly exists: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -142,6 +162,8 @@ export interface ForgePanelWorktree {
|
||||
readonly editable: boolean
|
||||
/** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */
|
||||
readonly blocker: ForgeWorktreeBlocker | null
|
||||
/** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */
|
||||
readonly namePrefix: string
|
||||
/** Open request, or null without one. */
|
||||
readonly request: ForgeWorktreeRequest | null
|
||||
/** Created worktree, or null before creation. */
|
||||
@@ -216,12 +238,35 @@ export interface ForgePanelState {
|
||||
readonly local: ForgeLocalChanges | null
|
||||
}
|
||||
|
||||
/** Local branches offered as the base of a new worktree. */
|
||||
export interface ForgeBranches {
|
||||
/** Checked-out branch, or null when HEAD is detached. */
|
||||
readonly current: string | null
|
||||
/** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */
|
||||
readonly branches: readonly string[]
|
||||
/** Branches offered as the base of a new worktree whose names contain a query. */
|
||||
export interface ForgeWorktreeBases {
|
||||
/** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */
|
||||
readonly current: ForgeBaseBranch | null
|
||||
/** Default branch of each remote that names one with `refs/remotes/<remote>/HEAD`, in remote order. */
|
||||
readonly defaults: readonly ForgeRemoteDefault[]
|
||||
/** Other local branches, most recently committed first, at most `maxBranches`. */
|
||||
readonly local: readonly ForgeBaseBranch[]
|
||||
/**
|
||||
* Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks,
|
||||
* then `origin`, then the others as Git lists them. Remotes without a matching branch are left out.
|
||||
*/
|
||||
readonly remotes: readonly ForgeRemoteBranches[]
|
||||
}
|
||||
|
||||
/** A remote's default branch, which `refs/remotes/<remote>/HEAD` names. */
|
||||
export interface ForgeRemoteDefault extends ForgeBaseBranch {
|
||||
/** Remote the branch belongs to; it may contain `/`. */
|
||||
readonly remote: string
|
||||
}
|
||||
|
||||
/** Remote-tracking branches of one remote, without its default branch. */
|
||||
export interface ForgeRemoteBranches {
|
||||
/** Remote name such as `origin`; it may contain `/`. */
|
||||
readonly name: string
|
||||
/** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */
|
||||
readonly repository: string | null
|
||||
/** Branches named `<remote>/<branch>`, most recently committed first, at most `maxBranches`. */
|
||||
readonly branches: readonly ForgeBaseBranch[]
|
||||
}
|
||||
|
||||
/** A branch the `branch` scope can compare with. */
|
||||
@@ -545,6 +590,10 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
'forgePanel/worktrees-unavailable': Record<string, never>
|
||||
/** The requested base branch name is empty. */
|
||||
'forgePanel/invalid-branch': Record<string, never>
|
||||
/** The requested new branch name breaks one of Git's branch-name rules, or the worktree service's refusal of a leading `-`. */
|
||||
'forgePanel/invalid-name': Record<string, never>
|
||||
/** A local branch with the requested new branch name exists in the Session's checkout. */
|
||||
'forgePanel/branch-exists': Record<string, never>
|
||||
/** The Session has no created worktree to restore or leave. */
|
||||
'forgePanel/no-worktree': Record<string, never>
|
||||
/** The Session's Agent is not loaded or has other work, so its checkout cannot change now. */
|
||||
|
||||
@@ -11,9 +11,10 @@ import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-se
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import { z } from 'zod'
|
||||
import { isRemoteRef } from './branch-name.ts'
|
||||
import type {
|
||||
ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRestoration, ForgeWorktreeState,
|
||||
ForgeWorktreeWaiting, WorktreeRecord,
|
||||
ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRequest, ForgeWorktreeRestoration,
|
||||
ForgeWorktreeState, ForgeWorktreeWaiting, WorktreeRecord,
|
||||
} from './types.ts'
|
||||
|
||||
/** Plugin record type of worktree requests, withdrawals, and creations. */
|
||||
@@ -30,7 +31,7 @@ const worktreeSchema: z.ZodType<ForgeSessionWorktree> = z.object({
|
||||
}).strict()
|
||||
|
||||
const recordSchema: z.ZodType<WorktreeRecord> = z.discriminatedUnion('action', [
|
||||
z.object({ action: z.literal('request'), from: z.string().min(1).nullable() }).strict(),
|
||||
z.object({ action: z.literal('request'), from: z.string().min(1).nullable(), name: z.string().min(1).exactOptional() }).strict(),
|
||||
z.object({ action: z.literal('cancel') }).strict(),
|
||||
z.object({ action: z.literal('created'), worktree: worktreeSchema }).strict(),
|
||||
z.object({ action: z.literal('restoring') }).strict(),
|
||||
@@ -38,7 +39,7 @@ const recordSchema: z.ZodType<WorktreeRecord> = z.discriminatedUnion('action', [
|
||||
])
|
||||
|
||||
const stateSchema: z.ZodType<ForgeWorktreeState> = z.object({
|
||||
request: z.object({ from: z.string().min(1).nullable() }).strict().nullable(),
|
||||
request: z.object({ from: z.string().min(1).nullable(), name: z.string().min(1).nullable() }).strict().nullable(),
|
||||
created: worktreeSchema.nullable(),
|
||||
locked: z.boolean(),
|
||||
stepped: z.boolean(),
|
||||
@@ -59,7 +60,7 @@ const stateSchema: z.ZodType<ForgeWorktreeState> = z.object({
|
||||
*/
|
||||
export const forgeWorktreeProjection = {
|
||||
key: 'forgeWorktree',
|
||||
stateVersion: 7,
|
||||
stateVersion: 8,
|
||||
stateSchema,
|
||||
init: header => ({ ...EMPTY, cwd: header.cwd ?? null }),
|
||||
apply,
|
||||
@@ -118,7 +119,7 @@ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorkt
|
||||
const settled = state.created !== null
|
||||
switch (data.action) {
|
||||
case 'request':
|
||||
return state.locked || settled ? state : { ...state, request: { from: data.from } }
|
||||
return state.locked || settled ? state : { ...state, request: { from: data.from, name: data.name ?? null } }
|
||||
case 'cancel':
|
||||
return state.locked || settled || state.request === null ? state : { ...state, request: null }
|
||||
case 'created':
|
||||
@@ -134,6 +135,9 @@ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorkt
|
||||
|
||||
/** A failed attempt to create a requested worktree; `cause` holds the worktree service's error. */
|
||||
export class CreationFailure extends Error {
|
||||
/** Whether the branch or the checkout directory of that name already existed. */
|
||||
readonly exists: boolean
|
||||
|
||||
/**
|
||||
* @param branch - branch the attempt created.
|
||||
* @param phase - step that failed.
|
||||
@@ -143,21 +147,31 @@ export class CreationFailure extends Error {
|
||||
constructor(readonly branch: string, readonly phase: CreateWorktreePhase, readonly reason: string, cause: unknown) {
|
||||
super(`The requested worktree ${branch} could not be created`, { cause })
|
||||
this.name = 'CreationFailure'
|
||||
// The worktree service's failures are routed by name and code; a rebuilt error keeps both.
|
||||
this.exists = cause instanceof Error && cause.name === 'WorktreeError' && 'code' in cause && cause.code === 'WORKTREE_ALREADY_EXISTS'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The failure a waiting message shows for an attempt.
|
||||
* @param error - what the attempt threw.
|
||||
* @param from - base branch of the attempt, or null for HEAD.
|
||||
* @param from - base of the attempt, or null for HEAD.
|
||||
* @param fetch - whether the attempt fetched its remote base branch first.
|
||||
* @returns the failure.
|
||||
*/
|
||||
function failureOf(error: unknown, from: string | null): ForgeWorktreeFailure {
|
||||
function failureOf(error: unknown, from: string | null, fetch: boolean): ForgeWorktreeFailure {
|
||||
return error instanceof CreationFailure
|
||||
? { branch: error.branch, from, phase: error.phase, message: error.reason }
|
||||
: { branch: null, from, phase: 'prepare', message: messageOf(error) }
|
||||
? { branch: error.branch, from, fetch, phase: error.phase, message: error.reason, exists: error.exists }
|
||||
: { branch: null, from, fetch, phase: fetch ? 'fetch' : 'prepare', message: messageOf(error), exists: false }
|
||||
}
|
||||
|
||||
/** The next decision on a message that waits after a failed or stopped attempt. */
|
||||
type CreationDecision =
|
||||
/** Make another attempt; `fetch` false skips fetching a remote base branch for it. */
|
||||
| { readonly kind: 'retry'; readonly fetch: boolean }
|
||||
/** The request no longer asks for a worktree, so the message goes on. */
|
||||
| { readonly kind: 'recheck' }
|
||||
|
||||
/** Work on a Session's checkout that runs as maintenance of its Agent. */
|
||||
export type HeldWork = (agent: Agent, signal: AbortSignal) => Promise<void>
|
||||
|
||||
@@ -167,7 +181,7 @@ interface CreationHold {
|
||||
/** Stops the running attempt. */
|
||||
stop: AbortController | undefined
|
||||
/** The wait for the next decision: another attempt, or reading the request again. */
|
||||
next: PromiseWithResolvers<'retry' | 'recheck'> | undefined
|
||||
next: PromiseWithResolvers<CreationDecision> | undefined
|
||||
}
|
||||
|
||||
/** A message's wait for the restoration or leaving of the removed worktree the Session works in. */
|
||||
@@ -182,8 +196,10 @@ interface RestorationHold {
|
||||
type Hold = CreationHold | RestorationHold
|
||||
|
||||
/**
|
||||
* Creates requested worktrees, one attempt with a new branch name per call,
|
||||
* and holds the turn of a message while the Session's worktree is not ready.
|
||||
* Creates requested worktrees, one attempt per call on the requested branch
|
||||
* name or on a new generated one, fetching a remote-tracking base branch
|
||||
* first unless the attempt skips it, and holds the turn of a message while
|
||||
* the Session's worktree is not ready.
|
||||
* A hold is maintenance of the Session's Agent that starts while the message
|
||||
* enters the inbox, before the delivery wakes the Agent, so the Agent starts
|
||||
* the message's turn once the hold ends. A creation hold makes an attempt
|
||||
@@ -302,22 +318,27 @@ export class WorktreeCreations {
|
||||
/**
|
||||
* Make another attempt for the message that waits after a failed or stopped one.
|
||||
* @param session - Session whose message waits.
|
||||
* @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the
|
||||
* commit last fetched.
|
||||
* @returns whether a waiting message without a running attempt took the decision.
|
||||
*/
|
||||
retry(session: Session): boolean {
|
||||
retry(session: Session, fetch: boolean): boolean {
|
||||
const hold = this.holds.get(session)
|
||||
if (hold?.kind !== 'creation' || hold.next === undefined) return false
|
||||
hold.next.resolve('retry')
|
||||
hold.next.resolve({ kind: 'retry', fetch })
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the request again after it changed; a withdrawn request lets the waiting message go on.
|
||||
* Read the request again after it changed: a request that no longer asks for a worktree lets the waiting message
|
||||
* go on, and a request that still does keeps it waiting for another attempt.
|
||||
* @param session - Session whose request changed.
|
||||
*/
|
||||
recheck(session: Session): void {
|
||||
const hold = this.holds.get(session)
|
||||
if (hold?.kind === 'creation') hold.next?.resolve('recheck')
|
||||
if (hold?.kind !== 'creation') return
|
||||
const state = this.states.stateOf(session)
|
||||
if (state.request === null || state.created !== null || state.locked) hold.next?.resolve({ kind: 'recheck' })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -395,32 +416,39 @@ export class WorktreeCreations {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Session's requested worktree with a new branch name, enter it, and
|
||||
* record it on the Session. The running creation is readable through
|
||||
* {@link WorktreeCreations.of} until the record exists or the attempt fails.
|
||||
* Create a Session's requested worktree on the requested branch name, or on a
|
||||
* new generated one, enter it, and record it on the Session. The running
|
||||
* creation is readable through {@link WorktreeCreations.of} until the record
|
||||
* exists or the attempt fails.
|
||||
* @param agent - Agent of the Session.
|
||||
* @param from - base branch, or null for HEAD of the current checkout.
|
||||
* @param request - base, or null for HEAD of the current checkout, and branch name, or null to generate one.
|
||||
* @param signal - cancellation of the attempt.
|
||||
* @param held - whether a message waits for the creation before its turn starts.
|
||||
* @param fetch - whether the attempt fetches its base first; true only for a remote-tracking base branch.
|
||||
* @returns the created worktree.
|
||||
* @throws {@link CreationFailure} when the attempt fails; the cancellation reason once `signal` aborts.
|
||||
*/
|
||||
async create(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise<CreatedWorktree> {
|
||||
return await this.run(signal, operation => this.createCheckout(agent, from, operation, held))
|
||||
async create(agent: Agent, request: ForgeWorktreeRequest, signal: AbortSignal, held: boolean, fetch: boolean): Promise<CreatedWorktree> {
|
||||
return await this.run(signal, operation => this.createCheckout(agent, request, operation, held, fetch))
|
||||
}
|
||||
|
||||
private async createCheckout(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise<CreatedWorktree> {
|
||||
private async createCheckout(
|
||||
agent: Agent, { from, name }: ForgeWorktreeRequest, signal: AbortSignal, held: boolean, fetch: boolean,
|
||||
): Promise<CreatedWorktree> {
|
||||
const worktrees = this.ctx.get('worktrees')
|
||||
if (worktrees === undefined) throw new Error('No worktree service is mounted')
|
||||
const session = agent.session
|
||||
let status: ForgeWorktreeCreation = { phase: 'prepare', branch: generatedWorktreeName(this.prefix, session.id), from, held }
|
||||
let status: ForgeWorktreeCreation = {
|
||||
phase: fetch ? 'fetch' : 'prepare', branch: name ?? generatedWorktreeName(this.prefix, session.id), from, fetch, held,
|
||||
}
|
||||
this.failures.delete(session)
|
||||
this.live.set(session, status)
|
||||
this.changed(session)
|
||||
try {
|
||||
let created: CreatedWorktree
|
||||
try {
|
||||
created = await worktrees.create(agent, { name: status.branch, ...from === null ? {} : { from } }, signal, (phase) => {
|
||||
const request = { name: status.branch, ...from === null ? {} : { from }, ...fetch ? { fetch } : {} }
|
||||
created = await worktrees.create(agent, request, signal, (phase) => {
|
||||
status = { ...status, phase }
|
||||
this.live.set(session, status)
|
||||
this.changed(session)
|
||||
@@ -492,26 +520,28 @@ export class WorktreeCreations {
|
||||
*/
|
||||
private async runCreation(agent: Agent, hold: CreationHold, signal: AbortSignal): Promise<void> {
|
||||
const session = agent.session
|
||||
let skipFetch = false
|
||||
for (;;) {
|
||||
const state = this.states.stateOf(session)
|
||||
if (state.request === null || state.created !== null || state.locked) return
|
||||
const stop = new AbortController()
|
||||
hold.stop = stop
|
||||
const fetch = !skipFetch && isRemoteRef(state.request.from)
|
||||
try {
|
||||
await this.create(agent, state.request.from, AbortSignal.any([signal, stop.signal]), true)
|
||||
await this.create(agent, state.request, AbortSignal.any([signal, stop.signal]), true, fetch)
|
||||
return
|
||||
} catch (error) {
|
||||
signal.throwIfAborted()
|
||||
if (stop.signal.aborted) this.failures.delete(session)
|
||||
else this.failures.set(session, failureOf(error, state.request.from))
|
||||
else this.failures.set(session, failureOf(error, state.request.from, fetch))
|
||||
this.changed(session)
|
||||
} finally {
|
||||
hold.stop = undefined
|
||||
}
|
||||
while (await this.wait(hold, signal) !== 'retry') {
|
||||
const current = this.states.stateOf(session)
|
||||
if (current.request === null || current.created !== null || current.locked) return
|
||||
}
|
||||
const decision = await this.wait(hold, signal)
|
||||
// A recheck decides only once the request no longer asks for a worktree.
|
||||
if (decision.kind === 'recheck') return
|
||||
skipFetch = !decision.fetch
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,7 +596,7 @@ export class WorktreeCreations {
|
||||
private async preStep(agent: Agent, step: number, signal: AbortSignal, next: () => Promise<PreStepDecision>): Promise<PreStepDecision> {
|
||||
const state = this.states.stateOf(agent.session)
|
||||
if (step !== 1 || state.request === null || state.created !== null || state.stepped) return await next()
|
||||
await this.create(agent, state.request.from, signal, false)
|
||||
await this.create(agent, state.request, signal, false, isRemoteRef(state.request.from))
|
||||
const decision = await next()
|
||||
if (decision.kind === 'reject' || decision.messages.length === 0) return decision
|
||||
const notices = agent.inbox.nextStep.filter(message => message.source.kind === 'working-directory')
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/** Branch-name rules and branch labels shared by the Host and the Client. */
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { branchLabel, branchNameProblem, isRemoteRef } from '../src/branch-name.ts'
|
||||
|
||||
/** Whether Git accepts `name` as a new branch, as the worktree service checks it at creation. */
|
||||
function gitAccepts(name: string): boolean {
|
||||
try {
|
||||
execFileSync('git', ['check-ref-format', `refs/heads/${name}`], { stdio: 'ignore' })
|
||||
return true
|
||||
} catch (error) {
|
||||
void error // A nonzero exit is Git's refusal.
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
describe('branchNameProblem', () => {
|
||||
it.each([
|
||||
['', 'empty'],
|
||||
['fix login', 'space'],
|
||||
['fix\tlogin', 'space'],
|
||||
['fix\u007flogin', 'character'],
|
||||
['fix~1', 'character'],
|
||||
['fix^', 'character'],
|
||||
['a:b', 'character'],
|
||||
['a?b', 'character'],
|
||||
['a*b', 'character'],
|
||||
['a[b', 'character'],
|
||||
['a\\b', 'character'],
|
||||
['-fix', 'leading-dash'],
|
||||
['/fix', 'leading-slash'],
|
||||
['fix/', 'trailing-slash'],
|
||||
['fix//login', 'double-slash'],
|
||||
['fix..login', 'double-dot'],
|
||||
['fix.', 'trailing-dot'],
|
||||
['@', 'at'],
|
||||
['fix@{1}', 'at-brace'],
|
||||
['fix/.login', 'dot-segment'],
|
||||
['.fix', 'dot-segment'],
|
||||
['fix.lock/login', 'lock-segment'],
|
||||
['fix.lock', 'lock-segment'],
|
||||
] as const)('refuses %j as %s', (name, problem) => {
|
||||
expect(branchNameProblem(name)).toBe(problem)
|
||||
})
|
||||
|
||||
it.each(['fix-login', 'dsh-0a1b2c3d-9f3e', 'fix/login', 'a./b', 'a/@/b', 'é', 'HEAD'])('accepts %j', (name) => {
|
||||
expect(branchNameProblem(name)).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses every name that Git refuses among these', () => {
|
||||
for (const name of ['fix login', 'a..b', 'x@{y', 'a/.b', 'a/b.', 'aa.lock', 'fix//x', '/x', 'x/', 'a~b', 'a\\b', 'a[b']) {
|
||||
expect(gitAccepts(name)).toBe(false)
|
||||
expect(branchNameProblem(name)).not.toBeNull()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('branchLabel', () => {
|
||||
it('drops the prefix of a full local or remote-tracking branch name and keeps any other revision', () => {
|
||||
expect(branchLabel('refs/heads/fix/login')).toBe('fix/login')
|
||||
expect(branchLabel('refs/remotes/origin/main')).toBe('origin/main')
|
||||
expect(branchLabel('main')).toBe('main')
|
||||
expect(branchLabel('refs/heads/')).toBe('refs/heads/')
|
||||
expect(branchLabel('refs/tags/v1')).toBe('refs/tags/v1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRemoteRef', () => {
|
||||
it('recognizes the full name of a remote-tracking branch', () => {
|
||||
expect(isRemoteRef('refs/remotes/origin/main')).toBe(true)
|
||||
expect(isRemoteRef('refs/remotes/')).toBe(false)
|
||||
expect(isRemoteRef('refs/heads/main')).toBe(false)
|
||||
expect(isRemoteRef('origin/main')).toBe(false)
|
||||
expect(isRemoteRef(null)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
/** One change request card: state glyph, title link, collapsed summary, read notices, and expanded details and actions. */
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, onTestFinished, 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'
|
||||
@@ -10,6 +10,7 @@ import css from '../src/client/Forge.module.css'
|
||||
import overview from '../src/client/ChangeRequestOverview.module.css'
|
||||
import type { ForgePanelChangeRequest } from '../src/types.ts'
|
||||
import { check, entry, snapshot, unserved } from './client-fixtures.client.ts'
|
||||
import './fonts-dom.client.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
@@ -19,7 +20,7 @@ const NOW = Date.parse('2026-10-09T12:00:00Z')
|
||||
const MINUS = '−'
|
||||
|
||||
/** Render one card inside its list, with every action recorded unless `actions` replaces it. */
|
||||
function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; actions?: Partial<ChangeRequestActions> } = {}) {
|
||||
function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; actions?: Partial<ChangeRequestActions>; t?: typeof t } = {}) {
|
||||
const openLink = vi.fn<(url: string) => void>()
|
||||
const copyLink = vi.fn<(url: string) => void>()
|
||||
const retry = vi.fn<() => void>()
|
||||
@@ -28,7 +29,8 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act
|
||||
const actions: ChangeRequestActions = { openLink, copyLink, retry, remove, ...options.actions }
|
||||
const view = render(
|
||||
<ul>
|
||||
<ChangeRequestCard locale="en" entry={value} expanded={options.expanded ?? false} onToggle={onToggle} now={NOW} actions={actions} t={t} />
|
||||
<ChangeRequestCard locale="en" entry={value} expanded={options.expanded ?? false} onToggle={onToggle} now={NOW} actions={actions}
|
||||
t={options.t ?? t} />
|
||||
</ul>,
|
||||
)
|
||||
const item = view.container.querySelector('[data-forge-change]')
|
||||
@@ -134,6 +136,19 @@ describe('ChangeRequestCard head', () => {
|
||||
}
|
||||
})
|
||||
|
||||
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', () => {
|
||||
const b = card(entry(7, snapshot(7)))
|
||||
expect(b.item.hasAttribute('data-expanded')).toBe(false)
|
||||
@@ -189,6 +204,59 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
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']}`)
|
||||
})
|
||||
|
||||
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']],
|
||||
|
||||
@@ -224,6 +224,16 @@ function hostStream<F>(frames: readonly F[], failure?: unknown): HostStream<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the view shows its reading state: the reading status above file card placeholders, with the files menu naming
|
||||
* no count.
|
||||
*/
|
||||
function reading(view: ReturnType<typeof render>): boolean {
|
||||
return view.queryByRole('status')?.textContent === en['diff.loading']
|
||||
&& view.container.querySelector('[data-forge-changes-skeleton]') !== null
|
||||
&& view.queryByRole('button', { name: en['diff.allFilesLoading'] }) !== null
|
||||
}
|
||||
|
||||
/** Let the Remote reads the view awaits settle. */
|
||||
async function settle(): Promise<void> {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) })
|
||||
@@ -576,9 +586,18 @@ describe('ChangesTab tooltips', () => {
|
||||
})
|
||||
|
||||
describe('ChangesTab local reads', () => {
|
||||
it('draws the placeholders of a changed file in two columns only while sides are split', async () => {
|
||||
const m = mount({ state: null })
|
||||
const columns = (): number => m.view.container.querySelectorAll('[data-forge-changes-skeleton] > :first-child > :last-child > *').length
|
||||
expect(reading(m.view)).toBe(true)
|
||||
expect(columns()).toBe(2)
|
||||
act(() => { m.store.actions.toggledSplit(TAB) })
|
||||
expect(columns()).toBe(1)
|
||||
})
|
||||
|
||||
it('waits for the panel state, then reads the branch scope and draws its files', async () => {
|
||||
const m = mount({ state: null })
|
||||
expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
expect(m.view.queryByRole('button', { name: en['changes.local.create'] })).toBeNull()
|
||||
expect(m.view.container.querySelector('[data-forge-head]')?.textContent).toBe('HEAD')
|
||||
expect(m.faces.localDiff).not.toHaveBeenCalled()
|
||||
@@ -627,7 +646,7 @@ describe('ChangesTab local reads', () => {
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Branch' }))
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: 'Staged' }))
|
||||
expect(m.store.getSnapshot().byTab[TAB]?.scope).toBe('staged')
|
||||
expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
expect(m.view.getByText('The index compared with HEAD')).toBeTruthy()
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'staged' }, expect.any(AbortSignal))
|
||||
await settle()
|
||||
@@ -858,7 +877,7 @@ describe('ChangesTab base branch', () => {
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: 'topic' }))
|
||||
expect(m.store.getSnapshot().byTab[TAB]?.base).toEqual(TOPIC)
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', base: TOPIC.ref, commits: null }, expect.any(AbortSignal))
|
||||
expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
await settle()
|
||||
expect(m.paths()).toHaveLength(6)
|
||||
|
||||
@@ -1453,7 +1472,7 @@ describe('ChangesTab change requests', () => {
|
||||
const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.staleHead) } })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce()
|
||||
expect(m.view.queryByRole('status')).toBeNull()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
expect(m.paths()).toEqual([])
|
||||
|
||||
// A later status with the same head reads again, as when the host's answers disagreed for a moment.
|
||||
@@ -1465,7 +1484,7 @@ describe('ChangesTab change requests', () => {
|
||||
act(() => { m.panel.set({ state: later(2, HEAD), disconnected: false }) })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(2)
|
||||
expect(m.view.queryByRole('status')).toBeNull()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
|
||||
act(() => { m.panel.set({ state: later(3, 'b'.repeat(40)), disconnected: false }) })
|
||||
await settle()
|
||||
@@ -1520,7 +1539,7 @@ describe('ChangesTab change requests', () => {
|
||||
const m = mount({ source, state: ready({ changeRequests: [entry(7, null)] }) })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestDiff).not.toHaveBeenCalled()
|
||||
expect(m.view.queryByRole('status')).toBeNull()
|
||||
expect(reading(m.view)).toBe(true)
|
||||
act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7))] }), disconnected: false }) })
|
||||
await settle()
|
||||
expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce()
|
||||
|
||||
@@ -138,12 +138,12 @@ export function created(overrides: Partial<ForgeSessionWorktree> = {}): ForgeSes
|
||||
|
||||
/** Running creation of the branch `dsh/0a1b2c3d` from `main`, in its preparation step, that a message waits for. */
|
||||
export function creation(overrides: Partial<ForgeWorktreeCreation> = {}): ForgeWorktreeCreation {
|
||||
return { phase: 'prepare', branch: 'dsh/0a1b2c3d', from: 'main', held: true, ...overrides }
|
||||
return { phase: 'prepare', branch: 'dsh/0a1b2c3d', from: 'main', fetch: false, held: true, ...overrides }
|
||||
}
|
||||
|
||||
/** Failed attempt to create the branch `dsh/0a1b2c3d` from `main`, in its preparation step. */
|
||||
export function failure(overrides: Partial<ForgeWorktreeFailure> = {}): ForgeWorktreeFailure {
|
||||
return { branch: 'dsh/0a1b2c3d', from: 'main', phase: 'prepare', message: 'fatal: invalid reference: main', ...overrides }
|
||||
return { branch: 'dsh/0a1b2c3d', from: 'main', fetch: false, phase: 'prepare', message: 'fatal: invalid reference: main', exists: false, ...overrides }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,8 +152,8 @@ export function failure(overrides: Partial<ForgeWorktreeFailure> = {}): ForgeWor
|
||||
*/
|
||||
export function worktree(overrides: Partial<ForgePanelWorktree> = {}): ForgePanelWorktree {
|
||||
return {
|
||||
editable: false, blocker: null, request: null, created: null, creation: null, failure: null, missing: null, restoration: null,
|
||||
waiting: null, ...overrides,
|
||||
editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null,
|
||||
restoration: null, waiting: null, ...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,9 +171,12 @@ export function ready(overrides: Partial<ForgePanelState> = {}, checkoutOverride
|
||||
}
|
||||
}
|
||||
|
||||
/** Ready panel state of a Session that waits to start in a worktree requested from `from`, with further worktree facts. */
|
||||
export function requested(from: string | null = 'main', overrides: Partial<ForgePanelWorktree> = {}): ForgePanelState {
|
||||
return ready({ worktree: worktree({ editable: true, request: { from }, ...overrides }) })
|
||||
/**
|
||||
* Ready panel state of a Session that waits to start in a worktree requested from `from` on the branch `name`, or on a
|
||||
* generated branch for null, with further worktree facts.
|
||||
*/
|
||||
export function requested(from: string | null = 'main', overrides: Partial<ForgePanelWorktree> = {}, name: string | null = null): ForgePanelState {
|
||||
return ready({ worktree: worktree({ editable: true, request: { from, name }, ...overrides }) })
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -62,8 +62,8 @@ const ready = (state: ForgePanelState): boolean => state.checkout.state === 'rea
|
||||
|
||||
/** Worktree facts of a Session without a worktree service, request, or creation, whose checkout can host a worktree. */
|
||||
const UNAVAILABLE = {
|
||||
editable: false, blocker: null, request: null, created: null, creation: null, failure: null, missing: null, restoration: null,
|
||||
waiting: null,
|
||||
editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null,
|
||||
restoration: null, waiting: null,
|
||||
}
|
||||
|
||||
/** Matches a generated branch name with the default prefix. */
|
||||
@@ -106,7 +106,7 @@ function worktreeState(opened: Bench, session: Session = opened.session): ForgeW
|
||||
* @returns the created worktree.
|
||||
*/
|
||||
async function startInWorktree(opened: Bench, from: string | null = null): Promise<ForgeSessionWorktree> {
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, from, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, from, null, signal)
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await opened.agent.whenIdle()
|
||||
const created = worktreeState(opened)?.created ?? null
|
||||
@@ -964,9 +964,9 @@ describe('forgePanel worktree requests', () => {
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const requested = await follower.next(() => true)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)
|
||||
const replaced = await follower.next(() => true)
|
||||
await opened.ctx.forgePanel.cancelWorktree(opened.session, signal)
|
||||
const withdrawn = await follower.next(() => true)
|
||||
@@ -975,8 +975,8 @@ describe('forgePanel worktree requests', () => {
|
||||
|
||||
const editable = { ...UNAVAILABLE, editable: true }
|
||||
expect(follower.states[0]?.worktree).toEqual(editable)
|
||||
expect(requested.worktree).toEqual({ ...editable, request: { from: null } })
|
||||
expect(replaced.worktree).toEqual({ ...editable, request: { from: 'main' } })
|
||||
expect(requested.worktree).toEqual({ ...editable, request: { from: null, name: null } })
|
||||
expect(replaced.worktree).toEqual({ ...editable, request: { from: 'main', name: null } })
|
||||
expect(withdrawn.worktree).toEqual(editable)
|
||||
expect(started.worktree).toEqual(UNAVAILABLE)
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'request', from: 'main' }, { action: 'cancel' }])
|
||||
@@ -987,7 +987,7 @@ describe('forgePanel worktree requests', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
|
||||
await opened.ctx.forgePanel.cancelWorktree(opened.session, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)
|
||||
await opened.ctx.forgePanel.cancelWorktree(opened.session, signal)
|
||||
await opened.ctx.forgePanel.cancelWorktree(opened.session, signal)
|
||||
|
||||
@@ -997,10 +997,10 @@ describe('forgePanel worktree requests', () => {
|
||||
it('refuses worktree changes after the first turn starts', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
startTurn(opened.session, 1)
|
||||
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
})
|
||||
@@ -1008,12 +1008,12 @@ describe('forgePanel worktree requests', () => {
|
||||
it('refuses worktree changes once the worktree exists, before any turn starts', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
await proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')], decision: { kind: 'reject' } })
|
||||
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null }, locked: false, stepped: false, restoring: false })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, locked: false, stepped: false, restoring: false })
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(opened.created).toHaveLength(1)
|
||||
})
|
||||
@@ -1032,13 +1032,13 @@ describe('forgePanel worktree requests', () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/worktrees-unavailable' })
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)).rejects.toMatchObject({ code: 'forgePanel/worktrees-unavailable' })
|
||||
expect(opened.records).toEqual([])
|
||||
appendPluginRecord(opened.session, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
const follower = reader(opened)
|
||||
sendPrompt(opened.agent, 'first')
|
||||
const failed = await follower.until(state => state.worktree.failure !== null)
|
||||
expect(failed.worktree.failure).toEqual({ branch: null, from: null, phase: 'prepare', message: 'No worktree service is mounted' })
|
||||
expect(failed.worktree.failure).toEqual({ branch: null, from: null, fetch: false, phase: 'prepare', message: 'No worktree service is mounted', exists: false })
|
||||
// Withdrawing needs no worktree service, so the waiting message can go on.
|
||||
await opened.ctx.forgePanel.cancelWorktree(opened.session, signal)
|
||||
await opened.agent.whenIdle()
|
||||
@@ -1056,7 +1056,7 @@ describe('forgePanel worktree requests', () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/invalid-branch' })
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, '', null, signal)).rejects.toMatchObject({ code: 'forgePanel/invalid-branch' })
|
||||
expect(opened.records).toEqual([])
|
||||
})
|
||||
|
||||
@@ -1065,7 +1065,7 @@ describe('forgePanel worktree requests', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
|
||||
startTurn(opened.session, 1)
|
||||
await proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('Fix the bug')] })
|
||||
@@ -1080,7 +1080,7 @@ describe('forgePanel worktree requests', () => {
|
||||
repository: demo,
|
||||
readiness: { state: 'ready', message: null, signIn: null },
|
||||
changeRequests: [],
|
||||
worktree: { ...UNAVAILABLE, request: { from: null }, created },
|
||||
worktree: { ...UNAVAILABLE, request: { from: null, name: null }, created },
|
||||
local: { base: created?.baseCommit.slice(0, 7), files: [] },
|
||||
})
|
||||
expect(opened.provider.probes).toEqual(['fake.test'])
|
||||
@@ -1105,7 +1105,7 @@ describe('forgePanel worktree requests', () => {
|
||||
|
||||
const worktree: ForgeSessionWorktree = { path: join(repo, 'elsewhere'), branch: 'dsh/0a1b2c3d', from: null, baseCommit: 'c'.repeat(40), repositoryRoot: repo }
|
||||
appendPluginRecord(opened.session, WORKTREE_RECORD, { action: 'created', worktree })
|
||||
await expect(pending).resolves.toMatchObject({ worktree: { ...UNAVAILABLE, request: { from: null }, created: worktree } })
|
||||
await expect(pending).resolves.toMatchObject({ worktree: { ...UNAVAILABLE, request: { from: null, name: null }, created: worktree } })
|
||||
|
||||
const later = follower.next(() => true)
|
||||
let republished = false
|
||||
@@ -1117,13 +1117,105 @@ describe('forgePanel worktree requests', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('forgePanel named and remote-based worktrees', () => {
|
||||
/** Whether the checkout was inspected; a clone of a local path names no code host, so no sign-in state follows. */
|
||||
const inspected = (state: ForgePanelState): boolean => state.checkout.state === 'ready'
|
||||
|
||||
/** A clone of a fresh repository, which then gains a commit the clone has not fetched. */
|
||||
async function behind(): Promise<{ repo: string; fetched: string }> {
|
||||
const { path, remove } = await scratch('dsh-forge-remote-')
|
||||
cleanups.push(remove)
|
||||
const upstream = await repository(path, 'upstream')
|
||||
const repo = join(path, 'clone')
|
||||
await git(path, 'clone', '--quiet', upstream, repo)
|
||||
return { repo, fetched: await commitAt(upstream, 'remote.txt', '2026-02-01T00:00:00Z') }
|
||||
}
|
||||
|
||||
it('records a request that names its branch, and refuses an invalid or taken name without recording it', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await git(repo, 'branch', 'taken')
|
||||
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'fix/', signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/invalid-name' })
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'taken', signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/branch-exists' })
|
||||
expect(opened.records).toEqual([])
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'fix/login', signal)
|
||||
|
||||
expect(opened.records).toEqual([{ action: 'request', from: 'refs/heads/main', name: 'fix/login' }])
|
||||
expect(worktreeState(opened).request).toEqual({ from: 'refs/heads/main', name: 'fix/login' })
|
||||
})
|
||||
|
||||
it('refuses a named request outside a checkout', async () => {
|
||||
const opened = await open(await plain(), {}, { worktrees: true })
|
||||
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' })
|
||||
})
|
||||
|
||||
it('says a named attempt found its branch taken, and creates the worktree once the request names another branch', 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, 'fix/login', signal)
|
||||
// The branch appears after the request was checked, as when another checkout creates it meanwhile.
|
||||
await git(repo, 'branch', 'fix/login')
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login-2', signal)
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
expect(failed.worktree.failure).toMatchObject({ branch: 'fix/login', phase: 'prepare', exists: true, fetch: false })
|
||||
expect(worktreeState(opened).created).toMatchObject({ branch: 'fix/login-2', from: null })
|
||||
expect(queued(opened)).toEqual(['first'])
|
||||
})
|
||||
|
||||
it('fetches a remote base branch before creating the worktree from the fetched commit', async () => {
|
||||
const { repo, fetched } = await behind()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(inspected)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/remotes/origin/main', null, signal)
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
const fetching = await follower.until(state => state.worktree.creation?.phase === 'fetch')
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
expect(fetching.worktree.creation).toMatchObject({ from: 'refs/remotes/origin/main', fetch: true, held: true })
|
||||
expect(worktreeState(opened).created).toMatchObject({ from: 'refs/remotes/origin/main', baseCommit: fetched })
|
||||
})
|
||||
|
||||
it('keeps the message waiting after a failed fetch, and starts from the last fetched commit when asked to skip the fetch', async () => {
|
||||
const { repo } = await behind()
|
||||
const last = await git(repo, 'rev-parse', 'refs/remotes/origin/main')
|
||||
await git(repo, 'remote', 'set-url', 'origin', join(repo, 'missing.git'))
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(inspected)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/remotes/origin/main', null, signal)
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null)
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, false, signal)
|
||||
const retrying = await follower.next(state => state.worktree.creation !== null)
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
expect(failed.worktree.failure).toMatchObject({ phase: 'fetch', fetch: true, exists: false, from: 'refs/remotes/origin/main' })
|
||||
expect(retrying.worktree.creation).toMatchObject({ phase: 'prepare', fetch: false })
|
||||
expect(worktreeState(opened).created).toMatchObject({ baseCommit: last })
|
||||
})
|
||||
})
|
||||
|
||||
describe('forgePanel worktree creation while a message waits', () => {
|
||||
it('creates the requested worktree as Agent maintenance while the first message waits in the inbox, showing each step, then starts its turn', 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, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const preparing = hold(opened.sandbox, 'check-ref-format')
|
||||
const checkingOut = hold(opened.sandbox, 'reset')
|
||||
|
||||
@@ -1140,11 +1232,11 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const moved = await follower.until(state => state.directory === created?.path && state.checkout.state === 'ready' && state.worktree.waiting === null)
|
||||
|
||||
const branch = created?.branch ?? ''
|
||||
const running = { branch, from: null, held: true }
|
||||
const waiting = { ...UNAVAILABLE, editable: true, request: { from: null }, waiting: 'creation' }
|
||||
const running = { branch, from: null, fetch: false, held: true }
|
||||
const waiting = { ...UNAVAILABLE, editable: true, request: { from: null, name: null }, waiting: 'creation' }
|
||||
expect(prepare.worktree).toEqual({ ...waiting, creation: { ...running, phase: 'prepare' } })
|
||||
expect(checkout.worktree).toEqual({ ...waiting, creation: { ...running, phase: 'checkout' } })
|
||||
expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created })
|
||||
expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created })
|
||||
expect(moved.checkout).toEqual({ state: 'ready', checkout: { root: created?.path, branch, linked: true, commit: COMMIT } })
|
||||
expect(created).toEqual({
|
||||
path: join(repo, '.agents', 'worktrees', ...branch.split('/')),
|
||||
@@ -1168,19 +1260,19 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal)
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null)
|
||||
expect(opened.agent.wakes).toBe(0)
|
||||
await git(repo, 'branch', 'later')
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, signal)
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)
|
||||
const retrying = await follower.next(state => state.worktree.creation !== null)
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
expect(failed.worktree).toEqual({
|
||||
...UNAVAILABLE, editable: true, request: { from: 'later' }, waiting: 'creation',
|
||||
failure: { branch: GENERATED_BRANCH, from: 'later', phase: 'prepare', message: MISSING_BASE },
|
||||
...UNAVAILABLE, editable: true, request: { from: 'later', name: null }, waiting: 'creation',
|
||||
failure: { branch: GENERATED_BRANCH, from: 'later', fetch: false, phase: 'prepare', message: MISSING_BASE, exists: false },
|
||||
})
|
||||
expect(retrying.worktree.failure).toBeNull()
|
||||
const created = worktreeState(opened)?.created ?? null
|
||||
@@ -1197,20 +1289,20 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal)
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await follower.until(state => state.worktree.failure !== null)
|
||||
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'gone', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'gone', null, signal)
|
||||
const changed = await follower.next(state => state.worktree.request?.from === 'gone')
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, signal)
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)
|
||||
const failedAgain = await follower.next(state => state.worktree.failure !== null)
|
||||
const withdrawal = follower.next(state => state.worktree.request === null && state.worktree.waiting === null)
|
||||
await opened.ctx.forgePanel.cancelWorktree(opened.session, signal)
|
||||
await opened.agent.whenIdle()
|
||||
const withdrawn = await withdrawal
|
||||
|
||||
expect(changed.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'gone' }, waiting: 'creation' })
|
||||
expect(changed.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'gone', name: null }, waiting: 'creation' })
|
||||
expect(failedAgain.worktree.failure).toMatchObject({ from: 'gone' })
|
||||
expect(withdrawn.worktree).toEqual({ ...UNAVAILABLE, editable: true })
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
@@ -1225,7 +1317,7 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
await opened.ctx.forgePanel.stopCreation(opened.session, signal)
|
||||
const held = hold(opened.sandbox, 'check-ref-format')
|
||||
|
||||
@@ -1236,10 +1328,10 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
held.release()
|
||||
const stopped = await stopping
|
||||
const before = { wakes: opened.agent.wakes, records: [...opened.records], cwd: opened.ctx.workingDirectory.get(opened.session) }
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, signal)
|
||||
await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
expect(stopped.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null }, waiting: 'creation' })
|
||||
expect(stopped.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null, name: null }, waiting: 'creation' })
|
||||
expect(before).toEqual({ wakes: 0, records: [{ action: 'request', from: null }], cwd: repo })
|
||||
expect(worktreeState(opened)?.created).toMatchObject({ from: null, repositoryRoot: repo })
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
@@ -1250,14 +1342,14 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal)
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await follower.until(state => state.worktree.failure !== null)
|
||||
await git(repo, 'branch', 'later')
|
||||
|
||||
// Both decisions arrive before the wait resumes, so the next attempt reads the withdrawn request.
|
||||
await Promise.all([
|
||||
opened.ctx.forgePanel.retryWorktree(opened.session, signal),
|
||||
opened.ctx.forgePanel.retryWorktree(opened.session, true, signal),
|
||||
opened.ctx.forgePanel.cancelWorktree(opened.session, signal),
|
||||
])
|
||||
await opened.agent.whenIdle()
|
||||
@@ -1270,13 +1362,13 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
it('refuses another attempt while no message waits or an attempt runs', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await expect(opened.ctx.forgePanel.retryWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await expect(opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const held = hold(opened.sandbox, 'check-ref-format')
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await held.reached
|
||||
await expect(opened.ctx.forgePanel.retryWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' })
|
||||
await expect(opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' })
|
||||
held.release()
|
||||
await opened.agent.whenIdle()
|
||||
|
||||
@@ -1289,7 +1381,7 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal)
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await follower.until(state => state.worktree.failure !== null)
|
||||
|
||||
@@ -1298,16 +1390,16 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
await opened.agent.whenIdle()
|
||||
const ended = await ending
|
||||
|
||||
expect(ended.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'later' } })
|
||||
expect(ended.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'later', name: null } })
|
||||
expect(opened.agent.wakes).toBe(0)
|
||||
expect(queued(opened)).toEqual([])
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: 'later' }, created: null })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: 'later', name: null }, created: null })
|
||||
})
|
||||
|
||||
it('lets the waiting message go on when the panel stops', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal)
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await vi.waitFor(() => { expect(() => opened.agent.runMaintenance(() => Promise.resolve())).toThrow('already has active work') })
|
||||
|
||||
@@ -1316,13 +1408,13 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
expect(queued(opened)).toEqual(['first'])
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: 'later' }, created: null })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: 'later', name: null }, created: null })
|
||||
})
|
||||
|
||||
it('holds one wait for every message that arrives during it', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const held = hold(opened.sandbox, 'check-ref-format')
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
@@ -1342,7 +1434,7 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const follower = reader(opened)
|
||||
await follower.until(ready)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
await follower.until(state => state.worktree.request !== null)
|
||||
const release = occupy(opened)
|
||||
|
||||
@@ -1351,16 +1443,16 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
const busy = follower.states.at(-1)
|
||||
await release()
|
||||
|
||||
expect(busy?.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null } })
|
||||
expect(busy?.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null, name: null } })
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null }, created: null })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, created: null })
|
||||
expect(await branches(repo)).toEqual(['main'])
|
||||
})
|
||||
|
||||
it('lets a message go on without a wait once the first turn started, leaving the worktree to the first step', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
startTurn(opened.session, 1)
|
||||
|
||||
sendPrompt(opened.agent, 'steer')
|
||||
@@ -1368,7 +1460,7 @@ describe('forgePanel worktree creation while a message waits', () => {
|
||||
|
||||
expect(opened.agent.wakes).toBe(1)
|
||||
expect(queued(opened)).toEqual(['steer'])
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null }, created: null, locked: true })
|
||||
expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, created: null, locked: true })
|
||||
expect(await branches(repo)).toEqual(['main'])
|
||||
})
|
||||
})
|
||||
@@ -1377,13 +1469,13 @@ describe('forgePanel worktree requests during a creation', () => {
|
||||
it('refuses to change or withdraw the request while the worktree is being created, so the creation is recorded', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const held = hold(opened.sandbox, 'check-ref-format')
|
||||
|
||||
sendPrompt(opened.agent, 'first')
|
||||
await held.reached
|
||||
await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-busy' })
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal))
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/session-busy' })
|
||||
held.release()
|
||||
await opened.agent.whenIdle()
|
||||
@@ -1425,11 +1517,11 @@ describe('forgePanel removed worktrees', () => {
|
||||
await opened.agent.whenIdle()
|
||||
const restored = await restoration
|
||||
|
||||
expect(missing.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created, missing: { branchExists: true }, waiting: 'restoration' })
|
||||
expect(missing.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created, missing: { branchExists: true }, waiting: 'restoration' })
|
||||
expect(preparing.worktree).toMatchObject({ missing: { branchExists: true }, restoration: { phase: 'prepare' }, waiting: 'restoration' })
|
||||
expect(checkingOut.worktree.restoration).toEqual({ phase: 'checkout' })
|
||||
expect(restored).toMatchObject({ directory: created.path, checkout: { state: 'ready', checkout: { root: created.path, branch: created.branch } } })
|
||||
expect(restored.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created })
|
||||
expect(restored.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created })
|
||||
expect(await git(created.path, 'rev-parse', 'HEAD')).toBe(tip)
|
||||
expect(await readFile(join(created.path, 'later.txt'), 'utf8')).toBe('later.txt\n')
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(created.path)
|
||||
@@ -1458,7 +1550,7 @@ describe('forgePanel removed worktrees', () => {
|
||||
await opened.agent.whenIdle()
|
||||
const restored = await restoration
|
||||
|
||||
expect(gone.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created, missing: { branchExists: false }, waiting: 'restoration' })
|
||||
expect(gone.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created, missing: { branchExists: false }, waiting: 'restoration' })
|
||||
expect(await git(repo, 'rev-parse', created.branch)).toBe(created.baseCommit)
|
||||
expect(restored.checkout).toEqual({ state: 'ready', checkout: { root: created.path, branch: created.branch, linked: true, commit: COMMIT } })
|
||||
await expect(access(join(created.path, 'later.txt'))).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
@@ -1677,7 +1769,7 @@ describe('forgePanel leaving a worktree', () => {
|
||||
expect(opened.agent.inbox.nextStep).toEqual([notice(repo)])
|
||||
expect(queued(opened)).toEqual(['next'])
|
||||
expect(moved.checkout).toEqual({ state: 'ready', checkout: { root: repo, branch: 'main', linked: false, commit: COMMIT } })
|
||||
expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created })
|
||||
expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created })
|
||||
expect(await branches(repo)).toEqual([created.branch, 'main'])
|
||||
})
|
||||
|
||||
@@ -1991,23 +2083,37 @@ describe('forgePanel actions', () => {
|
||||
expect(opened.provider.actions).toEqual([])
|
||||
})
|
||||
|
||||
it('lists the base branches of the Session\'s current checkout, at most maxBranches', async () => {
|
||||
it('lists the bases of a new worktree: the checked-out branch, remote defaults, local branches, and each remote, at most maxBranches each', async () => {
|
||||
const { repo } = await project()
|
||||
await withDefaultBranch(repo)
|
||||
await git(repo, 'remote', 'add', 'fork', '/srv/fork.git')
|
||||
await commitAt(repo, 'main.txt', '2026-03-01T00:00:00Z')
|
||||
await git(repo, 'checkout', '-b', 'older')
|
||||
await commitAt(repo, 'older.txt', '2026-01-01T00:00:00Z')
|
||||
await git(repo, 'update-ref', 'refs/remotes/origin/topic', 'HEAD')
|
||||
await git(repo, 'update-ref', 'refs/remotes/fork/idea', 'HEAD')
|
||||
await git(repo, 'checkout', '-b', 'newer', 'main')
|
||||
await commitAt(repo, 'newer.txt', '2026-02-01T00:00:00Z')
|
||||
const opened = await open(repo, { maxBranches: 2 })
|
||||
const opened = await open(repo, { maxBranches: 1 })
|
||||
|
||||
await expect(opened.ctx.forgePanel.branches(opened.session, signal)).resolves.toEqual({ current: 'newer', branches: ['newer', 'main'] })
|
||||
await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', signal)).resolves.toEqual({
|
||||
current: { ref: 'refs/heads/newer', name: 'newer' },
|
||||
defaults: [{ ref: 'refs/remotes/origin/main', name: 'origin/main', remote: 'origin' }],
|
||||
local: [{ ref: 'refs/heads/main', name: 'main' }],
|
||||
remotes: [
|
||||
{ name: 'origin', repository: 'octo/demo', branches: [{ ref: 'refs/remotes/origin/topic', name: 'origin/topic' }] },
|
||||
{ name: 'fork', repository: '/srv/fork.git', branches: [{ ref: 'refs/remotes/fork/idea', name: 'fork/idea' }] },
|
||||
],
|
||||
})
|
||||
await expect(opened.ctx.forgePanel.worktreeBases(opened.session, 'IDEA', signal)).resolves.toEqual({
|
||||
current: null, defaults: [], local: [], remotes: [{ name: 'fork', repository: '/srv/fork.git', branches: [{ ref: 'refs/remotes/fork/idea', name: 'fork/idea' }] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses to list branches outside a checkout', async () => {
|
||||
it('refuses to list worktree bases outside a checkout', async () => {
|
||||
const opened = await open(await plain())
|
||||
|
||||
await expect(opened.ctx.forgePanel.branches(opened.session, signal))
|
||||
.rejects.toThrow(/^git (symbolic-ref|for-each-ref) failed \(128\): fatal: not a git repository/)
|
||||
await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' })
|
||||
})
|
||||
|
||||
it('checks the caller signal before every action', async () => {
|
||||
@@ -2025,8 +2131,8 @@ describe('forgePanel actions', () => {
|
||||
await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(1), 'a'.repeat(40), 'x', controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.markReady(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.merge(opened.session, pullUrl(1), 'merge', 'a'.repeat(40), controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.branches(opened.session, controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, null, controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.stopCreation(opened.session, controller.signal)).rejects.toThrow('closed')
|
||||
await expect(opened.ctx.forgePanel.restoreWorktree(opened.session, controller.signal)).rejects.toThrow('closed')
|
||||
@@ -2039,7 +2145,7 @@ describe('forgePanel lifecycle', () => {
|
||||
it('removes its Remote, worktree projection, and inbox and pre-step listeners when stopped, and folds the recorded request again after a restart', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const proposed = prompt('go')
|
||||
const row = opened.ctx.sessionProjections.checkpoint(opened.session).forgeWorktree
|
||||
|
||||
@@ -2057,7 +2163,7 @@ describe('forgePanel lifecycle', () => {
|
||||
await opened.ctx.plugin(ForgePanelController, {})
|
||||
|
||||
expect(opened.ctx.sessionProjections.checkpoint(opened.session).forgeWorktree?.val)
|
||||
.toEqual({ request: { from: null }, created: null, locked: false, stepped: false, cwd: repo, restoring: false })
|
||||
.toEqual({ request: { from: null, name: null }, created: null, locked: false, stepped: false, cwd: repo, restoring: false })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2142,7 +2248,7 @@ describe('worktree recovery and unload', () => {
|
||||
const opened = await open(repo, {}, { worktrees: true })
|
||||
const created = kind !== 'creation' ? await startInWorktree(opened) : undefined
|
||||
if (created !== undefined) await rm(created.path, { recursive: true, force: true })
|
||||
else await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)
|
||||
else await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)
|
||||
const entered: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const released: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
let cancellation: AbortSignal | undefined
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
|
||||
import LocalSandbox from '@deepseek-ai/dsh-sandbox-local'
|
||||
import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import { hasBranch, inspectCheckout, listBranches } from '../src/git.ts'
|
||||
import { hasBranch, inspectCheckout } from '../src/git.ts'
|
||||
import type { GitConfig } from '../src/git.ts'
|
||||
import { commitAt, git, gitContext, plainSession, repository, sandboxRecord, scratch, script } from './harness.ts'
|
||||
import type { SandboxRecord } from './harness.ts'
|
||||
@@ -67,10 +67,9 @@ describe('Session permissions for Git inspection', () => {
|
||||
const beforeStat = await stat(index)
|
||||
|
||||
await expect(inspectCheckout(ctx, CONFIG, current, repo, live())).resolves.toMatchObject({ checkout: { branch: 'main' } })
|
||||
await expect(listBranches(ctx, CONFIG, current, repo, 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] })
|
||||
await expect(hasBranch(ctx, CONFIG, current, repo, 'main', live())).resolves.toBe(true)
|
||||
|
||||
expect(record.calls).toHaveLength(mode === 'danger-full-access' ? 0 : 10)
|
||||
expect(record.calls).toHaveLength(mode === 'danger-full-access' ? 0 : 8)
|
||||
expect(record.calls.every(call => call.policy.mode === mode)).toBe(true)
|
||||
expect(await readFile(index)).toEqual(before)
|
||||
expect((await stat(index)).mtimeMs).toBe(beforeStat.mtimeMs)
|
||||
@@ -128,7 +127,7 @@ describe('inspectCheckout', () => {
|
||||
'rev-parse --path-format=absolute --git-dir',
|
||||
'rev-parse --short HEAD',
|
||||
'rev-parse --show-toplevel',
|
||||
'symbolic-ref --quiet --short HEAD',
|
||||
'symbolic-ref --quiet HEAD',
|
||||
])
|
||||
for (const call of record.calls) {
|
||||
expect(call.policy).toMatchObject({ mode: 'workspace-write', workspaceRoot: repo })
|
||||
@@ -174,6 +173,19 @@ describe('inspectCheckout', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('names the checked-out branch while a tag shares its name, and no branch while HEAD names another ref', async () => {
|
||||
const root = await directory()
|
||||
const repo = await repository(root)
|
||||
await git(repo, 'tag', 'main')
|
||||
const ctx = await context(sandboxRecord(), repo)
|
||||
|
||||
// `git symbolic-ref --short HEAD` prints `heads/main` here.
|
||||
expect((await inspectCheckout(ctx, CONFIG, session(repo), repo, live()))?.checkout.branch).toBe('main')
|
||||
await git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD')
|
||||
await git(repo, 'symbolic-ref', 'HEAD', 'refs/remotes/origin/main')
|
||||
expect((await inspectCheckout(ctx, CONFIG, session(repo), repo, live()))?.checkout.branch).toBeNull()
|
||||
})
|
||||
|
||||
it('stops when the caller aborts', async () => {
|
||||
const root = await directory()
|
||||
const ctx = await context(sandboxRecord(), root)
|
||||
@@ -243,7 +255,7 @@ describe.skipIf(!posix)('inspectCheckout with a stand-in Git', () => {
|
||||
` *--git-common-dir*) echo "${alias}/.git" ;;`,
|
||||
` *--git-dir*) echo "${alias}/.git" ;;`,
|
||||
' *"rev-parse --short"*) echo 0a1b2c3 ;;',
|
||||
' *symbolic-ref*) echo main ;;',
|
||||
' *symbolic-ref*) echo refs/heads/main ;;',
|
||||
' *--abbrev-ref*) echo origin/main ;;',
|
||||
'esac',
|
||||
].join('\n'))
|
||||
@@ -307,79 +319,6 @@ describe.skipIf(!posix)('inspectCheckout with a stand-in Git', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('listBranches', () => {
|
||||
it('lists the checked-out branch first, then local branches by latest commit, with two read-only commands', async () => {
|
||||
const root = await directory()
|
||||
const repo = await branched(root)
|
||||
const record = sandboxRecord()
|
||||
const ctx = await context(record, repo)
|
||||
|
||||
await expect(listBranches(ctx, CONFIG, session(repo), repo, 50, live())).resolves.toEqual({
|
||||
current: 'main', branches: ['main', 'newer', 'older'],
|
||||
})
|
||||
expect(commands(record)).toEqual([
|
||||
'for-each-ref --sort=-committerdate --count=50 --format=%(refname:lstrip=2) refs/heads/',
|
||||
'symbolic-ref --quiet --short HEAD',
|
||||
])
|
||||
for (const call of record.calls) {
|
||||
expect(call.policy).toMatchObject({ mode: 'workspace-write', workspaceRoot: repo })
|
||||
expect(call.argv.slice(1, 1 + GIT_PREFIX.length)).toEqual(GIT_PREFIX)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the checked-out branch first when the limit cuts it from the listing', async () => {
|
||||
const root = await directory()
|
||||
const repo = await branched(root)
|
||||
await git(repo, 'checkout', 'older')
|
||||
const ctx = await context(sandboxRecord(), repo)
|
||||
|
||||
await expect(listBranches(ctx, CONFIG, session(repo), repo, 2, live())).resolves.toEqual({ current: 'older', branches: ['older', 'main'] })
|
||||
await expect(listBranches(ctx, CONFIG, session(repo), repo, 1, live())).resolves.toEqual({ current: 'older', branches: ['older'] })
|
||||
})
|
||||
|
||||
it('lists the branches of a detached HEAD without a current one, and an unborn branch alone', async () => {
|
||||
const root = await directory()
|
||||
const repo = await branched(root)
|
||||
await git(repo, 'checkout', '--detach', 'main')
|
||||
await git(root, 'init', '-b', 'main', 'empty')
|
||||
const ctx = await context(sandboxRecord(), root)
|
||||
|
||||
await expect(listBranches(ctx, CONFIG, session(root), repo, 2, live())).resolves.toEqual({ current: null, branches: ['main', 'newer'] })
|
||||
await expect(listBranches(ctx, CONFIG, session(root), join(root, 'empty'), 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] })
|
||||
})
|
||||
|
||||
it('fails outside a checkout', async () => {
|
||||
const root = await directory()
|
||||
const ctx = await context(sandboxRecord(), root)
|
||||
|
||||
await expect(listBranches(ctx, CONFIG, session(root), root, 50, live()))
|
||||
.rejects.toThrow(/^git (symbolic-ref|for-each-ref) failed \(128\): fatal: not a git repository/)
|
||||
})
|
||||
|
||||
it.skipIf(!posix)('names a failing branch listing', async () => {
|
||||
const root = await directory()
|
||||
const fake = await script(join(root, 'git'), [
|
||||
'case "$*" in',
|
||||
' *for-each-ref*) echo "fatal: bad ref" >&2; exit 2 ;;',
|
||||
' *symbolic-ref*) echo main ;;',
|
||||
'esac',
|
||||
].join('\n'))
|
||||
const ctx = await context(sandboxRecord(), root)
|
||||
|
||||
await expect(listBranches(ctx, { ...CONFIG, gitCommand: fake }, session(root), root, 50, live()))
|
||||
.rejects.toThrow('git for-each-ref failed (2): fatal: bad ref')
|
||||
})
|
||||
|
||||
it('stops when the caller aborts', async () => {
|
||||
const root = await directory()
|
||||
const ctx = await context(sandboxRecord(), root)
|
||||
const controller = new AbortController()
|
||||
controller.abort(new Error('closed'))
|
||||
|
||||
await expect(listBranches(ctx, CONFIG, session(root), root, 50, controller.signal)).rejects.toThrow('closed')
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasBranch', () => {
|
||||
it('reports whether a local branch exists with one read-only command per question', async () => {
|
||||
const root = await directory()
|
||||
@@ -445,7 +384,7 @@ const sandboxUsable = await (async () => {
|
||||
})()
|
||||
|
||||
describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => {
|
||||
it('reads a checkout and lists its branches under read-only confinement without writing its index', async () => {
|
||||
it('reads a checkout under read-only confinement without writing its index', async () => {
|
||||
const root = await directory()
|
||||
const repo = await repository(root)
|
||||
await writeFile(join(repo, 'tracked.txt'), 'changed\n')
|
||||
@@ -460,9 +399,8 @@ describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () =>
|
||||
checkout: { root: repo, branch: 'main', linked: false, commit: await git(repo, 'rev-parse', '--short', 'HEAD') },
|
||||
commonDir: join(repo, '.git'), upstream: null, remotes: [],
|
||||
})
|
||||
await expect(listBranches(ctx, CONFIG, readOnly, repo, 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] })
|
||||
|
||||
expect(confine).toHaveBeenCalledTimes(9)
|
||||
expect(confine).toHaveBeenCalledTimes(7)
|
||||
expect(confine.mock.calls.every(call => call[1].mode === 'read-only')).toBe(true)
|
||||
expect((await stat(index)).mtimeMs).toBe(before.mtimeMs)
|
||||
await expect(access(join(repo, '.git', 'index.lock'))).rejects.toThrow()
|
||||
@@ -471,7 +409,7 @@ describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () =>
|
||||
|
||||
|
||||
describe('parallel inspection cleanup', () => {
|
||||
it.each(['checkout', 'branches'] as const)('cancels and joins sibling reads when %s inspection fails', async (kind) => {
|
||||
it('cancels and joins sibling reads when checkout inspection fails', async () => {
|
||||
const root = await directory()
|
||||
const repo = await repository(root)
|
||||
const ctx = await context(sandboxRecord(), repo)
|
||||
@@ -480,8 +418,8 @@ describe('parallel inspection cleanup', () => {
|
||||
const original = ctx.sandbox.confine.bind(ctx.sandbox)
|
||||
let sibling: AbortSignal | undefined
|
||||
const failure = new Error('inspection failed')
|
||||
const heldArg = kind === 'checkout' ? '--git-common-dir' : 'symbolic-ref'
|
||||
const failedArg = kind === 'checkout' ? 'remote' : 'for-each-ref'
|
||||
const heldArg = '--git-common-dir'
|
||||
const failedArg = 'remote'
|
||||
const probe = vi.spyOn(ctx.sandbox, 'confine').mockImplementation(async (argv, policy, signal) => {
|
||||
if (argv.includes(heldArg)) {
|
||||
sibling = signal
|
||||
@@ -492,9 +430,7 @@ describe('parallel inspection cleanup', () => {
|
||||
return original(argv, policy, signal)
|
||||
})
|
||||
let settled = false
|
||||
const operation = (kind === 'checkout'
|
||||
? inspectCheckout(ctx, CONFIG, session(repo), repo, live())
|
||||
: listBranches(ctx, CONFIG, session(repo), repo, 50, live()))
|
||||
const operation = inspectCheckout(ctx, CONFIG, session(repo), repo, live())
|
||||
.then(() => { settled = true; return undefined }, (error: unknown) => { settled = true; return error })
|
||||
try {
|
||||
await entered.promise
|
||||
|
||||
@@ -43,9 +43,9 @@ import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFiel
|
||||
import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
import type {
|
||||
ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame,
|
||||
ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame,
|
||||
ForgeLensRequest,
|
||||
ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState,
|
||||
ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, ForgeWorktreeBases,
|
||||
} from '../src/types.ts'
|
||||
import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
@@ -53,7 +53,7 @@ import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
const REMOTE: TypertRemoteContribution = { package: '@deepseek-ai/dsh-experimental-client-ui-forge', descriptors: [] }
|
||||
const S1 = brandString<SessionId>('s1')
|
||||
const S2 = brandString<SessionId>('s2')
|
||||
const BRANCHES: ForgeBranches = { current: 'main', branches: ['main', 'release'] }
|
||||
const BASES: ForgeWorktreeBases = { current: { ref: 'refs/heads/main', name: 'main' }, defaults: [], local: [], remotes: [] }
|
||||
const LOCAL: ForgeLocalDiff = { base: 'origin/main', files: [], omitted: 0 }
|
||||
const CHANGE: ForgeChangeRequestDiff = { headSha: 'a'.repeat(40), files: [], localAhead: null, fileUrls: {} }
|
||||
const COMMITS: ForgeCommitList = { headSha: 'a'.repeat(40), commits: [], truncated: false }
|
||||
@@ -98,6 +98,8 @@ const REFUSED = {
|
||||
busy: { ok: false, error: new RemoteError('forgePanel/session-busy', 'busy', {}) },
|
||||
restore: { ok: false, error: new RemoteError('forgePanel/restore-failed', 'fatal: \'/work/repo-dsh\' already exists', {}) },
|
||||
failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) },
|
||||
exists: { ok: false, error: new RemoteError('forgePanel/branch-exists', 'taken', {}) },
|
||||
invalidName: { ok: false, error: new RemoteError('forgePanel/invalid-name', 'invalid', {}) },
|
||||
stale: { ok: false, error: new RemoteError('forgePanel/stale-head', 'Head branch was modified', {}) },
|
||||
refused: { ok: false, error: new RemoteError('forgePanel/action-failed', 'Pull Request is not mergeable', {}) },
|
||||
unknown: { ok: false, error: new RemoteError('forgePanel/action-unknown', 'Something went wrong', {}) },
|
||||
@@ -128,7 +130,7 @@ function isAttentionFace(value: Record<string, unknown>): value is Record<string
|
||||
}
|
||||
|
||||
function isWorktreeFace(value: Record<string, unknown>): value is Record<string, unknown> & WorktreeToggleInjected {
|
||||
return typeof value.request === 'function' && typeof value.branches === 'function'
|
||||
return typeof value.request === 'function' && typeof value.bases === 'function'
|
||||
}
|
||||
|
||||
function isProgressFace(value: Record<string, unknown>): value is Record<string, unknown> & WorktreeProgressInjected {
|
||||
@@ -204,13 +206,14 @@ async function base() {
|
||||
): Read<ForgeViewedFiles | null> => ({ ok: true, value: null })),
|
||||
setFileViewed: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeViewedRequest): Promise<RemoteResult<void>> => OK),
|
||||
refresh: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null): Promise<RemoteResult<void>> => OK),
|
||||
requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null, _name: string | null): Promise<RemoteResult<void>> => OK),
|
||||
cancelWorktree: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
stopCreation: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
retryWorktree: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
retryWorktree: vi.fn(async (_sessionId: SessionId, _fetch: boolean): Promise<RemoteResult<void>> => OK),
|
||||
restoreWorktree: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
continueInProject: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<void>> => OK),
|
||||
branches: vi.fn(async (_sessionId: SessionId): Promise<RemoteResult<ForgeBranches>> => ({ ok: true, value: BRANCHES })),
|
||||
worktreeBases: vi.fn(async (_sessionId: SessionId, _query: string, _signal?: AbortSignal): Read<ForgeWorktreeBases> =>
|
||||
({ ok: true, value: BASES })),
|
||||
localDiff: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _signal?: AbortSignal): Read<ForgeLocalDiff> =>
|
||||
({ ok: true, value: LOCAL })),
|
||||
localText: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _path: string): Read<string> => ({ ok: true, value: 'a\n' })),
|
||||
@@ -854,10 +857,10 @@ describe('mountForgePanel worktree actions', () => {
|
||||
it('requests and withdraws a worktree through the Remote', async () => {
|
||||
const f = await fixture()
|
||||
const option = f.worktree(S1)
|
||||
expect(await option.request('release')).toBe(true)
|
||||
expect(await option.request(null)).toBe(true)
|
||||
expect(await option.request('refs/heads/release', 'fix/x')).toBe('accepted')
|
||||
expect(await option.request(null, null)).toBe('accepted')
|
||||
expect(await option.cancel()).toBe(true)
|
||||
expect(f.forgePanel.requestWorktree.mock.calls).toEqual([[S1, 'release'], [S1, null]])
|
||||
expect(f.forgePanel.requestWorktree.mock.calls).toEqual([[S1, 'refs/heads/release', 'fix/x'], [S1, null, null]])
|
||||
expect(f.forgePanel.cancelWorktree).toHaveBeenCalledWith(S1)
|
||||
expect(f.notice()).toBeNull()
|
||||
await f.dispose()
|
||||
@@ -871,7 +874,7 @@ describe('mountForgePanel worktree actions', () => {
|
||||
const f = await fixture()
|
||||
const option = f.worktree(S1)
|
||||
f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal)
|
||||
expect(await option.request('main')).toBe(false)
|
||||
expect(await option.request('refs/heads/main', null)).toBe('failed')
|
||||
expect(f.notice()).toMatchObject({ key, tone: 'failure', seq: 1 })
|
||||
f.forgePanel.cancelWorktree.mockResolvedValueOnce(refusal)
|
||||
expect(await option.cancel()).toBe(false)
|
||||
@@ -879,33 +882,42 @@ describe('mountForgePanel worktree actions', () => {
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('lists the branches of the Session checkout and reports when they cannot be read', async () => {
|
||||
it.each([
|
||||
['branch-exists', REFUSED.exists],
|
||||
['invalid-name', REFUSED.invalidName],
|
||||
] as const)('returns a branch name refused as %s to the naming dialog without a notice', async (result, refusal) => {
|
||||
const f = await fixture()
|
||||
expect(await f.worktree(S1).branches()).toEqual(BRANCHES)
|
||||
expect(f.forgePanel.branches).toHaveBeenCalledWith(S1)
|
||||
f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal)
|
||||
expect(await f.worktree(S1).request(null, 'taken')).toBe(result)
|
||||
f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal)
|
||||
expect(await f.progress(S1).request(null, 'taken')).toBe(result)
|
||||
expect(f.notice()).toBeNull()
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
f.forgePanel.branches.mockResolvedValueOnce(REFUSED.failed)
|
||||
expect(await f.worktree(S1).branches()).toBeUndefined()
|
||||
expect(f.notice()).toMatchObject({ key: 'toast.branchesFailed', tone: 'failure' })
|
||||
it('lists the bases of a new worktree through the Remote', async () => {
|
||||
const f = await fixture()
|
||||
const signal = new AbortController().signal
|
||||
expect(await f.worktree(S1).bases('rel', signal)).toEqual({ ok: true, value: BASES })
|
||||
expect(f.forgePanel.worktreeBases).toHaveBeenCalledWith(S1, 'rel', signal)
|
||||
await f.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mountForgePanel worktree card actions', () => {
|
||||
it.each([
|
||||
['stops the attempt a message waits for', 'stop' as const, 'stopCreation' as const],
|
||||
['makes another attempt for the waiting message', 'retry' as const, 'retryWorktree' as const],
|
||||
['withdraws the request so the waiting message goes on', 'withdraw' as const, 'cancelWorktree' as const],
|
||||
])('%s through the Remote and reports only a failure', async (_label, action, method) => {
|
||||
['stops the attempt a message waits for', 'stop' as const, 'stopCreation' as const, []],
|
||||
['makes another attempt for the waiting message', 'retry' as const, 'retryWorktree' as const, [false]],
|
||||
['withdraws the request so the waiting message goes on', 'withdraw' as const, 'cancelWorktree' as const, []],
|
||||
])('%s through the Remote and reports only a failure', async (_label, action, method, args) => {
|
||||
const f = await fixture()
|
||||
f.progress(S1)[action]()
|
||||
f.progress(S1)[action](false)
|
||||
await settle()
|
||||
expect(f.forgePanel[method]).toHaveBeenCalledWith(S1)
|
||||
expect(f.forgePanel[method]).toHaveBeenCalledWith(S1, ...args)
|
||||
expect(f.notice()).toBeNull()
|
||||
|
||||
f.forgePanel[method].mockResolvedValueOnce(REFUSED.busy)
|
||||
f.progress(S1)[action]()
|
||||
f.progress(S1)[action](false)
|
||||
await settle()
|
||||
expect(f.notice()).toMatchObject({ key: 'toast.worktreeFailed', tone: 'failure' })
|
||||
await f.dispose()
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { baseBranches, parseBaseBranches, parseName, parseRemotes, parseTopLevel, remoteOrder, upstreamBranch } from '../src/parse.ts'
|
||||
import {
|
||||
parseBaseBranches, parseName, parseRemotes, parseTopLevel, parseWorktreeBases, remoteOrder, remoteRepository, upstreamBranch,
|
||||
} from '../src/parse.ts'
|
||||
import type { GitRemote } from '../src/parse.ts'
|
||||
|
||||
describe('parseTopLevel', () => {
|
||||
@@ -27,24 +29,85 @@ describe('parseName', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('baseBranches', () => {
|
||||
it('puts the checked-out branch first without repeating it', () => {
|
||||
expect(baseBranches('feat', 'main\nfeat\nfix\n', 10)).toEqual(['feat', 'main', 'fix'])
|
||||
describe('parseWorktreeBases', () => {
|
||||
const remotes: GitRemote[] = [
|
||||
{ name: 'upstream', urls: ['https://github.com/acme/demo.git'] },
|
||||
{ name: 'origin', urls: ['[email protected]:me/demo.git'] },
|
||||
{ name: 'team/fork', urls: ['/srv/team.git'] },
|
||||
{ name: 'empty', urls: [] },
|
||||
]
|
||||
const output = [
|
||||
'refs/remotes/upstream/HEAD\0refs/remotes/upstream/master',
|
||||
'refs/remotes/origin/HEAD\0refs/remotes/origin/main',
|
||||
'refs/remotes/team/fork/HEAD\0refs/remotes/team/fork/gone',
|
||||
'refs/remotes/empty/HEAD\0refs/heads/main',
|
||||
'refs/remotes/origin/alias\0refs/remotes/origin/main',
|
||||
'refs/heads/alias\0refs/heads/main',
|
||||
'refs/heads/topic\0',
|
||||
'refs/remotes/upstream/master\0',
|
||||
'refs/remotes/origin/main\0',
|
||||
'refs/remotes/team/fork/feature\0',
|
||||
'refs/remotes/upstream/release/2.4\0',
|
||||
'refs/remotes/upstream/dev\0',
|
||||
'refs/heads/main\0',
|
||||
'refs/remotes/stray/main\0',
|
||||
'refs/heads/Fix/Login\0',
|
||||
'refs/tags/v1\0',
|
||||
'',
|
||||
].join('\r\n')
|
||||
const repositories = (remote: GitRemote): string | null => remote.urls[0] ?? null
|
||||
|
||||
it('pins the checked-out branch and each remote default, then groups local branches and each remote in remote order', () => {
|
||||
expect(parseWorktreeBases(output, 'main', remotes, '', 10, repositories)).toEqual({
|
||||
current: { ref: 'refs/heads/main', name: 'main' },
|
||||
defaults: [
|
||||
{ ref: 'refs/remotes/upstream/master', name: 'upstream/master', remote: 'upstream' },
|
||||
{ ref: 'refs/remotes/origin/main', name: 'origin/main', remote: 'origin' },
|
||||
],
|
||||
local: [{ ref: 'refs/heads/topic', name: 'topic' }, { ref: 'refs/heads/Fix/Login', name: 'Fix/Login' }],
|
||||
remotes: [
|
||||
{
|
||||
name: 'upstream',
|
||||
repository: 'https://github.com/acme/demo.git',
|
||||
branches: [{ ref: 'refs/remotes/upstream/release/2.4', name: 'upstream/release/2.4' }, { ref: 'refs/remotes/upstream/dev', name: 'upstream/dev' }],
|
||||
},
|
||||
{ name: 'team/fork', repository: '/srv/team.git', branches: [{ ref: 'refs/remotes/team/fork/feature', name: 'team/fork/feature' }] },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the checked-out branch when the listing omits it', () => {
|
||||
expect(baseBranches('old', 'main\nfeat\n', 2)).toEqual(['old', 'main'])
|
||||
expect(baseBranches('main', '', 50)).toEqual(['main'])
|
||||
it('keeps the branches whose names contain the query, ignoring case, at most `limit` in each group', () => {
|
||||
expect(parseWorktreeBases(output, 'main', remotes, ' FIX ', 10, repositories)).toEqual({ current: null, defaults: [], local: [{ ref: 'refs/heads/Fix/Login', name: 'Fix/Login' }], remotes: [] })
|
||||
const limited = parseWorktreeBases(output, null, remotes, '', 1, repositories)
|
||||
expect(limited.current).toBeNull()
|
||||
expect(limited.local).toEqual([{ ref: 'refs/heads/topic', name: 'topic' }])
|
||||
expect(limited.remotes.map(remote => remote.branches.length)).toEqual([1, 1])
|
||||
})
|
||||
|
||||
it('lists the branches of a detached HEAD in listed order', () => {
|
||||
expect(baseBranches(null, 'main\r\nfeat\r\n', 10)).toEqual(['main', 'feat'])
|
||||
expect(baseBranches(null, '', 10)).toEqual([])
|
||||
it('names no current branch on a detached HEAD or an unborn branch', () => {
|
||||
expect(parseWorktreeBases(output, null, remotes, '', 10, repositories).current).toBeNull()
|
||||
expect(parseWorktreeBases('', 'main', [], '', 10, repositories)).toEqual({ current: null, defaults: [], local: [], remotes: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('remoteRepository', () => {
|
||||
const recognize = (url: string) => url.startsWith('https://host.test/') ? { owner: 'acme', name: 'demo' } : undefined
|
||||
|
||||
it('names the first recognized repository, else the first URL, else nothing', () => {
|
||||
expect(remoteRepository({ name: 'origin', urls: ['/srv/demo.git', 'https://host.test/acme/demo.git'] }, recognize)).toBe('acme/demo')
|
||||
expect(remoteRepository({ name: 'fork', urls: ['/srv/fork.git'] }, recognize)).toBe('/srv/fork.git')
|
||||
expect(remoteRepository({ name: 'empty', urls: [] }, recognize)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns at most `limit` names and skips empty lines', () => {
|
||||
expect(baseBranches('main', '\nmain\n\nfeat\nfix\n', 2)).toEqual(['main', 'feat'])
|
||||
expect(baseBranches(null, 'main\nfeat\nfix\n', 1)).toEqual(['main'])
|
||||
it.each([
|
||||
['a user name and token', 'https://oauth2:[email protected]/group/repo.git', 'https://gitlab.internal.test/group/repo.git'],
|
||||
['a token as the user name', 'https://[email protected]/acme/demo.git', 'https://git.internal.test/acme/demo.git'],
|
||||
['an `@` in the password', 'https://user:p@[email protected]:8443/repo', 'https://git.internal.test:8443/repo'],
|
||||
['an SSH user', 'ssh://[email protected]:2222/acme/demo.git', 'ssh://git.internal.test:2222/acme/demo.git'],
|
||||
['an `@` only in the path', 'https://git.internal.test/users/@me/repo.git', 'https://git.internal.test/users/@me/repo.git'],
|
||||
['the scp-like form, which has no password', '[email protected]:acme/demo.git', '[email protected]:acme/demo.git'],
|
||||
])('shows an unrecognized URL with %s without its user information', (_label, url, shown) => {
|
||||
expect(remoteRepository({ name: 'selfhost', urls: [url] }, recognize)).toBe(shown)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Naming dialog of a worktree branch: the starting text, the rules checked while typing, the Host's refusals, and the retry mode. */
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
import { WorktreeNameDialog, type WorktreeNameDialogProps } from '../src/client/WorktreeNameDialog.tsx'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
const t = makeTranslate(en)
|
||||
|
||||
function mount(props: Partial<WorktreeNameDialogProps> = {}) {
|
||||
const submit = vi.fn<WorktreeNameDialogProps['submit']>(async () => 'accepted')
|
||||
const close = vi.fn()
|
||||
render(<WorktreeNameDialog mode="name" initial="dsh-" prefix="dsh-" from="refs/heads/main" named={false} submit={submit} close={close}
|
||||
t={t} {...props} />)
|
||||
const dialog = (): HTMLElement => screen.getByRole('dialog')
|
||||
const field = (): HTMLInputElement => within(dialog()).getByRole('textbox', { name: en['nameDialog.field'] })
|
||||
const confirm = (): HTMLElement => within(dialog()).getByRole('button', { name: props.mode === 'retry' ? en['nameDialog.retry'] : en['nameDialog.confirm'] })
|
||||
const type = (value: string): void => { fireEvent.change(field(), { target: { value } }) }
|
||||
const message = (): string | null => field().getAttribute('aria-describedby') === null
|
||||
? null : document.getElementById(field().getAttribute('aria-describedby') ?? '')?.textContent ?? null
|
||||
return { submit, close, dialog, field, confirm, type, message }
|
||||
}
|
||||
|
||||
describe('WorktreeNameDialog rules', () => {
|
||||
it.each([
|
||||
['', en['branchName.empty']],
|
||||
['fix login', en['branchName.space']],
|
||||
['fix~1', en['branchName.character']],
|
||||
['-fix', en['branchName.leading-dash']],
|
||||
['/fix', en['branchName.leading-slash']],
|
||||
['worktree/', en['branchName.trailing-slash']],
|
||||
['fix//login', en['branchName.double-slash']],
|
||||
['fix..login', en['branchName.double-dot']],
|
||||
['fix.', en['branchName.trailing-dot']],
|
||||
['@', en['branchName.at']],
|
||||
['fix@{1}', en['branchName.at-brace']],
|
||||
['fix/.login', en['branchName.dot-segment']],
|
||||
['fix.lock/login', en['branchName.lock-segment']],
|
||||
])('refuses %j while it is typed', (value, reason) => {
|
||||
const d = mount()
|
||||
d.type(value)
|
||||
expect(d.message()).toBe(reason)
|
||||
expect(within(d.dialog()).getByRole('alert').textContent).toBe(reason)
|
||||
expect(d.field().getAttribute('aria-invalid')).toBe('true')
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.keyDown(d.field(), { key: 'Enter' })
|
||||
expect(d.submit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hints at the prefix it starts with, and at the base once a name follows it', () => {
|
||||
const d = mount({ prefix: 'agent/', initial: 'agent/' })
|
||||
expect(d.message()).toBe(en['nameDialog.prefixOnly'])
|
||||
expect(d.field().getAttribute('aria-invalid')).toBe('false')
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(true)
|
||||
d.type('agent/fix')
|
||||
expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name')
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('without a prefix, starts empty with the base hint, and names the current HEAD for a request without a base', () => {
|
||||
const d = mount({ prefix: '', initial: '', from: null })
|
||||
expect(d.message()).toBe(en['nameDialog.hintHead'])
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('takes the keyboard with the caret after the starting text', () => {
|
||||
const d = mount({ initial: 'dsh-fix', named: true })
|
||||
expect(document.activeElement).toBe(d.field())
|
||||
expect(d.field().selectionStart).toBe(7)
|
||||
})
|
||||
})
|
||||
|
||||
describe('WorktreeNameDialog requests', () => {
|
||||
it('requests the name with Enter, ignores Enter while composing, and closes once the request is accepted', async () => {
|
||||
const d = mount()
|
||||
d.type('dsh-fix')
|
||||
fireEvent.keyDown(d.field(), { key: 'Enter', isComposing: true })
|
||||
expect(d.submit).not.toHaveBeenCalled()
|
||||
fireEvent.keyDown(d.field(), { key: 'a' })
|
||||
await act(async () => { fireEvent.keyDown(d.field(), { key: 'Enter' }) })
|
||||
expect(d.submit).toHaveBeenCalledWith('dsh-fix')
|
||||
expect(d.close).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('stays busy until the Host answers, then shows its refusal for that name only', async () => {
|
||||
let answer: (result: 'branch-exists' | 'invalid-name' | 'failed') => void = () => {}
|
||||
const d = mount()
|
||||
d.submit.mockImplementation(() => new Promise((resolve) => { answer = resolve }))
|
||||
d.type('dsh-taken')
|
||||
fireEvent.click(d.confirm())
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(true)
|
||||
await act(async () => { answer('branch-exists') })
|
||||
expect(d.message()).toBe('A branch named dsh-taken already exists')
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(true)
|
||||
|
||||
d.type('dsh-odd')
|
||||
expect(d.confirm().hasAttribute('disabled')).toBe(false)
|
||||
fireEvent.click(d.confirm())
|
||||
await act(async () => { answer('invalid-name') })
|
||||
expect(d.message()).toBe(en['branchName.invalid'])
|
||||
|
||||
d.type('dsh-other')
|
||||
fireEvent.click(d.confirm())
|
||||
await act(async () => { answer('failed') })
|
||||
expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name')
|
||||
expect(d.close).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns a named request to generated names, ignoring a refusal that names no branch', async () => {
|
||||
const d = mount({ initial: 'dsh-fix', named: true })
|
||||
d.submit.mockResolvedValueOnce('branch-exists')
|
||||
await act(async () => { fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.auto'] })) })
|
||||
expect(d.submit).toHaveBeenCalledWith(null)
|
||||
expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name')
|
||||
await act(async () => { fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.auto'] })) })
|
||||
expect(d.close).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('renames for another attempt in retry mode, without the return to generated names', async () => {
|
||||
const d = mount({ mode: 'retry', initial: 'dsh-fix', named: true })
|
||||
expect(screen.getByRole('dialog', { name: en['nameDialog.retryTitle'] })).toBeTruthy()
|
||||
expect(within(d.dialog()).queryByRole('button', { name: en['nameDialog.auto'] })).toBeNull()
|
||||
d.type('dsh-fix-2')
|
||||
await act(async () => { fireEvent.click(d.confirm()) })
|
||||
expect(d.submit).toHaveBeenCalledWith('dsh-fix-2')
|
||||
})
|
||||
|
||||
it('closes without a request from Cancel and the close button', () => {
|
||||
const d = mount()
|
||||
fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.cancel'] }))
|
||||
fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.close'] }))
|
||||
expect(d.close).toHaveBeenCalledTimes(2)
|
||||
expect(d.submit).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -3,13 +3,13 @@
|
||||
* Worktree card: a running creation, which can be stopped while a message waits for it; the failed or stopped attempt a
|
||||
* message waits after; and a removed worktree.
|
||||
*/
|
||||
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
import type { PanelSnapshot } from '../src/client/source.ts'
|
||||
import { WorktreeProgress } from '../src/client/WorktreeProgress.tsx'
|
||||
import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx'
|
||||
import css from '../src/client/WorktreeProgress.module.css'
|
||||
import type { ForgePanelState } from '../src/types.ts'
|
||||
import { created, creation, failure, ready, removed, requested, worktree } from './client-fixtures.client.ts'
|
||||
@@ -21,8 +21,9 @@ const t = makeTranslate(en)
|
||||
function card(state: ForgePanelState | null) {
|
||||
const panel = createSnapshotStore<PanelSnapshot>({ state, disconnected: false })
|
||||
const stop = vi.fn<() => void>()
|
||||
const retry = vi.fn<() => void>()
|
||||
const retry = vi.fn<WorktreeProgressInjected['retry']>()
|
||||
const withdraw = vi.fn<() => void>()
|
||||
const request = vi.fn<WorktreeProgressInjected['request']>(async () => 'accepted')
|
||||
const restore = vi.fn(async (): Promise<string | undefined> => undefined)
|
||||
const leave = vi.fn<() => void>()
|
||||
const view = render(
|
||||
@@ -31,6 +32,7 @@ function card(state: ForgePanelState | null) {
|
||||
stop={stop}
|
||||
retry={retry}
|
||||
withdraw={withdraw}
|
||||
request={request}
|
||||
restore={restore}
|
||||
leave={leave}
|
||||
t={t}
|
||||
@@ -40,7 +42,7 @@ function card(state: ForgePanelState | null) {
|
||||
const publish = (next: ForgePanelState | null): void => {
|
||||
act(() => { panel.set({ state: next, disconnected: false }) })
|
||||
}
|
||||
return { view, stop, retry, withdraw, restore, leave, root, publish }
|
||||
return { view, stop, retry, withdraw, request, restore, leave, root, publish }
|
||||
}
|
||||
|
||||
/** Glyph a step shows for its state. */
|
||||
@@ -66,7 +68,7 @@ function details(view: ReturnType<typeof render>): string[][] | null {
|
||||
|
||||
/** Names of the action buttons the card offers, in order. */
|
||||
function actions(view: ReturnType<typeof render>): string[] {
|
||||
const names = [en['creation.retry'], en['creation.skip'], en['creation.cancel']]
|
||||
const names = [en['creation.retry'], en['creation.skip'], en['creation.cancel'], en['creation.useFetched'], en['creation.rename']]
|
||||
return view.getAllByRole('button').map(button => button.textContent).filter(name => names.includes(name))
|
||||
}
|
||||
|
||||
@@ -194,11 +196,58 @@ describe('WorktreeProgress waiting after a failed attempt', () => {
|
||||
const b = card(requested('main', { failure: failure(), waiting: 'creation' }))
|
||||
fireEvent.click(b.view.getByRole('button', { name: en['creation.retry'] }))
|
||||
fireEvent.click(b.view.getByRole('button', { name: en['creation.skip'] }))
|
||||
expect(b.retry).toHaveBeenCalledOnce()
|
||||
expect(b.retry).toHaveBeenCalledExactlyOnceWith(true)
|
||||
expect(b.withdraw).toHaveBeenCalledOnce()
|
||||
expect(b.stop).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('offers to start from the last fetched version after a failed fetch of a remote base branch', () => {
|
||||
const fetchFailure = failure({ from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch', message: 'fatal: unable to access' })
|
||||
const b = card(requested('refs/remotes/origin/main', { failure: fetchFailure, waiting: 'creation' }))
|
||||
expect(steps(b.view)).toEqual([
|
||||
['Fetch origin/main', 'failed', 'cross'], [en['creation.prepare'], 'waiting', 'ring'], [en['creation.checkout'], 'waiting', 'ring'],
|
||||
])
|
||||
expect(details(b.view)).toEqual([['Branch', 'dsh/0a1b2c3d'], ['From', 'origin/main'], ['Reason', 'fatal: unable to access']])
|
||||
expect(actions(b.view)).toEqual([en['creation.retry'], en['creation.useFetched'], en['creation.skip']])
|
||||
fireEvent.click(b.view.getByRole('button', { name: en['creation.useFetched'] }))
|
||||
fireEvent.click(b.view.getByRole('button', { name: en['creation.retry'] }))
|
||||
expect(b.retry.mock.calls).toEqual([[false], [true]])
|
||||
})
|
||||
|
||||
it('renames a chosen branch that already exists, then tries again on the new name', async () => {
|
||||
const taken = failure({ branch: 'fix/login', exists: true, message: 'worktree branch already exists: fix/login' })
|
||||
const b = card(requested('refs/heads/main', { failure: taken, waiting: 'creation' }, 'fix/login'))
|
||||
expect(actions(b.view)).toEqual([en['creation.rename'], en['creation.retry'], en['creation.skip']])
|
||||
fireEvent.click(b.view.getByRole('button', { name: en['creation.rename'] }))
|
||||
const dialog = screen.getByRole('dialog', { name: en['nameDialog.retryTitle'] })
|
||||
const field = within(dialog).getByRole('textbox')
|
||||
expect((field as HTMLInputElement).value).toBe('fix/login')
|
||||
|
||||
b.request.mockResolvedValueOnce('branch-exists')
|
||||
fireEvent.change(field, { target: { value: 'fix/login-2' } })
|
||||
await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.retry'] })) })
|
||||
expect(b.retry).not.toHaveBeenCalled()
|
||||
fireEvent.change(field, { target: { value: 'fix/login-3' } })
|
||||
await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.retry'] })) })
|
||||
expect(b.request.mock.calls).toEqual([['refs/heads/main', 'fix/login-2'], ['refs/heads/main', 'fix/login-3']])
|
||||
expect(b.retry).toHaveBeenCalledExactlyOnceWith(true)
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('offers no rename for a taken generated name, whose next attempt takes another one', () => {
|
||||
const b = card(requested('main', { failure: failure({ exists: true }), waiting: 'creation' }))
|
||||
expect(actions(b.view)).toEqual([en['creation.retry'], en['creation.skip']])
|
||||
})
|
||||
|
||||
it('shows the fetch step of a running creation from a remote base branch', () => {
|
||||
const b = card(requested('refs/remotes/origin/main', { creation: creation({ from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch' }), waiting: 'creation' }))
|
||||
expect(steps(b.view)).toEqual([
|
||||
['Fetch origin/main', 'running', 'spinner'], [en['creation.prepare'], 'waiting', 'ring'], [en['creation.checkout'], 'waiting', 'ring'],
|
||||
])
|
||||
b.publish(requested('refs/remotes/origin/main', { creation: creation({ from: 'refs/remotes/origin/main', fetch: true, phase: 'checkout' }), waiting: 'creation' }))
|
||||
expect(steps(b.view).map(step => step[1])).toEqual(['done', 'done', 'running'])
|
||||
})
|
||||
|
||||
it('shows a stopped attempt without steps, with the request\'s base and the same choices', () => {
|
||||
const b = card(requested(null, { waiting: 'creation' }))
|
||||
expect(b.root()?.getAttribute('data-forge-creation')).toBe('stopped')
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
// @vitest-environment jsdom
|
||||
/** New Session worktree option: when it shows, why it is disabled, the optimistic checkbox, the base menu, and a running creation. */
|
||||
/**
|
||||
* New Session worktree option: when it shows, why it is disabled, the optimistic checkbox, the searchable base menu
|
||||
* with remote groups, naming the branch, and a running creation.
|
||||
*/
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import menuCss from '@deepseek-ai/dsh-client-ui-primitives/src/Menu.module.css'
|
||||
import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
import type { PanelSnapshot } from '../src/client/source.ts'
|
||||
import { WorktreeToggle } from '../src/client/WorktreeToggle.tsx'
|
||||
import type { ForgeBranches, ForgeCheckoutState, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBlocker } from '../src/types.ts'
|
||||
import type { WorktreeRequestResult } from '../src/client/WorktreeNameDialog.tsx'
|
||||
import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx'
|
||||
import type { ForgeCheckoutState, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBases, ForgeWorktreeBlocker } from '../src/types.ts'
|
||||
import { creation, failure, ready, worktree } from './client-fixtures.client.ts'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
const t = makeTranslate(en)
|
||||
const BRANCHES: ForgeBranches = { current: 'main', branches: ['main', 'release', 'feat/x'] }
|
||||
const BASES: ForgeWorktreeBases = {
|
||||
current: { ref: 'refs/heads/main', name: 'main' },
|
||||
defaults: [{ ref: 'refs/remotes/upstream/master', name: 'upstream/master', remote: 'upstream' }],
|
||||
local: [{ ref: 'refs/heads/release', name: 'release' }, { ref: 'refs/heads/feat/x', name: 'feat/x' }],
|
||||
remotes: [
|
||||
{ name: 'upstream', repository: 'acme/demo', branches: [{ ref: 'refs/remotes/upstream/feat/y', name: 'upstream/feat/y' }] },
|
||||
{ name: 'team/fork', repository: null, branches: [{ ref: 'refs/remotes/team/fork/idea', name: 'team/fork/idea' }] },
|
||||
],
|
||||
}
|
||||
|
||||
function ok(value: ForgeWorktreeBases): RemoteResult<ForgeWorktreeBases> {
|
||||
return { ok: true, value }
|
||||
}
|
||||
|
||||
/** Panel state of a Session that can still start in a worktree. */
|
||||
function editable(overrides: Partial<ForgePanelWorktree> = {}, checkout?: ForgeCheckoutState): ForgePanelState {
|
||||
@@ -32,17 +49,22 @@ function deferred<T>() {
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
/** Let the listing reads the menu awaits settle, past the search delay when `ms` is given. */
|
||||
async function settle(ms = 0): Promise<void> {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, ms)) })
|
||||
}
|
||||
|
||||
function option(state: ForgePanelState | null, translate = t) {
|
||||
const panel = createSnapshotStore<PanelSnapshot>({ state, disconnected: false })
|
||||
const request = vi.fn(async (_from: string | null) => true)
|
||||
const request = vi.fn<WorktreeToggleInjected['request']>(async () => 'accepted')
|
||||
const cancel = vi.fn(async () => true)
|
||||
const branches = vi.fn(async (): Promise<ForgeBranches | undefined> => BRANCHES)
|
||||
const bases = vi.fn<WorktreeToggleInjected['bases']>(async () => ok(BASES))
|
||||
const view = render(
|
||||
<WorktreeToggle
|
||||
usePanel={bindSnapshotSelector(panel)}
|
||||
request={request}
|
||||
cancel={cancel}
|
||||
branches={branches}
|
||||
bases={bases}
|
||||
t={translate}
|
||||
/>,
|
||||
)
|
||||
@@ -58,12 +80,15 @@ function option(state: ForgePanelState | null, translate = t) {
|
||||
const publish = (next: ForgePanelState): void => {
|
||||
act(() => { panel.set({ state: next, disconnected: false }) })
|
||||
}
|
||||
return { view, panel, request, cancel, branches, checkbox, base, publish }
|
||||
const rows = (): string[] => screen.queryAllByRole('menuitem').map(row => row.textContent ?? '')
|
||||
const search = (): HTMLElement => screen.getByRole('textbox', { name: en['diff.base.search'] })
|
||||
return { view, panel, request, cancel, bases, checkbox, base, publish, rows, search }
|
||||
}
|
||||
|
||||
/** Open the base branch menu and wait for its branches. */
|
||||
/** Open the base menu and wait for its branches. */
|
||||
async function openMenu(b: ReturnType<typeof option>): Promise<HTMLElement> {
|
||||
await act(async () => { fireEvent.click(b.base()!) })
|
||||
fireEvent.click(b.base()!)
|
||||
await settle()
|
||||
return screen.getByRole('menu')
|
||||
}
|
||||
|
||||
@@ -76,7 +101,6 @@ function hint(b: ReturnType<typeof option>): string | null {
|
||||
act(() => { vi.advanceTimersByTime(500) })
|
||||
return screen.getByRole('tooltip').textContent
|
||||
}
|
||||
|
||||
describe('WorktreeToggle visibility', () => {
|
||||
it.each([
|
||||
['before the first state', null],
|
||||
@@ -92,7 +116,7 @@ describe('WorktreeToggle visibility', () => {
|
||||
const b = option(ready())
|
||||
b.publish(editable())
|
||||
expect(b.checkbox().checked).toBe(false)
|
||||
b.publish(ready({ worktree: worktree({ editable: false, request: { from: 'main' } }) }))
|
||||
b.publish(ready({ worktree: worktree({ editable: false, request: { from: 'main', name: null } }) }))
|
||||
expect(b.view.container.innerHTML).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -111,8 +135,8 @@ describe('WorktreeToggle checkbox', () => {
|
||||
})
|
||||
|
||||
it.each(['read-only', 'outside-writable-root'] as const)('keeps the selected base visible after %s blocks a request until it is withdrawn', async (blocker) => {
|
||||
const b = option(editable({ request: { from: 'release' } }))
|
||||
b.publish(editable({ blocker, request: { from: 'release' } }))
|
||||
const b = option(editable({ request: { from: 'release', name: null } }))
|
||||
b.publish(editable({ blocker, request: { from: 'release', name: null } }))
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
expect(b.checkbox().disabled).toBe(false)
|
||||
expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(false)
|
||||
@@ -130,10 +154,10 @@ describe('WorktreeToggle checkbox', () => {
|
||||
})
|
||||
|
||||
it('preserves a HEAD base while blocked and restores the selected branch menu when permission returns', () => {
|
||||
const b = option(editable({ blocker: 'read-only', request: { from: null } }))
|
||||
const b = option(editable({ blocker: 'read-only', request: { from: null, name: null } }))
|
||||
expect(b.view.getByRole('button', { name: en['worktree.baseHead'] })).toBeTruthy()
|
||||
b.publish(editable({ blocker: 'read-only', request: { from: 'release' } }))
|
||||
b.publish(editable({ request: { from: 'release' } }))
|
||||
b.publish(editable({ blocker: 'read-only', request: { from: 'release', name: null } }))
|
||||
b.publish(editable({ request: { from: 'release', name: null } }))
|
||||
expect(b.base()?.textContent).toBe('From release')
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
})
|
||||
@@ -157,7 +181,7 @@ describe('WorktreeToggle checkbox', () => {
|
||||
b.publish(ready({ worktree: worktree({ editable: true }) }, { branch: null, commit: null }))
|
||||
expect(b.view.getByRole('button', { name: copy['checkout.detached'] })).toBeTruthy()
|
||||
expect(b.request).not.toHaveBeenCalled()
|
||||
expect(b.branches).not.toHaveBeenCalled()
|
||||
expect(b.bases).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('offers the option again once the blocker clears', () => {
|
||||
@@ -178,22 +202,22 @@ describe('WorktreeToggle checkbox', () => {
|
||||
const current = b.view.getByText('main')
|
||||
fireEvent.click(current)
|
||||
expect(b.request).not.toHaveBeenCalled()
|
||||
expect(b.branches).not.toHaveBeenCalled()
|
||||
expect(b.bases).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requests a worktree from the current branch and holds the checked state until the Host answers', async () => {
|
||||
const b = option(editable())
|
||||
const answer = deferred<boolean>()
|
||||
const answer = deferred<WorktreeRequestResult>()
|
||||
b.request.mockReturnValueOnce(answer.promise)
|
||||
|
||||
fireEvent.click(b.checkbox())
|
||||
expect(b.request).toHaveBeenCalledWith('main')
|
||||
expect(b.request).toHaveBeenCalledWith('refs/heads/main', null)
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
expect(b.checkbox().disabled).toBe(true)
|
||||
expect(b.base()?.textContent).toBe('From main')
|
||||
|
||||
b.publish(editable({ request: { from: 'main' } }))
|
||||
await act(async () => { answer.resolve(true) })
|
||||
b.publish(editable({ request: { from: 'main', name: null } }))
|
||||
await act(async () => { answer.resolve('accepted') })
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
expect(b.checkbox().disabled).toBe(false)
|
||||
expect(b.base()?.textContent).toBe('From main')
|
||||
@@ -203,14 +227,14 @@ describe('WorktreeToggle checkbox', () => {
|
||||
const b = option(ready({ worktree: worktree({ editable: true }) }, { branch: null }))
|
||||
expect(b.view.getByText(`${en['checkout.detached']} · 0a1b2c3`)).toBeTruthy()
|
||||
await act(async () => { fireEvent.click(b.checkbox()) })
|
||||
expect(b.request).toHaveBeenCalledWith(null)
|
||||
b.publish(ready({ worktree: worktree({ editable: true, request: { from: null } }) }, { branch: null }))
|
||||
expect(b.request).toHaveBeenCalledWith(null, null)
|
||||
b.publish(ready({ worktree: worktree({ editable: true, request: { from: null, name: null } }) }, { branch: null }))
|
||||
expect(b.base()?.textContent).toBe(en['worktree.baseHead'])
|
||||
})
|
||||
|
||||
it('returns to the Host state when the Host refuses the request', async () => {
|
||||
const b = option(editable())
|
||||
b.request.mockResolvedValueOnce(false)
|
||||
b.request.mockResolvedValueOnce('failed')
|
||||
await act(async () => { fireEvent.click(b.checkbox()) })
|
||||
expect(b.checkbox().checked).toBe(false)
|
||||
expect(b.checkbox().disabled).toBe(false)
|
||||
@@ -218,7 +242,7 @@ describe('WorktreeToggle checkbox', () => {
|
||||
})
|
||||
|
||||
it('withdraws an open request and shows the current branch until the Host answers', async () => {
|
||||
const b = option(editable({ request: { from: 'release' } }))
|
||||
const b = option(editable({ request: { from: 'release', name: null } }))
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
expect(b.base()?.textContent).toBe('From release')
|
||||
const answer = deferred<boolean>()
|
||||
@@ -238,93 +262,171 @@ describe('WorktreeToggle checkbox', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('WorktreeToggle base branch menu', () => {
|
||||
it('names the current branch for a request from HEAD', () => {
|
||||
const b = option(editable({ request: { from: null } }))
|
||||
expect(b.base()?.textContent).toBe('From main')
|
||||
|
||||
describe('WorktreeToggle base menu', () => {
|
||||
it('names the current branch for a request from HEAD and the short name of a requested branch', () => {
|
||||
expect(option(editable({ request: { from: null, name: null } })).base()?.textContent).toBe('From the current HEAD')
|
||||
cleanup()
|
||||
expect(option(editable({ request: { from: 'refs/remotes/upstream/master', name: null } })).base()?.textContent).toBe('From upstream/master')
|
||||
})
|
||||
|
||||
it('sits before the checkbox and opens below its anchor, aligned to the anchor\'s right edge', async () => {
|
||||
const b = option(editable({ request: { from: 'main' } }))
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: null } }))
|
||||
const anchor = b.base()
|
||||
if (anchor === null) throw new Error('no base branch anchor')
|
||||
expect(anchor.compareDocumentPosition(b.checkbox()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
const wrapper = anchor.parentElement
|
||||
if (wrapper === null) throw new Error('no menu wrapper')
|
||||
const menu = await openMenu(b)
|
||||
expect(anchor.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(menu.dataset.anchorSide).toBe('bottom')
|
||||
expect(menu.dataset.anchorAlign).toBe('end')
|
||||
expect(menu.style.positionAnchor).not.toBe('')
|
||||
expect(menu.style.positionAnchor).toBe(wrapper.style.anchorName)
|
||||
})
|
||||
|
||||
it('lists the local branches, marks the current and the chosen one, and requests another base', async () => {
|
||||
const b = option(editable({ request: { from: 'main' } }))
|
||||
const answer = deferred<ForgeBranches | undefined>()
|
||||
b.branches.mockReturnValueOnce(answer.promise)
|
||||
it('pins the current branch and remote defaults, then lists local branches and each remote with its repository', async () => {
|
||||
const b = option(editable({ request: { from: 'main', name: null } }))
|
||||
fireEvent.click(b.base()!)
|
||||
expect(b.branches).toHaveBeenCalledOnce()
|
||||
expect(b.base()?.disabled).toBe(true)
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
expect(screen.getByRole('status').textContent).toBe(en['diff.base.loading'])
|
||||
await settle()
|
||||
expect(b.bases).toHaveBeenCalledWith('', expect.any(AbortSignal))
|
||||
expect(b.rows()).toEqual([
|
||||
`main${en['worktree.currentBranch']}`, `upstream/master${en['worktree.remoteDefault']}`, 'release', 'feat/x', 'upstream/feat/y',
|
||||
'team/fork/idea', `${en['worktree.name.add']}${en['worktree.name.auto']}`,
|
||||
])
|
||||
expect(screen.getAllByRole('group').map(group => group.getAttribute('aria-label'))).toEqual([
|
||||
en['worktree.pinned'], en['diff.base.local'], 'Remote · upstream', 'Remote · team/fork',
|
||||
])
|
||||
expect(screen.getByRole('group', { name: 'Remote · upstream' }).textContent).toContain('acme/demo')
|
||||
// The short name that earlier panels recorded for a local branch selects that branch.
|
||||
expect(screen.getByRole('menuitem', { name: /^main/ }).getAttribute('aria-current')).toBe('page')
|
||||
|
||||
await act(async () => { answer.resolve(BRANCHES) })
|
||||
expect(b.base()?.disabled).toBe(false)
|
||||
expect(b.base()?.getAttribute('aria-expanded')).toBe('true')
|
||||
const menu = screen.getByRole('menu')
|
||||
expect(within(menu).getByText(en['worktree.baseMenu'])).toBeTruthy()
|
||||
const items = within(menu).getAllByRole('menuitem')
|
||||
expect(items.map(item => item.textContent)).toEqual([`main${en['worktree.currentBranch']}`, 'release', 'feat/x'])
|
||||
expect(items.map(item => item.matches(`.${menuCss.selected}`))).toEqual([true, false, false])
|
||||
|
||||
fireEvent.click(items[1]!)
|
||||
expect(b.request).toHaveBeenCalledWith('release')
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: 'team/fork/idea' }))
|
||||
expect(b.request).toHaveBeenCalledWith('refs/remotes/team/fork/idea', null)
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
})
|
||||
|
||||
it('closes without a request when the chosen base is selected again', async () => {
|
||||
const b = option(editable({ request: { from: 'release' } }))
|
||||
const menu = await openMenu(b)
|
||||
fireEvent.click(within(menu).getByRole('menuitem', { name: 'release' }))
|
||||
expect(b.request).not.toHaveBeenCalled()
|
||||
it('closes without a request when the chosen base is chosen again, from its anchor, and on Escape', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/release', name: 'fix/x' } }))
|
||||
await openMenu(b)
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: 'release' }))
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
})
|
||||
|
||||
it('closes from its anchor and on Escape', async () => {
|
||||
const b = option(editable({ request: { from: 'main' } }))
|
||||
await openMenu(b)
|
||||
fireEvent.click(b.base()!)
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
expect(b.branches).toHaveBeenCalledOnce()
|
||||
|
||||
await openMenu(b)
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
expect(b.request).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stays closed when the branches cannot be read', async () => {
|
||||
const b = option(editable({ request: { from: 'main' } }))
|
||||
b.branches.mockResolvedValueOnce(undefined)
|
||||
await act(async () => { fireEvent.click(b.base()!) })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
expect(b.base()?.disabled).toBe(false)
|
||||
expect(b.base()?.getAttribute('aria-expanded')).toBe('false')
|
||||
it('keeps the chosen name when the base changes', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/x' } }))
|
||||
await openMenu(b)
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: /^upstream\/master/ }))
|
||||
expect(b.request).toHaveBeenCalledWith('refs/remotes/upstream/master', 'fix/x')
|
||||
})
|
||||
})
|
||||
|
||||
describe('WorktreeToggle while the worktree is created', () => {
|
||||
it('freezes the checkbox and the base branch until the creation fails, which leaves both open to change', () => {
|
||||
const b = option(editable({ request: { from: 'main' }, creation: creation() }))
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
it('filters the listed rows at once, reads the search after a pause, and chooses the first match with Enter', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: null } }))
|
||||
b.bases.mockImplementation(async query => ok(query === '' ? BASES : { ...BASES, current: null, defaults: [], local: [] }))
|
||||
await openMenu(b)
|
||||
fireEvent.change(b.search(), { target: { value: 'IDEA' } })
|
||||
expect(b.rows()).toEqual(['team/fork/idea', `${en['worktree.name.add']}${en['worktree.name.auto']}`])
|
||||
await settle(200)
|
||||
expect(b.bases).toHaveBeenLastCalledWith('IDEA', expect.any(AbortSignal))
|
||||
fireEvent.keyDown(b.search(), { key: 'Enter' })
|
||||
expect(b.request).toHaveBeenCalledWith('refs/remotes/team/fork/idea', null)
|
||||
})
|
||||
|
||||
it('says when no branch matches, keeps Enter from choosing, and still offers to name the branch', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: null } }))
|
||||
await openMenu(b)
|
||||
fireEvent.change(b.search(), { target: { value: 'hotfix' } })
|
||||
expect(screen.getByText(en['diff.base.empty'])).toBeTruthy()
|
||||
fireEvent.keyDown(b.search(), { key: 'Enter' })
|
||||
expect(b.request).not.toHaveBeenCalled()
|
||||
expect(b.rows()).toEqual([`${en['worktree.name.add']}${en['worktree.name.auto']}`])
|
||||
})
|
||||
|
||||
it('reports a failed listing with a retry', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: null } }))
|
||||
b.bases.mockResolvedValueOnce({ ok: false, error: new RemoteError('forgePanel/not-a-checkout', 'gone', {}) })
|
||||
await openMenu(b)
|
||||
const status = screen.getByRole('status')
|
||||
expect(status.textContent).toBe(`${en['toast.branchesFailed']}${en.retry}`)
|
||||
fireEvent.click(within(status).getByRole('button', { name: en.retry }))
|
||||
await settle()
|
||||
expect(b.bases).toHaveBeenCalledTimes(2)
|
||||
expect(b.rows()).toHaveLength(7)
|
||||
})
|
||||
|
||||
it('stays fixed while the worktree is being created, and opens again once the attempt failed', () => {
|
||||
const b = option(editable({ request: { from: 'main', name: null }, creation: creation() }))
|
||||
expect(b.checkbox().disabled).toBe(true)
|
||||
expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(true)
|
||||
expect(b.base()?.disabled).toBe(true)
|
||||
|
||||
b.publish(editable({ request: { from: 'main' }, failure: failure() }))
|
||||
expect(b.checkbox().checked).toBe(true)
|
||||
b.publish(editable({ request: { from: 'main', name: null }, failure: failure() }))
|
||||
expect(b.checkbox().disabled).toBe(false)
|
||||
expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(false)
|
||||
expect(b.base()?.disabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('WorktreeToggle branch name', () => {
|
||||
/** Open the naming dialog from the menu's last row. */
|
||||
async function nameDialog(b: ReturnType<typeof option>): Promise<HTMLElement> {
|
||||
await openMenu(b)
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: /^(Name the new branch|New branch name)/ }))
|
||||
return screen.getByRole('dialog', { name: en['nameDialog.title'] })
|
||||
}
|
||||
|
||||
it('starts the name from the prefix of generated names and requests the worktree on the typed name', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/remotes/upstream/master', name: null }, namePrefix: 'agent/' }))
|
||||
const dialog = await nameDialog(b)
|
||||
const field = within(dialog).getByRole('textbox', { name: en['nameDialog.field'] })
|
||||
expect((field as HTMLInputElement).value).toBe('agent/')
|
||||
expect(within(dialog).getByText(en['nameDialog.prefixOnly'])).toBeTruthy()
|
||||
expect(within(dialog).getByRole('button', { name: en['nameDialog.confirm'] }).hasAttribute('disabled')).toBe(true)
|
||||
expect(within(dialog).queryByRole('button', { name: en['nameDialog.auto'] })).toBeNull()
|
||||
|
||||
fireEvent.change(field, { target: { value: 'agent/fix-login' } })
|
||||
expect(within(dialog).getByText(en['nameDialog.hint'].replace('{branch}', 'upstream/master'))).toBeTruthy()
|
||||
await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.confirm'] })) })
|
||||
expect(b.request).toHaveBeenCalledWith('refs/remotes/upstream/master', 'agent/fix-login')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows a chosen name before its base and offers generated names again', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/login' } }))
|
||||
const trigger = b.base()!
|
||||
expect(trigger.textContent).toBe('fix/login · From main')
|
||||
expect(trigger.getAttribute('aria-label')).toBe('New branch fix/login from main')
|
||||
const dialog = await nameDialog(b)
|
||||
expect(within(dialog).getByRole<HTMLInputElement>('textbox').value).toBe('fix/login')
|
||||
await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.auto'] })) })
|
||||
expect(b.request).toHaveBeenCalledWith('refs/heads/main', null)
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('names the current HEAD for a named request without a base', () => {
|
||||
const b = option(editable({ request: { from: null, name: 'fix/login' } }))
|
||||
expect(b.base()?.getAttribute('aria-label')).toBe('New branch fix/login from the current HEAD')
|
||||
})
|
||||
|
||||
it('keeps the dialog open with the reason when the Host refuses the name, and closes it on Cancel', async () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: null } }))
|
||||
const dialog = await nameDialog(b)
|
||||
const field = within(dialog).getByRole('textbox')
|
||||
fireEvent.change(field, { target: { value: 'taken' } })
|
||||
b.request.mockResolvedValueOnce('branch-exists')
|
||||
await act(async () => { fireEvent.keyDown(field, { key: 'Enter' }) })
|
||||
expect(within(dialog).getByRole('alert').textContent).toBe('A branch named taken already exists')
|
||||
fireEvent.change(field, { target: { value: 'taken-2' } })
|
||||
expect(within(dialog).queryByRole('alert')).toBeNull()
|
||||
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.cancel'] }))
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(b.request).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows a chosen name in Chinese copy', () => {
|
||||
const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/login' } }), makeTranslate(zh))
|
||||
expect(b.base()?.textContent).toBe('fix/login · 基于 main')
|
||||
})
|
||||
})
|
||||
@@ -123,9 +123,9 @@ describe('forgeWorktree projection', () => {
|
||||
const { session, state } = await folded()
|
||||
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
expect(state()?.request).toEqual({ from: null })
|
||||
expect(state()?.request).toEqual({ from: null, name: null })
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' })
|
||||
expect(state()?.request).toEqual({ from: 'main' })
|
||||
expect(state()?.request).toEqual({ from: 'main', name: null })
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' })
|
||||
const withdrawn = state()
|
||||
expect(withdrawn).toEqual(EMPTY)
|
||||
@@ -135,12 +135,24 @@ describe('forgeWorktree projection', () => {
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'feat' })
|
||||
startTurn(session, 1)
|
||||
const locked = state()
|
||||
expect(locked).toEqual({ ...EMPTY, request: { from: 'feat' }, locked: true })
|
||||
expect(locked).toEqual({ ...EMPTY, request: { from: 'feat', name: null }, locked: true })
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' })
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' })
|
||||
expect(state()).toBe(locked)
|
||||
})
|
||||
|
||||
it('keeps the branch name a request chooses, and none for a request that names no branch or an empty one', async () => {
|
||||
const { session, state } = await folded()
|
||||
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'refs/remotes/origin/main', name: 'fix/login' })
|
||||
expect(state()?.request).toEqual({ from: 'refs/remotes/origin/main', name: 'fix/login' })
|
||||
const named = state()
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null, name: '' })
|
||||
expect(state()).toBe(named)
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
expect(state()?.request).toEqual({ from: null, name: null })
|
||||
})
|
||||
|
||||
it('applies the first created worktree of an open request, after which requests, withdrawals, and creations change nothing', async () => {
|
||||
const { session, state } = await folded()
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' })
|
||||
@@ -151,7 +163,7 @@ describe('forgeWorktree projection', () => {
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null })
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' })
|
||||
|
||||
expect(created).toEqual({ ...EMPTY, request: { from: 'main' }, created: { ...WORKTREE, from: 'main' } })
|
||||
expect(created).toEqual({ ...EMPTY, request: { from: 'main', name: null }, created: { ...WORKTREE, from: 'main' } })
|
||||
expect(state()).toBe(created)
|
||||
})
|
||||
|
||||
@@ -164,8 +176,8 @@ describe('forgeWorktree projection', () => {
|
||||
const created = state()
|
||||
startStep(session, 1)
|
||||
|
||||
expect(created).toEqual({ ...EMPTY, request: { from: null }, created: WORKTREE, locked: true })
|
||||
expect(state()).toEqual({ ...EMPTY, request: { from: null }, created: WORKTREE, locked: true, stepped: true })
|
||||
expect(created).toEqual({ ...EMPTY, request: { from: null, name: null }, created: WORKTREE, locked: true })
|
||||
expect(state()).toEqual({ ...EMPTY, request: { from: null, name: null }, created: WORKTREE, locked: true, stepped: true })
|
||||
})
|
||||
|
||||
it('ignores a created worktree without an open request or after the first step starts', async () => {
|
||||
@@ -186,7 +198,7 @@ describe('forgeWorktree projection', () => {
|
||||
const stepped = state()
|
||||
appendPluginRecord(session, WORKTREE_RECORD, { action: 'created', worktree: WORKTREE })
|
||||
|
||||
expect(stepped).toEqual({ ...EMPTY, request: { from: null }, locked: true, stepped: true })
|
||||
expect(stepped).toEqual({ ...EMPTY, request: { from: null, name: null }, locked: true, stepped: true })
|
||||
expect(state()).toBe(stepped)
|
||||
})
|
||||
|
||||
@@ -221,7 +233,7 @@ describe('forgeWorktree projection', () => {
|
||||
session.append('step/end', { turn: 1, step: 1 })
|
||||
|
||||
expect(state()).toBe(requested)
|
||||
expect(requested).toEqual({ ...EMPTY, request: { from: 'main' } })
|
||||
expect(requested).toEqual({ ...EMPTY, request: { from: 'main', name: null } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -286,7 +298,7 @@ describe('creating a requested worktree', () => {
|
||||
const head = await git(repo, 'rev-parse', 'HEAD')
|
||||
request(opened, null)
|
||||
|
||||
const result = await opened.creations.create(opened.agent, null, signal, false)
|
||||
const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)
|
||||
|
||||
const branch = result.branch
|
||||
expect(branch).toMatch(/^dsh-[0-9a-f]{8}$/)
|
||||
@@ -308,9 +320,9 @@ describe('creating a requested worktree', () => {
|
||||
const opened = await creating(repo)
|
||||
request(opened, null)
|
||||
|
||||
const result = await opened.creations.create(opened.agent, null, signal, false)
|
||||
const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)
|
||||
|
||||
const running = { branch: result.branch, from: null, held: false }
|
||||
const running = { branch: result.branch, from: null, fetch: false, held: false }
|
||||
expect(opened.changes).toEqual([{ ...running, phase: 'prepare' }, { ...running, phase: 'prepare' }, { ...running, phase: 'checkout' }, null])
|
||||
expect(opened.recorded).toEqual([null, null, null, worktreeOf(opened)])
|
||||
expect(worktreeOf(opened)).not.toBeNull()
|
||||
@@ -325,7 +337,7 @@ describe('creating a requested worktree', () => {
|
||||
const opened = await creating(repo)
|
||||
request(opened, 'base')
|
||||
|
||||
await opened.creations.create(opened.agent, 'base', signal, false)
|
||||
await opened.creations.create(opened.agent, { from: 'base', name: null }, signal, false, false)
|
||||
|
||||
const created = worktreeOf(opened)
|
||||
expect(created).toMatchObject({ from: 'base', baseCommit: base })
|
||||
@@ -339,7 +351,7 @@ describe('creating a requested worktree', () => {
|
||||
const opened = await creating(repo, { prefix: 'agent/task-' })
|
||||
request(opened, null)
|
||||
|
||||
const result = await opened.creations.create(opened.agent, null, signal, false)
|
||||
const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)
|
||||
|
||||
expect(result.branch).toMatch(/^agent\/task-[0-9a-f]{8}$/)
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(join(repo, '.agents', 'worktrees', ...result.branch.split('/')))
|
||||
@@ -350,7 +362,7 @@ describe('creating a requested worktree', () => {
|
||||
const opened = await creating(repo)
|
||||
request(opened, 'later')
|
||||
|
||||
const attempt = opened.creations.create(opened.agent, 'later', signal, false)
|
||||
const attempt = opened.creations.create(opened.agent, { from: 'later', name: null }, signal, false, false)
|
||||
const branch = opened.changes[0]?.branch
|
||||
const cause: unknown = expect.objectContaining({ message: MISSING_BASE })
|
||||
|
||||
@@ -364,10 +376,10 @@ describe('creating a requested worktree', () => {
|
||||
cause,
|
||||
})
|
||||
expect(branch).toEqual(GENERATED_BRANCH)
|
||||
const running = { phase: 'prepare', branch, from: 'later', held: false }
|
||||
const running = { phase: 'prepare', branch, from: 'later', fetch: false, held: false }
|
||||
expect(opened.changes).toEqual([running, running, null])
|
||||
expect(opened.records).toEqual([{ action: 'request', from: 'later' }])
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later' }, cwd: repo })
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later', name: null }, cwd: repo })
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo)
|
||||
})
|
||||
|
||||
@@ -377,7 +389,7 @@ describe('creating a requested worktree', () => {
|
||||
request(opened, null)
|
||||
opened.sandbox.gate = argv => argv.includes('reset') ? Promise.reject(new Error('checkout refused')) : undefined
|
||||
|
||||
const attempt = opened.creations.create(opened.agent, null, signal, false)
|
||||
const attempt = opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)
|
||||
const branch = opened.changes[0]?.branch ?? ''
|
||||
|
||||
await expect(attempt).rejects.toMatchObject({
|
||||
@@ -392,13 +404,52 @@ describe('creating a requested worktree', () => {
|
||||
expect(await branches(repo)).toEqual([branch, 'main'])
|
||||
})
|
||||
|
||||
it('creates the branch a request names on every attempt', async () => {
|
||||
const repo = await project()
|
||||
const opened = await creating(repo)
|
||||
|
||||
const result = await opened.creations.create(opened.agent, { from: null, name: 'fix/login' }, signal, false, false)
|
||||
|
||||
expect(result.branch).toBe('fix/login')
|
||||
expect(opened.changes[0]).toMatchObject({ branch: 'fix/login', phase: 'prepare', fetch: false })
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(join(repo, '.agents', 'worktrees', 'fix', 'login'))
|
||||
})
|
||||
|
||||
it('fetches a remote base branch first, then starts from the fetched commit', async () => {
|
||||
const { path: parent, remove } = await scratch('dsh-forge-worktree-fetch-')
|
||||
cleanups.push(remove)
|
||||
const upstream = await repository(parent, 'upstream')
|
||||
const repo = join(parent, 'clone')
|
||||
await git(parent, 'clone', '--quiet', upstream, repo)
|
||||
const fetched = await commitAt(upstream, 'remote.txt', '2026-02-01T00:00:00Z')
|
||||
const opened = await creating(repo)
|
||||
|
||||
const result = await opened.creations.create(opened.agent, { from: 'refs/remotes/origin/main', name: null }, signal, false, true)
|
||||
|
||||
expect(result.baseCommit).toBe(fetched)
|
||||
expect(opened.changes.map(change => change?.phase ?? null)).toEqual(['fetch', 'fetch', 'prepare', 'checkout', null])
|
||||
expect(opened.changes[0]).toMatchObject({ from: 'refs/remotes/origin/main', fetch: true })
|
||||
await expect(access(join(result.path, 'remote.txt'))).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('says when the branch an attempt names already exists', async () => {
|
||||
const repo = await project()
|
||||
const opened = await creating(repo)
|
||||
|
||||
await expect(opened.creations.create(opened.agent, { from: null, name: 'main' }, signal, false, false))
|
||||
.rejects.toMatchObject({ name: 'CreationFailure', branch: 'main', phase: 'prepare', exists: true })
|
||||
opened.sandbox.failure = new Error('confinement denied')
|
||||
await expect(opened.creations.create(opened.agent, { from: null, name: 'other' }, signal, false, false))
|
||||
.rejects.toMatchObject({ name: 'CreationFailure', exists: false })
|
||||
})
|
||||
|
||||
it('reports a failure that is not an Error by its text', async () => {
|
||||
const repo = await project()
|
||||
const opened = await creating(repo)
|
||||
request(opened, null)
|
||||
opened.sandbox.failure = 'confinement denied'
|
||||
|
||||
await expect(opened.creations.create(opened.agent, null, signal, false))
|
||||
await expect(opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false))
|
||||
.rejects.toMatchObject({ phase: 'prepare', reason: 'confinement denied', cause: 'confinement denied' })
|
||||
expect(opened.changes.at(-1)).toBeNull()
|
||||
})
|
||||
@@ -503,7 +554,7 @@ describe('worktree creation at the first step proposal', () => {
|
||||
const repo = await project()
|
||||
const opened = await creating(repo)
|
||||
request(opened, null)
|
||||
const created = await opened.creations.create(opened.agent, null, signal, false)
|
||||
const created = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)
|
||||
const reports = opened.changes.length
|
||||
const proposed = prompt('go')
|
||||
|
||||
@@ -526,7 +577,7 @@ describe('worktree creation at the first step proposal', () => {
|
||||
await expect(proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')] }))
|
||||
.rejects.toMatchObject({ name: 'CreationFailure', branch: GENERATED_BRANCH, phase: 'prepare', reason: MISSING_BASE })
|
||||
const failed = opened.changes[0]?.branch
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later' }, locked: true, cwd: repo })
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later', name: null }, locked: true, cwd: repo })
|
||||
expect(opened.records).toEqual([{ action: 'request', from: 'later' }])
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo)
|
||||
|
||||
@@ -557,7 +608,7 @@ describe('worktree creation at the first step proposal', () => {
|
||||
expect(await settled).toBe(cause)
|
||||
expect(opened.changes.at(-1)).toBeNull()
|
||||
expect(opened.records).toEqual([{ action: 'request', from: null }])
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null }, cwd: repo })
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null, name: null }, cwd: repo })
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo)
|
||||
expect(await branches(repo)).toEqual(['main'])
|
||||
})
|
||||
@@ -569,13 +620,24 @@ describe('worktree creation at the first step proposal', () => {
|
||||
|
||||
await expect(proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')] }))
|
||||
.rejects.toThrow('No worktree service is mounted')
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null }, cwd: repo })
|
||||
expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null, name: null }, cwd: repo })
|
||||
expect(opened.changes).toEqual([])
|
||||
expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
it('names the fetch as the failed step of a remote-based attempt that fails before it reaches the worktree service', async () => {
|
||||
const opened = await creating(await project(), { worktrees: false })
|
||||
request(opened, 'refs/remotes/origin/main')
|
||||
opened.creations.holdCreation(opened.agent)
|
||||
await vi.waitFor(() => { expect(opened.creations.failureOf(opened.session)).not.toBeNull() })
|
||||
expect(opened.creations.failureOf(opened.session)).toEqual({
|
||||
branch: null, from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch', message: 'No worktree service is mounted', exists: false,
|
||||
})
|
||||
await opened.creations.dispose()
|
||||
})
|
||||
|
||||
it('does not admit a new message hold after worktree operations stop', async () => {
|
||||
const opened = await creating(await project())
|
||||
request(opened, null)
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
},
|
||||
"include": [
|
||||
"src/client",
|
||||
"src/branch-name.ts",
|
||||
"src/commit-range.ts",
|
||||
"src/css-modules.d.ts",
|
||||
"src/lens-version.ts",
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
},
|
||||
"files": [
|
||||
"src/index.ts",
|
||||
"src/branch-name.ts",
|
||||
"src/commit-range.ts",
|
||||
"src/diff.ts",
|
||||
"src/git.ts",
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-tool-worktree/use-this-package:
|
||||
en: a5d25494fde4f73d
|
||||
zh: e99a6f7a485d56f5
|
||||
en: b3652422c8c3b641
|
||||
zh: 00f358f343b92e91
|
||||
/deepseek-ai-dsh-experimental-tool-worktree/understand-the-implementation:
|
||||
en: 01d5f02b2b840cf0
|
||||
zh: db3c4f57ce636b34
|
||||
|
||||
@@ -34,7 +34,7 @@ For an explicit composition, mount this function plugin after the worktree runti
|
||||
- name: '@deepseek-ai/dsh-experimental-tool-worktree'
|
||||
```
|
||||
|
||||
Call `enter_worktree({ name?: string, from?: string })`. When the worktree pool of the checkout the Session is in holds a registered worktree of that name, the call moves the Session into it, leaves branches and files as they are, and returns its `path`, its `branch` when one is checked out, the `repositoryRoot` the Session came from, and `created: false`. Otherwise it creates a new branch and checkout from `from`, HEAD by default, enters it, and returns `path`, `branch`, the pinned `baseCommit`, `repositoryRoot`, and `created: true`. Omitting `name` always creates one with a generated name. `from` asks for a new worktree, so it fails with `WORKTREE_ALREADY_EXISTS` when the name is taken. To leave, call `exit_worktree()`: it returns the Session to the checkout it created or entered the worktree from and reports that worktree's record; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description.
|
||||
Call `enter_worktree({ name?: string, from?: string })`. The tool forwards only these two fields to the runtime, so it never fetches. When the worktree pool of the checkout the Session is in holds a registered worktree of that name, the call moves the Session into it, leaves branches and files as they are, and returns its `path`, its `branch` when one is checked out, the `repositoryRoot` the Session came from, and `created: false`. Otherwise it creates a new branch and checkout from `from`, HEAD by default, enters it, and returns `path`, `branch`, the pinned `baseCommit`, `repositoryRoot`, and `created: true`. Omitting `name` always creates one with a generated name. `from` asks for a new worktree, so it fails with `WORKTREE_ALREADY_EXISTS` when the name is taken. To leave, call `exit_worktree()`: it returns the Session to the checkout it created or entered the worktree from and reports that worktree's record; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ kind: "package-bundle"
|
||||
- name: '@deepseek-ai/dsh-experimental-tool-worktree'
|
||||
```
|
||||
|
||||
调用 `enter_worktree({ name?: string, from?: string })`。Session 所在检出的工作树池中已有同名的已登记工作树时,调用把 Session 移入其中,分支与文件保持原样,返回它的 `path`、检出了分支时的 `branch`、Session 进入前所在的 `repositoryRoot`,以及 `created: false`。否则从 `from`(默认 HEAD)创建新的分支与检出目录并进入,返回 `path`、`branch`、固定提交 `baseCommit`、`repositoryRoot`,以及 `created: true`。省略 `name` 时总是用生成的名称新建。`from` 表示要新建工作树,所以名称已被占用时以 `WORKTREE_ALREADY_EXISTS` 失败。离开时调用 `exit_worktree()`:它把 Session 送回创建或进入该工作树时所在的检出,并返回该工作树的记录;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。
|
||||
调用 `enter_worktree({ name?: string, from?: string })`。工具只把这两个字段转给运行时,因此从不执行 fetch。Session 所在检出的工作树池中已有同名的已登记工作树时,调用把 Session 移入其中,分支与文件保持原样,返回它的 `path`、检出了分支时的 `branch`、Session 进入前所在的 `repositoryRoot`,以及 `created: false`。否则从 `from`(默认 HEAD)创建新的分支与检出目录并进入,返回 `path`、`branch`、固定提交 `baseCommit`、`repositoryRoot`,以及 `created: true`。省略 `name` 时总是用生成的名称新建。`from` 表示要新建工作树,所以名称已被占用时以 `WORKTREE_ALREADY_EXISTS` 失败。离开时调用 `exit_worktree()`:它把 Session 送回创建或进入该工作树时所在的检出,并返回该工作树的记录;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -53,17 +53,19 @@ export function apply(ctx: Context): void {
|
||||
schema: ENTERED_SCHEMA,
|
||||
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
||||
},
|
||||
async execute(args, exec) {
|
||||
async execute({ name, from }, exec) {
|
||||
if (exec.agent === undefined) throw new ToolContextUnavailableError('enter_worktree requires a calling agent')
|
||||
// A start revision asks for a new worktree, as does a call without a name.
|
||||
if (args.name !== undefined && args.from === undefined) {
|
||||
if (name !== undefined && from === undefined) {
|
||||
try {
|
||||
return { ...await ctx.worktrees.enter(exec.agent, { name: args.name }, exec.signal), created: false }
|
||||
return { ...await ctx.worktrees.enter(exec.agent, { name }, exec.signal), created: false }
|
||||
} catch (error) {
|
||||
if (!(error instanceof WorktreeError && error.code === 'WORKTREE_NOT_FOUND')) throw error
|
||||
}
|
||||
}
|
||||
return { ...await ctx.worktrees.create(exec.agent, args, exec.signal), created: true }
|
||||
// The parameter object is open, so only the declared fields reach the runtime; it never fetches for this tool.
|
||||
const request = { ...name === undefined ? {} : { name }, ...from === undefined ? {} : { from } }
|
||||
return { ...await ctx.worktrees.create(exec.agent, request, exec.signal), created: true }
|
||||
},
|
||||
presentCall: args => ({ card: 'generic', title: 'enter_worktree', rawInput: args }),
|
||||
}))
|
||||
|
||||
@@ -115,6 +115,16 @@ describe('worktree tool through real Loader composition', () => {
|
||||
// Inside the new worktree the name selects its own empty pool, and the branch of a nested worktree already exists.
|
||||
const nested = await enter({ name: 'new-checkout' }, agent)
|
||||
expect(nested.isError && nested.error.info).toEqual({ name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS' })
|
||||
// A forwarded `fetch` would make the runtime refuse `main`, which is not a remote-tracking branch.
|
||||
const undeclared = await executeToolFixture(context, {
|
||||
name: 'enter_worktree', callId: brandString<ToolCallId>('undeclared'), arguments: { from: 'main', fetch: true }, agent,
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
expect(undeclared.isError).not.toBe(true)
|
||||
expect(undeclared.value).toMatchObject({ baseCommit, repositoryRoot: path, created: true })
|
||||
// Leaving the generated worktree returns the Session to `new-checkout`.
|
||||
expect((await exit(agent)).value).toMatchObject({ baseCommit, repositoryRoot: path })
|
||||
expect(context.workingDirectory.get(agent.session)).toBe(path)
|
||||
expect(context.tools.get('enter_worktree')!.presentCall!({ name: 'named' })).toEqual({
|
||||
card: 'generic', title: 'enter_worktree', rawInput: { name: 'named' },
|
||||
})
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-worktree/use-this-package:
|
||||
en: e2ecd292a52a7284
|
||||
zh: 1fe98990612ba2c0
|
||||
en: f753e7aaf507f783
|
||||
zh: 27e72c58f915da5c
|
||||
/deepseek-ai-dsh-experimental-worktree/understand-the-implementation:
|
||||
en: 6971a7ca9073bef1
|
||||
zh: b977c28a75c7f963
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 6826dfaadb24f3da
|
||||
zh: 2e2ee715247fc015
|
||||
/deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work:
|
||||
en: 5fd0cba55c3f5990
|
||||
zh: 633ce8bb3a94db9e
|
||||
en: d095a74827c8457d
|
||||
zh: 7ec986f6426543a6
|
||||
/deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note:
|
||||
en: ad12746a6cc96d8a
|
||||
zh: 66275f30a35c88e4
|
||||
@@ -32,7 +32,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, `
|
||||
- name: '@deepseek-ai/dsh-experimental-tool-worktree'
|
||||
```
|
||||
|
||||
`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw.
|
||||
`ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`. With `fetch: true`, `from` must be the full name of a remote-tracking branch, `refs/remotes/<remote>/<branch>`, of a configured remote, the longest remote name winning when names nest; creation first runs `git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance <remote> +refs/heads/<branch>:<from>`, so only that branch is fetched, then resolves the fetched commit. The fetch runs under the Session's sandbox policy and the command deadline, without prompts, and a failed fetch creates nothing; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `fetch` first when the request asks to fetch, `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw.
|
||||
|
||||
`ctx.worktrees.enter(agent, { name }, signal?)` moves the Session into an existing worktree in the pool of the checkout it works in, through `ctx.workingDirectory.set`. `name` is the directory relative to that pool, the name `create` gave the worktree. The directory must resolve inside the pool and be a registered worktree of the repository; otherwise the call rejects with `WORKTREE_NOT_FOUND` and the Session stays where it is. Entry runs no Git command that writes, and resolves to the checkout's `path`, its `branch` unless HEAD is detached, and the `repositoryRoot` the Session entered from.
|
||||
|
||||
@@ -94,7 +94,7 @@ This package contributes no prompt text. Its consumers own the appended tool res
|
||||
|
||||
- **Entry by pool name** — `enter` reaches only registered worktrees inside the configured pool of the checkout the Session works in. A worktree in another checkout's pool is entered from that checkout, and one outside every pool is not reachable.
|
||||
- **Retained artifacts** — leaving a worktree keeps its branch and files, and archive cleanup never deletes a branch. Setup failures can also retain partial artifacts, and a failed removal can leave a partial directory for the retained branch to be restored over.
|
||||
- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail.
|
||||
- **Local revisions unless asked** — creation fetches only the one remote branch a request asks for; it does not fetch other commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail.
|
||||
- **Filtered representations** — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation.
|
||||
- **Execution requirements** — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor `GIT_NO_LAZY_FETCH`, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The `git --no-lazy-fetch` option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes.
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ kind: "package-reference"
|
||||
- name: '@deepseek-ai/dsh-experimental-tool-worktree'
|
||||
```
|
||||
|
||||
`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。
|
||||
`ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`。`fetch: true` 时,`from` 必须是某个已配置远程的远程跟踪分支完整引用名 `refs/remotes/<remote>/<branch>`,远程名相互嵌套时取最长的;创建前先运行 `git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance <remote> +refs/heads/<branch>:<from>`,只获取这一个分支,再解析获取到的提交。获取在 Session 的沙箱策略与命令期限下运行,不会提示输入,获取失败时不创建任何东西;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在请求要求获取时先收到 `fetch`,在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。
|
||||
|
||||
`ctx.worktrees.enter(agent, { name }, signal?)` 通过 `ctx.workingDirectory.set` 把 Session 移入它所在检出的池中已有的工作树。`name` 是相对该池的目录,即 `create` 给工作树的名称。该目录必须解析到池内,并且是仓库已登记的工作树;否则调用以 `WORKTREE_NOT_FOUND` 拒绝,Session 留在原处。进入不执行任何会写入的 Git 命令,返回检出目录的 `path`、HEAD 未分离时的 `branch`,以及 Session 进入前所在的 `repositoryRoot`。
|
||||
|
||||
@@ -94,7 +94,7 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调
|
||||
|
||||
- **按池内名称进入**——`enter` 只能到达 Session 所在检出的配置池中已登记的工作树。位于另一个检出的池中的工作树要从那个检出进入,位于所有池之外的工作树无法到达。
|
||||
- **保留的产物**——离开工作树时保留其分支和文件,归档清理也从不删除分支。安装失败同样可能保留部分产物;删除失败可能留下部分目录,可在保留的分支上恢复覆盖。
|
||||
- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。
|
||||
- **默认仅限本地提交**——创建操作只获取请求指定的那一个远程分支,不会获取其他远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。
|
||||
- **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。
|
||||
- **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 与 Node。Git 必须识别 `GIT_NO_LAZY_FETCH`:Git 2.45 及 2.39.4、2.40.2、2.41.1、2.42.2、2.43.4、2.44.1 维护版本均支持;更早的版本会忽略该变量并继续执行而不报错,因此创建操作可能从 promisor 远程获取缺失的部分克隆对象。`git --no-lazy-fetch` 选项会拒绝这些版本,但它仅在 Git 2.45 及以后存在,也会拒绝上述已修补的维护版本。现有沙箱必须允许写入检出目录与共享 Git 元数据。
|
||||
|
||||
|
||||
@@ -70,8 +70,13 @@ type ResolvedConfig = Required<Config> & ProcessConfig
|
||||
interface WorktreeSpec {
|
||||
branch: string
|
||||
revision: string
|
||||
/** Whether the remote-tracking branch `revision` is fetched before it is resolved. */
|
||||
fetch: boolean
|
||||
}
|
||||
|
||||
/** Prefix of the full names of remote-tracking branches. */
|
||||
const REMOTE_REFS = 'refs/remotes/'
|
||||
|
||||
/** Runs one confined Git command; output with an exit code outside `allowedExitCodes` throws. */
|
||||
type GitRun = (directory: string, args: string[], allowedExitCodes?: number[], env?: NodeJS.ProcessEnv) => ReturnType<typeof runCommand>
|
||||
|
||||
@@ -154,19 +159,21 @@ export class WorktreeService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it.
|
||||
* Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch
|
||||
* first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit.
|
||||
* Existing branches or checkout paths fail. Uncommitted files stay in the source checkout.
|
||||
* Checkout disables configured clean, smudge, and process filters without changing Git config.
|
||||
* Repository-local replacement refs still apply; baseCommit reports the resolved object name.
|
||||
* The new checkout becomes current only after Git setup succeeds. Failures may retain newly
|
||||
* allocated Git/filesystem artifacts; no branch or checkout is removed automatically.
|
||||
* @param agent - caller whose current directory selects the source repository and file policy.
|
||||
* @param request - optional new name and local revision; defaults are generated name and HEAD.
|
||||
* @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch.
|
||||
* @param signal - cancellation of lookup, creation, and working-directory publication.
|
||||
* @param onPhase - receives each stage before it begins; it must not throw.
|
||||
* @returns canonical checkout path, branch name, pinned commit, and source repository root.
|
||||
* @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out
|
||||
* command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
* @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a
|
||||
* configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the
|
||||
* fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
*/
|
||||
async create(
|
||||
agent: Agent,
|
||||
@@ -196,7 +203,7 @@ export class WorktreeService extends Service {
|
||||
* @param agent - caller whose sandbox policy confines the commands.
|
||||
* @param request - recorded directory, branch, base commit, and source repository root.
|
||||
* @param signal - cancellation of the restoration.
|
||||
* @param onPhase - receives each stage before it begins; it must not throw.
|
||||
* @param onPhase - receives each stage before it begins, never `fetch`; it must not throw.
|
||||
* @returns the directory and whether the branch was created again.
|
||||
* @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized,
|
||||
* or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.
|
||||
@@ -205,7 +212,7 @@ export class WorktreeService extends Service {
|
||||
agent: Agent,
|
||||
request: RestoreWorktreeRequest,
|
||||
signal?: AbortSignal,
|
||||
onPhase?: (phase: CreateWorktreePhase) => void,
|
||||
onPhase?: (phase: Exclude<CreateWorktreePhase, 'fetch'>) => void,
|
||||
): Promise<RestoredWorktree> {
|
||||
const operationSignal = signal === undefined ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal])
|
||||
operationSignal.throwIfAborted()
|
||||
@@ -314,16 +321,20 @@ export class WorktreeService extends Service {
|
||||
if (!relativePath(branch) || branch.startsWith('-')) throw new WorktreeError('worktree name must be a relative Git branch name', 'WORKTREE_INVALID_ARGUMENT')
|
||||
const revision = request.from ?? 'HEAD'
|
||||
if (revision.length === 0) throw new WorktreeError('worktree from must name a local commit, branch, or tag', 'WORKTREE_INVALID_ARGUMENT')
|
||||
return { branch, revision }
|
||||
const fetch = request.fetch === true
|
||||
if (fetch && !revision.startsWith(REMOTE_REFS)) {
|
||||
throw new WorktreeError('worktree fetch needs from to name a remote-tracking branch under refs/remotes/', 'WORKTREE_INVALID_ARGUMENT')
|
||||
}
|
||||
return { branch, revision, fetch }
|
||||
}
|
||||
|
||||
private async createCheckout(
|
||||
agent: Agent,
|
||||
{ branch, revision }: WorktreeSpec,
|
||||
{ branch, revision, fetch }: WorktreeSpec,
|
||||
signal: AbortSignal,
|
||||
onPhase: ((phase: CreateWorktreePhase) => void) | undefined,
|
||||
): Promise<CreatedWorktree> {
|
||||
onPhase?.('prepare')
|
||||
onPhase?.(fetch ? 'fetch' : 'prepare')
|
||||
const cwd = await this.ctx.workingDirectory.ensure(agent, signal)
|
||||
const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session })
|
||||
const run = this.gitRunner(policy, signal)
|
||||
@@ -331,6 +342,10 @@ export class WorktreeService extends Service {
|
||||
const rootOutput = await run(cwd, ['rev-parse', '--show-toplevel'])
|
||||
const rootTarget = await this.ctx.fs.resolve(rootOutput.stdout.replace(/\r?\n$/, ''), { cwd, signal })
|
||||
const repositoryRoot = this.ctx.fs.processPath(rootTarget)
|
||||
if (fetch) {
|
||||
await fetchRemoteBranch(run, repositoryRoot, revision)
|
||||
onPhase?.('prepare')
|
||||
}
|
||||
const base = await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${revision}^{commit}`])
|
||||
const baseCommit = base.stdout.trim()
|
||||
const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1])
|
||||
@@ -383,7 +398,7 @@ export class WorktreeService extends Service {
|
||||
agent: Agent,
|
||||
{ path, branch, baseCommit, repositoryRoot }: RestoreWorktreeRequest,
|
||||
signal: AbortSignal,
|
||||
onPhase: ((phase: CreateWorktreePhase) => void) | undefined,
|
||||
onPhase: ((phase: Exclude<CreateWorktreePhase, 'fetch'>) => void) | undefined,
|
||||
): Promise<RestoredWorktree> {
|
||||
onPhase?.('prepare')
|
||||
const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session })
|
||||
@@ -464,6 +479,32 @@ async function assertBranchName(run: GitRun, directory: string, branch: string,
|
||||
if (checked.exitCode !== 0) throw new WorktreeError(`${field} must be a valid Git branch name`, 'WORKTREE_INVALID_ARGUMENT')
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch one remote branch into its remote-tracking branch, without tags, submodules, `FETCH_HEAD`, or automatic
|
||||
* maintenance.
|
||||
* @param run - confined Git runner.
|
||||
* @param repositoryRoot - root of the source checkout.
|
||||
* @param ref - remote-tracking branch `refs/remotes/<remote>/<branch>`.
|
||||
* @throws {WorktreeError} `WORKTREE_INVALID_ARGUMENT` when no configured remote owns `ref`; the command's failure when
|
||||
* listing the remotes or fetching fails.
|
||||
*/
|
||||
async function fetchRemoteBranch(run: GitRun, repositoryRoot: string, ref: string): Promise<void> {
|
||||
const rest = ref.slice(REMOTE_REFS.length)
|
||||
const listed = await run(repositoryRoot, ['remote'])
|
||||
// A remote name may contain slashes, so the longest configured name that owns the ref wins.
|
||||
const [remote] = listed.stdout.split(/\r?\n/)
|
||||
.filter(name => name.length > 0 && rest.startsWith(`${name}/`))
|
||||
.sort((left, right) => right.length - left.length)
|
||||
const branch = remote === undefined ? '' : rest.slice(remote.length + 1)
|
||||
if (remote === undefined || !relativePath(branch)) {
|
||||
throw new WorktreeError(`worktree from is not a remote-tracking branch of a configured remote: ${ref}`, 'WORKTREE_INVALID_ARGUMENT')
|
||||
}
|
||||
await run(repositoryRoot, [
|
||||
'fetch', '--quiet', '--no-tags', '--no-recurse-submodules', '--no-write-fetch-head', '--no-auto-maintenance',
|
||||
'--end-of-options', remote, `+refs/heads/${branch}:${ref}`,
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* Add retained-artifact context to a failure without changing its routable identity:
|
||||
* a `HarnessError` keeps its `name` and `code`, and caller cancellation stays an `AbortError`.
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
* for restoring a removed one.
|
||||
*/
|
||||
|
||||
/** A new checkout from a locally available Git commit, branch, or tag. */
|
||||
/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */
|
||||
export interface CreateWorktreeRequest {
|
||||
/** New branch name, also used as the relative checkout directory; omission generates a name. */
|
||||
name?: string
|
||||
/** Local revision to resolve before creation; omission selects HEAD. */
|
||||
from?: string
|
||||
/**
|
||||
* Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking
|
||||
* branch, `refs/remotes/<remote>/<branch>`, of a configured remote; only that branch is fetched, without tags.
|
||||
*/
|
||||
fetch?: boolean
|
||||
}
|
||||
|
||||
/** Committed Git baseline and the calling Session's resulting working directory. */
|
||||
@@ -40,12 +45,13 @@ export interface EnteredWorktree {
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage of one creation or restoration, reported before it begins: `prepare`
|
||||
* Stage of one creation or restoration, reported before it begins: `fetch`
|
||||
* fetches the remote base branch of a creation that asks for it; `prepare`
|
||||
* validates the request, allocates the checkout directory, and creates the
|
||||
* branch, which a restoration creates again only when it is gone; `checkout`
|
||||
* writes the files and, for a creation, enters the checkout.
|
||||
*/
|
||||
export type CreateWorktreePhase = 'prepare' | 'checkout'
|
||||
export type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout'
|
||||
|
||||
/** A removed checkout to check out again at its recorded directory. */
|
||||
export interface RestoreWorktreeRequest {
|
||||
|
||||
@@ -578,6 +578,93 @@ describe('creating and entering retained worktrees', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetching the remote base branch first', () => {
|
||||
/** A clone of a new repository, which then gains a commit, a tag, and a branch that the clone has not fetched. */
|
||||
async function behindClone(origin = 'origin'): Promise<{ upstream: string; clone: string; fetched: string }> {
|
||||
const upstream = await repo()
|
||||
const clone = join(upstream, 'clone')
|
||||
await git(upstream, 'clone', '--origin', origin, pathToFileURL(upstream).href, clone)
|
||||
// As `repository` does: a runner's global newline conversion would otherwise rewrite the files a worktree checks out.
|
||||
await git(clone, 'config', 'core.autocrlf', 'false')
|
||||
await writeFile(join(upstream, 'tracked.txt'), 'remote\n')
|
||||
await git(upstream, 'commit', '-am', 'remote')
|
||||
await git(upstream, 'tag', 'v1')
|
||||
await git(upstream, 'branch', 'other')
|
||||
return { upstream, clone, fetched: await git(upstream, 'rev-parse', 'HEAD') }
|
||||
}
|
||||
|
||||
it('fetches only the chosen branch, without tags, then pins and checks out the fetched commit without an upstream', async () => {
|
||||
const { clone, fetched } = await behindClone()
|
||||
ctx = await harness(clone)
|
||||
const agent = testAgent(ctx, clone)
|
||||
const phases: string[] = []
|
||||
|
||||
const result = await ctx.worktrees.create(agent, { name: 'fresh', from: 'refs/remotes/origin/main', fetch: true }, undefined, (phase) => {
|
||||
phases.push(phase)
|
||||
})
|
||||
|
||||
expect(phases).toEqual(['fetch', 'prepare', 'checkout'])
|
||||
expect(result.baseCommit).toBe(fetched)
|
||||
expect(await git(clone, 'rev-parse', 'refs/remotes/origin/main')).toBe(fetched)
|
||||
expect(await contents(join(result.path, 'tracked.txt'))).toBe('remote\n')
|
||||
expect(await git(clone, 'tag', '--list')).toBe('')
|
||||
expect(await git(clone, 'for-each-ref', '--format=%(refname)', 'refs/remotes/origin/other')).toBe('')
|
||||
expect(existsSync(join(clone, '.git', 'FETCH_HEAD'))).toBe(false)
|
||||
await expect(git(clone, 'config', '--get', 'branch.fresh.merge')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('fetches from the longest configured remote name that owns the branch', async () => {
|
||||
const { upstream, clone, fetched } = await behindClone('team/fork')
|
||||
// Newer `git remote add` refuses a name nested with another remote's, but configuration written earlier or by hand
|
||||
// can hold both.
|
||||
await git(clone, 'config', 'remote.team.url', join(upstream, 'missing.git'))
|
||||
await git(clone, 'config', 'remote.team.fetch', '+refs/heads/*:refs/remotes/team/*')
|
||||
ctx = await harness(clone)
|
||||
const agent = testAgent(ctx, clone)
|
||||
|
||||
const result = await ctx.worktrees.create(agent, { name: 'forked', from: 'refs/remotes/team/fork/main', fetch: true })
|
||||
|
||||
expect(result.baseCommit).toBe(fetched)
|
||||
expect(await git(clone, 'rev-parse', 'refs/remotes/team/fork/main')).toBe(fetched)
|
||||
})
|
||||
|
||||
it('refuses a base that is not a remote-tracking branch of a configured remote', async () => {
|
||||
const { clone } = await behindClone()
|
||||
ctx = await harness(clone)
|
||||
const agent = testAgent(ctx, clone)
|
||||
const phases: string[] = []
|
||||
const record = (phase: string): void => { phases.push(phase) }
|
||||
|
||||
await expect(ctx.worktrees.create(agent, { name: 'local', from: 'main', fetch: true }, undefined, record))
|
||||
.rejects.toMatchObject({ code: 'WORKTREE_INVALID_ARGUMENT' })
|
||||
expect(phases).toEqual([])
|
||||
for (const from of ['refs/remotes/gone/main', 'refs/remotes/origin/']) {
|
||||
await expect(ctx.worktrees.create(agent, { name: 'stray', from, fetch: true }, undefined, record))
|
||||
.rejects.toMatchObject({ code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining(from) as string })
|
||||
}
|
||||
expect(phases).toEqual(['fetch', 'fetch'])
|
||||
expect(ctx.workingDirectory.get(agent.session)).toBe(clone)
|
||||
expect(await git(clone, 'branch', '--list', 'stray')).toBe('')
|
||||
})
|
||||
|
||||
it('reports a failed fetch without creating a branch, a checkout, or the pool', async () => {
|
||||
const { upstream, clone } = await behindClone()
|
||||
await git(clone, 'remote', 'set-url', 'origin', join(upstream, 'missing.git'))
|
||||
ctx = await harness(clone)
|
||||
const agent = testAgent(ctx, clone)
|
||||
const phases: string[] = []
|
||||
|
||||
await expect(ctx.worktrees.create(agent, { name: 'offline', from: 'refs/remotes/origin/main', fetch: true }, undefined, (phase) => {
|
||||
phases.push(phase)
|
||||
})).rejects.toMatchObject({ code: 'WORKTREE_COMMAND_FAILED' })
|
||||
|
||||
expect(phases).toEqual(['fetch'])
|
||||
expect(await git(clone, 'branch', '--list', 'offline')).toBe('')
|
||||
expect(existsSync(join(clone, '.agents'))).toBe(false)
|
||||
expect(ctx.workingDirectory.get(agent.session)).toBe(clone)
|
||||
})
|
||||
})
|
||||
|
||||
describe('restoring removed worktrees', () => {
|
||||
/** The checkout directories Git registers for `root`, in Git's notation. */
|
||||
async function registered(root: string): Promise<string[]> {
|
||||
|
||||
@@ -1491,11 +1491,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
returns: 'the cleanup state, or null without a worktree service, an attempt, or a current revision.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote async branches(session: Session, signal: AbortSignal): Promise<ForgeBranches>',
|
||||
description: 'List the local branches that can start a worktree of the Session\'s current checkout.',
|
||||
parameters: [{ name: 'session', description: 'Session whose current directory is listed.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the checked-out branch and at most `maxBranches` local branches, the checked-out one first.',
|
||||
throws: ['when the current directory is not inside a checkout or Git fails.'],
|
||||
signature: '@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases>',
|
||||
description: 'List the branches that can start a worktree of the Session\'s current checkout: the checked-out branch, each remote\'s default branch, other local branches, and each remote\'s other remote-tracking branches, remotes in the order the panel recognizes code hosts.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'query', description: 'text the branch names must contain, ignoring case; empty for every branch.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>',
|
||||
@@ -1661,10 +1661,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host\'s reason when the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not confirm whether it started the update.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise<void>',
|
||||
description: 'Ask for a new worktree before the Session\'s first turn, replacing an open request and forgetting a failed attempt. While the next message waits in the inbox, or else at the first step proposal, the panel creates a branch from `from`, or from HEAD of the current checkout when it is null, and enters its checkout. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.',
|
||||
parameters: [{ name: 'session', description: 'Session without a started turn.' }, { name: 'from', description: 'local base branch, or null for HEAD.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
throws: ['`forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` without a worktree service; `forgePanel/session-started` after a turn started or the worktree was created; `forgePanel/session-busy` while the worktree is being created.'],
|
||||
signature: '@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise<void>',
|
||||
description: 'Ask for a new worktree before the Session\'s first turn, replacing an open request and forgetting a failed attempt. While the next message waits in the inbox, or else at the first step proposal, the panel creates the branch `name`, or a generated branch per attempt when it is null, from `from`, or from HEAD of the current checkout when it is null, and enters its checkout; a remote-tracking `from` is fetched first. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.',
|
||||
parameters: [{ name: 'session', description: 'Session without a started turn.' }, { name: 'from', description: 'full name of a local or remote-tracking base branch, or null for HEAD.' }, { name: 'name', description: 'new branch name, or null to generate one per attempt.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
throws: ['`forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` without a worktree service; `forgePanel/session-started` after a turn started or the worktree was created; `forgePanel/session-busy` while the worktree is being created.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async cancelWorktree(session: Session, signal: AbortSignal): Promise<void>',
|
||||
@@ -1678,9 +1678,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
parameters: [{ name: 'session', description: 'Session whose creation stops.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise<void>',
|
||||
description: 'Make another attempt, with a new branch name, at the worktree a message of the Session waits for after a failed or stopped attempt.',
|
||||
parameters: [{ name: 'session', description: 'Session whose message waits.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
signature: '@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise<void>',
|
||||
description: 'Make another attempt, on the requested branch name or a new generated one, at the worktree a message of the Session waits for after a failed or stopped attempt.',
|
||||
parameters: [{ name: 'session', description: 'Session whose message waits.' }, { name: 'fetch', description: 'false skips fetching a remote-tracking base branch for this attempt, which then starts from the commit last fetched.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
throws: ['`forgePanel/not-waiting` when no message waits or an attempt is running.'],
|
||||
},
|
||||
{
|
||||
@@ -5090,15 +5090,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
methods: [
|
||||
{
|
||||
signature: 'async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<CreatedWorktree>',
|
||||
description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.',
|
||||
parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name and local revision; defaults are generated name and HEAD.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }],
|
||||
description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.',
|
||||
parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }],
|
||||
returns: 'canonical checkout path, branch name, pinned commit, and source repository root.',
|
||||
throws: ['{WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'],
|
||||
throws: ['{WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'],
|
||||
},
|
||||
{
|
||||
signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise<RestoredWorktree>',
|
||||
signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude<CreateWorktreePhase, \'fetch\'>) => void, ): Promise<RestoredWorktree>',
|
||||
description: 'Check out a removed worktree again at its recorded directory: its branch when the branch still exists, otherwise a new branch of the same name at `baseCommit`. Only the missing target\'s unlocked registration is removed, and an existing directory fails. Changes that were never committed are not recovered. Checkout disables configured clean, smudge, and process filters, as creation does. The calling Session\'s working directory does not change. Failures may retain newly allocated Git/filesystem artifacts.',
|
||||
parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }],
|
||||
parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins, never `fetch`; it must not throw.' }],
|
||||
returns: 'the directory and whether the branch was created again.',
|
||||
throws: ['{WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'],
|
||||
},
|
||||
@@ -6754,11 +6754,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'CreateWorktreePhase',
|
||||
declaration: 'export type CreateWorktreePhase = \'prepare\' | \'checkout\';',
|
||||
declaration: 'export type CreateWorktreePhase = \'fetch\' | \'prepare\' | \'checkout\';',
|
||||
},
|
||||
{
|
||||
name: 'CreateWorktreeRequest',
|
||||
declaration: 'export interface CreateWorktreeRequest {\n name?: string;\n from?: string;\n}',
|
||||
declaration: 'export interface CreateWorktreeRequest {\n name?: string;\n from?: string;\n fetch?: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'CredentialInfo',
|
||||
@@ -7056,10 +7056,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ForgeBaseBranches',
|
||||
declaration: 'export interface ForgeBaseBranches {\n readonly automatic: ForgeAutomaticBase | null;\n readonly remote: readonly ForgeBaseBranch[];\n readonly local: readonly ForgeBaseBranch[];\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeBranches',
|
||||
declaration: 'export interface ForgeBranches {\n readonly current: string | null;\n readonly branches: readonly string[];\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeChangedFile',
|
||||
declaration: 'export interface ForgeChangedFile {\n readonly path: string;\n readonly additions: number;\n readonly deletions: number;\n readonly binary: boolean;\n}',
|
||||
@@ -7226,7 +7222,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ForgePanelWorktree',
|
||||
declaration: 'export interface ForgePanelWorktree {\n readonly editable: boolean;\n readonly blocker: ForgeWorktreeBlocker | null;\n readonly request: ForgeWorktreeRequest | null;\n readonly created: ForgeSessionWorktree | null;\n readonly creation: ForgeWorktreeCreation | null;\n readonly failure: ForgeWorktreeFailure | null;\n readonly missing: ForgeMissingWorktree | null;\n readonly restoration: ForgeWorktreeRestoration | null;\n readonly waiting: ForgeWorktreeWaiting | null;\n}',
|
||||
declaration: 'export interface ForgePanelWorktree {\n readonly editable: boolean;\n readonly blocker: ForgeWorktreeBlocker | null;\n readonly namePrefix: string;\n readonly request: ForgeWorktreeRequest | null;\n readonly created: ForgeSessionWorktree | null;\n readonly creation: ForgeWorktreeCreation | null;\n readonly failure: ForgeWorktreeFailure | null;\n readonly missing: ForgeMissingWorktree | null;\n readonly restoration: ForgeWorktreeRestoration | null;\n readonly waiting: ForgeWorktreeWaiting | null;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgePendingReview',
|
||||
@@ -7244,6 +7240,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ForgeRegisteredLens',
|
||||
declaration: 'export interface ForgeRegisteredLens {\n readonly id: string;\n readonly version: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeRemoteBranches',
|
||||
declaration: 'export interface ForgeRemoteBranches {\n readonly name: string;\n readonly repository: string | null;\n readonly branches: readonly ForgeBaseBranch[];\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeRemoteDefault',
|
||||
declaration: 'export interface ForgeRemoteDefault extends ForgeBaseBranch {\n readonly remote: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeRepository',
|
||||
declaration: 'export interface ForgeRepository {\n readonly forge: string;\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}',
|
||||
@@ -7320,21 +7324,25 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ForgeViewedState',
|
||||
declaration: 'export type ForgeViewedState = \'viewed\' | \'unviewed\' | \'dismissed\';',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeBases',
|
||||
declaration: 'export interface ForgeWorktreeBases {\n readonly current: ForgeBaseBranch | null;\n readonly defaults: readonly ForgeRemoteDefault[];\n readonly local: readonly ForgeBaseBranch[];\n readonly remotes: readonly ForgeRemoteBranches[];\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeBlocker',
|
||||
declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeCreation',
|
||||
declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly held: boolean;\n}',
|
||||
declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'fetch\' | \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly fetch: boolean;\n readonly held: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeFailure',
|
||||
declaration: 'export interface ForgeWorktreeFailure {\n readonly branch: string | null;\n readonly from: string | null;\n readonly phase: \'prepare\' | \'checkout\';\n readonly message: string;\n}',
|
||||
declaration: 'export interface ForgeWorktreeFailure {\n readonly branch: string | null;\n readonly from: string | null;\n readonly fetch: boolean;\n readonly phase: \'fetch\' | \'prepare\' | \'checkout\';\n readonly message: string;\n readonly exists: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeRequest',
|
||||
declaration: 'export interface ForgeWorktreeRequest {\n readonly from: string | null;\n}',
|
||||
declaration: 'export interface ForgeWorktreeRequest {\n readonly from: string | null;\n readonly name: string | null;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeWorktreeRestoration',
|
||||
|
||||
@@ -181,7 +181,7 @@ describe('PluginInventoryGateway', () => {
|
||||
name: 'cordis:not-installed',
|
||||
disabled: true,
|
||||
})
|
||||
await ctx.loader.create({ name: 'cordis:active', group: true })
|
||||
await ctx.loader.create({ name: 'cordis:active', group: true, config: [] })
|
||||
|
||||
const snapshot = await inventory.list()
|
||||
// No agent-preset roster is composed, so the snapshot carries no presets.
|
||||
|
||||
@@ -56,7 +56,7 @@ export function bundleRoster(
|
||||
const layers = bundles.map(name => readLayer(name, anchor))
|
||||
const entries = applyEntryPatches([], layers.flatMap(layer => layer.patches), (message: string, ...args: unknown[]) => {
|
||||
throw new Error(`client-test-runtime: bundle patch ${describe(message, args)}`)
|
||||
})
|
||||
}).data
|
||||
const anchors = layers.map(layer => layer.manifestPath)
|
||||
const rows: ClientRosterRow[] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
Generated
+3
-3
@@ -20299,9 +20299,9 @@ importers:
|
||||
'@deepseek-ai/cosmokit':
|
||||
specifier: link:../cosmokit
|
||||
version: link:../cosmokit
|
||||
js-yaml:
|
||||
specifier: ^4.1.0
|
||||
version: 4.3.2
|
||||
yaml:
|
||||
specifier: ^2.9.0
|
||||
version: 2.9.0
|
||||
|
||||
vendor/loader:
|
||||
dependencies:
|
||||
|
||||
@@ -99,7 +99,7 @@ describe('Loader tree mutation reports', () => {
|
||||
describe('Include patch data ownership', () => {
|
||||
it('detaches file entries even with no patches', () => {
|
||||
const data: EntryOptions[] = [{ id: 'x', name: 'example', config: { value: 1 } }]
|
||||
const result = applyEntryPatches(data, undefined, vi.fn())
|
||||
const result = applyEntryPatches(data, undefined, vi.fn()).data
|
||||
result[0]!.disabled = true
|
||||
;(result[0]!.config as { value: number }).value = 2
|
||||
expect(data).toEqual([{ id: 'x', name: 'example', config: { value: 1 } }])
|
||||
@@ -109,7 +109,7 @@ describe('Include patch data ownership', () => {
|
||||
const insert: EntryOptions[] = [{ id: 'g', name: 'group', group: true,
|
||||
config: [{ id: 'x', name: 'example', config: { value: 1 } }] }]
|
||||
const warn = vi.fn()
|
||||
const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn)
|
||||
const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn).data
|
||||
const children = result[0]!.config as Array<{ disabled?: boolean; config: { value: number } }>
|
||||
expect(children[0]!.disabled).toBe(true)
|
||||
children[0]!.config.value = 2
|
||||
|
||||
@@ -10,11 +10,15 @@ describe('Include YAML dialect', () => {
|
||||
expect(stringifyEntryYaml(parsed)).toBe(source)
|
||||
})
|
||||
|
||||
it('reads binary integers as numbers and dates as strings', () => {
|
||||
expect(parseEntryYaml('- 0b101\n- 2001-01-01\n- ~\n')).toEqual([5, '2001-01-01', null])
|
||||
it('reads scalars under the YAML 1.2 core schema', () => {
|
||||
expect(parseEntryYaml('- 0b101\n- 0o17\n- 0x1F\n- yes\n- 2001-01-01\n- ~\n')).toEqual(['0b101', 15, 31, 'yes', '2001-01-01', null])
|
||||
expect(parseEntryYaml('')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects unknown tags', () => {
|
||||
expect(() => parseEntryYaml('- !!binary aGVsbG8=\n- !custom value\n')).toThrow()
|
||||
})
|
||||
|
||||
it('writes repeated references in full', () => {
|
||||
const shared = { value: 1 }
|
||||
expect(stringifyEntryYaml([{ config: shared }, { config: shared }])).toBe('- config:\n value: 1\n- config:\n value: 1\n')
|
||||
@@ -35,5 +39,13 @@ describe('Include YAML dialect', () => {
|
||||
}
|
||||
expect(entryYamlErrorPosition(error)).toEqual({ line: 3, column: 1 })
|
||||
expect(entryYamlErrorPosition(new Error('other'))).toBeUndefined()
|
||||
let alias: unknown
|
||||
try {
|
||||
parseEntryYaml('- id: a\n config: *missing\n')
|
||||
} catch (caught) {
|
||||
alias = caught
|
||||
}
|
||||
expect(entryYamlErrorPosition(alias)).toEqual({ line: 2, column: 11 })
|
||||
expect(() => parseEntryYaml('- id: a\n config: *later\n- id: b\n config: &later {}\n')).toThrow('Alias *later must follow its anchor')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
/** Loader rc.9 and Include 1.2 entry validation, located config errors and module lookup failures. */
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { Context, FiberState } from '@deepseek-ai/cordis'
|
||||
import Loader, { EntryValidationError, Group, ModuleNotFoundError, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
|
||||
import Include, { ConfigFileError } from '@deepseek-ai/cordis-plugin-include'
|
||||
import Schema from '@deepseek-ai/schemastery'
|
||||
import { describe, expect, it, onTestFinished } from 'vitest'
|
||||
|
||||
const Typed = Object.assign((_ctx: Context, _config: { value: number }) => {}, {
|
||||
Config: Schema.object({ value: Schema.number().required() }),
|
||||
})
|
||||
|
||||
// `rows.yml` is the file the root Include reads; other files are reachable through nested includes.
|
||||
async function fixture(files: Record<string, string>) {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'dsh-loader-rc9-'))
|
||||
const pathOf = (name: string) => join(dir, name)
|
||||
for (const [name, content] of Object.entries(files)) await writeFile(pathOf(name), content)
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => {
|
||||
await ctx.fiber.dispose()
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 3 })
|
||||
})
|
||||
const errors: unknown[] = []
|
||||
const warnings: unknown[] = []
|
||||
ctx.logger.exporter({
|
||||
export: ({ type, args }: { type: string; args: unknown[] }) => {
|
||||
if (type === 'error') errors.push(...args)
|
||||
if (type === 'warn') warnings.push(...args)
|
||||
},
|
||||
})
|
||||
ctx.baseUrl = pathToFileURL(dir).href + '/'
|
||||
await ctx.plugin(Loader)
|
||||
Object.assign(ctx.loader.builtins, { include: Include, group: Group, example: () => {}, typed: Typed })
|
||||
const id = await ctx.loader.create({ name: 'cordis:include', config: { path: './rows.yml' } })
|
||||
await ctx.loader.await()
|
||||
const entry = ctx.loader.resolve(id)
|
||||
return { ctx, path: pathOf('rows.yml'), pathOf, entry, include: entry.subtree as Include | undefined, errors, warnings }
|
||||
}
|
||||
|
||||
describe('Loader 1.0.0-rc.9 entry options', () => {
|
||||
it('rejects invalid options before a tree changes', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(Loader)
|
||||
ctx.loader.builtins.example = () => {}
|
||||
// Options read from a file are untyped; set the invalid values past the compiler.
|
||||
const invalid = { name: 'cordis:example' } as EntryOptions
|
||||
Reflect.set(invalid, 'disabled', 'yes')
|
||||
Reflect.set(invalid, 'isolate', { svc: 1 })
|
||||
const error = await ctx.loader.create(invalid).catch((caught: unknown) => caught)
|
||||
expect(error).toBeInstanceOf(EntryValidationError)
|
||||
expect((error as EntryValidationError).issues).toEqual([
|
||||
{ message: 'disabled must be a boolean', path: ['disabled'] },
|
||||
{ message: 'isolate.svc must be true or a string', path: ['isolate', 'svc'] },
|
||||
])
|
||||
expect(ctx.loader.root.data).toEqual([])
|
||||
await expect(ctx.loader.create({ name: 'cordis:example', group: true })).rejects.toThrow('config is required')
|
||||
})
|
||||
|
||||
it('accepts explicit ids containing the separator from a file', async () => {
|
||||
const app = await fixture({ 'rows.yml': '- id: pkg:row\n name: cordis:example\n' })
|
||||
expect(app.include!.store['pkg:row']!.fiber!.state).toBe(FiberState.ACTIVE)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Include 1.2.0 config files', () => {
|
||||
it('reports invalid entries and config values at their file positions', async () => {
|
||||
const app = await fixture({ 'rows.yml': [
|
||||
'- id: bad',
|
||||
' name: cordis:example',
|
||||
' disabled: 1',
|
||||
'- id: typed',
|
||||
' name: cordis:typed',
|
||||
' config:',
|
||||
' value: text',
|
||||
'',
|
||||
].join('\n') })
|
||||
const messages = app.errors.map(String).join('\n')
|
||||
expect(messages).toContain(`disabled must be a boolean (at disabled, ${app.path}:3:13)`)
|
||||
expect(messages).toContain(`${app.path}:7:12`)
|
||||
expect(app.include!.store['bad']).toBeUndefined()
|
||||
expect(app.include!.store['typed']!.fiber!.state).not.toBe(FiberState.ACTIVE)
|
||||
})
|
||||
|
||||
it('reports an unknown plugin module at its name position', async () => {
|
||||
const app = await fixture({ 'rows.yml': '- id: missing\n name: ./missing-plugin.js\n' })
|
||||
const error = app.errors.find(error => error instanceof ModuleNotFoundError)
|
||||
expect(error?.specifier).toBe('./missing-plugin.js')
|
||||
expect(error?.message).toContain(`(at name, ${app.path}:2:9)`)
|
||||
})
|
||||
|
||||
it('parses YAML 1.2 core scalars and locates syntax errors', async () => {
|
||||
const app = await fixture({ 'rows.yml': '- id: typed\n name: cordis:typed\n config:\n value: 0x10\n' })
|
||||
expect(app.include!.store['typed']!.fiber!.effectiveConfig).toEqual({ value: 16 })
|
||||
await writeFile(app.path, '- id: typed\n name: [\n')
|
||||
await app.include!.refresh()
|
||||
const error = app.warnings.find(warning => warning instanceof ConfigFileError)
|
||||
expect(error).toBeInstanceOf(ConfigFileError)
|
||||
expect((error as ConfigFileError).issues[0]!.location).toMatchObject({ filename: app.path, line: 3 })
|
||||
})
|
||||
|
||||
it('rejects a file with a non-mapping entry at its position', async () => {
|
||||
const app = await fixture({ 'rows.yml': '- id: ok\n name: cordis:example\n- id: g\n name: cordis:group\n group: true\n config:\n - plain\n' })
|
||||
const error = app.errors.find(error => error instanceof ConfigFileError)
|
||||
expect(error?.issues).toEqual([{ message: 'entry must be an object', location: { filename: app.path, line: 7, column: 7 } }])
|
||||
expect(app.entry.fiber!.state).not.toBe(FiberState.ACTIVE)
|
||||
})
|
||||
|
||||
it('locates an unresolved alias as a parse error', async () => {
|
||||
const app = await fixture({ 'rows.yml': '- id: typed\n name: cordis:typed\n config: *missing\n' })
|
||||
const error = app.errors.find(error => error instanceof ConfigFileError)
|
||||
expect(error?.stage).toBe('parse')
|
||||
expect(error?.issues[0]!.location).toEqual({ filename: app.path, line: 3, column: 11 })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['an override', ' patches:\n - id: typed\n config:\n value: text\n', '- id: typed\n name: cordis:typed\n config:\n value: 1\n', 8],
|
||||
['an inserted entry', ' patches:\n - insert:\n - id: typed\n name: cordis:typed\n config:\n value: text\n', '[]\n', 10],
|
||||
])('locates a config value supplied by %s in the parent file', async (_kind, patches, inner, line) => {
|
||||
const app = await fixture({
|
||||
'rows.yml': `- id: inner\n name: cordis:include\n config:\n path: ./inner.yml\n${patches}`,
|
||||
'inner.yml': inner,
|
||||
})
|
||||
expect(app.errors.map(String).join('\n')).toContain(`(at value, ${app.path}:${String(line)}:`)
|
||||
})
|
||||
})
|
||||
@@ -84,15 +84,18 @@ describe('Loader project resolution', () => {
|
||||
await expect(tree.import('./missing.js')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('retains native import when helper creation is denied', async () => {
|
||||
it('retains native import while helper creation is denied and retries it later', async () => {
|
||||
const { root, baseUrl } = await fixture()
|
||||
const tree = await treeFor(baseUrl)
|
||||
const denied = vi.mocked(fs.mkdir).mockRejectedValueOnce(Object.assign(new Error('read-only project'), { code: 'EACCES' }))
|
||||
const denied = vi.mocked(fs.mkdir).mockRejectedValue(Object.assign(new Error('read-only project'), { code: 'EACCES' }))
|
||||
onTestFinished(() => { denied.mockReset() })
|
||||
expect(await createResolve(baseUrl)).toBeUndefined()
|
||||
expect(await tree.import('node:path')).toMatchObject({ join })
|
||||
await expect(tree.import('fixture-dep')).rejects.toThrow()
|
||||
expect(existsSync(join(root, '.cordis'))).toBe(false)
|
||||
denied.mockReset()
|
||||
expect(await tree.import('fixture-dep')).toMatchObject({ tag: 'bare-dep' })
|
||||
expect(existsSync(join(root, '.cordis', 'resolve.mjs'))).toBe(true)
|
||||
})
|
||||
|
||||
it('retains native import without a file-backed package scope', async () => {
|
||||
|
||||
@@ -438,7 +438,9 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
ForgeReviewRequest: 'forge.md',
|
||||
ForgeReviewResult: 'forge.md',
|
||||
ForgeBaseBranches: 'forge.md',
|
||||
ForgeBranches: 'forge.md',
|
||||
ForgeRemoteBranches: 'forge.md',
|
||||
ForgeRemoteDefault: 'forge.md',
|
||||
ForgeWorktreeBases: 'forge.md',
|
||||
ForgeChangeRequestDiff: 'forge.md',
|
||||
ForgeCommit: 'forge.md',
|
||||
ForgeCommitList: 'forge.md',
|
||||
|
||||
@@ -2781,7 +2781,17 @@
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeBranches",
|
||||
"symbol": "ForgeWorktreeBases",
|
||||
"source": "packages/experimental/client-ui-forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeRemoteDefault",
|
||||
"source": "packages/experimental/client-ui-forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeRemoteBranches",
|
||||
"source": "packages/experimental/client-ui-forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -219,7 +219,7 @@ export function verifyDefaultProductIsolation(root: string): ProductIsolationRes
|
||||
failures.push(`${display(filename)}: included composition must contain an entry array`)
|
||||
return
|
||||
}
|
||||
const entries = applyEntryPatches(content as EntryOptions[], entry.config.patches as PatchOptions[] | undefined, () => {})
|
||||
const entries = applyEntryPatches(content as EntryOptions[], entry.config.patches as PatchOptions[] | undefined, () => {}).data
|
||||
scanEntries(entries, filename, true, nestedStack)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ export function verifyProductUse(
|
||||
const content: unknown = existsSync(filename) ? loadCordisYaml(readFileSync(filename, 'utf8')) : row.config.initial
|
||||
configs.add(filename)
|
||||
if (!Array.isArray(content)) { failures.push(`${display(filename)}: Include requires an entry array or initial entries`); continue }
|
||||
const entries = applyEntryPatches(content as EntryOptions[], row.config.patches as PatchOptions[] | undefined, () => {})
|
||||
const entries = applyEntryPatches(content as EntryOptions[], row.config.patches as PatchOptions[] | undefined, () => {}).data
|
||||
scanEntries(entries, filename, reach, new Set([...stack, filename]))
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+12
-12
@@ -13,31 +13,31 @@ This file covers the manifest, the local-modification log, and the procedure for
|
||||
| `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/shigma/cosmokit | `02e691c5aa7f37f6e0b1cee7ee8f4a21c2e34507` |
|
||||
| `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/shigma/schemastery (`packages/core`) | `cf0b7e5481d0e31d10cdc30bc45c09366c332f27` |
|
||||
| `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.12 | https://github.com/cordiverse/cordis (`packages/core`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
|
||||
| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.8 | https://github.com/cordiverse/cordis (`packages/loader`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` |
|
||||
| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.1.1 | https://github.com/cordiverse/cordis (`packages/include`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` |
|
||||
| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.9 | https://github.com/cordiverse/cordis (`packages/loader`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
|
||||
| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.2.0 | https://github.com/cordiverse/cordis (`packages/include`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
|
||||
| `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/group`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
|
||||
| `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
|
||||
| `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/cordiverse/cordis (`packages/hmr`) | `ed8a7755c26a27a72064a21dea036ad1d1d6833c` |
|
||||
| `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/logger-console`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
|
||||
|
||||
Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `js-yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`.
|
||||
Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`.
|
||||
|
||||
Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordisjs/utils`, `@cordisjs/element`, `@cordisjs/unyaml` (dev-time YAML import hook only).
|
||||
|
||||
## Local modifications
|
||||
|
||||
Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V29.
|
||||
Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V31.
|
||||
|
||||
- **V1 · `hmr/src/index.ts`**: removed the `./locales/en-US.yml` / `./locales/zh-CN.yml` imports, the `.i18n({...})` call on the `Config` schema, and the `src/locales/` directory. Rationale: those imports require a runtime YAML loader hook (`@cordisjs/unyaml`) that we do not vendor; the i18n texts only localize config descriptions.
|
||||
- **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, and Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes.
|
||||
- **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes, and Include declares `yaml@^2.9.0` instead of upstream's `^2.9.1` so the workspace installs one copy of `yaml`.
|
||||
- **V3 · All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references.
|
||||
- **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Core's upstream source already uses explicit `.ts` specifiers. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces.
|
||||
- **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface.
|
||||
- **V6 · `cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup.
|
||||
- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed.
|
||||
- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, the `!!js` discriminator, entry option validation, source positions and `ModuleNotFoundError`. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed.
|
||||
- **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`.
|
||||
- **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`).
|
||||
- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, and `_read()` parses through `parseEntryYaml`, so every DSH reader and writer of Include-dialect YAML uses Include's parser; `stringifyEntryYaml` always writes with `noRefs` and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`.
|
||||
- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` with its `PatchResult` type, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, using the `yaml` options with which `_read()` parses Include's own file, so every DSH reader and writer of Include-dialect YAML uses Include's parser. `parseEntryYaml` throws the first parse error or warning, such as an unknown tag or an alias without a preceding anchor (V30), adds line positions to alias errors so `entryYamlErrorPosition` reads them, and returns `undefined` for an empty document; `stringifyEntryYaml` always writes with `aliasDuplicateObjects: false`, matching the previous `noRefs` output, and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`.
|
||||
- **V14 · Include persistence results**: `include/src/index.ts` keeps an error for unsaved journal changes. `flush()` retries pending writes and rejects while changes remain unsaved; `stop()` returns the same result and always stops the child tree; a later successful flush clears previous errors. A failed `refresh()` can also reject while runtime changes remain unsaved. Patch-owned changes route to the parent Include, so callers that need them persisted must flush that parent too. The constructor omits upstream's `ctx.hmr.watch(this.filename, () => this.refresh())` registration because neither HMR provider exposes `watch()`; both find each Include by scanning loader entries for its `filename` and call `refresh()`. Ordinary Fiber teardown keeps its error containment. Covered by `scripts/cordis-include-journal.spec.ts` and `packages/host/directory-picker-auto/tests/loader-composition.spec.ts`.
|
||||
- **V15 · Configuration access across Core, Loader, Include and HMR**: rc.11 Core owns raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and awaited `internal/update(config, next)`. Root-fiber candidate resolution remains available without a plugin schema. Local `rawConfig`, `resolveConfig(candidate)` and `effectiveConfig` accessors retain the DSH consumer API. Fiber caches the object passed to activation or a successful update that keeps the instance; candidate resolution is pure, failed or superseded updates cannot replace the cache, and volatile updates retain references. Loader resolves only entry roots and excludes Group/Include tree carriers, so nested `!!js` expressions wait for their own injections. Include retains its tree-carrier marker and public patch exports, and HMR transfers raw config through the accessors. Covered by `scripts/cordis-config-access.spec.ts`, `scripts/cordis-core-lifecycle.spec.ts` and the boot/HMR suites.
|
||||
- **V16 · `cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match.
|
||||
@@ -46,15 +46,15 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each
|
||||
- **V23 · `loader/src/config/entry.ts` module identity**: retains each entry's raw import result as `moduleNamespace`, before plugin export normalization. HMR matches that object to Node's cached module namespace and updates it after a successful reload. `EntryTree.import()` keeps its existing arguments and return value; `loader/README.md` documents the additive field.
|
||||
- **V24 · `timer/locale/{en,zh}.json` display metadata**: local English and Chinese titles and descriptions for the Settings plugin inventory. `timer/package.json` exports and publishes these locale resources.
|
||||
- **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling.
|
||||
- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.11`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. In rc.11 the entry stays registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`.
|
||||
- **V27 · `loader/src/config/tree.ts` explicit ids with `:`**: `ensureId()` accepts explicit ids containing `EntryTree.sep`; upstream rejects them. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `<package name>:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`.
|
||||
- **V28 · Core rc.12 compatibility in Loader and Include**: `loader/src/index.ts` declares `[Service.metadata]`, resolves its intercept through `[Service.resolveIntercept]` and logs through `ctx[Context.root]`; `include/src/index.ts` logs through `ctx[Context.root]`. These lines match the `v4.0.0-rc.12` tag while the rest of both packages keeps its rc.11 baseline. Retire this entry when Loader and Include are synchronized to that tag.
|
||||
- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.12`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. Upstream at `v4.0.0-rc.12` keeps the entry registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`.
|
||||
- **V27 · `loader/src/config/utils.ts` explicit ids with `:`**: `validateOptions()` accepts ids containing `EntryTree.sep`, so `EntryTree.create()`, `EntryTree.update()` and group reconciliation admit them; upstream rejects them with an `id must not contain` issue. `validateOptions()` keeps its upstream `sep` parameter. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `<package name>:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts`, `scripts/cordis-loader-rc9.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`.
|
||||
- **V30 · `include/src/index.ts` unresolved aliases**: backports [cordiverse/cordis#354](https://github.com/cordiverse/cordis/pull/354) (`c9fe179ce5ac484620a387a1697409cb007d4178`), merged after `v4.0.0-rc.12`. `_read()` reports each alias without a preceding anchor as a `BAD_ALIAS` `YAMLParseError` with its position, distinguishing an unknown anchor from one written after the alias; at the tag, `document.toJS()` throws an unlocated `ReferenceError` outside `ConfigFileError`. `unresolvedAliases()` matches the upstream commit verbatim. Retire this entry when the vendored Include includes #354. Covered by `scripts/cordis-loader-rc9.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`.
|
||||
|
||||
### Resolver adaptations
|
||||
|
||||
Relative to the resolver source in Cordis `v4.0.0-rc.11`:
|
||||
Relative to the resolver source in Cordis `v4.0.0-rc.12`:
|
||||
|
||||
- **Web build imports:** `loader/src/resolve.ts` uses default imports for Node builtin modules to support the Web shell's browser externalization. The shell supplies its own module loader.
|
||||
- **Web build imports:** `loader/src/resolve.ts` and `loader/src/config/tree.ts` use default imports for Node builtin modules to support the Web shell's browser externalization. The shell supplies its own module loader.
|
||||
- **Package-scope cache keys:** `loader/src/resolve.ts` normalizes directory paths with `path.resolve()` before finding the package scope. A root config and a nested config in the same package therefore share the same cached resolver promise and helper-file write. Covered by `scripts/cordis-loader-resolve.spec.ts`.
|
||||
|
||||
## Sync procedure
|
||||
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user