Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78fb05040a | ||
|
|
46fc8ff3f2 |
No files matched your search
@@ -30,7 +30,7 @@ jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
@@ -376,16 +376,13 @@ jobs:
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build web package
|
||||
run: bun --filter=@t3tools/web run build
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun --filter=t3 run build
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
@@ -394,7 +391,7 @@ jobs:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
@@ -421,7 +418,7 @@ jobs:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -555,7 +552,7 @@ jobs:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
@@ -565,7 +562,7 @@ jobs:
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -597,7 +594,7 @@ jobs:
|
||||
needs.release.result == 'success' &&
|
||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
||||
needs: [preflight, release, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -616,19 +613,19 @@ jobs:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Announce prerelease on Discord
|
||||
if: needs.preflight.outputs.is_prerelease == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
|
||||
DISCORD_RELEASE_NIGHTLY_ROLE_ID: ${{ vars.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts prerelease \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--role-id "$DISCORD_RELEASE_NIGHTLY_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
|
||||
@@ -636,12 +633,12 @@ jobs:
|
||||
if: needs.preflight.outputs.make_latest == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
|
||||
DISCORD_RELEASE_LATEST_ROLE_ID: ${{ vars.DISCORD_RELEASE_LATEST_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts latest \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--role-id "$DISCORD_RELEASE_LATEST_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
@@ -1,216 +0,0 @@
|
||||
# Version Control Phase 1: VCS Driver Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
|
||||
|
||||
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
|
||||
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
|
||||
- Add server services under `apps/server/src/vcs`:
|
||||
- `Services/VcsDriver.ts`
|
||||
- `Services/VcsRepositoryResolver.ts`
|
||||
- `Services/VcsProcess.ts`
|
||||
- `Layers/GitVcsDriver.ts`
|
||||
- `errors.ts`
|
||||
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
|
||||
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
|
||||
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
|
||||
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
|
||||
- No T3 Review implementation yet.
|
||||
- No broad UI redesign.
|
||||
|
||||
## Driver Model
|
||||
|
||||
Use provider-neutral nouns in new APIs:
|
||||
|
||||
- `VcsDriver`: local repository mechanics.
|
||||
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
|
||||
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
|
||||
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
|
||||
- `RefName`: branch, bookmark, tag, or provider-specific ref.
|
||||
|
||||
The initial driver capabilities should be explicit:
|
||||
|
||||
```ts
|
||||
export interface VcsDriverCapabilities {
|
||||
readonly kind: "git" | "jj" | "sapling" | "unknown";
|
||||
readonly supportsWorktrees: boolean;
|
||||
readonly supportsBookmarks: boolean;
|
||||
readonly supportsAtomicSnapshot: boolean;
|
||||
readonly supportsPushDefaultRemote: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
|
||||
|
||||
- `detectRepository(cwd)`
|
||||
- `status(cwd, options)`
|
||||
- `listRefs(cwd, query/pagination)`
|
||||
- `checkoutRef(cwd, ref)`
|
||||
- `createRef(cwd, ref, from?)`
|
||||
- `createWorkspace(cwd, ref, path?)`
|
||||
- `removeWorkspace(path)`
|
||||
- `prepareChangeContext(cwd, filePaths?)`
|
||||
- `createChange(cwd, message, options)`
|
||||
- `push(cwd, target?)`
|
||||
- `rangeContext(cwd, base, head)`
|
||||
- `listWorkspaceFiles(cwd, options)`
|
||||
|
||||
## Effect Process Layer
|
||||
|
||||
Create a small reusable `VcsProcess` service instead of using `runProcess`.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
|
||||
- Support scoped acquisition/release for long-running commands and interruption.
|
||||
- Support bounded stdout/stderr collection with truncation markers.
|
||||
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
|
||||
- Support stdin.
|
||||
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
|
||||
- Stream output lines to progress callbacks as Effects.
|
||||
- Return a typed `ProcessOutput` value for successful execution.
|
||||
- Fail with typed errors, not generic thrown exceptions.
|
||||
|
||||
Errors should be schema-backed tagged classes, for example:
|
||||
|
||||
- `VcsProcessSpawnError`
|
||||
- `VcsProcessExitError`
|
||||
- `VcsProcessTimeoutError`
|
||||
- `VcsOutputDecodeError`
|
||||
- `VcsRepositoryDetectionError`
|
||||
- `VcsUnsupportedOperationError`
|
||||
|
||||
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
|
||||
|
||||
## Git Driver Rewrite
|
||||
|
||||
Rewrite Git support against `VcsProcess`.
|
||||
|
||||
Carry forward current behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.test.ts`
|
||||
- current Git status/branch/worktree contracts
|
||||
|
||||
But split the implementation into smaller modules:
|
||||
|
||||
- command execution and hardening config
|
||||
- repository detection
|
||||
- status parsing
|
||||
- branch/ref parsing
|
||||
- worktree operations
|
||||
- commit/range context generation
|
||||
- push/pull operations
|
||||
|
||||
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
|
||||
|
||||
## Freshness and Local Caching
|
||||
|
||||
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
|
||||
|
||||
Treat these as live/local:
|
||||
|
||||
- repository detection for the active cwd
|
||||
- working copy dirty state
|
||||
- staged/unstaged/untracked file summaries
|
||||
- current branch/bookmark/change name
|
||||
- local branch/bookmark lists
|
||||
- local worktree/workspace lists
|
||||
|
||||
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
|
||||
|
||||
Treat these as cached or explicit-refresh only:
|
||||
|
||||
- remote tracking branch refreshes
|
||||
- ahead/behind counts that require network fetches
|
||||
- default branch discovery from a remote provider
|
||||
- remote branch lists beyond locally known refs
|
||||
|
||||
The VCS driver should expose freshness metadata with status results:
|
||||
|
||||
```ts
|
||||
export interface VcsFreshness {
|
||||
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
|
||||
|
||||
Use Effect `Cache` for repository identity and expensive local metadata:
|
||||
|
||||
- key by resolved repository root plus VCS kind
|
||||
- invalidate on cwd/root changes and workspace mutation operations
|
||||
- use short TTLs for local status caches when filesystem events are unavailable
|
||||
- never hide command failures behind stale values unless the caller explicitly accepts stale data
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
Prefer direct migration and deletion over compatibility wrappers.
|
||||
|
||||
Rules:
|
||||
|
||||
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
|
||||
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
|
||||
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
|
||||
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
|
||||
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
|
||||
- No new feature work may depend on transitional modules.
|
||||
|
||||
Expected transitional candidates:
|
||||
|
||||
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
|
||||
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
|
||||
|
||||
## Tests
|
||||
|
||||
Add integration-style tests with real temporary Git repositories for the new Git driver:
|
||||
|
||||
- non-repository detection
|
||||
- status for clean/dirty/untracked/staged states
|
||||
- branch/ref list with pagination
|
||||
- checkout/create branch
|
||||
- worktree create/remove
|
||||
- commit context generation with file filters
|
||||
- commit creation with hook progress events
|
||||
- push behavior against a local bare remote
|
||||
- status polling does not perform remote network refresh by default
|
||||
- concurrent duplicate status requests are coalesced
|
||||
- bounded output/truncation
|
||||
- timeout/interruption
|
||||
- typed error shape for command failure and missing executable
|
||||
|
||||
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `vcs` contracts and tagged errors.
|
||||
2. Add `VcsProcess` and unit tests around process execution semantics.
|
||||
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
|
||||
4. Implement `GitVcsDriver` with real Git command integration tests.
|
||||
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
|
||||
6. Move commit/range/push callers to the VCS service directly.
|
||||
7. Delete migrated `GitCore` internals and tests as each caller group moves.
|
||||
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
|
||||
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Current Git branch/status/worktree/commit behavior remains intact.
|
||||
- New Git implementation does not depend on `processRunner.ts`.
|
||||
- New errors are typed and inspectable by tests.
|
||||
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
|
||||
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Background status refresh is local-only by default and cannot hit provider rate limits.
|
||||
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -1,268 +0,0 @@
|
||||
# Version Control Phase 2: Source Control Provider Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
|
||||
|
||||
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
|
||||
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
|
||||
- Add server services under `apps/server/src/sourceControl`:
|
||||
- `Services/SourceControlProvider.ts`
|
||||
- `Services/SourceControlProviderRegistry.ts`
|
||||
- `Services/SourceControlProcess.ts`
|
||||
- `Layers/GitHubSourceControlProvider.ts`
|
||||
- `errors.ts`
|
||||
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
|
||||
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
|
||||
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
|
||||
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
|
||||
- No in-app review UI yet.
|
||||
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
|
||||
|
||||
## Provider Model
|
||||
|
||||
Use provider-neutral names:
|
||||
|
||||
- `SourceControlProvider`: hosted repository and change-request mechanics.
|
||||
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
|
||||
- `ChangeRequestThread`: review or discussion thread.
|
||||
- `ChangeRequestComment`: top-level or inline comment.
|
||||
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
|
||||
|
||||
Core provider operations:
|
||||
|
||||
- `detectRemote(remoteUrl)`
|
||||
- `checkAuth(cwd)`
|
||||
- `getRepository(cwd | remoteUrl)`
|
||||
- `getDefaultTargetRef(repository)`
|
||||
- `listChangeRequests(repository, filters)`
|
||||
- `getChangeRequest(repository, reference)`
|
||||
- `createChangeRequest(repository, input)`
|
||||
- `checkoutChangeRequest(cwd, changeRequest, options)`
|
||||
- `getCloneUrls(repository)`
|
||||
|
||||
Review-facing operations should be designed now, even if unimplemented:
|
||||
|
||||
- `listReviewThreads(changeRequest)`
|
||||
- `createReviewComment(changeRequest, input)`
|
||||
- `replyToReviewThread(thread, input)`
|
||||
- `resolveReviewThread(thread)`
|
||||
- `submitReview(changeRequest, input)`
|
||||
|
||||
Each operation should be guarded by capabilities:
|
||||
|
||||
```ts
|
||||
export interface SourceControlProviderCapabilities {
|
||||
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
|
||||
readonly supportsCreateChangeRequest: boolean;
|
||||
readonly supportsCheckoutChangeRequest: boolean;
|
||||
readonly supportsReviewThreads: boolean;
|
||||
readonly supportsInlineComments: boolean;
|
||||
readonly supportsDraftChangeRequests: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Provider Registry
|
||||
|
||||
Add a registry that resolves a provider from repository remotes and explicit user input.
|
||||
|
||||
Rules:
|
||||
|
||||
- Detection should be pure where possible and testable without spawning CLIs.
|
||||
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
|
||||
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
|
||||
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
|
||||
|
||||
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
|
||||
|
||||
## Rate Limits and Provider Caching
|
||||
|
||||
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
|
||||
|
||||
Default behavior:
|
||||
|
||||
- Pure URL/remote parsing is always live because it is local.
|
||||
- Provider detection from local remotes is live-local.
|
||||
- Authentication checks are cached.
|
||||
- Repository metadata is cached.
|
||||
- Default branch metadata is cached.
|
||||
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
|
||||
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
|
||||
- Create/update operations invalidate affected cache keys immediately after success.
|
||||
|
||||
The provider API should make freshness explicit:
|
||||
|
||||
```ts
|
||||
export interface SourceControlFreshness {
|
||||
readonly source: "live-local" | "cached-provider" | "live-provider";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
readonly stale?: boolean;
|
||||
}
|
||||
|
||||
export type ProviderRefreshPolicy =
|
||||
| "cache-first"
|
||||
| "stale-while-revalidate"
|
||||
| "force-refresh"
|
||||
| "local-only";
|
||||
```
|
||||
|
||||
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
|
||||
|
||||
Use Effect `Cache` for provider data:
|
||||
|
||||
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
|
||||
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
|
||||
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
|
||||
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
|
||||
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
|
||||
|
||||
Provider drivers should surface rate-limit signals when available:
|
||||
|
||||
- remaining quota
|
||||
- reset time
|
||||
- retry-after duration
|
||||
- whether the limit is primary, secondary/abuse, or unknown
|
||||
|
||||
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
|
||||
|
||||
Avoid rate-limit footguns:
|
||||
|
||||
- no provider calls from render loops or fast status polling
|
||||
- no listing all PRs/MRs across all repos to infer one branch state
|
||||
- no silent GitHub fallback for unknown providers
|
||||
- no unbounded cache cardinality for branch names or free-form search queries
|
||||
- no per-thread duplicate provider refresh when multiple views observe the same repository
|
||||
|
||||
## GitHub Provider Rewrite
|
||||
|
||||
Rewrite GitHub support as `GitHubSourceControlProvider`.
|
||||
|
||||
Carry forward behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitHubCli.ts`
|
||||
- `apps/server/src/git/Layers/GitHubCli.test.ts`
|
||||
- `apps/server/src/git/githubPullRequests.ts`
|
||||
- GitHub-specific `GitManager` PR paths
|
||||
|
||||
Implementation requirements:
|
||||
|
||||
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
|
||||
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
|
||||
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
|
||||
- Keep stdout/stderr bounded.
|
||||
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
|
||||
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
|
||||
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
|
||||
|
||||
## GitManager Cutover
|
||||
|
||||
Refactor `GitManager` so it coordinates three independent services:
|
||||
|
||||
- `VcsDriver` for local repository mechanics.
|
||||
- `SourceControlProviderRegistry` for hosted provider selection.
|
||||
- `TextGeneration` for message/body generation.
|
||||
|
||||
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
|
||||
|
||||
The Commit + PR flow should become:
|
||||
|
||||
1. Resolve VCS repository and local status.
|
||||
2. Resolve source-control provider from remotes.
|
||||
3. Generate commit content through the existing text generation service.
|
||||
4. Create local change through `VcsDriver`.
|
||||
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
|
||||
6. Generate change-request title/body.
|
||||
7. Create the change request through `SourceControlProvider`.
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
This phase should aggressively remove old GitHub-specific internals.
|
||||
|
||||
Rules:
|
||||
|
||||
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
|
||||
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
|
||||
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
|
||||
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
|
||||
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
|
||||
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
|
||||
|
||||
## GitLab and Azure Readiness
|
||||
|
||||
Use the triaged references as implementation inputs, not merge targets:
|
||||
|
||||
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
|
||||
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
|
||||
|
||||
The abstraction should let Phase 3 add:
|
||||
|
||||
- `GitLabSourceControlProvider` using `glab`.
|
||||
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
|
||||
|
||||
No provider should need to edit GitHub code to join the registry.
|
||||
|
||||
## T3 Review Design Constraint
|
||||
|
||||
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
|
||||
|
||||
That means contracts should include stable IDs and enough metadata for:
|
||||
|
||||
- file-level diffs
|
||||
- inline review threads
|
||||
- resolved/unresolved state
|
||||
- top-level discussion comments
|
||||
- pending review submission
|
||||
- provider URL back-links
|
||||
|
||||
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
|
||||
|
||||
## Tests
|
||||
|
||||
Add tests at three levels:
|
||||
|
||||
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
|
||||
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
|
||||
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
|
||||
|
||||
Required cases:
|
||||
|
||||
- GitHub PR URL, number, and branch-ish references.
|
||||
- GitLab MR URL/reference parsing.
|
||||
- Azure DevOps PR URL parsing for same-repo URLs.
|
||||
- unknown provider returns unsupported-operation errors.
|
||||
- missing CLI and auth failures produce distinct typed errors.
|
||||
- invalid CLI JSON fails at decode boundary with useful context.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `sourceControl` contracts and provider-neutral schemas.
|
||||
2. Add shared remote/reference parser helpers and tests.
|
||||
3. Add `SourceControlProcess` and provider errors.
|
||||
4. Add provider registry with GitHub-only registration.
|
||||
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
|
||||
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
|
||||
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
|
||||
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
|
||||
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Existing GitHub Commit + PR and PR checkout flows still work.
|
||||
- `GitManager` no longer imports or depends on `GitHubCli`.
|
||||
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
|
||||
- Unknown/unsupported providers fail explicitly and visibly.
|
||||
- GitHub command execution does not depend on `processRunner.ts`.
|
||||
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
|
||||
- Rate-limit responses become typed errors with retry/reset metadata where available.
|
||||
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -10,5 +10,3 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
@@ -25,7 +25,10 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
@@ -74,11 +77,6 @@ import {
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -293,7 +291,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
projectionSnapshotQueryLayer,
|
||||
@@ -309,32 +307,31 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
});
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitWorkflowLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -345,12 +342,11 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
@@ -35,6 +35,9 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
|
||||
}
|
||||
}
|
||||
|
||||
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
|
||||
export type CheckpointStoreError =
|
||||
| GitCommandError
|
||||
| CheckpointInvariantError
|
||||
| CheckpointUnavailableError;
|
||||
|
||||
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
||||
@@ -8,27 +8,24 @@ import { describe, expect } from "vitest";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-store-test-",
|
||||
});
|
||||
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
|
||||
const GitCoreTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||
Layer.provideMerge(VcsDriverTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const TestLayer = CheckpointStoreTestLayer.pipe(
|
||||
Layer.provideMerge(VcsProcessTestLayer),
|
||||
Layer.provideMerge(VcsDriverTestLayer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(GitCoreTestLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
||||
|
||||
function makeTmpDir(
|
||||
prefix = "checkpoint-store-test-",
|
||||
@@ -52,12 +49,11 @@ function writeTextFile(
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||
return Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const result = yield* process.run({
|
||||
const gitCore = yield* GitCore;
|
||||
const result = yield* gitCore.execute({
|
||||
operation: "CheckpointStore.test.git",
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
@@ -70,11 +66,12 @@ function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
VcsError | PlatformError.PlatformError,
|
||||
VcsProcess.VcsProcess | FileSystem.FileSystem
|
||||
GitCommandError | PlatformError.PlatformError,
|
||||
GitCore | FileSystem.FileSystem
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
yield* git(cwd, ["init"]);
|
||||
const core = yield* GitCore;
|
||||
yield* core.initRepo({ cwd });
|
||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
||||
|
||||
@@ -14,8 +14,8 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
@@ -24,26 +24,10 @@ const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const vcsRegistry = yield* VcsDriverRegistry;
|
||||
const vcs = {
|
||||
execute: (input: {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) =>
|
||||
vcsRegistry
|
||||
.resolve({ cwd: input.cwd, requestedKind: "git" })
|
||||
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
|
||||
};
|
||||
const git = yield* GitCore;
|
||||
|
||||
const resolveHeadCommit = (cwd: string) =>
|
||||
vcs
|
||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveHeadCommit",
|
||||
cwd,
|
||||
@@ -52,7 +36,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
@@ -60,18 +44,21 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const hasHeadCommit = (cwd: string) =>
|
||||
vcs
|
||||
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.hasHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.exitCode === 0));
|
||||
.pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
|
||||
vcs
|
||||
const resolveCheckpointCommit = (
|
||||
cwd: string,
|
||||
checkpointRef: CheckpointRef,
|
||||
): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveCheckpointCommit",
|
||||
cwd,
|
||||
@@ -80,7 +67,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
@@ -89,7 +76,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||
vcs
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.isGitRepository",
|
||||
cwd,
|
||||
@@ -97,7 +84,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
|
||||
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
@@ -121,7 +108,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
@@ -129,14 +116,14 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* vcs.execute({
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
@@ -144,17 +131,16 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* vcs.execute({
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
@@ -162,16 +148,15 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
@@ -212,12 +197,12 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
@@ -225,7 +210,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
@@ -250,16 +235,15 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (!fromCommitOid || !toCommitOid) {
|
||||
return yield* new VcsProcessExitError({
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git diff",
|
||||
cwd: input.cwd,
|
||||
exitCode: 1,
|
||||
detail: "Checkpoint ref is unavailable for diff operation.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* vcs.execute({
|
||||
const result = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
@@ -278,7 +262,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
vcs.execute({
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
import {
|
||||
GitManagerError,
|
||||
GitCommandError,
|
||||
type VcsDriverKind,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
type VcsCreateRefResult,
|
||||
type VcsCreateWorktreeInput,
|
||||
type VcsCreateWorktreeResult,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
type GitManagerServiceError,
|
||||
type GitPreparePullRequestThreadInput,
|
||||
type GitPreparePullRequestThreadResult,
|
||||
type GitPullRequestRefInput,
|
||||
type VcsPullResult,
|
||||
type VcsRemoveWorktreeInput,
|
||||
type GitResolvePullRequestResult,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type VcsStatusInput,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusRemoteResult,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
export interface GitWorkflowServiceShape {
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly initRepo: (input: { readonly cwd: string }) => Effect.Effect<void, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitWorkflowService extends Context.Service<
|
||||
GitWorkflowService,
|
||||
GitWorkflowServiceShape
|
||||
>()("t3/git/GitWorkflowService") {}
|
||||
|
||||
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
|
||||
new GitManagerError({
|
||||
operation,
|
||||
detail: `${detail} (${cwd})`,
|
||||
});
|
||||
|
||||
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
|
||||
new GitCommandError({
|
||||
operation,
|
||||
command: "vcs-route",
|
||||
cwd,
|
||||
detail,
|
||||
});
|
||||
|
||||
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
|
||||
|
||||
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
|
||||
kind,
|
||||
isRepo,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: emptyWorkingTree,
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver;
|
||||
const gitManager = yield* GitManager;
|
||||
|
||||
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* registry
|
||||
.resolve({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* registry
|
||||
.resolve({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const routeGitManager =
|
||||
<Input extends { readonly cwd: string }, Output>(
|
||||
operation: string,
|
||||
run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
|
||||
) =>
|
||||
(input: Input) =>
|
||||
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
|
||||
|
||||
const localStatus: GitWorkflowServiceShape["localStatus"] = Effect.fn(
|
||||
"GitWorkflowService.localStatus",
|
||||
)(function* (input) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd: input.cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
"GitWorkflowService.localStatus",
|
||||
input.cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return nonGitLocalStatus("unknown", false);
|
||||
}
|
||||
if (handle.kind === "git") {
|
||||
return yield* gitManager.localStatus(input);
|
||||
}
|
||||
return nonGitLocalStatus(handle.kind, true);
|
||||
});
|
||||
|
||||
const remoteStatus: GitWorkflowServiceShape["remoteStatus"] = Effect.fn(
|
||||
"GitWorkflowService.remoteStatus",
|
||||
)(function* (input) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd: input.cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
"GitWorkflowService.remoteStatus",
|
||||
input.cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle?.kind === "git") {
|
||||
return yield* gitManager.remoteStatus(input);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const status: GitWorkflowServiceShape["status"] = Effect.fn("GitWorkflowService.status")(
|
||||
function* (input) {
|
||||
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
},
|
||||
);
|
||||
|
||||
return GitWorkflowService.of({
|
||||
status,
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
||||
invalidateStatus: gitManager.invalidateStatus,
|
||||
pullCurrentBranch: (cwd) =>
|
||||
ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
|
||||
Effect.andThen(git.pullCurrentBranch(cwd)),
|
||||
),
|
||||
runStackedAction: (input, options) =>
|
||||
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
|
||||
Effect.andThen(gitManager.runStackedAction(input, options)),
|
||||
),
|
||||
resolvePullRequest: routeGitManager(
|
||||
"GitWorkflowService.resolvePullRequest",
|
||||
gitManager.resolvePullRequest,
|
||||
),
|
||||
preparePullRequestThread: routeGitManager(
|
||||
"GitWorkflowService.preparePullRequestThread",
|
||||
gitManager.preparePullRequestThread,
|
||||
),
|
||||
listRefs: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.andThen(git.listRefs(input)),
|
||||
),
|
||||
createWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.createWorktree(input)),
|
||||
),
|
||||
removeWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.removeWorktree(input)),
|
||||
),
|
||||
createRef: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
|
||||
Effect.andThen(git.createRef(input)),
|
||||
),
|
||||
switchRef: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
||||
),
|
||||
initRepo: (input) => git.initRepo(input),
|
||||
renameBranch: (input) =>
|
||||
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
|
||||
Effect.andThen(git.renameBranch(input)),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitWorkflowService, make());
|
||||
+4
-4
@@ -5,9 +5,9 @@ import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import { sanitizeThreadTitle } from "../Utils.ts";
|
||||
import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
|
||||
|
||||
const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
@@ -184,7 +184,7 @@ function withFakeClaudeEnv<A, E, R>(
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
|
||||
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
|
||||
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
+5
-5
@@ -14,20 +14,20 @@ import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
getModelSelectionStringOptionValue,
|
||||
getProviderOptionDescriptors,
|
||||
@@ -37,8 +37,8 @@ import {
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
} from "../provider/Layers/ClaudeProvider.ts";
|
||||
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
|
||||
} from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
+3
-3
@@ -6,8 +6,8 @@ import { expect } from "vitest";
|
||||
|
||||
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
|
||||
@@ -168,7 +168,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
+10
-6
@@ -4,28 +4,28 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { expandHomePath } from "../pathExpansion.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
} from "./TextGeneration.ts";
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
@@ -386,3 +386,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
// NOTE: `CodexTextGenerationLive` (the singleton Layer) has been removed.
|
||||
// `makeCodexTextGeneration(codexConfig)` is now invoked directly by
|
||||
// `CodexDriver.create()` for each configured instance.
|
||||
+8
-8
@@ -11,12 +11,12 @@ import { expect } from "vitest";
|
||||
|
||||
import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function shellSingleQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
@@ -82,7 +82,7 @@ function waitForFileContent(path: string): Effect.Effect<string> {
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => {
|
||||
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
|
||||
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
|
||||
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
|
||||
@@ -100,9 +100,9 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-text-generation",
|
||||
stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
|
||||
{ id: "reasoning", value: "xhigh" },
|
||||
@@ -243,9 +243,9 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-runtime-close",
|
||||
stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
model: "composer-2",
|
||||
+11
-4
@@ -5,23 +5,26 @@ import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import {
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
applyCursorAcpModelSelection,
|
||||
makeCursorAcpRuntime,
|
||||
} from "../provider/acp/CursorAcpSupport.ts";
|
||||
} from "../../provider/acp/CursorAcpSupport.ts";
|
||||
|
||||
const CURSOR_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -274,3 +277,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
// NOTE: `CursorTextGenerationLive` (the singleton Layer) has been removed.
|
||||
// `makeCursorTextGeneration(cursorConfig)` is now invoked directly by
|
||||
// `CursorDriver.create()` so each provider instance owns its own closure.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+11
-10
@@ -2,21 +2,22 @@ import { assert, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("../processRunner", () => ({
|
||||
vi.mock("../../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { GitHubCliLive } from "./GitHubCli.ts";
|
||||
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const layer = it.layer(GitHubCli.layer);
|
||||
const layer = it.layer(GitHubCliLive);
|
||||
|
||||
afterEach(() => {
|
||||
mockedRunProcess.mockReset();
|
||||
});
|
||||
|
||||
layer("GitHubCli.layer", (it) => {
|
||||
layer("GitHubCliLive", (it) => {
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
@@ -43,7 +44,7 @@ layer("GitHubCli.layer", (it) => {
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
@@ -101,7 +102,7 @@ layer("GitHubCli.layer", (it) => {
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
@@ -154,7 +155,7 @@ layer("GitHubCli.layer", (it) => {
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
@@ -189,7 +190,7 @@ layer("GitHubCli.layer", (it) => {
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
@@ -213,7 +214,7 @@ layer("GitHubCli.layer", (it) => {
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
+16
-74
@@ -1,81 +1,21 @@
|
||||
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { GitHubCliError, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import type { ProcessRunResult } from "../processRunner.ts";
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
type GitHubCliShape,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../git/githubPullRequests.ts";
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state?: "open" | "closed" | "merged";
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
export interface GitHubRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
export interface GitHubCliShape {
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
|
||||
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
|
||||
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, GitHubCliError>;
|
||||
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, GitHubCliError>;
|
||||
|
||||
readonly checkoutPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, GitHubCliError>;
|
||||
}
|
||||
|
||||
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/source-control/GitHubCli",
|
||||
) {}
|
||||
|
||||
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: gh")) {
|
||||
@@ -161,7 +101,7 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.sync(() => {
|
||||
const makeGitHubCli = Effect.sync(() => {
|
||||
const execute: GitHubCliShape["execute"] = (input) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
@@ -172,7 +112,7 @@ export const make = Effect.sync(() => {
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
|
||||
return GitHubCli.of({
|
||||
const service = {
|
||||
execute,
|
||||
listOpenPullRequests: (input) =>
|
||||
execute({
|
||||
@@ -292,7 +232,9 @@ export const make = Effect.sync(() => {
|
||||
cwd: input.cwd,
|
||||
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
} satisfies GitHubCliShape;
|
||||
|
||||
return service;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitHubCli, make);
|
||||
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
|
||||
+53
-121
@@ -14,25 +14,23 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { type GitManagerShape } from "./GitManager.ts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
GitHubCli,
|
||||
} from "../sourceControl/GitHubCli.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { GitCoreLive } from "./GitCore.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { makeGitManager } from "./GitManager.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
ProjectSetupScriptRunner,
|
||||
type ProjectSetupScriptRunnerInput,
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
} from "../project/Services/ProjectSetupScriptRunner.ts";
|
||||
} from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
@@ -211,27 +209,18 @@ function runGit(
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Effect.Effect<
|
||||
{
|
||||
readonly exitCode: GitVcsDriver.ExecuteGitResult["exitCode"];
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
},
|
||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||
GitCommandError,
|
||||
GitVcsDriver.GitVcsDriver
|
||||
GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const result = yield* git.execute({
|
||||
const gitCore = yield* GitCore;
|
||||
return yield* gitCore.execute({
|
||||
operation: "GitManager.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
allowNonZeroExit,
|
||||
});
|
||||
return {
|
||||
exitCode: result.exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -240,7 +229,7 @@ function initRepo(
|
||||
): Effect.Effect<
|
||||
void,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
|
||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -256,7 +245,7 @@ function initRepo(
|
||||
function createBareRemote(): Effect.Effect<
|
||||
string,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
|
||||
FileSystem.FileSystem | Scope.Scope | GitCore
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
||||
@@ -270,7 +259,7 @@ function configureRemote(
|
||||
remoteName: string,
|
||||
remotePath: string,
|
||||
fetchNamespace: string,
|
||||
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
|
||||
): Effect.Effect<void, GitCommandError, GitCore> {
|
||||
return Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
|
||||
yield* runGit(cwd, [
|
||||
@@ -650,25 +639,13 @@ function makeManager(input?: {
|
||||
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
|
||||
const vcsDriverLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
const gitCoreLayer = GitCoreLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
);
|
||||
const sourceControlRegistryLayer = Layer.effect(
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry,
|
||||
GitHubSourceControlProvider.make().pipe(
|
||||
Effect.map((provider) =>
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
|
||||
resolveHandle: () => Effect.succeed({ provider, context: null }),
|
||||
resolve: () => Effect.succeed(provider),
|
||||
}),
|
||||
),
|
||||
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
|
||||
),
|
||||
);
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(GitHubCli, gitHubCli),
|
||||
Layer.succeed(TextGeneration, textGeneration),
|
||||
Layer.succeed(
|
||||
ProjectSetupScriptRunner,
|
||||
@@ -676,9 +653,9 @@ function makeManager(input?: {
|
||||
runForThread: () => Effect.succeed({ status: "no-script" as const }),
|
||||
},
|
||||
),
|
||||
vcsDriverLayer,
|
||||
gitCoreLayer,
|
||||
serverSettingsLayer,
|
||||
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
return makeGitManager().pipe(
|
||||
Effect.provide(managerLayer),
|
||||
@@ -688,9 +665,8 @@ function makeManager(input?: {
|
||||
|
||||
const asThreadId = (threadId: string) => threadId as ThreadId;
|
||||
|
||||
const GitManagerTestLayer = GitVcsDriver.layer.pipe(
|
||||
const GitManagerTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -722,15 +698,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.isRepo).toBe(true);
|
||||
expect(status.hasPrimaryRemote).toBe(true);
|
||||
expect(status.isDefaultRef).toBe(false);
|
||||
expect(status.refName).toBe("feature/status-open-pr");
|
||||
expect(status.hasOriginRemote).toBe(true);
|
||||
expect(status.isDefaultBranch).toBe(false);
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-open-pr",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -767,8 +743,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
number: 14,
|
||||
title: "Existing PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-trimmed-pr",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-trimmed-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -818,8 +794,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
number: 15,
|
||||
title: "Valid PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-valid-pr-entry",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-valid-pr-entry",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -867,8 +843,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-lowercase-state",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
@@ -883,9 +859,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -912,9 +888,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -996,7 +972,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("main");
|
||||
expect(status.branch).toBe("main");
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -1050,13 +1026,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("t3code/pr-488/statemachine");
|
||||
expect(status.branch).toBe("t3code/pr-488/statemachine");
|
||||
expect(status.pr).toEqual({
|
||||
number: 488,
|
||||
title: "Rebase this PR on latest main",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
|
||||
baseRef: "main",
|
||||
headRef: "statemachine",
|
||||
baseBranch: "main",
|
||||
headBranch: "statemachine",
|
||||
state: "open",
|
||||
});
|
||||
expect(ghCalls).toContain(
|
||||
@@ -1150,13 +1126,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("upstream/effect-atom");
|
||||
expect(status.branch).toBe("upstream/effect-atom");
|
||||
expect(status.pr).toEqual({
|
||||
number: 1618,
|
||||
title: "Correct PR",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1618",
|
||||
baseRef: "main",
|
||||
headRef: "effect-atom",
|
||||
baseBranch: "main",
|
||||
headBranch: "effect-atom",
|
||||
state: "open",
|
||||
});
|
||||
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
|
||||
@@ -1200,13 +1176,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("feature/status-merged-pr");
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-merged-pr",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
@@ -1237,7 +1213,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("main");
|
||||
expect(status.branch).toBe("main");
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -1277,13 +1253,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("feature/status-open-over-merged");
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseRef: "main",
|
||||
headRef: "feature/status-open-over-merged",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
@@ -1308,7 +1284,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("feature/status-no-gh");
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -1732,49 +1708,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("create_pr falls back to main when source control provider detection fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]);
|
||||
fs.writeFileSync(path.join(repoDir, "provider-fallback.txt"), "fallback\n");
|
||||
yield* runGit(repoDir, ["add", "provider-fallback.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 404,
|
||||
title: "Provider fallback",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/404",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/provider-fallback",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "create_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(404);
|
||||
expect(
|
||||
ghCalls.some((call) =>
|
||||
call.includes("pr create --base main --head feature/provider-fallback"),
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns existing PR metadata for commit/push/pr action", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -3056,7 +2989,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect.objectContaining({
|
||||
kind: "hook_finished",
|
||||
hookName: "pre-commit",
|
||||
exitCode: 0,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "action_finished",
|
||||
@@ -3187,7 +3119,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect.objectContaining({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: "Creating pull request...",
|
||||
label: "Creating GitHub pull request...",
|
||||
}),
|
||||
]);
|
||||
}),
|
||||
@@ -2,39 +2,29 @@ import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Array as Arr,
|
||||
Cache,
|
||||
Context,
|
||||
DateTime,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Order,
|
||||
Path,
|
||||
Ref,
|
||||
Result,
|
||||
} from "effect";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitActionProgressPhase,
|
||||
GitCommandError,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
GitResolvePullRequestResult,
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
VcsStatusInput,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
type GitStatusLocalResult,
|
||||
type GitStatusRemoteResult,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
detectGitHostingProviderFromRemoteUrl,
|
||||
mergeGitStatusParts,
|
||||
resolveAutoFeatureBranchName,
|
||||
sanitizeBranchFragment,
|
||||
@@ -42,52 +32,24 @@ import {
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import {
|
||||
GitManager,
|
||||
type GitActionProgressReporter,
|
||||
type GitManagerShape,
|
||||
type GitRunStackedActionOptions,
|
||||
} from "../Services/GitManager.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import type { GitStatusDetails } from "../Services/GitCore.ts";
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import { GitVcsDriver, type GitStatusDetails } from "../vcs/GitVcsDriver.ts";
|
||||
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitRunStackedActionOptions {
|
||||
readonly actionId?: string;
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
export interface GitManagerShape {
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/GitManager",
|
||||
) {}
|
||||
import {
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -113,14 +75,9 @@ interface OpenPrInfo {
|
||||
|
||||
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
|
||||
state: "open" | "closed" | "merged";
|
||||
updatedAt: Option.Option<DateTime.Utc>;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
|
||||
Order.flip(Option.makeOrder(DateTime.Order)),
|
||||
(pullRequest) => pullRequest.updatedAt,
|
||||
);
|
||||
|
||||
interface ResolvedPullRequest {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -131,9 +88,9 @@ interface ResolvedPullRequest {
|
||||
}
|
||||
|
||||
interface PullRequestHeadRemoteInfo {
|
||||
isCrossRepository?: boolean | undefined;
|
||||
headRepositoryNameWithOwner?: string | null | undefined;
|
||||
headRepositoryOwnerLogin?: string | null | undefined;
|
||||
isCrossRepository?: boolean;
|
||||
headRepositoryNameWithOwner?: string | null;
|
||||
headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
interface BranchHeadContext {
|
||||
@@ -299,7 +256,7 @@ function matchesBranchHeadContext(
|
||||
return true;
|
||||
}
|
||||
|
||||
function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
|
||||
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
|
||||
return {
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
@@ -307,7 +264,7 @@ function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state ?? "open",
|
||||
updatedAt: summary.updatedAt,
|
||||
updatedAt: null,
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
@@ -465,16 +422,16 @@ function toStatusPr(pr: PullRequestInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseRef: string;
|
||||
headRef: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
baseRef: pr.baseRefName,
|
||||
headRef: pr.headRefName,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
@@ -518,9 +475,9 @@ function shouldPreferSshRemote(url: string | null): boolean {
|
||||
}
|
||||
|
||||
function toPullRequestHeadRemoteInfo(pr: {
|
||||
isCrossRepository?: boolean | undefined;
|
||||
headRepositoryNameWithOwner?: string | null | undefined;
|
||||
headRepositoryOwnerLogin?: string | null | undefined;
|
||||
isCrossRepository?: boolean;
|
||||
headRepositoryNameWithOwner?: string | null;
|
||||
headRepositoryOwnerLogin?: string | null;
|
||||
}): PullRequestHeadRemoteInfo {
|
||||
return {
|
||||
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
|
||||
@@ -534,12 +491,10 @@ function toPullRequestHeadRemoteInfo(pr: {
|
||||
}
|
||||
|
||||
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const gitCore = yield* GitVcsDriver;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry;
|
||||
const gitCore = yield* GitCore;
|
||||
const gitHubCli = yield* GitHubCli;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
|
||||
|
||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const createProgressEmitter = (
|
||||
@@ -576,7 +531,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
|
||||
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
|
||||
cwd,
|
||||
repository: repositoryNameWithOwner,
|
||||
});
|
||||
@@ -631,7 +586,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
|
||||
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
|
||||
cwd,
|
||||
repository: repositoryNameWithOwner,
|
||||
});
|
||||
@@ -704,15 +659,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
: null;
|
||||
|
||||
return {
|
||||
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
|
||||
isRepo: details.isRepo,
|
||||
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
|
||||
hasPrimaryRemote: details.hasOriginRemote,
|
||||
isDefaultRef: details.isDefaultBranch,
|
||||
refName: details.branch,
|
||||
...(hostingProvider ? { hostingProvider } : {}),
|
||||
hasOriginRemote: details.hasOriginRemote,
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
} satisfies VcsStatusLocalResult;
|
||||
} satisfies GitStatusLocalResult;
|
||||
});
|
||||
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
@@ -750,7 +704,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
pr,
|
||||
} satisfies VcsStatusRemoteResult;
|
||||
} satisfies GitStatusRemoteResult;
|
||||
});
|
||||
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
@@ -774,7 +728,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
|
||||
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
|
||||
|
||||
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
|
||||
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
|
||||
});
|
||||
|
||||
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
|
||||
@@ -879,10 +833,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
>,
|
||||
) {
|
||||
for (const headSelector of headContext.headSelectors) {
|
||||
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
|
||||
const pullRequests = yield* gitHubCli.listOpenPullRequests({
|
||||
cwd,
|
||||
headSelector,
|
||||
state: "open",
|
||||
limit: 1,
|
||||
});
|
||||
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
|
||||
@@ -898,7 +851,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
baseRefName: firstPullRequest.baseRefName,
|
||||
headRefName: firstPullRequest.headRefName,
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
updatedAt: null,
|
||||
} satisfies PullRequestInfo;
|
||||
}
|
||||
}
|
||||
@@ -914,14 +867,46 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const parsedByNumber = new Map<number, PullRequestInfo>();
|
||||
|
||||
for (const headSelector of headContext.headSelectors) {
|
||||
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
|
||||
cwd,
|
||||
headSelector,
|
||||
state: "all",
|
||||
limit: 20,
|
||||
});
|
||||
const stdout = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
headSelector,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"20",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
for (const pr of pullRequests.map(toPullRequestInfo)) {
|
||||
const raw = stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
gitManagerError(
|
||||
"findLatestPr",
|
||||
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
decoded.failure,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const pr of pullRequests) {
|
||||
if (!matchesBranchHeadContext(pr, headContext)) {
|
||||
continue;
|
||||
}
|
||||
@@ -929,7 +914,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
|
||||
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
|
||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||
return right - left;
|
||||
});
|
||||
|
||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||
if (latestOpenPr) {
|
||||
@@ -1046,12 +1035,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
|
||||
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
if (defaultFromProvider) {
|
||||
return defaultFromProvider;
|
||||
const defaultFromGh = yield* gitHubCli
|
||||
.getDefaultBranch({ cwd })
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (defaultFromGh) {
|
||||
return defaultFromGh;
|
||||
}
|
||||
|
||||
return "main";
|
||||
@@ -1284,12 +1272,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: "Creating pull request...",
|
||||
label: "Creating GitHub pull request...",
|
||||
});
|
||||
yield* (yield* sourceControlProvider(cwd))
|
||||
.createChangeRequest({
|
||||
yield* gitHubCli
|
||||
.createPullRequest({
|
||||
cwd,
|
||||
baseRefName: baseBranch,
|
||||
baseBranch,
|
||||
headSelector: headContext.preferredHeadSelector,
|
||||
title: generated.title,
|
||||
bodyFile,
|
||||
@@ -1347,8 +1335,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
|
||||
function* (input) {
|
||||
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
|
||||
.getChangeRequest({
|
||||
const pullRequest = yield* gitHubCli
|
||||
.getPullRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizePullRequestReference(input.reference),
|
||||
})
|
||||
@@ -1382,14 +1370,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return yield* Effect.gen(function* () {
|
||||
const normalizedReference = normalizePullRequestReference(input.reference);
|
||||
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
|
||||
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
|
||||
const pullRequestSummary = yield* gitHubCli.getPullRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizedReference,
|
||||
});
|
||||
const pullRequest = toResolvedPullRequest(pullRequestSummary);
|
||||
|
||||
if (input.mode === "local") {
|
||||
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
|
||||
yield* gitHubCli.checkoutPullRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizedReference,
|
||||
force: true,
|
||||
@@ -1432,9 +1420,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
const findLocalHeadBranch = (cwd: string) =>
|
||||
gitCore.listRefs({ cwd }).pipe(
|
||||
gitCore.listBranches({ cwd }).pipe(
|
||||
Effect.map((result) => {
|
||||
const localBranch = result.refs.find(
|
||||
const localBranch = result.branches.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
if (localBranch) {
|
||||
@@ -1444,7 +1432,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
result.refs.find(
|
||||
result.branches.find(
|
||||
(branch) =>
|
||||
!branch.isRemote &&
|
||||
branch.name === pullRequest.headBranch &&
|
||||
@@ -1507,7 +1495,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const worktree = yield* gitCore.createWorktree({
|
||||
cwd: input.cwd,
|
||||
refName: localPullRequestBranch,
|
||||
branch: localPullRequestBranch,
|
||||
path: null,
|
||||
});
|
||||
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
|
||||
@@ -1515,7 +1503,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
return {
|
||||
pullRequest,
|
||||
branch: worktree.worktree.refName,
|
||||
branch: worktree.worktree.branch,
|
||||
worktreePath: worktree.worktree.path,
|
||||
};
|
||||
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
|
||||
@@ -1547,8 +1535,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||
|
||||
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
|
||||
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||
|
||||
return {
|
||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||
@@ -1749,4 +1737,4 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
} satisfies GitManagerShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitManager, makeGitManager());
|
||||
export const GitManagerLive = Layer.effect(GitManager, makeGitManager());
|
||||
+84
-138
@@ -1,56 +1,52 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Deferred, Effect, Exit, FileSystem, Layer, Option, Path, Scope, Stream } from "effect";
|
||||
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
|
||||
import type {
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import {
|
||||
VcsStatusBroadcaster,
|
||||
layer as VcsStatusBroadcasterLayer,
|
||||
} from "./VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
|
||||
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
|
||||
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
|
||||
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
|
||||
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
kind: "git",
|
||||
const baseLocalStatus: GitStatusLocalResult = {
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
hostingProvider: {
|
||||
kind: "github",
|
||||
name: "GitHub",
|
||||
baseUrl: "https://github.com",
|
||||
},
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/status-broadcast",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/status-broadcast",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
const baseRemoteStatus: VcsStatusRemoteResult = {
|
||||
const baseRemoteStatus: GitStatusRemoteResult = {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
|
||||
const baseStatus: VcsStatusResult = {
|
||||
const baseStatus: GitStatusResult = {
|
||||
...baseLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
};
|
||||
|
||||
function makeTestLayer(state: {
|
||||
currentLocalStatus: VcsStatusLocalResult;
|
||||
currentRemoteStatus: VcsStatusRemoteResult | null;
|
||||
currentLocalStatus: GitStatusLocalResult;
|
||||
currentRemoteStatus: GitStatusRemoteResult | null;
|
||||
localStatusCalls: number;
|
||||
remoteStatusCalls: number;
|
||||
localInvalidationCalls: number;
|
||||
remoteInvalidationCalls: number;
|
||||
}) {
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
const gitManager: GitManagerShape = {
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
@@ -61,6 +57,7 @@ function makeTestLayer(state: {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
status: () => Effect.die("status should not be called in this test"),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
@@ -69,16 +66,18 @@ function makeTestLayer(state: {
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
});
|
||||
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
|
||||
preparePullRequestThread: () =>
|
||||
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||
};
|
||||
|
||||
return VcsStatusBroadcasterLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
);
|
||||
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
|
||||
}
|
||||
|
||||
describe("VcsStatusBroadcaster", () => {
|
||||
it.effect("reuses the cached VCS status across repeated reads", () => {
|
||||
describe("GitStatusBroadcasterLive", () => {
|
||||
it.effect("reuses the cached git status across repeated reads", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
@@ -89,7 +88,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
|
||||
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
@@ -114,12 +113,12 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
refName: "feature/updated-status",
|
||||
branch: "feature/updated-status",
|
||||
};
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
@@ -155,12 +154,12 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
state.currentLocalStatus = {
|
||||
...baseLocalStatus,
|
||||
refName: "feature/local-only-refresh",
|
||||
branch: "feature/local-only-refresh",
|
||||
hasWorkingTreeChanges: true,
|
||||
};
|
||||
|
||||
@@ -180,66 +179,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("normalizes symlinked CWDs before cache lookup and workflow calls", () => {
|
||||
const seenCwds: string[] = [];
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
localStatus: (input) =>
|
||||
Effect.sync(() => {
|
||||
seenCwds.push(input.cwd);
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: (input) =>
|
||||
Effect.sync(() => {
|
||||
seenCwds.push(input.cwd);
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowServiceShape>);
|
||||
const testLayer = VcsStatusBroadcasterLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const realDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-status-real-",
|
||||
});
|
||||
const linkParent = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-status-link-",
|
||||
});
|
||||
const linkDir = path.join(linkParent, "repo-link");
|
||||
yield* fileSystem.symlink(realDir, linkDir);
|
||||
const realPath = yield* fileSystem.realPath(realDir);
|
||||
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: linkDir });
|
||||
yield* broadcaster.getStatus({ cwd: realDir });
|
||||
|
||||
assert.deepStrictEqual(seenCwds, [realPath, realPath]);
|
||||
assert.equal(state.localStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("streams a local snapshot first and remote updates later", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
@@ -251,9 +190,9 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
|
||||
if (event._tag === "snapshot") {
|
||||
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
|
||||
@@ -272,11 +211,11 @@ describe("VcsStatusBroadcaster", () => {
|
||||
_tag: "snapshot",
|
||||
local: baseLocalStatus,
|
||||
remote: null,
|
||||
} satisfies VcsStatusStreamEvent);
|
||||
} satisfies GitStatusStreamEvent);
|
||||
assert.deepStrictEqual(remoteUpdated, {
|
||||
_tag: "remoteUpdated",
|
||||
remote: baseRemoteStatus,
|
||||
} satisfies VcsStatusStreamEvent);
|
||||
} satisfies GitStatusStreamEvent);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
@@ -291,40 +230,47 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
remoteStartedDeferred
|
||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
|
||||
Effect.onInterrupt(() =>
|
||||
remoteInterruptedDeferred
|
||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowServiceShape>);
|
||||
const testLayer = VcsStatusBroadcasterLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
const testLayer = GitStatusBroadcasterLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(GitManager, {
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
remoteStartedDeferred
|
||||
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
|
||||
Effect.onInterrupt(() =>
|
||||
remoteInterruptedDeferred
|
||||
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
status: () => Effect.die("status should not be called in this test"),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
|
||||
resolvePullRequest: () =>
|
||||
Effect.die("resolvePullRequest should not be called in this test"),
|
||||
preparePullRequestThread: () =>
|
||||
Effect.die("preparePullRequestThread should not be called in this test"),
|
||||
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
|
||||
} satisfies GitManagerShape),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
@@ -333,9 +279,9 @@ describe("VcsStatusBroadcaster", () => {
|
||||
remoteInterruptedDeferred = remoteInterrupted;
|
||||
remoteStartedDeferred = remoteStarted;
|
||||
|
||||
const broadcaster = yield* VcsStatusBroadcaster;
|
||||
const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
const broadcaster = yield* GitStatusBroadcaster;
|
||||
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
|
||||
const firstScope = yield* Scope.make();
|
||||
const secondScope = yield* Scope.make();
|
||||
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
|
||||
@@ -356,11 +302,11 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
yield* Scope.close(firstScope, Exit.void);
|
||||
assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
|
||||
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
|
||||
|
||||
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
|
||||
yield* Deferred.await(remoteInterrupted);
|
||||
assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
|
||||
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
PubSub,
|
||||
Ref,
|
||||
Scope,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import type {
|
||||
GitStatusInput,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../Services/GitStatusBroadcaster.ts";
|
||||
import { GitManager } from "../Services/GitManager.ts";
|
||||
|
||||
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
interface GitStatusChange {
|
||||
readonly cwd: string;
|
||||
readonly event: GitStatusStreamEvent;
|
||||
}
|
||||
|
||||
interface CachedValue<T> {
|
||||
readonly fingerprint: string;
|
||||
readonly value: T;
|
||||
}
|
||||
|
||||
interface CachedGitStatus {
|
||||
readonly local: CachedValue<GitStatusLocalResult> | null;
|
||||
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
|
||||
}
|
||||
|
||||
interface ActiveRemotePoller {
|
||||
readonly fiber: Fiber.Fiber<void, never>;
|
||||
readonly subscriberCount: number;
|
||||
}
|
||||
|
||||
function normalizeCwd(cwd: string): string {
|
||||
try {
|
||||
return realpathSync.native(cwd);
|
||||
} catch {
|
||||
return cwd;
|
||||
}
|
||||
}
|
||||
|
||||
function fingerprintStatusPart(status: unknown): string {
|
||||
return JSON.stringify(status);
|
||||
}
|
||||
|
||||
export const GitStatusBroadcasterLive = Layer.effect(
|
||||
GitStatusBroadcaster,
|
||||
Effect.gen(function* () {
|
||||
const gitManager = yield* GitManager;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<GitStatusChange>(),
|
||||
(pubsub) => PubSub.shutdown(pubsub),
|
||||
);
|
||||
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
|
||||
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
|
||||
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
|
||||
});
|
||||
|
||||
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
|
||||
cwd: string,
|
||||
local: GitStatusLocalResult,
|
||||
options?: { publish?: boolean },
|
||||
) {
|
||||
const nextLocal = {
|
||||
fingerprint: fingerprintStatusPart(local),
|
||||
value: local,
|
||||
} satisfies CachedValue<GitStatusLocalResult>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
...previous,
|
||||
local: nextLocal,
|
||||
});
|
||||
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
yield* PubSub.publish(changesPubSub, {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "localUpdated",
|
||||
local,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return local;
|
||||
});
|
||||
|
||||
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
remote: GitStatusRemoteResult | null,
|
||||
options?: { publish?: boolean },
|
||||
) {
|
||||
const nextRemote = {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<GitStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
...previous,
|
||||
remote: nextRemote,
|
||||
});
|
||||
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
yield* PubSub.publish(changesPubSub, {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "remoteUpdated",
|
||||
remote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return remote;
|
||||
});
|
||||
|
||||
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
|
||||
const local = yield* gitManager.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local);
|
||||
});
|
||||
|
||||
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
|
||||
const remote = yield* gitManager.remoteStatus({ cwd });
|
||||
return yield* updateCachedRemoteStatus(cwd, remote);
|
||||
});
|
||||
|
||||
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (cached?.local) {
|
||||
return cached.local.value;
|
||||
}
|
||||
return yield* loadLocalStatus(cwd);
|
||||
});
|
||||
|
||||
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (cached?.remote) {
|
||||
return cached.remote.value;
|
||||
}
|
||||
return yield* loadRemoteStatus(cwd);
|
||||
});
|
||||
|
||||
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
|
||||
input: GitStatusInput,
|
||||
) {
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
getOrLoadLocalStatus(normalizedCwd),
|
||||
getOrLoadRemoteStatus(normalizedCwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
|
||||
"refreshLocalStatus",
|
||||
)(function* (cwd) {
|
||||
const normalizedCwd = normalizeCwd(cwd);
|
||||
yield* gitManager.invalidateLocalStatus(normalizedCwd);
|
||||
const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
|
||||
return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
|
||||
});
|
||||
|
||||
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
|
||||
yield* gitManager.invalidateRemoteStatus(cwd);
|
||||
const remote = yield* gitManager.remoteStatus({ cwd });
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
});
|
||||
|
||||
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
|
||||
function* (cwd) {
|
||||
const normalizedCwd = normalizeCwd(cwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
refreshLocalStatus(normalizedCwd),
|
||||
refreshRemoteStatus(normalizedCwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
},
|
||||
);
|
||||
|
||||
const makeRemoteRefreshLoop = (cwd: string) => {
|
||||
const logRefreshFailure = (error: Error) =>
|
||||
Effect.logWarning("git remote status refresh failed", {
|
||||
cwd,
|
||||
detail: error.message,
|
||||
});
|
||||
|
||||
return refreshRemoteStatus(cwd).pipe(
|
||||
Effect.catch(logRefreshFailure),
|
||||
Effect.andThen(
|
||||
Effect.forever(
|
||||
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
|
||||
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
|
||||
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (existing) {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount + 1,
|
||||
});
|
||||
return Effect.succeed([undefined, nextPollers] as const);
|
||||
}
|
||||
|
||||
return makeRemoteRefreshLoop(cwd).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
fiber,
|
||||
subscriberCount: 1,
|
||||
});
|
||||
return [undefined, nextPollers] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
|
||||
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (!existing) {
|
||||
return [null, activePollers] as const;
|
||||
}
|
||||
|
||||
if (existing.subscriberCount > 1) {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount - 1,
|
||||
});
|
||||
return [null, nextPollers] as const;
|
||||
}
|
||||
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.delete(cwd);
|
||||
return [existing.fiber, nextPollers] as const;
|
||||
});
|
||||
|
||||
if (pollerToInterrupt) {
|
||||
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
|
||||
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
|
||||
yield* retainRemotePoller(normalizedCwd);
|
||||
|
||||
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
_tag: "snapshot" as const,
|
||||
local: initialLocal,
|
||||
remote: initialRemote,
|
||||
}),
|
||||
Stream.fromSubscription(subscription).pipe(
|
||||
Stream.filter((event) => event.cwd === normalizedCwd),
|
||||
Stream.map((event) => event.event),
|
||||
),
|
||||
).pipe(Stream.ensuring(release));
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
getStatus,
|
||||
refreshLocalStatus,
|
||||
refreshStatus,
|
||||
streamStatus,
|
||||
} satisfies GitStatusBroadcasterShape;
|
||||
}),
|
||||
);
|
||||
+5
-5
@@ -6,13 +6,13 @@ import { TestClock } from "effect/testing";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { beforeEach, expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../provider/opencodeRuntime.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
const runtimeMock = {
|
||||
@@ -158,7 +158,7 @@ const advanceIdleClock = Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
|
||||
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -306,7 +306,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
|
||||
"OpenCodeTextGeneration with configured server URL",
|
||||
"OpenCodeTextGenerationLive with configured server URL",
|
||||
(it) => {
|
||||
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
|
||||
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
+6
-6
@@ -10,21 +10,21 @@ import {
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
} from "../Prompts.ts";
|
||||
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
extractJsonObject,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
type OpenCodeServerConnection,
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
openCodeRuntimeErrorDetail,
|
||||
parseOpenCodeModelSlug,
|
||||
toOpenCodeFileParts,
|
||||
} from "../provider/opencodeRuntime.ts";
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
|
||||
+4
-4
@@ -5,11 +5,11 @@ import { describe, expect } from "vitest";
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import type { ProviderInstanceRegistryShape } from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { TextGenerationShape } from "./TextGeneration.ts";
|
||||
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
|
||||
import type { ProviderInstanceRegistryShape } from "../../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
|
||||
import { makeTextGenerationFromRegistry } from "./TextGeneration.ts";
|
||||
import { makeTextGenerationFromRegistry } from "./TextGenerationLive.ts";
|
||||
|
||||
const makeStubTextGeneration = (overrides: Partial<TextGenerationShape>): TextGenerationShape => ({
|
||||
generateCommitMessage: () =>
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* TextGenerationLive — registry-backed implementation of the `TextGeneration`
|
||||
* service tag.
|
||||
*
|
||||
* The `TextGeneration` tag is kept as a thin facade over
|
||||
* `ProviderInstanceRegistry`. Every op pulls `modelSelection.instanceId`,
|
||||
* looks up the matching `ProviderInstance`, and delegates to that instance's
|
||||
* own `textGeneration` closure (built by its driver's `create()`).
|
||||
*
|
||||
* There is deliberately no per-driver dispatch here — the registry already
|
||||
* knows which driver backs each instance, and each `ProviderInstance`
|
||||
* carries the fully-bound `TextGenerationShape` produced by its driver.
|
||||
* That means:
|
||||
*
|
||||
* - Multiple instances of the same driver (e.g. `codex_personal`,
|
||||
* `codex_work`) each get their own text-generation closure bound to
|
||||
* their own settings — the routing is by instance, not by driver.
|
||||
* - Unknown or disabled instances surface a `TextGenerationError` with
|
||||
* the missing `instanceId`, instead of silently falling back to a
|
||||
* default.
|
||||
*
|
||||
* This replaces the old `RoutingTextGenerationLive`, which tried to route
|
||||
* by driver-kind and misused `modelSelection.instanceId` as a driver-id
|
||||
* literal.
|
||||
*
|
||||
* @module git/Layers/TextGenerationLive
|
||||
*/
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import type { ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
ProviderInstanceRegistry,
|
||||
type ProviderInstanceRegistryShape,
|
||||
} from "../../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
|
||||
|
||||
type TextGenerationOp =
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
|
||||
const resolveInstance = (
|
||||
registry: ProviderInstanceRegistryShape,
|
||||
operation: TextGenerationOp,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance
|
||||
? Effect.succeed(instance.textGeneration)
|
||||
: Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `No provider instance registered for id '${instanceId}'.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Build a `TextGenerationShape` that routes every call through the
|
||||
* registry. Exposed separately from the Layer so tests can construct it
|
||||
* against a stub registry without layering gymnastics.
|
||||
*/
|
||||
export const makeTextGenerationFromRegistry = (
|
||||
registry: ProviderInstanceRegistryShape,
|
||||
): TextGenerationShape => ({
|
||||
generateCommitMessage: (input) =>
|
||||
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((tg) => tg.generateCommitMessage(input)),
|
||||
),
|
||||
generatePrContent: (input) =>
|
||||
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((tg) => tg.generatePrContent(input)),
|
||||
),
|
||||
generateBranchName: (input) =>
|
||||
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((tg) => tg.generateBranchName(input)),
|
||||
),
|
||||
generateThreadTitle: (input) =>
|
||||
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((tg) => tg.generateThreadTitle(input)),
|
||||
),
|
||||
});
|
||||
|
||||
/**
|
||||
* `TextGeneration` Layer wired to the `ProviderInstanceRegistry`. The rest
|
||||
* of the server keeps using `yield* TextGeneration` — only the underlying
|
||||
* wiring changed from kind-based routing to instance-based routing.
|
||||
*/
|
||||
export const TextGenerationLive = Layer.effect(
|
||||
TextGeneration,
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry;
|
||||
return makeTextGenerationFromRegistry(registry);
|
||||
}),
|
||||
);
|
||||
+2
-2
@@ -5,8 +5,8 @@ import {
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
|
||||
} from "./Prompts.ts";
|
||||
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
describe("buildCommitMessagePrompt", () => {
|
||||
+1
-17
@@ -9,13 +9,7 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { limitSection } from "./TextGenerationUtils.ts";
|
||||
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
|
||||
|
||||
function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
|
||||
const trimmed = instruction?.trim();
|
||||
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
|
||||
}
|
||||
import { limitSection } from "./Utils.ts";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Commit message
|
||||
@@ -26,7 +20,6 @@ export interface CommitMessagePromptInput {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
@@ -44,7 +37,6 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||
: []),
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
...policyInstruction(input.policy?.commitInstructions),
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
"",
|
||||
@@ -85,7 +77,6 @@ export interface PrContentPromptInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
@@ -97,7 +88,6 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
...policyInstruction(input.policy?.changeRequestInstructions),
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
@@ -127,7 +117,6 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
export interface BranchNamePromptInput {
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
interface PromptFromMessageInput {
|
||||
@@ -136,7 +125,6 @@ interface PromptFromMessageInput {
|
||||
rules: ReadonlyArray<string>;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
additionalInstructions?: string | undefined;
|
||||
}
|
||||
|
||||
function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
@@ -152,7 +140,6 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
|
||||
"",
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
...policyInstruction(input.additionalInstructions),
|
||||
];
|
||||
if (attachmentLines.length > 0) {
|
||||
promptSections.push(
|
||||
@@ -177,7 +164,6 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
||||
],
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
additionalInstructions: input.policy?.branchInstructions,
|
||||
});
|
||||
const outputSchema = Schema.Struct({
|
||||
branch: Schema.String,
|
||||
@@ -193,7 +179,6 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
|
||||
export interface ThreadTitlePromptInput {
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||
@@ -208,7 +193,6 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
|
||||
],
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
additionalInstructions: input.policy?.threadTitleInstructions,
|
||||
});
|
||||
const outputSchema = Schema.Struct({
|
||||
title: Schema.String,
|
||||
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* GitCore - Effect service contract for low-level Git operations.
|
||||
*
|
||||
* Wraps core repository primitives used by higher-level orchestration
|
||||
* services and WebSocket routes.
|
||||
*
|
||||
* @module GitCore
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCheckoutResult,
|
||||
GitCreateBranchInput,
|
||||
GitCreateBranchResult,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
GitPullResult,
|
||||
GitRemoveWorktreeInput,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface ExecuteGitProgress {
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitProgress {
|
||||
readonly onOutputLine?: (input: {
|
||||
stream: "stdout" | "stderr";
|
||||
text: string;
|
||||
}) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitOptions {
|
||||
readonly timeoutMs?: number;
|
||||
readonly progress?: GitCommitProgress;
|
||||
}
|
||||
|
||||
export interface GitPushResult {
|
||||
status: "pushed" | "skipped_up_to_date";
|
||||
branch: string;
|
||||
upstreamBranch?: string | undefined;
|
||||
setUpstream?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface GitRangeContext {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface GitListWorkspaceFilesResult {
|
||||
readonly paths: ReadonlyArray<string>;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchInput {
|
||||
cwd: string;
|
||||
oldBranch: string;
|
||||
newBranch: string;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchResult {
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface GitFetchPullRequestBranchInput {
|
||||
cwd: string;
|
||||
prNumber: number;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface GitEnsureRemoteInput {
|
||||
cwd: string;
|
||||
preferredName: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface GitFetchRemoteBranchInput {
|
||||
cwd: string;
|
||||
remoteName: string;
|
||||
remoteBranch: string;
|
||||
localBranch: string;
|
||||
}
|
||||
|
||||
export interface GitSetBranchUpstreamInput {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
remoteName: string;
|
||||
remoteBranch: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||
*/
|
||||
export interface GitCoreShape {
|
||||
/**
|
||||
* Execute a raw Git command.
|
||||
*/
|
||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read Git status for a repository.
|
||||
*/
|
||||
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read detailed working tree / branch status for a repository.
|
||||
*/
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read detailed working tree / branch status without refreshing remote tracking refs.
|
||||
*/
|
||||
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Build staged change context for commit generation.
|
||||
*/
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Create a commit with provided subject/body.
|
||||
*/
|
||||
readonly commit: (
|
||||
cwd: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
options?: GitCommitOptions,
|
||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Push current branch, setting upstream if needed.
|
||||
*/
|
||||
readonly pushCurrentBranch: (
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Collect commit/diff context between base branch and current HEAD.
|
||||
*/
|
||||
readonly readRangeContext: (
|
||||
cwd: string,
|
||||
baseBranch: string,
|
||||
) => Effect.Effect<GitRangeContext, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read a Git config value from the local repository.
|
||||
*/
|
||||
readonly readConfigValue: (
|
||||
cwd: string,
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Determine whether the provided cwd is inside a git work tree.
|
||||
*/
|
||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List tracked and untracked workspace file paths relative to cwd.
|
||||
*/
|
||||
readonly listWorkspaceFiles: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Remove gitignored paths from a relative path list.
|
||||
*/
|
||||
readonly filterIgnoredPaths: (
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local + remote branches and branch metadata.
|
||||
*/
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Pull current branch from upstream using fast-forward only.
|
||||
*/
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Create a worktree and branch from a base branch.
|
||||
*/
|
||||
readonly createWorktree: (
|
||||
input: GitCreateWorktreeInput,
|
||||
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Materialize a GitHub pull request head as a local branch without switching checkout.
|
||||
*/
|
||||
readonly fetchPullRequestBranch: (
|
||||
input: GitFetchPullRequestBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
|
||||
*/
|
||||
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Fetch a remote branch into a local branch without checkout.
|
||||
*/
|
||||
readonly fetchRemoteBranch: (
|
||||
input: GitFetchRemoteBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Set the upstream tracking branch for a local branch.
|
||||
*/
|
||||
readonly setBranchUpstream: (
|
||||
input: GitSetBranchUpstreamInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Remove an existing worktree.
|
||||
*/
|
||||
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Rename an existing local branch.
|
||||
*/
|
||||
readonly renameBranch: (
|
||||
input: GitRenameBranchInput,
|
||||
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Create a local branch.
|
||||
*/
|
||||
readonly createBranch: (
|
||||
input: GitCreateBranchInput,
|
||||
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (
|
||||
input: GitCheckoutInput,
|
||||
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
*/
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branch names (short format).
|
||||
*/
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitCore - Service tag for low-level Git repository operations.
|
||||
*/
|
||||
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* GitHubCli - Effect service contract for `gh` process interactions.
|
||||
*
|
||||
* Provides thin command execution helpers used by Git workflow orchestration.
|
||||
*
|
||||
* @module GitHubCli
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner.ts";
|
||||
import type { GitHubCliError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state?: "open" | "closed" | "merged";
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
export interface GitHubRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHubCliShape - Service API for executing GitHub CLI commands.
|
||||
*/
|
||||
export interface GitHubCliShape {
|
||||
/**
|
||||
* Execute a GitHub CLI command and return full process output.
|
||||
*/
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* List open pull requests for a head branch.
|
||||
*/
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Resolve a pull request by URL, number, or branch-ish identifier.
|
||||
*/
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Resolve clone URLs for a GitHub repository.
|
||||
*/
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Create a pull request from branch context and body file.
|
||||
*/
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Resolve repository default branch through GitHub metadata.
|
||||
*/
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Checkout a pull request into the current repository worktree.
|
||||
*/
|
||||
readonly checkoutPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, GitHubCliError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHubCli - Service tag for GitHub CLI process execution.
|
||||
*/
|
||||
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/git/Services/GitHubCli",
|
||||
) {}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* GitManager - Effect service contract for stacked Git workflows.
|
||||
*
|
||||
* Orchestrates status inspection and commit/push/PR flows by composing
|
||||
* lower-level Git and external tool services.
|
||||
*
|
||||
* @module GitManager
|
||||
*/
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
GitResolvePullRequestResult,
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusLocalResult,
|
||||
GitStatusRemoteResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitRunStackedActionOptions {
|
||||
readonly actionId?: string;
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManagerShape - Service API for high-level Git workflow actions.
|
||||
*/
|
||||
export interface GitManagerShape {
|
||||
/**
|
||||
* Read current repository Git status plus open PR metadata when available.
|
||||
*/
|
||||
readonly status: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Read local repository status without remote hosting enrichment.
|
||||
*/
|
||||
readonly localStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Read remote tracking / PR status for a repository.
|
||||
*/
|
||||
readonly remoteStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Clear any cached local status snapshot for a repository.
|
||||
*/
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Clear any cached remote status snapshot for a repository.
|
||||
*/
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Clear any cached status snapshot for a repository so the next read is fresh.
|
||||
*/
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
|
||||
/**
|
||||
* Resolve a pull request by URL/number against the current repository.
|
||||
*/
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Prepare a new thread workspace from a pull request in local or worktree mode.
|
||||
*/
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
|
||||
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*/
|
||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/Services/GitManager",
|
||||
) {}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type {
|
||||
GitManagerServiceError,
|
||||
GitStatusInput,
|
||||
GitStatusLocalResult,
|
||||
GitStatusResult,
|
||||
GitStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface GitStatusBroadcasterShape {
|
||||
readonly getStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: GitStatusInput,
|
||||
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitStatusBroadcaster extends Context.Service<
|
||||
GitStatusBroadcaster,
|
||||
GitStatusBroadcasterShape
|
||||
>()("t3/git/Services/GitStatusBroadcaster") {}
|
||||
+14
-62
@@ -1,13 +1,18 @@
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
/**
|
||||
* TextGeneration - Effect service contract for AI-generated Git content.
|
||||
*
|
||||
* Generates commit messages and pull request titles/bodies from repository
|
||||
* context prepared by Git services.
|
||||
*
|
||||
* @module TextGeneration
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
ProviderInstanceRegistry,
|
||||
type ProviderInstanceRegistryShape,
|
||||
} from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import type { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
@@ -114,58 +119,5 @@ export interface TextGenerationShape {
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
||||
"t3/text-generation/TextGeneration",
|
||||
"t3/git/Services/TextGeneration",
|
||||
) {}
|
||||
|
||||
type TextGenerationOp =
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
|
||||
const resolveInstance = (
|
||||
registry: ProviderInstanceRegistryShape,
|
||||
operation: TextGenerationOp,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance
|
||||
? Effect.succeed(instance.textGeneration)
|
||||
: Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `No provider instance registered for id '${instanceId}'.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const makeTextGenerationFromRegistry = (
|
||||
registry: ProviderInstanceRegistryShape,
|
||||
): TextGenerationShape => ({
|
||||
generateCommitMessage: (input) =>
|
||||
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),
|
||||
),
|
||||
generatePrContent: (input) =>
|
||||
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),
|
||||
),
|
||||
generateBranchName: (input) =>
|
||||
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),
|
||||
),
|
||||
generateThreadTitle: (input) =>
|
||||
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
|
||||
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
|
||||
),
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
TextGeneration,
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry;
|
||||
return makeTextGenerationFromRegistry(registry);
|
||||
}),
|
||||
);
|
||||
@@ -1,6 +1,171 @@
|
||||
/**
|
||||
* Shared utilities for text generation layers (Codex, Claude, etc.).
|
||||
*
|
||||
* @module textGenerationUtils
|
||||
*/
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
|
||||
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
|
||||
export function toJsonSchemaObject(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return { ...document.schema, $defs: document.definitions };
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
|
||||
export function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
export function extractJsonObject(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const start = trimmed.indexOf("{");
|
||||
if (start < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaping = false;
|
||||
for (let index = start; index < trimmed.length; index += 1) {
|
||||
const char = trimmed[index];
|
||||
if (inString) {
|
||||
if (escaping) {
|
||||
escaping = false;
|
||||
} else if (char === "\\") {
|
||||
escaping = true;
|
||||
} else if (char === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "{") {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
return trimmed.slice(start, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed.slice(start);
|
||||
}
|
||||
|
||||
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
|
||||
export function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
/** Normalise a raw PR title to a single line with a sensible fallback. */
|
||||
export function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
|
||||
export function sanitizeThreadTitle(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.split(/\r?\n/g)[0]
|
||||
?.trim()
|
||||
.replace(/^['"`]+|['"`]+$/g, "")
|
||||
.trim()
|
||||
.replace(/\s+/g, " ");
|
||||
|
||||
if (!normalized || normalized.trim().length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
if (normalized.length <= 50) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return `${normalized.slice(0, 47).trimEnd()}...`;
|
||||
}
|
||||
|
||||
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
|
||||
function cliLabel(cliName: string): string {
|
||||
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
|
||||
return `${capitalized} CLI (\`${cliName}\`)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an unknown error from a CLI text generation process into a
|
||||
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
|
||||
* and Claude (and future providers) can share the same logic.
|
||||
*/
|
||||
export function normalizeCliError(
|
||||
cliName: string,
|
||||
operation: string,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
error.message.includes(`Command not found: ${cliName}`) ||
|
||||
lower.includes(`spawn ${cliName}`) ||
|
||||
lower.includes("enoent")
|
||||
) {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${fallback}: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: fallback,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
|
||||
import { Cause, Exit, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface NormalizedGitHubPullRequestRecord {
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
||||
readonly updatedAt: string | null;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
@@ -23,7 +23,7 @@ const GitHubPullRequestSchema = Schema.Struct({
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
||||
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
@@ -80,7 +80,8 @@ function normalizeGitHubPullRequestRecord(
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizeGitHubPullRequestState(raw),
|
||||
updatedAt: raw.updatedAt ?? Option.none(),
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
|
||||
@@ -24,9 +24,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
@@ -283,7 +282,7 @@ describe("CheckpointReactor", () => {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-reactor-test-",
|
||||
});
|
||||
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
|
||||
const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
@@ -291,10 +290,9 @@ describe("CheckpointReactor", () => {
|
||||
}).pipe(
|
||||
Effect.as({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -307,16 +305,11 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(gitStatusBroadcasterLayer),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -24,7 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||
|
||||
type ReactorInput =
|
||||
@@ -70,7 +70,7 @@ const make = Effect.gen(function* () {
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
|
||||
const appendRevertFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -508,7 +508,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
|
||||
@@ -33,7 +33,12 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
@@ -47,8 +52,6 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
@@ -240,10 +243,9 @@ describe("ProviderCommandReactor", () => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "renamed-branch",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "renamed-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -322,19 +324,15 @@ describe("ProviderCommandReactor", () => {
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
renameBranch,
|
||||
} satisfies Partial<GitWorkflowServiceShape>),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
}),
|
||||
} satisfies GitStatusBroadcasterShape),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(TextGeneration, {
|
||||
|
||||
@@ -16,10 +16,12 @@ import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream }
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
@@ -27,8 +29,6 @@ import {
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -168,8 +168,8 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const git = yield* GitCore;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
@@ -587,7 +587,7 @@ const make = Effect.gen(function* () {
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return;
|
||||
|
||||
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
@@ -595,7 +595,7 @@ const make = Effect.gen(function* () {
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import type { RepositoryIdentity } from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, Exit, Layer } from "effect";
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
normalizeGitRemoteUrl,
|
||||
} from "@t3tools/shared/git";
|
||||
import { detectGitHostingProviderFromRemoteUrl, normalizeGitRemoteUrl } from "@t3tools/shared/git";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import {
|
||||
@@ -48,7 +45,7 @@ function buildRepositoryIdentity(input: {
|
||||
readonly rootPath: string;
|
||||
}): RepositoryIdentity {
|
||||
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
|
||||
const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
|
||||
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
|
||||
const repositoryPath = canonicalKey.split("/").slice(1).join("/");
|
||||
const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
|
||||
const [owner] = repositoryPathSegments;
|
||||
@@ -63,7 +60,7 @@ function buildRepositoryIdentity(input: {
|
||||
},
|
||||
rootPath: input.rootPath,
|
||||
...(repositoryPath ? { displayName: repositoryPath } : {}),
|
||||
...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
|
||||
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
|
||||
...(owner ? { owner } : {}),
|
||||
...(repositoryName ? { name: repositoryName } : {}),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
AcpRegistrySettings,
|
||||
ProviderDriverKind,
|
||||
TextGenerationError,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
type ProviderInstance,
|
||||
} from "../ProviderDriver.ts";
|
||||
import {
|
||||
buildServerProvider,
|
||||
providerModelsFromSettings,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
|
||||
|
||||
export type AcpRegistryDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
|
||||
const unsupportedTextGeneration = (operation: string) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Generic ACP providers do not support git text generation yet.",
|
||||
}),
|
||||
);
|
||||
|
||||
const makeTextGeneration = () => ({
|
||||
generateCommitMessage: () => unsupportedTextGeneration("generateCommitMessage"),
|
||||
generatePrContent: () => unsupportedTextGeneration("generatePrContent"),
|
||||
generateBranchName: () => unsupportedTextGeneration("generateBranchName"),
|
||||
generateThreadTitle: () => unsupportedTextGeneration("generateThreadTitle"),
|
||||
});
|
||||
|
||||
function withIdentity(input: {
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) {
|
||||
return (snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
...snapshot,
|
||||
instanceId: input.instanceId,
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
}
|
||||
|
||||
function initialSnapshot(settings: AcpRegistrySettings): ServerProviderDraft {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const command = settings.command.trim();
|
||||
const enabled = settings.enabled && command.length > 0;
|
||||
return buildServerProvider({
|
||||
presentation: {
|
||||
displayName: "ACP Registry",
|
||||
badgeLabel: "ACP",
|
||||
showInteractionModeToggle: true,
|
||||
},
|
||||
enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[{ slug: "default", name: "Default", isCustom: false, capabilities: null }],
|
||||
DRIVER_KIND,
|
||||
settings.customModels,
|
||||
{ optionDescriptors: [] },
|
||||
),
|
||||
probe: {
|
||||
installed: enabled,
|
||||
version: null,
|
||||
status: enabled ? "ready" : "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: enabled ? "ACP provider configured." : "Configure a launch command to enable.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDriverEnv> = {
|
||||
driverKind: DRIVER_KIND,
|
||||
metadata: {
|
||||
displayName: "ACP Registry",
|
||||
supportsMultipleInstances: true,
|
||||
},
|
||||
configSchema: AcpRegistrySettings,
|
||||
defaultConfig: (): AcpRegistrySettings => Schema.decodeSync(AcpRegistrySettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const effectiveConfig = { ...config, enabled: enabled && config.enabled };
|
||||
const effectiveIconUrl = iconUrl ?? effectiveConfig.iconUrl;
|
||||
const processEnv = {
|
||||
...effectiveConfig.env,
|
||||
...mergeProviderInstanceEnvironment(environment),
|
||||
};
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const stamp = withIdentity({
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl: effectiveIconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
|
||||
const adapter = yield* makeCursorAdapter(
|
||||
{
|
||||
enabled: effectiveConfig.enabled,
|
||||
binaryPath: effectiveConfig.command || "acp",
|
||||
apiEndpoint: "",
|
||||
customModels: effectiveConfig.customModels,
|
||||
},
|
||||
{
|
||||
provider: DRIVER_KIND,
|
||||
instanceId,
|
||||
environment: processEnv,
|
||||
readyReason: "ACP session ready",
|
||||
applyCursorModelOptions: false,
|
||||
normalizeModel: (model) => model?.trim() || "default",
|
||||
authMethodId: "none",
|
||||
clientCapabilities: {},
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
spawn: ({ cwd, environment: spawnEnv }) => ({
|
||||
command: effectiveConfig.command.trim(),
|
||||
args: effectiveConfig.args,
|
||||
cwd,
|
||||
...(spawnEnv ? { env: spawnEnv } : {}),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<AcpRegistrySettings>({
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stamp(initialSnapshot(settings)),
|
||||
checkProvider: Effect.succeed(stamp(initialSnapshot(effectiveConfig))),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: `Failed to build ACP Registry snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
instanceId,
|
||||
driverKind: DRIVER_KIND,
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl: effectiveIconUrl,
|
||||
enabled: effectiveConfig.enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
textGeneration: makeTextGeneration(),
|
||||
} satisfies ProviderInstance;
|
||||
}),
|
||||
};
|
||||
@@ -16,7 +16,7 @@ import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tool
|
||||
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import { makeClaudeTextGeneration } from "../../git/Layers/ClaudeTextGeneration.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
@@ -52,6 +52,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -60,6 +61,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -71,7 +73,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
},
|
||||
configSchema: ClaudeSettings,
|
||||
defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
@@ -87,6 +89,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey,
|
||||
});
|
||||
|
||||
@@ -148,6 +151,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
},
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -25,7 +25,7 @@ import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import { makeCodexTextGeneration } from "../../git/Layers/CodexTextGeneration.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
@@ -67,6 +67,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -75,6 +76,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -86,7 +88,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
},
|
||||
configSchema: CodexSettings,
|
||||
defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
@@ -97,6 +99,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
yield* materializeCodexShadowHome(homeLayout).pipe(
|
||||
@@ -162,6 +165,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -17,7 +17,7 @@ import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
import { makeCursorTextGeneration } from "../../git/Layers/CursorTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
import {
|
||||
@@ -50,6 +50,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -58,6 +59,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -69,7 +71,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
},
|
||||
configSchema: CursorSettings,
|
||||
defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -84,6 +86,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
|
||||
@@ -139,6 +142,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -16,7 +16,7 @@ import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3to
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import { makeOpenCodeTextGeneration } from "../../git/Layers/OpenCodeTextGeneration.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
@@ -51,6 +51,7 @@ const withInstanceIdentity =
|
||||
readonly instanceId: ProviderInstance["instanceId"];
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor: string | undefined;
|
||||
readonly iconUrl: string | undefined;
|
||||
readonly continuationGroupKey: string;
|
||||
}) =>
|
||||
(snapshot: ServerProviderDraft): ServerProvider => ({
|
||||
@@ -59,6 +60,7 @@ const withInstanceIdentity =
|
||||
driver: DRIVER_KIND,
|
||||
...(input.displayName ? { displayName: input.displayName } : {}),
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
continuation: { groupKey: input.continuationGroupKey },
|
||||
});
|
||||
|
||||
@@ -70,7 +72,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
},
|
||||
configSchema: OpenCodeSettings,
|
||||
defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
@@ -84,6 +86,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
instanceId,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
|
||||
@@ -126,6 +129,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
continuationIdentity,
|
||||
displayName,
|
||||
accentColor,
|
||||
iconUrl,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
|
||||
@@ -87,6 +87,22 @@ export interface CursorAdapterLiveOptions {
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
readonly provider?: ProviderDriverKind;
|
||||
readonly readyReason?: string;
|
||||
readonly spawn?: (input: {
|
||||
readonly settings: CursorSettings;
|
||||
readonly cwd: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) => {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
};
|
||||
readonly normalizeModel?: (model: string | null | undefined) => string;
|
||||
readonly applyCursorModelOptions?: boolean;
|
||||
readonly authMethodId?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
/**
|
||||
* Selections are honored when `modelSelection.instanceId` matches this value.
|
||||
* Defaults to the legacy built-in instance id (`cursor`).
|
||||
@@ -244,6 +260,8 @@ function applyRequestedSessionConfiguration<E>(input: {
|
||||
readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly normalizeModel: (model: string | null | undefined) => string;
|
||||
readonly applyCursorModelOptions: boolean;
|
||||
readonly mapError: (context: {
|
||||
readonly cause: import("effect-acp/errors").AcpError;
|
||||
readonly method: "session/set_config_option" | "session/set_mode";
|
||||
@@ -251,16 +269,30 @@ function applyRequestedSessionConfiguration<E>(input: {
|
||||
}): Effect.Effect<void, E> {
|
||||
return Effect.gen(function* () {
|
||||
if (input.modelSelection) {
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime: input.runtime,
|
||||
model: input.modelSelection.model,
|
||||
selections: input.modelSelection.options,
|
||||
mapError: ({ cause }) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
});
|
||||
if (input.applyCursorModelOptions) {
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime: input.runtime,
|
||||
model: input.modelSelection.model,
|
||||
selections: input.modelSelection.options,
|
||||
mapError: ({ cause }) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
const normalizedModel = input.normalizeModel(input.modelSelection.model);
|
||||
if (normalizedModel !== "default") {
|
||||
yield* input.runtime.setModel(normalizedModel).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const requestedModeId = resolveRequestedModeId({
|
||||
@@ -304,6 +336,10 @@ export function makeCursorAdapter(
|
||||
options?: CursorAdapterLiveOptions,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providerKind = options?.provider ?? PROVIDER;
|
||||
const readyReason = options?.readyReason ?? "Cursor ACP session ready";
|
||||
const normalizeModel = options?.normalizeModel ?? resolveCursorAcpBaseModelId;
|
||||
const applyCursorModelOptions = options?.applyCursorModelOptions ?? true;
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
@@ -365,7 +401,7 @@ export function makeCursorAdapter(
|
||||
event: {
|
||||
id: crypto.randomUUID(),
|
||||
kind: "notification",
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
createdAt: observedAt,
|
||||
method,
|
||||
threadId,
|
||||
@@ -398,7 +434,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload,
|
||||
@@ -415,7 +451,7 @@ export function makeCursorAdapter(
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
|
||||
new ProviderAdapterSessionNotFoundError({ provider: providerKind, threadId }),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(ctx);
|
||||
@@ -435,7 +471,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
payload: { exitKind: "graceful" },
|
||||
});
|
||||
@@ -445,16 +481,16 @@ export function makeCursorAdapter(
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
if (input.provider !== undefined && input.provider !== providerKind) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
issue: `Expected provider '${providerKind}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
@@ -480,7 +516,7 @@ export function makeCursorAdapter(
|
||||
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
@@ -499,17 +535,30 @@ export function makeCursorAdapter(
|
||||
const acp = yield* makeCursorAcpRuntime({
|
||||
cursorSettings: effectiveCursorSettings,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
...(options?.spawn
|
||||
? {
|
||||
spawn: options.spawn({
|
||||
settings: effectiveCursorSettings,
|
||||
cwd,
|
||||
...(options.environment ? { environment: options.environment } : {}),
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(options?.authMethodId ? { authMethodId: options.authMethodId } : {}),
|
||||
...(options?.clientCapabilities
|
||||
? { clientCapabilities: options.clientCapabilities }
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
@@ -532,7 +581,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
@@ -548,7 +597,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
@@ -568,7 +617,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
payload: { planMarkdown: extractPlanMarkdown(params) },
|
||||
@@ -633,7 +682,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
@@ -650,7 +699,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
@@ -672,7 +721,7 @@ export function makeCursorAdapter(
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
|
||||
mapAcpToAdapterError(providerKind, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -681,13 +730,15 @@ export function makeCursorAdapter(
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: undefined,
|
||||
modelSelection: cursorModelSelection,
|
||||
normalizeModel,
|
||||
applyCursorModelOptions,
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
mapAcpToAdapterError(providerKind, input.threadId, method, cause),
|
||||
});
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
providerInstanceId: boundInstanceId,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
@@ -726,7 +777,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
@@ -738,7 +789,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
@@ -771,7 +822,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
@@ -789,7 +840,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
@@ -810,21 +861,21 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: "Cursor ACP session ready" },
|
||||
payload: { state: "ready", reason: readyReason },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
@@ -840,7 +891,7 @@ export function makeCursorAdapter(
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
const resolvedModel = normalizeModel(model);
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
@@ -852,8 +903,10 @@ export function makeCursorAdapter(
|
||||
model,
|
||||
options: turnModelSelection?.options,
|
||||
},
|
||||
normalizeModel,
|
||||
applyCursorModelOptions,
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
mapAcpToAdapterError(providerKind, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
@@ -866,7 +919,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
@@ -884,7 +937,7 @@ export function makeCursorAdapter(
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
@@ -893,7 +946,7 @@ export function makeCursorAdapter(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
@@ -910,7 +963,7 @@ export function makeCursorAdapter(
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
@@ -922,7 +975,7 @@ export function makeCursorAdapter(
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
mapAcpToAdapterError(providerKind, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -937,7 +990,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
@@ -961,7 +1014,7 @@ export function makeCursorAdapter(
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
mapAcpToAdapterError(providerKind, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -977,7 +1030,7 @@ export function makeCursorAdapter(
|
||||
const pending = ctx.pendingApprovals.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
method: "session/request_permission",
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
@@ -995,7 +1048,7 @@ export function makeCursorAdapter(
|
||||
const pending = ctx.pendingUserInputs.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
method: "cursor/ask_question",
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
@@ -1014,7 +1067,7 @@ export function makeCursorAdapter(
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
@@ -1055,7 +1108,7 @@ export function makeCursorAdapter(
|
||||
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
provider: providerKind,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
|
||||
@@ -14,7 +14,7 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import type { TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
|
||||
@@ -120,6 +120,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
reason: `Driver '${entry.driver}' is not registered in this build.`,
|
||||
}),
|
||||
};
|
||||
@@ -142,6 +143,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
|
||||
}),
|
||||
};
|
||||
@@ -161,6 +163,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
environment: entry.environment ?? [],
|
||||
enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
|
||||
config: typedConfig,
|
||||
@@ -180,6 +183,7 @@ const buildEntry = <R>(input: {
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
iconUrl: entry.iconUrl,
|
||||
reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -28,7 +28,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import type { Effect, Schema, Scope } from "effect";
|
||||
|
||||
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
|
||||
import type { TextGenerationShape } from "../git/Services/TextGeneration.ts";
|
||||
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
@@ -65,6 +65,7 @@ export interface ProviderInstance {
|
||||
readonly continuationIdentity: ProviderContinuationIdentity;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly snapshot: ServerProviderShape;
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
@@ -96,6 +97,7 @@ export interface ProviderDriverCreateInput<Config> {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly environment: ProviderInstanceEnvironment;
|
||||
readonly enabled: boolean;
|
||||
readonly config: Config;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export class AcpRegistryClientError extends Schema.TaggedErrorClass<AcpRegistryClientError>()(
|
||||
"AcpRegistryClientError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/cont
|
||||
import { Effect, Layer, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import {
|
||||
CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
@@ -24,6 +25,9 @@ export interface CursorAcpRuntimeInput extends Omit<
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly spawn?: AcpSpawnInput;
|
||||
readonly authMethodId?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
}
|
||||
|
||||
export interface CursorAcpModelSelectionErrorContext {
|
||||
@@ -55,9 +59,12 @@ export const makeCursorAcpRuntime = (
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),
|
||||
authMethodId: "cursor_login",
|
||||
clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
spawn:
|
||||
input.spawn ??
|
||||
buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),
|
||||
authMethodId: input.authMethodId ?? "cursor_login",
|
||||
clientCapabilities:
|
||||
input.clientCapabilities ?? CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
|
||||
@@ -24,6 +24,7 @@ import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
|
||||
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
|
||||
import { AcpRegistryDriver, type AcpRegistryDriverEnv } from "./Drivers/AcpRegistryDriver.ts";
|
||||
import type { AnyProviderDriver } from "./ProviderDriver.ts";
|
||||
|
||||
/**
|
||||
@@ -35,7 +36,8 @@ export type BuiltInDriversEnv =
|
||||
| ClaudeDriverEnv
|
||||
| CodexDriverEnv
|
||||
| CursorDriverEnv
|
||||
| OpenCodeDriverEnv;
|
||||
| OpenCodeDriverEnv
|
||||
| AcpRegistryDriverEnv;
|
||||
|
||||
/**
|
||||
* Ordered list of built-in drivers. Order matters only for tie-breaking in
|
||||
@@ -47,4 +49,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
|
||||
ClaudeDriver,
|
||||
CursorDriver,
|
||||
OpenCodeDriver,
|
||||
AcpRegistryDriver,
|
||||
];
|
||||
@@ -33,6 +33,7 @@ export interface ProviderProbeResult {
|
||||
|
||||
export interface ServerProviderPresentation {
|
||||
readonly displayName: string;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly badgeLabel?: string;
|
||||
readonly showInteractionModeToggle?: boolean;
|
||||
}
|
||||
@@ -192,6 +193,7 @@ export function buildServerProvider(input: {
|
||||
}): ServerProviderDraft {
|
||||
return {
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.iconUrl ? { iconUrl: input.presentation.iconUrl } : {}),
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
...(typeof input.presentation.showInteractionModeToggle === "boolean"
|
||||
? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface UnavailableProviderSnapshotInput {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly displayName?: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly iconUrl?: string | undefined;
|
||||
readonly reason: string;
|
||||
/**
|
||||
* Optional override for `checkedAt`. Defaulted to `new Date()` so callers
|
||||
@@ -62,6 +63,7 @@ export function buildUnavailableProviderSnapshot(
|
||||
...base,
|
||||
instanceId: input.instanceId,
|
||||
...(input.accentColor ? { accentColor: input.accentColor } : {}),
|
||||
...(input.iconUrl ? { iconUrl: input.iconUrl } : {}),
|
||||
driver:
|
||||
typeof input.driverKind === "string"
|
||||
? ProviderDriverKind.make(input.driverKind)
|
||||
|
||||
+124
-236
@@ -29,7 +29,6 @@ import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
|
||||
import {
|
||||
Deferred,
|
||||
DateTime,
|
||||
Duration,
|
||||
Effect,
|
||||
FileSystem,
|
||||
@@ -39,7 +38,6 @@ import {
|
||||
Path,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpBody,
|
||||
@@ -52,8 +50,6 @@ import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
import { vi } from "vitest";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
import type { ServerConfigShape } from "./config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "./config.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
@@ -62,7 +58,13 @@ import {
|
||||
CheckpointDiffQuery,
|
||||
type CheckpointDiffQueryShape,
|
||||
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/GitManager.ts";
|
||||
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "./git/Services/GitStatusBroadcaster.ts";
|
||||
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
|
||||
import { Open, type OpenShape } from "./open.ts";
|
||||
import {
|
||||
@@ -103,19 +105,6 @@ import {
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import type { VcsDriverShape } from "./vcs/VcsDriver.ts";
|
||||
import {
|
||||
VcsStatusBroadcaster,
|
||||
type VcsStatusBroadcasterShape,
|
||||
layer as VcsStatusBroadcasterLayer,
|
||||
} from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import {
|
||||
VcsDriverRegistry,
|
||||
type VcsDriverRegistryShape,
|
||||
type VcsDriverHandle,
|
||||
} from "./vcs/VcsDriverRegistry.ts";
|
||||
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
|
||||
@@ -206,6 +195,16 @@ const makeDefaultOrchestrationThreadShell = (
|
||||
};
|
||||
};
|
||||
|
||||
const workspaceAndProjectServicesLayer = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
|
||||
WorkspaceFileSystemLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
),
|
||||
ProjectFaviconResolverLive,
|
||||
);
|
||||
|
||||
const browserOtlpTracingLayer = Layer.mergeAll(
|
||||
FetchHttpClient.layer,
|
||||
OtlpSerialization.layerJson,
|
||||
@@ -325,11 +324,9 @@ const buildAppUnderTest = (options?: {
|
||||
providerRegistry?: Partial<ProviderRegistryShape>;
|
||||
serverSettings?: Partial<ServerSettingsShape>;
|
||||
open?: Partial<OpenShape>;
|
||||
vcsDriver?: Partial<VcsDriverShape>;
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
gitCore?: Partial<GitCoreShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
|
||||
gitStatusBroadcaster?: Partial<GitStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
@@ -375,108 +372,22 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.config,
|
||||
};
|
||||
const layerConfig = Layer.succeed(ServerConfig, config);
|
||||
const defaultVcsDriver: VcsDriverShape = {
|
||||
capabilities: {
|
||||
kind: "git",
|
||||
supportsWorktrees: true,
|
||||
supportsBookmarks: false,
|
||||
supportsAtomicSnapshot: false,
|
||||
supportsPushDefaultRemote: true,
|
||||
ignoreClassifier: "native",
|
||||
},
|
||||
execute: () =>
|
||||
Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
detectRepository: () => Effect.succeed(null),
|
||||
const gitCoreLayer = Layer.mock(GitCore)({
|
||||
isInsideWorkTree: () => Effect.succeed(false),
|
||||
listWorkspaceFiles: () =>
|
||||
Effect.succeed({
|
||||
paths: [],
|
||||
truncated: false,
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
listRemotes: () =>
|
||||
Effect.succeed({
|
||||
remotes: [],
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
|
||||
...options?.layers?.vcsDriver,
|
||||
};
|
||||
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
detect: (input) =>
|
||||
defaultVcsDriver.detectRepository(input.cwd).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
repository
|
||||
? Effect.succeed(repository)
|
||||
: defaultVcsDriver.isInsideWorkTree(input.cwd).pipe(
|
||||
Effect.map((isInsideWorkTree) =>
|
||||
isInsideWorkTree
|
||||
? {
|
||||
kind: "git" as const,
|
||||
rootPath: input.cwd,
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((repository) =>
|
||||
repository
|
||||
? ({
|
||||
kind: repository.kind,
|
||||
repository,
|
||||
driver: defaultVcsDriver,
|
||||
} satisfies VcsDriverHandle)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
resolve: (input) =>
|
||||
Effect.succeed({
|
||||
kind:
|
||||
input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind,
|
||||
repository: {
|
||||
kind:
|
||||
input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind,
|
||||
rootPath: input.cwd,
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
},
|
||||
driver: defaultVcsDriver,
|
||||
}),
|
||||
...options?.layers?.vcsDriverRegistry,
|
||||
});
|
||||
const gitVcsDriverLayer = Layer.mock(GitVcsDriver.GitVcsDriver)({
|
||||
...options?.layers?.gitVcsDriver,
|
||||
...options?.layers?.gitCore,
|
||||
});
|
||||
const gitManagerLayer = Layer.mock(GitManager)({
|
||||
...options?.layers?.gitManager,
|
||||
});
|
||||
const workspaceEntriesLayer = WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(vcsDriverRegistryLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
);
|
||||
const workspaceAndProjectServicesLayer = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
@@ -487,16 +398,11 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
ProjectFaviconResolverLive,
|
||||
);
|
||||
const gitWorkflowLayer = GitWorkflowServiceLayer.pipe(
|
||||
Layer.provideMerge(vcsDriverRegistryLayer),
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provideMerge(gitManagerLayer),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster)({
|
||||
...options.layers.vcsStatusBroadcaster,
|
||||
const gitStatusBroadcasterLayer = options?.layers?.gitStatusBroadcaster
|
||||
? Layer.mock(GitStatusBroadcaster)({
|
||||
...options.layers.gitStatusBroadcaster,
|
||||
})
|
||||
: VcsStatusBroadcasterLayer.pipe(Layer.provide(gitWorkflowLayer));
|
||||
: GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -535,10 +441,9 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.open,
|
||||
}),
|
||||
),
|
||||
Layer.provide(gitCoreLayer),
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provideMerge(gitStatusBroadcasterLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectSetupScriptRunner)({
|
||||
runForThread: () => Effect.succeed({ status: "no-script" as const }),
|
||||
@@ -2163,17 +2068,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
gitCore: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
listWorkspaceFiles: () =>
|
||||
Effect.succeed({
|
||||
paths: ["src/tracked.ts"],
|
||||
truncated: false,
|
||||
freshness: {
|
||||
source: "live-local",
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) =>
|
||||
Effect.succeed(
|
||||
@@ -2373,10 +2273,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2390,10 +2289,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
status: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -2474,16 +2372,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
worktreePath: null,
|
||||
}),
|
||||
},
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
pullCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
status: "pulled",
|
||||
refName: "main",
|
||||
upstreamRef: "origin/main",
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
}),
|
||||
listRefs: () =>
|
||||
listBranches: () =>
|
||||
Effect.succeed({
|
||||
refs: [
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -2492,17 +2390,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
],
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
}),
|
||||
createWorktree: () =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/tmp/wt", refName: "feature/demo" },
|
||||
worktree: { path: "/tmp/wt", branch: "feature/demo" },
|
||||
}),
|
||||
removeWorktree: () => Effect.void,
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
createBranch: (input) => Effect.succeed({ branch: input.branch }),
|
||||
checkoutBranch: (input) => Effect.succeed({ branch: input.branch }),
|
||||
initRepo: () => Effect.void,
|
||||
},
|
||||
},
|
||||
@@ -2511,13 +2409,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
|
||||
const pull = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })),
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
|
||||
);
|
||||
assert.equal(pull.status, "pulled");
|
||||
|
||||
const refreshedStatus = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsRefreshStatus]({ cwd: "/tmp/repo" }),
|
||||
client[WS_METHODS.gitRefreshStatus]({ cwd: "/tmp/repo" }),
|
||||
),
|
||||
);
|
||||
assert.equal(refreshedStatus.isRepo, true);
|
||||
@@ -2561,25 +2459,27 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
assert.equal(prepared.branch, "feature/demo");
|
||||
|
||||
const refs = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsListRefs]({ cwd: "/tmp/repo" })),
|
||||
const branches = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.gitListBranches]({ cwd: "/tmp/repo" }),
|
||||
),
|
||||
);
|
||||
assert.equal(refs.refs[0]?.name, "main");
|
||||
assert.equal(branches.branches[0]?.name, "main");
|
||||
|
||||
const worktree = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsCreateWorktree]({
|
||||
client[WS_METHODS.gitCreateWorktree]({
|
||||
cwd: "/tmp/repo",
|
||||
refName: "main",
|
||||
branch: "main",
|
||||
path: null,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(worktree.worktree.refName, "feature/demo");
|
||||
assert.equal(worktree.worktree.branch, "feature/demo");
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsRemoveWorktree]({
|
||||
client[WS_METHODS.gitRemoveWorktree]({
|
||||
cwd: "/tmp/repo",
|
||||
path: "/tmp/wt",
|
||||
}),
|
||||
@@ -2588,25 +2488,25 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsCreateRef]({
|
||||
client[WS_METHODS.gitCreateBranch]({
|
||||
cwd: "/tmp/repo",
|
||||
refName: "feature/new",
|
||||
branch: "feature/new",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsSwitchRef]({
|
||||
client[WS_METHODS.gitCheckout]({
|
||||
cwd: "/tmp/repo",
|
||||
refName: "main",
|
||||
branch: "main",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.vcsInit]({
|
||||
client[WS_METHODS.gitInit]({
|
||||
cwd: "/tmp/repo",
|
||||
}),
|
||||
),
|
||||
@@ -2626,7 +2526,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
let statusCalls = 0;
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
pullCurrentBranch: () => Effect.fail(gitError),
|
||||
},
|
||||
gitManager: {
|
||||
@@ -2645,10 +2545,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2667,10 +2566,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -2685,7 +2583,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })).pipe(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })).pipe(
|
||||
Effect.result,
|
||||
),
|
||||
);
|
||||
@@ -2724,10 +2622,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2746,10 +2643,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
@@ -2784,12 +2680,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
pullCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
status: "pulled" as const,
|
||||
refName: "main",
|
||||
upstreamRef: "origin/main",
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
}),
|
||||
},
|
||||
gitManager: {
|
||||
@@ -2798,10 +2694,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2821,7 +2716,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const startedAt = Date.now();
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })),
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
|
||||
);
|
||||
const elapsedMs = Date.now() - startedAt;
|
||||
|
||||
@@ -2842,10 +2737,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -2919,10 +2813,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.andThen(
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -3586,10 +3479,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "t3code/bootstrap-refName",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "t3code/bootstrap-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -3602,14 +3494,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const createWorktree = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
|
||||
@@ -3624,10 +3515,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
vcsStatusBroadcaster: {
|
||||
gitStatusBroadcaster: {
|
||||
refreshStatus,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
@@ -3675,7 +3566,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -3697,8 +3588,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
refName: "main",
|
||||
newRefName: "t3code/bootstrap-refName",
|
||||
branch: "main",
|
||||
newBranch: "t3code/bootstrap-branch",
|
||||
path: null,
|
||||
});
|
||||
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
|
||||
@@ -3728,14 +3619,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
|
||||
@@ -3744,7 +3634,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
@@ -3792,7 +3682,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -3822,14 +3712,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
|
||||
@@ -3845,7 +3734,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
@@ -3909,7 +3798,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -3941,14 +3830,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
it.effect("cleans up created bootstrap threads when worktree creation defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.die(new Error("worktree exploded")),
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.die(new Error("worktree exploded")),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
@@ -3993,7 +3881,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: false,
|
||||
},
|
||||
|
||||
+18
-47
@@ -25,11 +25,13 @@ import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReap
|
||||
import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
|
||||
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore.ts";
|
||||
import { GitHubCliLive } from "./git/Layers/GitHubCli.ts";
|
||||
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
|
||||
import { TextGenerationLive } from "./git/Layers/TextGenerationLive.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
|
||||
import * as GitManager from "./git/GitManager.ts";
|
||||
import { GitManagerLive } from "./git/Layers/GitManager.ts";
|
||||
import { KeybindingsLive } from "./keybindings.ts";
|
||||
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup.ts";
|
||||
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
|
||||
@@ -45,13 +47,6 @@ import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdent
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
|
||||
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
|
||||
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
|
||||
@@ -138,6 +133,11 @@ const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
);
|
||||
|
||||
const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointDiffQueryLive),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
@@ -155,49 +155,24 @@ const ProviderLayerLive = ProviderServiceLive.pipe(
|
||||
|
||||
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
|
||||
|
||||
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProjectConfig.layer),
|
||||
);
|
||||
|
||||
const GitManagerLayerLive = GitManager.layer.pipe(
|
||||
const GitManagerLayerLive = GitManagerLive.pipe(
|
||||
Layer.provideMerge(ProjectSetupScriptRunnerLive),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(
|
||||
SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(GitHubCli.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(TextGeneration.layer),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(TextGenerationLive),
|
||||
);
|
||||
|
||||
const GitLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(GitManagerLayerLive),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
);
|
||||
|
||||
const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointDiffQueryLive),
|
||||
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
);
|
||||
|
||||
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
|
||||
|
||||
const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
);
|
||||
|
||||
const WorkspaceFileSystemLayerLive = WorkspaceFileSystemLive.pipe(
|
||||
@@ -221,11 +196,10 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
);
|
||||
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(VcsLayerLive),
|
||||
Layer.provideMerge(ProviderRuntimeLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
@@ -255,9 +229,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(ServerEnvironmentLive),
|
||||
Layer.provideMerge(AuthLayerLive),
|
||||
);
|
||||
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
@@ -338,7 +310,6 @@ export const makeServerLayer = Layer.unwrap(
|
||||
Layer.provideMerge(HttpServerLive),
|
||||
Layer.provide(ObservabilityLive),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(PlatformServicesLive),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
|
||||
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
|
||||
const processResult = (stdout: string) => ({
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
function makeProvider(github: Partial<GitHubCliShape>) {
|
||||
return GitHubSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitHubCli)(github)));
|
||||
}
|
||||
|
||||
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
getPullRequest: () =>
|
||||
Effect.succeed({
|
||||
number: 42,
|
||||
title: "Add GitHub provider",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
}),
|
||||
});
|
||||
|
||||
const changeRequest = yield* provider.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequest, {
|
||||
provider: "github",
|
||||
number: 42,
|
||||
title: "Add GitHub provider",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses gh json listing for non-open change request state queries", () =>
|
||||
Effect.gen(function* () {
|
||||
let executeArgs: ReadonlyArray<string> = [];
|
||||
const provider = yield* makeProvider({
|
||||
execute: (input) => {
|
||||
executeArgs = input.args;
|
||||
return Effect.succeed(
|
||||
processResult(
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 7,
|
||||
title: "Merged work",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/7",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/merged",
|
||||
state: "merged",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const changeRequests = yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/merged",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(executeArgs, [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
"feature/merged",
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"10",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
]);
|
||||
assert.strictEqual(changeRequests[0]?.provider, "github");
|
||||
assert.strictEqual(changeRequests[0]?.state, "merged");
|
||||
assert.deepStrictEqual(
|
||||
changeRequests[0]?.updatedAt,
|
||||
Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("treats empty non-open change request listing output as no results", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
execute: () => Effect.succeed(processResult("")),
|
||||
});
|
||||
|
||||
const changeRequests = yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/empty",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequests, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates GitHub PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<GitHubCliShape["createPullRequest"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
createPullRequest: (input) => {
|
||||
createInput = input;
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.createChangeRequest({
|
||||
cwd: "/repo",
|
||||
baseRefName: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(createInput, {
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,145 +0,0 @@
|
||||
import { Effect, Layer, Option, Result, Schema } from "effect";
|
||||
import {
|
||||
SourceControlProviderError,
|
||||
type ChangeRequest,
|
||||
type ChangeRequestState,
|
||||
type GitHubCliError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "./GitHubCli.ts";
|
||||
import { decodeGitHubPullRequestListJson } from "../git/githubPullRequests.ts";
|
||||
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
|
||||
|
||||
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "github",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state ?? "open",
|
||||
updatedAt: Option.none(),
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
...(summary.headRepositoryNameWithOwner !== undefined
|
||||
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
|
||||
: {}),
|
||||
...(summary.headRepositoryOwnerLogin !== undefined
|
||||
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
const github = yield* GitHubCli;
|
||||
|
||||
const listChangeRequests: SourceControlProviderShape["listChangeRequests"] = (input) => {
|
||||
if (input.state === "open") {
|
||||
return github
|
||||
.listOpenPullRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
}
|
||||
|
||||
const stateArg: ChangeRequestState | "all" = input.state;
|
||||
return github
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headSelector,
|
||||
"--state",
|
||||
stateArg,
|
||||
"--limit",
|
||||
String(input.limit ?? 20),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return Effect.succeed([]);
|
||||
}
|
||||
return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) =>
|
||||
Result.isSuccess(decoded)
|
||||
? Effect.succeed(
|
||||
decoded.success.map((item) => ({
|
||||
...toChangeRequest(item),
|
||||
updatedAt: item.updatedAt,
|
||||
})),
|
||||
)
|
||||
: Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(SourceControlProviderError)(error)
|
||||
? error
|
||||
: providerError("listChangeRequests", error),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
return SourceControlProvider.of({
|
||||
kind: "github",
|
||||
listChangeRequests,
|
||||
getChangeRequest: (input) =>
|
||||
github.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
),
|
||||
createChangeRequest: (input) =>
|
||||
github
|
||||
.createPullRequest({
|
||||
cwd: input.cwd,
|
||||
baseBranch: input.baseRefName,
|
||||
headSelector: input.headSelector,
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error))),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
github
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
github
|
||||
.getDefaultBranch(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
checkoutChangeRequest: (input) =>
|
||||
github
|
||||
.checkoutPullRequest(input)
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider, make());
|
||||
@@ -1,68 +0,0 @@
|
||||
import { Context, Effect } from "effect";
|
||||
import type {
|
||||
ChangeRequest,
|
||||
ChangeRequestState,
|
||||
SourceControlProviderError,
|
||||
SourceControlProviderInfo,
|
||||
SourceControlProviderKind,
|
||||
SourceControlRepositoryCloneUrls,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface SourceControlProviderContext {
|
||||
readonly provider: SourceControlProviderInfo;
|
||||
readonly remoteName: string;
|
||||
readonly remoteUrl: string;
|
||||
}
|
||||
|
||||
export interface SourceControlRefSelector {
|
||||
readonly refName: string;
|
||||
readonly owner?: string;
|
||||
readonly repository?: string;
|
||||
}
|
||||
|
||||
export interface SourceControlProviderShape {
|
||||
readonly kind: SourceControlProviderKind;
|
||||
readonly listChangeRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
readonly headSelector: string;
|
||||
readonly state: ChangeRequestState | "all";
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<ChangeRequest>, SourceControlProviderError>;
|
||||
readonly getChangeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<ChangeRequest, SourceControlProviderError>;
|
||||
readonly createChangeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
readonly target?: SourceControlRefSelector;
|
||||
readonly baseRefName: string;
|
||||
readonly headSelector: string;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, SourceControlProviderError>;
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
}) => Effect.Effect<string | null, SourceControlProviderError>;
|
||||
readonly checkoutChangeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, SourceControlProviderError>;
|
||||
}
|
||||
|
||||
export class SourceControlProvider extends Context.Service<
|
||||
SourceControlProvider,
|
||||
SourceControlProviderShape
|
||||
>()("t3/source-control/SourceControlProvider") {}
|
||||
@@ -1,101 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
|
||||
import { GitHubCli } from "./GitHubCli.ts";
|
||||
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
function makeRegistry(input: {
|
||||
readonly remotes: ReadonlyArray<{
|
||||
readonly name: string;
|
||||
readonly url: string;
|
||||
}>;
|
||||
}) {
|
||||
const driver = {
|
||||
listRemotes: () =>
|
||||
Effect.succeed({
|
||||
remotes: input.remotes.map((remote) => ({
|
||||
...remote,
|
||||
pushUrl: Option.none(),
|
||||
isPrimary: remote.name === "origin",
|
||||
})),
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
} satisfies Partial<VcsDriverShape>;
|
||||
|
||||
const registryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
resolve: () =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
repository: {
|
||||
kind: "git",
|
||||
rootPath: "/repo",
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: TEST_EPOCH,
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
},
|
||||
driver: driver as unknown as VcsDriverShape,
|
||||
}),
|
||||
});
|
||||
|
||||
return SourceControlProviderRegistry.make().pipe(
|
||||
Effect.provide(Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}))),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("routes GitHub remotes to the GitHub provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:pingdotgg/t3code.git" }],
|
||||
});
|
||||
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(provider.kind, "github");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"detects GitLab remotes and returns an unsupported provider until one is registered",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
|
||||
});
|
||||
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(provider.kind, "gitlab");
|
||||
const error = yield* Effect.flip(
|
||||
provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/source-control",
|
||||
state: "open",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error.provider, "gitlab");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to a non-origin remote when origin is not configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
|
||||
});
|
||||
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(provider.kind, "azure-devops");
|
||||
}),
|
||||
);
|
||||
@@ -1,155 +0,0 @@
|
||||
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
|
||||
import { SourceControlProviderError } from "@t3tools/contracts";
|
||||
import type { SourceControlProviderKind } from "@t3tools/contracts";
|
||||
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
|
||||
|
||||
import {
|
||||
SourceControlProvider,
|
||||
type SourceControlProviderContext,
|
||||
type SourceControlProviderShape,
|
||||
} from "./SourceControlProvider.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
|
||||
const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
|
||||
|
||||
export interface SourceControlProviderRegistration {
|
||||
readonly kind: SourceControlProviderKind;
|
||||
readonly provider: SourceControlProviderShape;
|
||||
}
|
||||
|
||||
export interface SourceControlProviderHandle {
|
||||
readonly provider: SourceControlProviderShape;
|
||||
readonly context: SourceControlProviderContext | null;
|
||||
}
|
||||
|
||||
export interface SourceControlProviderRegistryShape {
|
||||
readonly resolveHandle: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
|
||||
readonly resolve: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
|
||||
}
|
||||
|
||||
export class SourceControlProviderRegistry extends Context.Service<
|
||||
SourceControlProviderRegistry,
|
||||
SourceControlProviderRegistryShape
|
||||
>()("t3/source-control/SourceControlProviderRegistry") {}
|
||||
|
||||
function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProviderShape {
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: kind,
|
||||
operation,
|
||||
detail: `No ${kind} source control provider is registered.`,
|
||||
}),
|
||||
);
|
||||
|
||||
return SourceControlProvider.of({
|
||||
kind,
|
||||
listChangeRequests: () => unsupported("listChangeRequests"),
|
||||
getChangeRequest: () => unsupported("getChangeRequest"),
|
||||
createChangeRequest: () => unsupported("createChangeRequest"),
|
||||
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
|
||||
getDefaultBranch: () => unsupported("getDefaultBranch"),
|
||||
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
|
||||
});
|
||||
}
|
||||
|
||||
function providerDetectionError(operation: string, cwd: string, cause: unknown) {
|
||||
return new SourceControlProviderError({
|
||||
provider: "unknown",
|
||||
operation,
|
||||
detail: `Failed to detect source control provider for ${cwd}.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function selectProviderContext(
|
||||
remotes: ReadonlyArray<{
|
||||
readonly name: string;
|
||||
readonly url: string;
|
||||
}>,
|
||||
): SourceControlProviderContext | null {
|
||||
const candidates = remotes
|
||||
.map((remote) => {
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
|
||||
return provider
|
||||
? {
|
||||
provider,
|
||||
remoteName: remote.name,
|
||||
remoteUrl: remote.url,
|
||||
}
|
||||
: null;
|
||||
})
|
||||
.filter((value): value is SourceControlProviderContext => value !== null);
|
||||
|
||||
return (
|
||||
candidates.find((candidate) => candidate.remoteName === "origin") ??
|
||||
candidates.find((candidate) => candidate.provider.kind !== "unknown") ??
|
||||
candidates[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
|
||||
function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
|
||||
const vcsRegistry = yield* VcsDriverRegistry;
|
||||
const providers = new Map<SourceControlProviderKind, SourceControlProviderShape>(
|
||||
registrations.map((registration) => [registration.kind, registration.provider]),
|
||||
);
|
||||
|
||||
const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
|
||||
function* (cwd: string) {
|
||||
const handle = yield* vcsRegistry
|
||||
.resolve({ cwd })
|
||||
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
|
||||
const remotes = yield* handle.driver
|
||||
.listRemotes(cwd)
|
||||
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
|
||||
|
||||
return selectProviderContext(remotes.remotes);
|
||||
},
|
||||
);
|
||||
|
||||
const providerContextCache = yield* Cache.makeWith<
|
||||
string,
|
||||
SourceControlProviderContext | null,
|
||||
SourceControlProviderError
|
||||
>(detectProviderContext, {
|
||||
capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
|
||||
const resolveHandle: SourceControlProviderRegistryShape["resolveHandle"] = (input) =>
|
||||
Cache.get(providerContextCache, input.cwd).pipe(
|
||||
Effect.map((context) => {
|
||||
const kind = context?.provider.kind ?? "unknown";
|
||||
return {
|
||||
provider: providers.get(kind) ?? unsupportedProvider(kind),
|
||||
context,
|
||||
} satisfies SourceControlProviderHandle;
|
||||
}),
|
||||
);
|
||||
|
||||
return SourceControlProviderRegistry.of({
|
||||
resolveHandle,
|
||||
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
|
||||
const github = yield* GitHubSourceControlProvider.make();
|
||||
return yield* makeWithProviders([
|
||||
{
|
||||
kind: "github",
|
||||
provider: github,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProviderRegistry, make());
|
||||
@@ -1,19 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const TextGenerationPolicyKind = Schema.Literals([
|
||||
"default",
|
||||
"conventional_commits",
|
||||
"repo_conventions",
|
||||
"custom",
|
||||
]);
|
||||
export type TextGenerationPolicyKind = typeof TextGenerationPolicyKind.Type;
|
||||
|
||||
export const TextGenerationPolicy = Schema.Struct({
|
||||
kind: TextGenerationPolicyKind,
|
||||
commitInstructions: Schema.optional(Schema.String),
|
||||
changeRequestInstructions: Schema.optional(Schema.String),
|
||||
branchInstructions: Schema.optional(Schema.String),
|
||||
threadTitleInstructions: Schema.optional(Schema.String),
|
||||
inferRepositoryConventions: Schema.Boolean,
|
||||
});
|
||||
export type TextGenerationPolicy = typeof TextGenerationPolicy.Type;
|
||||
@@ -1,41 +0,0 @@
|
||||
import type { TextGenerationPolicy, TextGenerationPolicyKind } from "./TextGenerationPolicy.ts";
|
||||
|
||||
export const defaultTextGenerationPolicy: TextGenerationPolicy = {
|
||||
kind: "default",
|
||||
inferRepositoryConventions: false,
|
||||
};
|
||||
|
||||
export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = {
|
||||
kind: "conventional_commits",
|
||||
commitInstructions:
|
||||
"Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff.",
|
||||
changeRequestInstructions:
|
||||
"Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.",
|
||||
inferRepositoryConventions: false,
|
||||
};
|
||||
|
||||
export const repositoryConventionsTextGenerationPolicy: TextGenerationPolicy = {
|
||||
kind: "repo_conventions",
|
||||
commitInstructions:
|
||||
"Follow the repository's established commit message style when examples are available.",
|
||||
changeRequestInstructions:
|
||||
"Follow the repository's established change request title and body style when examples are available.",
|
||||
inferRepositoryConventions: true,
|
||||
};
|
||||
|
||||
export const customTextGenerationPolicy = (
|
||||
overrides: Omit<Partial<TextGenerationPolicy>, "kind">,
|
||||
): TextGenerationPolicy => ({
|
||||
kind: "custom",
|
||||
inferRepositoryConventions: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
export const textGenerationPresets: Record<
|
||||
Exclude<TextGenerationPolicyKind, "custom">,
|
||||
TextGenerationPolicy
|
||||
> = {
|
||||
default: defaultTextGenerationPolicy,
|
||||
conventional_commits: conventionalCommitsTextGenerationPolicy,
|
||||
repo_conventions: repositoryConventionsTextGenerationPolicy,
|
||||
};
|
||||
@@ -1,159 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
|
||||
export function toJsonSchemaObject(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return { ...document.schema, $defs: document.definitions };
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
|
||||
export function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
export function extractJsonObject(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const start = trimmed.indexOf("{");
|
||||
if (start < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaping = false;
|
||||
for (let index = start; index < trimmed.length; index += 1) {
|
||||
const char = trimmed[index];
|
||||
if (inString) {
|
||||
if (escaping) {
|
||||
escaping = false;
|
||||
} else if (char === "\\") {
|
||||
escaping = true;
|
||||
} else if (char === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "{") {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
return trimmed.slice(start, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed.slice(start);
|
||||
}
|
||||
|
||||
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
|
||||
export function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
/** Normalise a raw PR title to a single line with a sensible fallback. */
|
||||
export function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
|
||||
export function sanitizeThreadTitle(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.split(/\r?\n/g)[0]
|
||||
?.trim()
|
||||
.replace(/^['"`]+|['"`]+$/g, "")
|
||||
.trim()
|
||||
.replace(/\s+/g, " ");
|
||||
|
||||
if (!normalized || normalized.trim().length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
if (normalized.length <= 50) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return `${normalized.slice(0, 47).trimEnd()}...`;
|
||||
}
|
||||
|
||||
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
|
||||
function cliLabel(cliName: string): string {
|
||||
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
|
||||
return `${capitalized} CLI (\`${cliName}\`)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an unknown error from a CLI text generation process into a
|
||||
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
|
||||
* and Claude (and future providers) can share the same logic.
|
||||
*/
|
||||
export function normalizeCliError(
|
||||
cliName: string,
|
||||
operation: string,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
error.message.includes(`Command not found: ${cliName}`) ||
|
||||
lower.includes(`spawn ${cliName}`) ||
|
||||
lower.includes("enoent")
|
||||
) {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${fallback}: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: fallback,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-git-vcs-contract-",
|
||||
});
|
||||
const GitContractLayer = Layer.mergeAll(GitVcsDriver.vcsLayer, GitVcsDriver.layer).pipe(
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* driver.execute({
|
||||
operation: "GitVcsDriver.contract.git",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
type GitContractError = GitCommandError | PlatformError.PlatformError;
|
||||
|
||||
runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
|
||||
name: "Git",
|
||||
kind: "git",
|
||||
layer: GitContractLayer,
|
||||
fixture: {
|
||||
createRepo: (cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["init"]);
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "Test"]);
|
||||
}),
|
||||
writeFile: (cwd, relativePath, contents) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(absolutePath, contents);
|
||||
}),
|
||||
trackFile: (cwd, relativePath) => runGit(cwd, ["add", relativePath]),
|
||||
commit: (cwd, message) => runGit(cwd, ["commit", "-m", message]),
|
||||
ignorePath: (cwd, pattern) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
|
||||
let observedEnv: NodeJS.ProcessEnv | undefined;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.makeVcsDriverShape();
|
||||
|
||||
yield* driver.execute({
|
||||
operation: "GitVcsDriver.test.env",
|
||||
cwd: "/repo",
|
||||
args: ["status"],
|
||||
env: {
|
||||
GIT_INDEX_FILE: "/tmp/t3-index",
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(observedEnv, {
|
||||
GIT_INDEX_FILE: "/tmp/t3-index",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedEnv = input.env;
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,528 +0,0 @@
|
||||
import { Context, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
GitCommandError,
|
||||
VcsProcessExitError,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
type VcsCreateRefResult,
|
||||
type VcsCreateWorktreeInput,
|
||||
type VcsCreateWorktreeResult,
|
||||
type VcsInitInput,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
type VcsPullResult,
|
||||
type VcsRemoveWorktreeInput,
|
||||
type VcsStatusInput,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
|
||||
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
|
||||
import { nowFreshness } from "./VcsFreshness.ts";
|
||||
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
readonly exitCode: ChildProcessSpawner.ExitCode;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface GitStatusDetails {
|
||||
isRepo: boolean;
|
||||
sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
|
||||
hasOriginRemote: boolean;
|
||||
isDefaultBranch: boolean;
|
||||
branch: string | null;
|
||||
upstreamRef: string | null;
|
||||
hasWorkingTreeChanges: boolean;
|
||||
workingTree: VcsStatusResult["workingTree"];
|
||||
hasUpstream: boolean;
|
||||
aheadCount: number;
|
||||
behindCount: number;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface ExecuteGitProgress {
|
||||
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitProgress {
|
||||
readonly onOutputLine?: (input: {
|
||||
stream: "stdout" | "stderr";
|
||||
text: string;
|
||||
}) => Effect.Effect<void, never>;
|
||||
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
|
||||
readonly onHookFinished?: (input: {
|
||||
hookName: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number | null;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export interface GitCommitOptions {
|
||||
readonly timeoutMs?: number;
|
||||
readonly progress?: GitCommitProgress;
|
||||
}
|
||||
|
||||
export interface GitPushResult {
|
||||
status: "pushed" | "skipped_up_to_date";
|
||||
branch: string;
|
||||
upstreamBranch?: string | undefined;
|
||||
setUpstream?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface GitRangeContext {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchInput {
|
||||
cwd: string;
|
||||
oldBranch: string;
|
||||
newBranch: string;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchResult {
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface GitFetchPullRequestBranchInput {
|
||||
cwd: string;
|
||||
prNumber: number;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface GitEnsureRemoteInput {
|
||||
cwd: string;
|
||||
preferredName: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface GitFetchRemoteBranchInput {
|
||||
cwd: string;
|
||||
remoteName: string;
|
||||
remoteBranch: string;
|
||||
localBranch: string;
|
||||
}
|
||||
|
||||
export interface GitSetBranchUpstreamInput {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
remoteName: string;
|
||||
remoteBranch: string;
|
||||
}
|
||||
|
||||
export interface GitVcsDriverShape {
|
||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||
readonly commit: (
|
||||
cwd: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
options?: GitCommitOptions,
|
||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||
readonly pushCurrentBranch: (
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||
readonly readRangeContext: (
|
||||
cwd: string,
|
||||
baseRef: string,
|
||||
) => Effect.Effect<GitRangeContext, GitCommandError>;
|
||||
readonly readConfigValue: (
|
||||
cwd: string,
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly fetchPullRequestBranch: (
|
||||
input: GitFetchPullRequestBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
|
||||
readonly fetchRemoteBranch: (
|
||||
input: GitFetchRemoteBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly setBranchUpstream: (
|
||||
input: GitSetBranchUpstreamInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly renameBranch: (
|
||||
input: GitRenameBranchInput,
|
||||
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
export class GitVcsDriver extends Context.Service<GitVcsDriver, GitVcsDriverShape>()(
|
||||
"t3/vcs/GitVcsDriver",
|
||||
) {}
|
||||
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
] as const;
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
|
||||
const chunks: string[][] = [];
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length > 0) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function parseGitRemoteVerboseOutput(
|
||||
output: string,
|
||||
): Map<string, { url?: string; pushUrl?: string }> {
|
||||
const remotes = new Map<string, { url?: string; pushUrl?: string }>();
|
||||
for (const line of output.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
|
||||
if (!match) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = match[1];
|
||||
const url = match[2];
|
||||
const direction = match[3];
|
||||
if (!name || !url || !direction) {
|
||||
continue;
|
||||
}
|
||||
const remote = remotes.get(name) ?? {};
|
||||
if (direction === "fetch") {
|
||||
remote.url = url;
|
||||
} else {
|
||||
remote.pushUrl = url;
|
||||
}
|
||||
remotes.set(name, remote);
|
||||
}
|
||||
return remotes;
|
||||
}
|
||||
|
||||
const gitCommand = (
|
||||
process: VcsProcessShape,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: {
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
},
|
||||
) =>
|
||||
process.run({
|
||||
operation,
|
||||
command: "git",
|
||||
args,
|
||||
cwd,
|
||||
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
...(options?.env !== undefined ? { env: options.env } : {}),
|
||||
...(options?.allowNonZeroExit !== undefined
|
||||
? { allowNonZeroExit: options.allowNonZeroExit }
|
||||
: {}),
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
...(options?.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
|
||||
: {}),
|
||||
});
|
||||
|
||||
export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
const capabilities = {
|
||||
kind: "git" as const,
|
||||
supportsWorktrees: true,
|
||||
supportsBookmarks: false,
|
||||
supportsAtomicSnapshot: false,
|
||||
supportsPushDefaultRemote: true,
|
||||
ignoreClassifier: "native" as const,
|
||||
};
|
||||
|
||||
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
|
||||
gitCommand(
|
||||
process,
|
||||
"GitVcsDriver.isInsideWorkTree",
|
||||
cwd,
|
||||
["rev-parse", "--is-inside-work-tree"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
|
||||
|
||||
const execute: VcsDriverShape["execute"] = (input) =>
|
||||
gitCommand(process, input.operation, input.cwd, input.args, {
|
||||
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
|
||||
...(input.env !== undefined ? { env: input.env } : {}),
|
||||
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
|
||||
...(input.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
|
||||
function* (cwd) {
|
||||
if (!(yield* isInsideWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
|
||||
"rev-parse",
|
||||
"--show-toplevel",
|
||||
]);
|
||||
const gitCommonDir = yield* gitCommand(
|
||||
process,
|
||||
"GitVcsDriver.detectRepository.commonDir",
|
||||
cwd,
|
||||
["rev-parse", "--git-common-dir"],
|
||||
).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
|
||||
return {
|
||||
kind: "git" as const,
|
||||
rootPath: root.stdout.trim(),
|
||||
metadataPath: gitCommonDir?.stdout.trim() || null,
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
|
||||
gitCommand(
|
||||
process,
|
||||
"GitVcsDriver.listWorkspaceFiles",
|
||||
cwd,
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode === 0
|
||||
? Effect.gen(function* () {
|
||||
const freshness = yield* nowFreshness();
|
||||
return {
|
||||
paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
|
||||
truncated: result.stdoutTruncated,
|
||||
freshness,
|
||||
};
|
||||
})
|
||||
: Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitVcsDriver.listWorkspaceFiles",
|
||||
command: "git ls-files",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "git ls-files failed",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
|
||||
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
});
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation: "GitVcsDriver.listRemotes",
|
||||
command: "git remote -v",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "git remote -v failed",
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseGitRemoteVerboseOutput(result.stdout);
|
||||
const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
|
||||
if (!remote.url) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
name,
|
||||
url: remote.url,
|
||||
pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
|
||||
isPrimary: name === "origin",
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
return {
|
||||
remotes,
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
});
|
||||
|
||||
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
|
||||
function* (cwd, relativePaths) {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set<string>();
|
||||
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const result = yield* gitCommand(
|
||||
process,
|
||||
"GitVcsDriver.filterIgnoredPaths",
|
||||
cwd,
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.exitCode !== 0 && result.exitCode !== 1) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation: "GitVcsDriver.filterIgnoredPaths",
|
||||
command: "git check-ignore",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "git check-ignore failed",
|
||||
});
|
||||
}
|
||||
|
||||
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
execute,
|
||||
detectRepository,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
listRemotes,
|
||||
filterIgnoredPaths,
|
||||
} satisfies VcsDriverShape;
|
||||
});
|
||||
|
||||
export const makeVcsDriver = Effect.fn("makeGitVcsDriver")(function* () {
|
||||
const driver = yield* makeVcsDriverShape();
|
||||
return VcsDriver.of(driver);
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeGitVcsDriverService")(function* () {
|
||||
const git = yield* makeGitVcsDriverCore();
|
||||
return GitVcsDriver.of(git);
|
||||
});
|
||||
|
||||
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
|
||||
export const layer = Layer.effect(GitVcsDriver, make());
|
||||
@@ -1,246 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError, Scope } from "effect";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-git-vcs-driver-test-",
|
||||
});
|
||||
const TestLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const makeTmpDir = (
|
||||
prefix = "git-vcs-driver-test-",
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
||||
});
|
||||
|
||||
const writeTextFile = (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const filePath = pathService.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(pathService.dirname(filePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(filePath, contents);
|
||||
});
|
||||
|
||||
const git = (
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
env?: NodeJS.ProcessEnv,
|
||||
): Effect.Effect<string, GitCommandError, GitVcsDriver.GitVcsDriver> =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const result = yield* driver.execute({
|
||||
operation: "GitVcsDriver.test.git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
const initRepoWithCommit = (
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
{ readonly initialBranch: string },
|
||||
GitCommandError | PlatformError.PlatformError,
|
||||
GitVcsDriver.GitVcsDriver | FileSystem.FileSystem | Path.Path
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* driver.initRepo({ cwd });
|
||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(cwd, "README.md", "# test\n");
|
||||
yield* git(cwd, ["add", "."]);
|
||||
yield* git(cwd, ["commit", "-m", "initial commit"]);
|
||||
const initialBranch = yield* git(cwd, ["branch", "--show-current"]);
|
||||
return { initialBranch };
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
describe("repository status", () => {
|
||||
it.effect("reports non-repository directories without failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
assert.equal(refs.isRepo, false);
|
||||
assert.deepStrictEqual(refs.refs, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports refName and dirty state for a repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* writeTextFile(cwd, "feature.ts", "export const value = 1;\n");
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
|
||||
|
||||
assert.equal(status.isRepo, true);
|
||||
assert.equal(status.branch, initialBranch);
|
||||
assert.equal(status.hasWorkingTreeChanges, true);
|
||||
assert.include(
|
||||
status.workingTree.files.map((file) => file.path),
|
||||
"feature.ts",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("refName operations", () => {
|
||||
it.effect("creates, checks out, renames, and lists refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* driver.createRef({ cwd, refName: "feature/original" });
|
||||
const switchRef = yield* driver.switchRef({ cwd, refName: "feature/original" });
|
||||
assert.equal(switchRef.refName, "feature/original");
|
||||
|
||||
const renamed = yield* driver.renameBranch({
|
||||
cwd,
|
||||
oldBranch: "feature/original",
|
||||
newBranch: "feature/renamed",
|
||||
});
|
||||
assert.equal(renamed.branch, "feature/renamed");
|
||||
assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/renamed");
|
||||
|
||||
const refs = yield* driver.listRefs({ cwd });
|
||||
assert.equal(
|
||||
refs.refs.find((refName) => refName.name === "feature/renamed")?.current,
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the existing refName when rename source and target match", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const current = yield* git(cwd, ["branch", "--show-current"]);
|
||||
const result = yield* driver.renameBranch({
|
||||
cwd,
|
||||
oldBranch: current,
|
||||
newBranch: current,
|
||||
});
|
||||
|
||||
assert.equal(result.branch, current);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("worktree operations", () => {
|
||||
it.effect("creates and removes a worktree for a new refName", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
const pathService = yield* Path.Path;
|
||||
const worktreePath = pathService.join(
|
||||
yield* makeTmpDir("git-worktrees-"),
|
||||
"feature-worktree",
|
||||
);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const created = yield* driver.createWorktree({
|
||||
cwd,
|
||||
path: worktreePath,
|
||||
refName: initialBranch,
|
||||
newRefName: "feature/worktree",
|
||||
});
|
||||
|
||||
assert.equal(created.worktree.path, worktreePath);
|
||||
assert.equal(created.worktree.refName, "feature/worktree");
|
||||
assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "feature/worktree");
|
||||
|
||||
yield* driver.removeWorktree({ cwd, path: worktreePath });
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
assert.equal(yield* fileSystem.exists(worktreePath), false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("commit context", () => {
|
||||
it.effect("stages selected files and commits only those files", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* writeTextFile(cwd, "a.txt", "a\n");
|
||||
yield* writeTextFile(cwd, "b.txt", "b\n");
|
||||
|
||||
const context = yield* driver.prepareCommitContext(cwd, ["a.txt"]);
|
||||
assert.include(context?.stagedSummary ?? "", "a.txt");
|
||||
assert.notInclude(context?.stagedSummary ?? "", "b.txt");
|
||||
|
||||
const commit = yield* driver.commit(cwd, "Add a", "");
|
||||
assert.match(commit.commitSha, /^[a-f0-9]{40}$/);
|
||||
assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "Add a");
|
||||
|
||||
const status = yield* git(cwd, ["status", "--porcelain"]);
|
||||
assert.include(status, "?? b.txt");
|
||||
assert.notInclude(status, "a.txt");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("remote operations", () => {
|
||||
it.effect("pushes with upstream setup and skips when already up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-remote-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).createRef({
|
||||
cwd,
|
||||
refName: "feature/push",
|
||||
});
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({
|
||||
cwd,
|
||||
refName: "feature/push",
|
||||
});
|
||||
yield* writeTextFile(cwd, "feature.txt", "feature\n");
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).prepareCommitContext(cwd);
|
||||
yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add feature", "");
|
||||
|
||||
const pushed = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null);
|
||||
assert.deepInclude(pushed, {
|
||||
status: "pushed",
|
||||
branch: "feature/push",
|
||||
setUpstream: true,
|
||||
});
|
||||
assert.equal(
|
||||
yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
|
||||
"origin/feature/push",
|
||||
);
|
||||
|
||||
const skipped = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null);
|
||||
assert.deepInclude(skipped, {
|
||||
status: "skipped_up_to_date",
|
||||
branch: "feature/push",
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,193 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
|
||||
import { VcsProcess, layer as VcsProcessLayer } from "./VcsProcess.ts";
|
||||
import * as JjVcsDriver from "./JjVcsDriver.ts";
|
||||
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
|
||||
|
||||
const JjContractLayer = JjVcsDriver.vcsLayer.pipe(
|
||||
Layer.provideMerge(VcsProcessLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
|
||||
calls.map((call) => [call.command].concat(call.args));
|
||||
|
||||
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(exitCode),
|
||||
stdout,
|
||||
stderr,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const runJj = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
yield* process.run({
|
||||
operation: "JjVcsDriver.contract.jj",
|
||||
command: "jj",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
type JjContractError = PlatformError.PlatformError | VcsError;
|
||||
|
||||
runVcsDriverContractSuite<VcsProcess, JjContractError>({
|
||||
name: "JJ",
|
||||
kind: "jj",
|
||||
layer: JjContractLayer,
|
||||
fixture: {
|
||||
createRepo: (cwd) => runJj(cwd, ["git", "init", "--colocate"]),
|
||||
writeFile: (cwd, relativePath, contents) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(absolutePath, contents);
|
||||
}),
|
||||
ignorePath: (cwd, pattern) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
describe("JjVcsDriver", () => {
|
||||
it.effect("detects repository identity with jj root", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const identity = yield* driver.detectRepository("/repo/src");
|
||||
|
||||
assert.equal(identity?.kind, "jj");
|
||||
assert.equal(identity?.rootPath, "/repo");
|
||||
assert.equal(identity?.metadataPath, "/repo/.jj");
|
||||
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
return processOutput("/repo\n");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("lists workspace files using jj file list", () => {
|
||||
let observedInput: VcsProcessInput | null = null;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const result = yield* driver.listWorkspaceFiles("/repo");
|
||||
|
||||
assert.deepStrictEqual(result.paths, ["README.md", "src/index.ts"]);
|
||||
assert.deepStrictEqual(observedInput?.args, ["--no-pager", "file", "list"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedInput = input;
|
||||
return processOutput("README.md\nsrc/index.ts\n");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("filters paths with the git ignore oracle", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const result = yield* driver.filterIgnoredPaths("/repo", [
|
||||
"keep.ts",
|
||||
"debug.log",
|
||||
"src/index.ts",
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(result, ["keep.ts", "src/index.ts"]);
|
||||
assert.equal(calls[0]?.command, "git");
|
||||
assert.deepStrictEqual(calls[0]?.args.slice(-2), ["init", "--bare"]);
|
||||
assert.equal(calls[1]?.command, "git");
|
||||
assert.deepStrictEqual(calls[1]?.args.slice(-4), [
|
||||
"check-ignore",
|
||||
"--no-index",
|
||||
"-z",
|
||||
"--stdin",
|
||||
]);
|
||||
assert.equal(calls[1]?.stdin, "keep.ts\0debug.log\0src/index.ts\0");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
if (input.command === "git" && input.args.includes("check-ignore")) {
|
||||
return processOutput("debug.log\0");
|
||||
}
|
||||
return processOutput("");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards execute env to the VCS process", () => {
|
||||
let observedEnv: NodeJS.ProcessEnv | undefined;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
|
||||
yield* driver.execute({
|
||||
operation: "JjVcsDriver.test.env",
|
||||
cwd: "/repo",
|
||||
args: ["status"],
|
||||
env: {
|
||||
JJ_CONFIG: "/tmp/t3-jj-config.toml",
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(observedEnv, {
|
||||
JJ_CONFIG: "/tmp/t3-jj-config.toml",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedEnv = input.env;
|
||||
return processOutput("");
|
||||
}),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,518 +0,0 @@
|
||||
import { Context, Effect, FileSystem, Layer, Option } from "effect";
|
||||
|
||||
import { VcsOutputDecodeError, VcsProcessExitError, type VcsError } from "@t3tools/contracts";
|
||||
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
|
||||
import { nowFreshness } from "./VcsFreshness.ts";
|
||||
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
|
||||
|
||||
export interface JjVcsDriverShape extends VcsDriverShape {
|
||||
readonly capabilities: VcsDriverShape["capabilities"] & {
|
||||
readonly kind: "jj";
|
||||
readonly supportsBookmarks: true;
|
||||
readonly supportsAtomicSnapshot: true;
|
||||
readonly supportsWorktrees: false;
|
||||
readonly ignoreClassifier: "git-compatible-fallback";
|
||||
};
|
||||
readonly currentChange: (cwd: string) => Effect.Effect<JjCurrentChange | null, VcsError>;
|
||||
readonly listBookmarks: (cwd: string) => Effect.Effect<ReadonlyArray<JjBookmark>, VcsError>;
|
||||
readonly listWorkspaces: (cwd: string) => Effect.Effect<ReadonlyArray<JjWorkspace>, VcsError>;
|
||||
}
|
||||
|
||||
export interface JjCurrentChange {
|
||||
readonly changeId: string;
|
||||
readonly commitId: string | null;
|
||||
readonly description: string | null;
|
||||
}
|
||||
|
||||
export interface JjBookmark {
|
||||
readonly name: string;
|
||||
readonly target: string | null;
|
||||
}
|
||||
|
||||
export interface JjWorkspace {
|
||||
readonly name: string;
|
||||
readonly path: string | null;
|
||||
}
|
||||
|
||||
export class JjVcsDriver extends Context.Service<JjVcsDriver, JjVcsDriverShape>()(
|
||||
"t3/vcs/JjVcsDriver",
|
||||
) {}
|
||||
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function splitLineSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const lines = input.split(/\r?\n/g);
|
||||
if (truncated && lines[lines.length - 1]?.length) {
|
||||
lines.pop();
|
||||
}
|
||||
|
||||
return lines.map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
}
|
||||
|
||||
function parseJjRemoteList(output: string): Array<{ name: string; url: string }> {
|
||||
return output
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.flatMap((line) => {
|
||||
if (line.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const [name, ...urlParts] = line.split(/\s+/g);
|
||||
const url = urlParts.join(" ").trim();
|
||||
return name && url ? [{ name, url }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function parseNullRecord(record: string): string[] {
|
||||
return record.split("\0").map((value) => value.trim());
|
||||
}
|
||||
|
||||
function decodeJjCurrentChange(
|
||||
raw: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<JjCurrentChange | null, VcsOutputDecodeError> {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
|
||||
const [changeId, commitId, description] = parseNullRecord(trimmed);
|
||||
if (!changeId) {
|
||||
return Effect.fail(
|
||||
new VcsOutputDecodeError({
|
||||
operation: "JjVcsDriver.currentChange",
|
||||
command: "jj log",
|
||||
cwd,
|
||||
detail: "jj current change output did not include a change id",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
changeId,
|
||||
commitId: commitId || null,
|
||||
description: description || null,
|
||||
});
|
||||
}
|
||||
|
||||
function decodeJjBookmarkList(raw: string): ReadonlyArray<JjBookmark> {
|
||||
return raw
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const [name, target] = parseNullRecord(line);
|
||||
return {
|
||||
name: name ?? line,
|
||||
target: target || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function decodeJjWorkspaceList(raw: string): ReadonlyArray<JjWorkspace> {
|
||||
return raw
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const [name, path] = parseNullRecord(line);
|
||||
return {
|
||||
name: name ?? line,
|
||||
path: path || null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function chunkPathsForCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
|
||||
const chunks: string[][] = [];
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (chunk.length > 0 && chunkBytes + relativePathBytes > CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= CHECK_IGNORE_MAX_STDIN_BYTES) {
|
||||
chunks.push(chunk);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length > 0) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
const processCommand = (
|
||||
process: VcsProcessShape,
|
||||
command: string,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: {
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
},
|
||||
) =>
|
||||
process.run({
|
||||
operation,
|
||||
command,
|
||||
args,
|
||||
cwd,
|
||||
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
...(options?.env !== undefined ? { env: options.env } : {}),
|
||||
...(options?.allowNonZeroExit !== undefined
|
||||
? { allowNonZeroExit: options.allowNonZeroExit }
|
||||
: {}),
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
...(options?.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const jjCommand = (
|
||||
process: VcsProcessShape,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: {
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
},
|
||||
) => processCommand(process, "jj", operation, cwd, ["--no-pager", ...args], options);
|
||||
|
||||
const gitCommand = (
|
||||
process: VcsProcessShape,
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options?: Parameters<typeof processCommand>[5],
|
||||
) => processCommand(process, "git", operation, cwd, args, options);
|
||||
|
||||
function fileSystemError(operation: string, cwd: string, detail: string, cause: unknown) {
|
||||
return new VcsOutputDecodeError({
|
||||
operation,
|
||||
command: "git check-ignore",
|
||||
cwd,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
const makeScopedTempGitDir = (fileSystem: FileSystem.FileSystem, operation: string, cwd: string) =>
|
||||
fileSystem
|
||||
.makeTempDirectoryScoped({ prefix: "t3-jj-check-ignore-" })
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
fileSystemError(operation, cwd, "failed to create temp git dir", cause),
|
||||
),
|
||||
);
|
||||
|
||||
export const makeVcsDriverShape = Effect.fn("makeJjVcsDriverShape")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const capabilities = {
|
||||
kind: "jj" as const,
|
||||
supportsWorktrees: false as const,
|
||||
supportsBookmarks: true as const,
|
||||
supportsAtomicSnapshot: true as const,
|
||||
supportsPushDefaultRemote: false as const,
|
||||
ignoreClassifier: "git-compatible-fallback" as const,
|
||||
};
|
||||
|
||||
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
|
||||
jjCommand(process, "JjVcsDriver.isInsideWorkTree", cwd, ["root"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(
|
||||
Effect.map((result) => result.exitCode === 0 && result.stdout.trim().length > 0),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const execute: VcsDriverShape["execute"] = (input) =>
|
||||
jjCommand(process, input.operation, input.cwd, input.args, {
|
||||
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
|
||||
...(input.env !== undefined ? { env: input.env } : {}),
|
||||
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
|
||||
...(input.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
|
||||
function* (cwd) {
|
||||
const root = yield* jjCommand(process, "JjVcsDriver.detectRepository.root", cwd, ["root"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 4_096,
|
||||
}).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!root || root.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rootPath = root.stdout.trim();
|
||||
if (rootPath.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "jj" as const,
|
||||
rootPath,
|
||||
metadataPath: `${rootPath.replace(/[\\/]$/g, "")}/.jj`,
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
|
||||
jjCommand(process, "JjVcsDriver.listWorkspaceFiles", cwd, ["file", "list"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode === 0
|
||||
? Effect.gen(function* () {
|
||||
return {
|
||||
paths: splitLineSeparatedPaths(result.stdout, result.stdoutTruncated),
|
||||
truncated: result.stdoutTruncated,
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
})
|
||||
: Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "JjVcsDriver.listWorkspaceFiles",
|
||||
command: "jj file list",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "jj file list failed",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
|
||||
const result = yield* jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.listRemotes",
|
||||
cwd,
|
||||
["git", "remote", "list"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return {
|
||||
remotes: [],
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
remotes: parseJjRemoteList(result.stdout).map((remote) => ({
|
||||
name: remote.name,
|
||||
url: remote.url,
|
||||
pushUrl: Option.none(),
|
||||
isPrimary: remote.name === "origin",
|
||||
})),
|
||||
freshness: yield* nowFreshness(),
|
||||
};
|
||||
});
|
||||
|
||||
const currentChange: JjVcsDriverShape["currentChange"] = (cwd) =>
|
||||
jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.currentChange",
|
||||
cwd,
|
||||
[
|
||||
"log",
|
||||
"-r",
|
||||
"@",
|
||||
"--no-graph",
|
||||
"--template",
|
||||
'change_id ++ "\\0" ++ commit_id ++ "\\0" ++ description.first_line()',
|
||||
],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
},
|
||||
).pipe(Effect.flatMap((result) => decodeJjCurrentChange(result.stdout, cwd)));
|
||||
|
||||
const listBookmarks: JjVcsDriverShape["listBookmarks"] = (cwd) =>
|
||||
jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.listBookmarks",
|
||||
cwd,
|
||||
["bookmark", "list", "--template", 'name ++ "\\0" ++ target.commit_id() ++ "\\n"'],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) => (result.exitCode === 0 ? decodeJjBookmarkList(result.stdout) : [])),
|
||||
);
|
||||
|
||||
const listWorkspaces: JjVcsDriverShape["listWorkspaces"] = (cwd) =>
|
||||
jjCommand(
|
||||
process,
|
||||
"JjVcsDriver.listWorkspaces",
|
||||
cwd,
|
||||
["workspace", "list", "--template", 'name ++ "\\0" ++ root ++ "\\n"'],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) => (result.exitCode === 0 ? decodeJjWorkspaceList(result.stdout) : [])),
|
||||
);
|
||||
|
||||
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
|
||||
function* (cwd, relativePaths) {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const operation = "JjVcsDriver.filterIgnoredPaths";
|
||||
const ignoredPaths = new Set<string>();
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const gitDir = yield* makeScopedTempGitDir(fileSystem, operation, cwd);
|
||||
const initResult = yield* gitCommand(
|
||||
process,
|
||||
operation,
|
||||
cwd,
|
||||
["--git-dir", gitDir, "init", "--bare"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
if (initResult.exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git init --bare",
|
||||
cwd,
|
||||
exitCode: initResult.exitCode,
|
||||
detail: initResult.stderr.trim() || "git init --bare failed",
|
||||
});
|
||||
}
|
||||
|
||||
for (const chunk of chunkPathsForCheckIgnore(relativePaths)) {
|
||||
const result = yield* gitCommand(
|
||||
process,
|
||||
operation,
|
||||
cwd,
|
||||
[
|
||||
"--git-dir",
|
||||
gitDir,
|
||||
"--work-tree",
|
||||
cwd,
|
||||
"check-ignore",
|
||||
"--no-index",
|
||||
"-z",
|
||||
"--stdin",
|
||||
],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.exitCode !== 0 && result.exitCode !== 1) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git check-ignore",
|
||||
cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "git check-ignore failed",
|
||||
});
|
||||
}
|
||||
|
||||
for (const ignoredPath of splitNullSeparatedPaths(
|
||||
result.stdout,
|
||||
result.stdoutTruncated,
|
||||
)) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
execute,
|
||||
detectRepository,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
listRemotes,
|
||||
filterIgnoredPaths,
|
||||
currentChange,
|
||||
listBookmarks,
|
||||
listWorkspaces,
|
||||
} satisfies JjVcsDriverShape;
|
||||
});
|
||||
|
||||
export const makeJjVcsDriver = Effect.fn("makeJjVcsDriver")(function* () {
|
||||
const driver = yield* makeVcsDriverShape();
|
||||
return JjVcsDriver.of(driver);
|
||||
});
|
||||
|
||||
export const makeVcsDriver = Effect.fn("makeJjGenericVcsDriver")(function* () {
|
||||
const driver = yield* makeVcsDriverShape();
|
||||
return VcsDriver.of(driver);
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(JjVcsDriver, makeJjVcsDriver());
|
||||
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Context, type Effect } from "effect";
|
||||
|
||||
import type {
|
||||
VcsDriverCapabilities,
|
||||
VcsError,
|
||||
VcsListRemotesResult,
|
||||
VcsListWorkspaceFilesResult,
|
||||
VcsRepositoryIdentity,
|
||||
} from "@t3tools/contracts";
|
||||
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
|
||||
|
||||
export interface VcsDriverShape {
|
||||
readonly capabilities: VcsDriverCapabilities;
|
||||
readonly execute: (
|
||||
input: Omit<VcsProcessInput, "command">,
|
||||
) => Effect.Effect<VcsProcessOutput, VcsError>;
|
||||
readonly detectRepository: (cwd: string) => Effect.Effect<VcsRepositoryIdentity | null, VcsError>;
|
||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, VcsError>;
|
||||
readonly listWorkspaceFiles: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsListWorkspaceFilesResult, VcsError>;
|
||||
readonly listRemotes: (cwd: string) => Effect.Effect<VcsListRemotesResult, VcsError>;
|
||||
readonly filterIgnoredPaths: (
|
||||
cwd: string,
|
||||
relativePaths: ReadonlyArray<string>,
|
||||
) => Effect.Effect<ReadonlyArray<string>, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}
|
||||
@@ -1,141 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "./VcsProcess.ts";
|
||||
import { VcsProjectConfig } from "./VcsProjectConfig.ts";
|
||||
import { VcsDriverRegistry, make as makeVcsDriverRegistry } from "./VcsDriverRegistry.ts";
|
||||
|
||||
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
|
||||
calls.map((call) => [call.command].concat(call.args));
|
||||
|
||||
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(exitCode),
|
||||
stdout,
|
||||
stderr,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
describe("VcsDriverRegistry", () => {
|
||||
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
const command = input.args.join(" ");
|
||||
if (command === "rev-parse --is-inside-work-tree") {
|
||||
return processOutput("true\n");
|
||||
}
|
||||
if (command === "rev-parse --show-toplevel") {
|
||||
return processOutput("/repo\n");
|
||||
}
|
||||
if (command === "rev-parse --git-common-dir") {
|
||||
return processOutput("/repo/.git\n");
|
||||
}
|
||||
return processOutput("");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const first = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
|
||||
const second = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
|
||||
|
||||
assert.equal(first.repository.rootPath, "/repo");
|
||||
assert.equal(second.repository.rootPath, "/repo");
|
||||
assert.deepStrictEqual(
|
||||
calls.map((call) => call.args.join(" ")),
|
||||
[
|
||||
"rev-parse --is-inside-work-tree",
|
||||
"rev-parse --show-toplevel",
|
||||
"rev-parse --git-common-dir",
|
||||
],
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("resolves an explicitly requested jj repository", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
const command = input.args.join(" ");
|
||||
if (input.command === "jj" && command === "--no-pager root") {
|
||||
return processOutput("/repo\n");
|
||||
}
|
||||
return processOutput("", 1, "not found");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const handle = yield* registry.resolve({ cwd: "/repo", requestedKind: "jj" });
|
||||
|
||||
assert.equal(handle.kind, "jj");
|
||||
assert.equal(handle.repository.rootPath, "/repo");
|
||||
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("prefers jj auto-detection before git for colocated repositories", () => {
|
||||
const calls: VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
const command = input.args.join(" ");
|
||||
if (input.command === "jj" && command === "--no-pager root") {
|
||||
return processOutput("/repo\n");
|
||||
}
|
||||
if (input.command === "git") {
|
||||
return processOutput("true\n");
|
||||
}
|
||||
return processOutput("", 1, "not found");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const handle = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.equal(handle.kind, "jj");
|
||||
assert.equal(handle.repository.rootPath, "/repo");
|
||||
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
});
|
||||
@@ -1,158 +0,0 @@
|
||||
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
|
||||
|
||||
import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";
|
||||
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
import * as JjVcsDriver from "./JjVcsDriver.ts";
|
||||
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
|
||||
import type { VcsDriverShape } from "./VcsDriver.ts";
|
||||
|
||||
const DETECTION_CACHE_CAPACITY = 2_048;
|
||||
const DETECTION_CACHE_TTL = Duration.seconds(2);
|
||||
|
||||
export interface VcsDriverResolveInput {
|
||||
readonly cwd: string;
|
||||
readonly requestedKind?: VcsDriverKind | "auto";
|
||||
}
|
||||
|
||||
export interface VcsDriverHandle {
|
||||
readonly kind: VcsDriverKind;
|
||||
readonly repository: VcsRepositoryIdentity;
|
||||
readonly driver: VcsDriverShape;
|
||||
}
|
||||
|
||||
export interface VcsDriverRegistryShape {
|
||||
readonly detect: (
|
||||
input: VcsDriverResolveInput,
|
||||
) => Effect.Effect<VcsDriverHandle | null, VcsError>;
|
||||
readonly resolve: (input: VcsDriverResolveInput) => Effect.Effect<VcsDriverHandle, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsDriverRegistry extends Context.Service<VcsDriverRegistry, VcsDriverRegistryShape>()(
|
||||
"t3/vcs/VcsDriverRegistry",
|
||||
) {}
|
||||
|
||||
const unsupported = (operation: string, kind: VcsDriverKind, detail: string) =>
|
||||
new VcsUnsupportedOperationError({
|
||||
operation,
|
||||
kind,
|
||||
detail,
|
||||
});
|
||||
|
||||
function detectionCacheKey(input: {
|
||||
readonly cwd: string;
|
||||
readonly requestedKind: VcsDriverKind | "auto";
|
||||
}): string {
|
||||
return `${input.requestedKind}\0${input.cwd}`;
|
||||
}
|
||||
|
||||
function parseDetectionCacheKey(key: string): {
|
||||
readonly cwd: string;
|
||||
readonly requestedKind: VcsDriverKind | "auto";
|
||||
} {
|
||||
const separatorIndex = key.indexOf("\0");
|
||||
if (separatorIndex === -1) {
|
||||
return {
|
||||
cwd: key,
|
||||
requestedKind: "auto",
|
||||
};
|
||||
}
|
||||
return {
|
||||
requestedKind: key.slice(0, separatorIndex) as VcsDriverKind | "auto",
|
||||
cwd: key.slice(separatorIndex + 1),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
|
||||
const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
|
||||
const git = yield* GitVcsDriver.makeVcsDriverShape();
|
||||
const jj = yield* JjVcsDriver.makeVcsDriverShape();
|
||||
const drivers: Partial<Record<VcsDriverKind, VcsDriverShape>> = {
|
||||
git,
|
||||
jj,
|
||||
};
|
||||
|
||||
const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
|
||||
kind: VcsDriverKind,
|
||||
driver: VcsDriverShape,
|
||||
cwd: string,
|
||||
) {
|
||||
const repository = yield* driver.detectRepository(cwd);
|
||||
if (!repository) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind,
|
||||
repository,
|
||||
driver,
|
||||
} satisfies VcsDriverHandle;
|
||||
});
|
||||
|
||||
const detectResolvedKind = Effect.fn("VcsDriverRegistry.detectResolvedKind")(function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly requestedKind: VcsDriverKind | "auto";
|
||||
}) {
|
||||
const requestedKind = input.requestedKind;
|
||||
|
||||
if (requestedKind !== "auto" && requestedKind !== "unknown") {
|
||||
const driver = drivers[requestedKind];
|
||||
if (!driver) {
|
||||
return yield* unsupported(
|
||||
"VcsDriverRegistry.detect",
|
||||
requestedKind,
|
||||
`No ${requestedKind} VCS driver is registered.`,
|
||||
);
|
||||
}
|
||||
return yield* detectWithDriver(requestedKind, driver, input.cwd);
|
||||
}
|
||||
|
||||
const jjDetected = yield* detectWithDriver("jj", jj, input.cwd);
|
||||
if (jjDetected) {
|
||||
return jjDetected;
|
||||
}
|
||||
|
||||
return yield* detectWithDriver("git", git, input.cwd);
|
||||
});
|
||||
|
||||
const detectionCache = yield* Cache.makeWith<string, VcsDriverHandle | null, VcsError>(
|
||||
(key) => detectResolvedKind(parseDetectionCacheKey(key)),
|
||||
{
|
||||
capacity: DETECTION_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? DETECTION_CACHE_TTL : Duration.zero),
|
||||
},
|
||||
);
|
||||
|
||||
const detect: VcsDriverRegistryShape["detect"] = Effect.fn("VcsDriverRegistry.detect")(
|
||||
function* (input) {
|
||||
const requestedKind = yield* projectConfig.resolveKind(input);
|
||||
return yield* Cache.get(detectionCache, detectionCacheKey({ cwd: input.cwd, requestedKind }));
|
||||
},
|
||||
);
|
||||
|
||||
const resolve: VcsDriverRegistryShape["resolve"] = Effect.fn("VcsDriverRegistry.resolve")(
|
||||
function* (input) {
|
||||
const detected = yield* detect(input);
|
||||
if (detected) {
|
||||
return detected;
|
||||
}
|
||||
|
||||
const requestedKind = input.requestedKind ?? "auto";
|
||||
return yield* unsupported(
|
||||
"VcsDriverRegistry.resolve",
|
||||
requestedKind === "auto" ? "unknown" : requestedKind,
|
||||
requestedKind === "auto"
|
||||
? `No supported VCS repository was detected at ${input.cwd}.`
|
||||
: `No ${requestedKind} repository was detected at ${input.cwd}.`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return VcsDriverRegistry.of({
|
||||
detect,
|
||||
resolve,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(VcsDriverRegistry, make()).pipe(
|
||||
Layer.provide(VcsProjectConfig.layer),
|
||||
);
|
||||
@@ -1,10 +0,0 @@
|
||||
import { DateTime, Effect, Option } from "effect";
|
||||
|
||||
export const nowFreshness = Effect.fn("VcsFreshness.nowFreshness")(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
return {
|
||||
source: "live-local" as const,
|
||||
observedAt: now,
|
||||
expiresAt: Option.none(),
|
||||
};
|
||||
});
|
||||
@@ -1,259 +0,0 @@
|
||||
import { Duration, Context, Effect, Layer, Option, PlatformError, Sink, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
VcsOutputDecodeError,
|
||||
type VcsError,
|
||||
VcsProcessExitError,
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface VcsProcessInput {
|
||||
readonly operation: string;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd: string;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}
|
||||
|
||||
export interface VcsProcessOutput {
|
||||
readonly exitCode: ChildProcessSpawner.ExitCode;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface VcsProcessCollectedText {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export interface VcsProcessHandle {
|
||||
readonly pid: ChildProcessSpawner.ProcessId;
|
||||
readonly stdin: Sink.Sink<void, Uint8Array, never, VcsError>;
|
||||
readonly stdout: Stream.Stream<Uint8Array, VcsError>;
|
||||
readonly stderr: Stream.Stream<Uint8Array, VcsError>;
|
||||
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, VcsError>;
|
||||
readonly writeStdin: (input: string) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export interface VcsProcessShape {
|
||||
readonly withProcess: <A, E, R>(
|
||||
input: VcsProcessInput,
|
||||
use: (handle: VcsProcessHandle) => Effect.Effect<A, E, R>,
|
||||
) => Effect.Effect<A, E | VcsError, R>;
|
||||
readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
|
||||
}
|
||||
|
||||
export class VcsProcess extends Context.Service<VcsProcess, VcsProcessShape>()(
|
||||
"t3/vcs/VcsProcess",
|
||||
) {}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
|
||||
|
||||
function commandLabel(command: string, args: ReadonlyArray<string>): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function outputDecodeError(
|
||||
input: VcsProcessInput,
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): VcsOutputDecodeError {
|
||||
return new VcsOutputDecodeError({
|
||||
operation: input.operation,
|
||||
command: commandLabel(input.command, input.args),
|
||||
cwd: input.cwd,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
export const collectText = Effect.fn("VcsProcess.collectText")(function* (input: {
|
||||
readonly operation: string;
|
||||
readonly command: string;
|
||||
readonly cwd: string;
|
||||
readonly stream: Stream.Stream<Uint8Array, VcsError>;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) {
|
||||
const decoder = new TextDecoder();
|
||||
let text = "";
|
||||
let bytes = 0;
|
||||
let truncated = false;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
|
||||
|
||||
yield* Stream.runForEach(input.stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (truncated) return;
|
||||
|
||||
const remainingBytes = maxOutputBytes - bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextChunk = chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
text += decoder.decode(nextChunk, { stream: true });
|
||||
bytes += nextChunk.byteLength;
|
||||
|
||||
if (chunk.byteLength > remainingBytes) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (!truncated) {
|
||||
text += decoder.decode();
|
||||
}
|
||||
|
||||
return { text, truncated } satisfies VcsProcessCollectedText;
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeVcsProcess")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const spawn = Effect.fn("VcsProcess.spawn")(function* (input: VcsProcessInput) {
|
||||
const label = commandLabel(input.command, input.args);
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.command, [...input.args], {
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...input.env,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new VcsProcessSpawnError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
|
||||
const mapStreamError = (streamName: "stdout" | "stderr") =>
|
||||
Stream.mapError((cause: PlatformError.PlatformError) =>
|
||||
outputDecodeError(input, `failed to read process ${streamName}`, cause),
|
||||
);
|
||||
const mapEffectError = (detail: string) =>
|
||||
Effect.mapError((cause: PlatformError.PlatformError) =>
|
||||
outputDecodeError(input, detail, cause),
|
||||
);
|
||||
const writeStdin = (stdin: string) =>
|
||||
Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
|
||||
mapEffectError("failed to write process stdin"),
|
||||
);
|
||||
|
||||
return {
|
||||
pid: child.pid,
|
||||
stdin: child.stdin.pipe(
|
||||
Sink.mapError((cause) => outputDecodeError(input, "failed to write process stdin", cause)),
|
||||
),
|
||||
stdout: child.stdout.pipe(mapStreamError("stdout")),
|
||||
stderr: child.stderr.pipe(mapStreamError("stderr")),
|
||||
exitCode: child.exitCode.pipe(mapEffectError("failed to read process exit code")),
|
||||
writeStdin,
|
||||
} satisfies VcsProcessHandle;
|
||||
});
|
||||
|
||||
const withProcess: VcsProcessShape["withProcess"] = (input, use) =>
|
||||
Effect.scoped(spawn(input).pipe(Effect.flatMap(use)));
|
||||
|
||||
const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const label = commandLabel(input.command, input.args);
|
||||
|
||||
const runProcess = Effect.gen(function* () {
|
||||
const [stdout, stderr, exitCode] = yield* withProcess(input, (child) =>
|
||||
Effect.all(
|
||||
[
|
||||
collectText({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
stream: child.stdout,
|
||||
maxOutputBytes,
|
||||
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
|
||||
}),
|
||||
collectText({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
stream: child.stderr,
|
||||
maxOutputBytes,
|
||||
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
|
||||
}),
|
||||
child.exitCode,
|
||||
input.stdin === undefined ? Effect.void : child.writeStdin(input.stdin),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
exitCode,
|
||||
detail: stderr.text.trim() || `${label} exited with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies VcsProcessOutput;
|
||||
});
|
||||
|
||||
return yield* runProcess.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(timeoutMs)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new VcsProcessTimeoutError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
timeoutMs,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return VcsProcess.of({ withProcess, run });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(VcsProcess, make());
|
||||
@@ -1,67 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import { VcsProjectConfig, layer as VcsProjectConfigLayer } from "./VcsProjectConfig.ts";
|
||||
|
||||
const TestLayer = VcsProjectConfigLayer.pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
describe("VcsProjectConfig", () => {
|
||||
it.layer(TestLayer)("uses an explicit requested VCS kind before config", (it) => {
|
||||
it.effect("returns the requested kind", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* VcsProjectConfig;
|
||||
const kind = yield* config.resolveKind({
|
||||
cwd: "/repo",
|
||||
requestedKind: "jj",
|
||||
});
|
||||
|
||||
assert.equal(kind, "jj");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("discovers .t3code/vcs.json from nested workspaces", (it) => {
|
||||
it.effect("returns the configured kind", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-config-test-",
|
||||
});
|
||||
const configDir = path.join(root, ".t3code");
|
||||
const nested = path.join(root, "packages", "app");
|
||||
yield* fileSystem.makeDirectory(configDir, { recursive: true });
|
||||
yield* fileSystem.makeDirectory(nested, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(configDir, "vcs.json"),
|
||||
JSON.stringify({ vcs: { kind: "jj" } }),
|
||||
);
|
||||
|
||||
const config = yield* VcsProjectConfig;
|
||||
const kind = yield* config.resolveKind({ cwd: nested });
|
||||
|
||||
assert.equal(kind, "jj");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
|
||||
it.effect("returns auto", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-vcs-config-test-",
|
||||
});
|
||||
const config = yield* VcsProjectConfig;
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,117 +0,0 @@
|
||||
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { VcsDriverKind, type VcsDriverKind as VcsDriverKindType } from "@t3tools/contracts";
|
||||
|
||||
const ProjectVcsConfig = Schema.Struct({
|
||||
vcs: Schema.optional(
|
||||
Schema.Struct({
|
||||
kind: Schema.optional(VcsDriverKind),
|
||||
}),
|
||||
),
|
||||
vcsKind: Schema.optional(VcsDriverKind),
|
||||
});
|
||||
|
||||
interface ProjectVcsConfigFile {
|
||||
readonly vcs?:
|
||||
| {
|
||||
readonly kind?: VcsDriverKindType | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly vcsKind?: VcsDriverKindType | undefined;
|
||||
}
|
||||
|
||||
export interface VcsProjectConfigResolveInput {
|
||||
readonly cwd: string;
|
||||
readonly requestedKind?: VcsDriverKindType | "auto";
|
||||
}
|
||||
|
||||
export interface VcsProjectConfigShape {
|
||||
readonly resolveKind: (
|
||||
input: VcsProjectConfigResolveInput,
|
||||
) => Effect.Effect<VcsDriverKindType | "auto">;
|
||||
}
|
||||
|
||||
export class VcsProjectConfig extends Context.Service<VcsProjectConfig, VcsProjectConfigShape>()(
|
||||
"t3/vcs/VcsProjectConfig",
|
||||
) {}
|
||||
|
||||
function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto" {
|
||||
return config.vcs?.kind ?? config.vcsKind ?? "auto";
|
||||
}
|
||||
|
||||
function parseConfig(raw: string): ProjectVcsConfigFile | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return Schema.is(ProjectVcsConfig)(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const findConfigPath = Effect.fn("VcsProjectConfig.findConfigPath")(function* (cwd: string) {
|
||||
let current = cwd;
|
||||
while (true) {
|
||||
const candidate = path.join(current, ".t3code", "vcs.json");
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const parent = path.dirname(current);
|
||||
if (parent === current) {
|
||||
return null;
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfiguredKind = Effect.fn("VcsProjectConfig.readConfiguredKind")(function* (
|
||||
configPath: string,
|
||||
) {
|
||||
const raw = yield* fileSystem.readFileString(configPath).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to read VCS project config", {
|
||||
configPath,
|
||||
error,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
if (raw === null) {
|
||||
return "auto" as const;
|
||||
}
|
||||
|
||||
const parsed = parseConfig(raw);
|
||||
if (parsed === null) {
|
||||
yield* Effect.logWarning("invalid VCS project config", {
|
||||
configPath,
|
||||
});
|
||||
return "auto" as const;
|
||||
}
|
||||
|
||||
return configuredKind(parsed);
|
||||
});
|
||||
|
||||
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
|
||||
"VcsProjectConfig.resolveKind",
|
||||
)(function* (input) {
|
||||
if (input.requestedKind !== undefined && input.requestedKind !== "auto") {
|
||||
return input.requestedKind;
|
||||
}
|
||||
|
||||
const configPath = yield* findConfigPath(input.cwd);
|
||||
if (configPath === null) {
|
||||
return "auto";
|
||||
}
|
||||
|
||||
return yield* readConfiguredKind(configPath);
|
||||
});
|
||||
|
||||
return VcsProjectConfig.of({
|
||||
resolveKind,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(VcsProjectConfig, make());
|
||||
@@ -1,339 +0,0 @@
|
||||
import {
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Fiber,
|
||||
Layer,
|
||||
PubSub,
|
||||
Ref,
|
||||
Scope,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import type {
|
||||
GitManagerServiceError,
|
||||
VcsStatusInput,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import { GitWorkflowService } from "../git/GitWorkflowService.ts";
|
||||
|
||||
const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
|
||||
interface VcsStatusChange {
|
||||
readonly cwd: string;
|
||||
readonly event: VcsStatusStreamEvent;
|
||||
}
|
||||
|
||||
interface CachedValue<T> {
|
||||
readonly fingerprint: string;
|
||||
readonly value: T;
|
||||
}
|
||||
|
||||
interface CachedVcsStatus {
|
||||
readonly local: CachedValue<VcsStatusLocalResult> | null;
|
||||
readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
|
||||
}
|
||||
|
||||
interface ActiveRemotePoller {
|
||||
readonly fiber: Fiber.Fiber<void, never>;
|
||||
readonly subscriberCount: number;
|
||||
}
|
||||
|
||||
export interface VcsStatusBroadcasterShape {
|
||||
readonly getStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class VcsStatusBroadcaster extends Context.Service<
|
||||
VcsStatusBroadcaster,
|
||||
VcsStatusBroadcasterShape
|
||||
>()("t3/vcs/VcsStatusBroadcaster") {}
|
||||
|
||||
function fingerprintStatusPart(status: unknown): string {
|
||||
return JSON.stringify(status);
|
||||
}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
VcsStatusBroadcaster,
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<VcsStatusChange>(),
|
||||
(pubsub) => PubSub.shutdown(pubsub),
|
||||
);
|
||||
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
|
||||
const normalizeCwd = (cwd: string) =>
|
||||
fileSystem.realPath(cwd).pipe(Effect.catch(() => Effect.succeed(cwd)));
|
||||
|
||||
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
|
||||
});
|
||||
|
||||
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
|
||||
function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
|
||||
const nextLocal = {
|
||||
fingerprint: fingerprintStatusPart(local),
|
||||
value: local,
|
||||
} satisfies CachedValue<VcsStatusLocalResult>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
...previous,
|
||||
local: nextLocal,
|
||||
});
|
||||
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
yield* PubSub.publish(changesPubSub, {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "localUpdated",
|
||||
local,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return local;
|
||||
},
|
||||
);
|
||||
|
||||
const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
|
||||
function* (
|
||||
cwd: string,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
options?: { publish?: boolean },
|
||||
) {
|
||||
const nextRemote = {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
} satisfies CachedValue<VcsStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
const nextCache = new Map(cache);
|
||||
nextCache.set(cwd, {
|
||||
...previous,
|
||||
remote: nextRemote,
|
||||
});
|
||||
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
|
||||
});
|
||||
|
||||
if (options?.publish && shouldPublish) {
|
||||
yield* PubSub.publish(changesPubSub, {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "remoteUpdated",
|
||||
remote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return remote;
|
||||
},
|
||||
);
|
||||
|
||||
const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const local = yield* workflow.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local);
|
||||
});
|
||||
|
||||
const loadRemoteStatus = Effect.fn("VcsStatusBroadcaster.loadRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const remote = yield* workflow.remoteStatus({ cwd });
|
||||
return yield* updateCachedRemoteStatus(cwd, remote);
|
||||
});
|
||||
|
||||
const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (cached?.local) {
|
||||
return cached.local.value;
|
||||
}
|
||||
return yield* loadLocalStatus(cwd);
|
||||
});
|
||||
|
||||
const getOrLoadRemoteStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadRemoteStatus")(
|
||||
function* (cwd: string) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
if (cached?.remote) {
|
||||
return cached.remote.value;
|
||||
}
|
||||
return yield* loadRemoteStatus(cwd);
|
||||
},
|
||||
);
|
||||
|
||||
const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.getStatus",
|
||||
)(function* (input) {
|
||||
const cwd = yield* normalizeCwd(input.cwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
getOrLoadLocalStatus(cwd),
|
||||
getOrLoadRemoteStatus(cwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshLocalStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* normalizeCwd(rawCwd);
|
||||
yield* workflow.invalidateLocalStatus(cwd);
|
||||
const local = yield* workflow.localStatus({ cwd });
|
||||
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
|
||||
});
|
||||
|
||||
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
const remote = yield* workflow.remoteStatus({ cwd });
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
});
|
||||
|
||||
const refreshStatus: VcsStatusBroadcasterShape["refreshStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* normalizeCwd(rawCwd);
|
||||
const [local, remote] = yield* Effect.all([
|
||||
refreshLocalStatus(cwd),
|
||||
refreshRemoteStatus(cwd),
|
||||
]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const makeRemoteRefreshLoop = (cwd: string) => {
|
||||
const logRefreshFailure = (error: Error) =>
|
||||
Effect.logWarning("VCS remote status refresh failed", {
|
||||
cwd,
|
||||
detail: error.message,
|
||||
});
|
||||
|
||||
return refreshRemoteStatus(cwd).pipe(
|
||||
Effect.catch(logRefreshFailure),
|
||||
Effect.andThen(
|
||||
Effect.forever(
|
||||
Effect.sleep(VCS_STATUS_REFRESH_INTERVAL).pipe(
|
||||
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (existing) {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount + 1,
|
||||
});
|
||||
return Effect.succeed([undefined, nextPollers] as const);
|
||||
}
|
||||
|
||||
return makeRemoteRefreshLoop(cwd).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
fiber,
|
||||
subscriberCount: 1,
|
||||
});
|
||||
return [undefined, nextPollers] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
if (!existing) {
|
||||
return [null, activePollers] as const;
|
||||
}
|
||||
|
||||
if (existing.subscriberCount > 1) {
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.set(cwd, {
|
||||
...existing,
|
||||
subscriberCount: existing.subscriberCount - 1,
|
||||
});
|
||||
return [null, nextPollers] as const;
|
||||
}
|
||||
|
||||
const nextPollers = new Map(activePollers);
|
||||
nextPollers.delete(cwd);
|
||||
return [existing.fiber, nextPollers] as const;
|
||||
});
|
||||
|
||||
if (pollerToInterrupt) {
|
||||
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* normalizeCwd(input.cwd);
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
const initialLocal = yield* getOrLoadLocalStatus(cwd);
|
||||
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
|
||||
yield* retainRemotePoller(cwd);
|
||||
|
||||
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
_tag: "snapshot" as const,
|
||||
local: initialLocal,
|
||||
remote: initialRemote,
|
||||
}),
|
||||
Stream.fromSubscription(subscription).pipe(
|
||||
Stream.filter((event) => event.cwd === cwd),
|
||||
Stream.map((event) => event.event),
|
||||
),
|
||||
).pipe(Stream.ensuring(release));
|
||||
}),
|
||||
);
|
||||
|
||||
return VcsStatusBroadcaster.of({
|
||||
getStatus,
|
||||
refreshLocalStatus,
|
||||
refreshStatus,
|
||||
streamStatus,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,154 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Option } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path, type PlatformError, type Scope } from "effect";
|
||||
import { describe } from "vitest";
|
||||
|
||||
import type { VcsDriverKind } from "@t3tools/contracts";
|
||||
import { VcsDriver } from "../VcsDriver.ts";
|
||||
|
||||
export interface VcsDriverFixture<R, E> {
|
||||
readonly createRepo: (cwd: string) => Effect.Effect<void, E, R>;
|
||||
readonly writeFile: (
|
||||
cwd: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
) => Effect.Effect<void, E, R | FileSystem.FileSystem | Path.Path>;
|
||||
readonly trackFile?: (cwd: string, relativePath: string) => Effect.Effect<void, E, R>;
|
||||
readonly commit?: (cwd: string, message: string) => Effect.Effect<void, E, R>;
|
||||
readonly ignorePath: (
|
||||
cwd: string,
|
||||
pattern: string,
|
||||
) => Effect.Effect<void, E, R | FileSystem.FileSystem | Path.Path>;
|
||||
}
|
||||
|
||||
export interface VcsDriverContractSuiteInput<R, E> {
|
||||
readonly name: string;
|
||||
readonly kind: VcsDriverKind;
|
||||
readonly layer: Layer.Layer<VcsDriver | R | FileSystem.FileSystem | Path.Path, E, never>;
|
||||
readonly fixture: VcsDriverFixture<R, E>;
|
||||
}
|
||||
|
||||
export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInput<R, E>) {
|
||||
const makeTmpDir = (
|
||||
prefix = `t3-${input.kind}-vcs-contract-`,
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
||||
});
|
||||
|
||||
it.layer(input.layer)(`${input.name} VCS driver contract`, (it) => {
|
||||
describe("repository detection", () => {
|
||||
it.effect("returns null outside a repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* VcsDriver;
|
||||
|
||||
assert.equal(yield* driver.detectRepository(cwd), null);
|
||||
assert.equal(yield* driver.isInsideWorkTree(cwd), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("detects repository identity inside a repository and nested directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* VcsDriver;
|
||||
|
||||
yield* input.fixture.createRepo(cwd);
|
||||
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCwd = yield* fileSystem.realPath(cwd);
|
||||
const identity = yield* driver.detectRepository(cwd);
|
||||
assert.equal(identity?.kind, input.kind);
|
||||
assert.isTrue(identity?.rootPath.endsWith(realCwd));
|
||||
assert.equal(identity?.freshness.source, "live-local");
|
||||
assert.isTrue(DateTime.isDateTime(identity?.freshness.observedAt));
|
||||
assert.isTrue(Option.isNone(identity?.freshness.expiresAt ?? Option.none()));
|
||||
assert.equal(yield* driver.isInsideWorkTree(cwd), true);
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const nestedDir = path.join(cwd, "src");
|
||||
const nestedIdentity = yield* driver.detectRepository(nestedDir);
|
||||
assert.equal(nestedIdentity?.rootPath, identity?.rootPath);
|
||||
assert.equal(yield* driver.isInsideWorkTree(nestedDir), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("workspace files", () => {
|
||||
it.effect("lists tracked and untracked non-ignored files", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* VcsDriver;
|
||||
|
||||
yield* input.fixture.createRepo(cwd);
|
||||
yield* input.fixture.writeFile(cwd, "tracked.ts", "export const tracked = true;\n");
|
||||
if (input.fixture.trackFile && input.fixture.commit) {
|
||||
yield* input.fixture.trackFile(cwd, "tracked.ts");
|
||||
yield* input.fixture.commit(cwd, "Track file");
|
||||
}
|
||||
yield* input.fixture.writeFile(cwd, "untracked.ts", "export const untracked = true;\n");
|
||||
|
||||
const result = yield* driver.listWorkspaceFiles(cwd);
|
||||
|
||||
assert.include(result.paths, "tracked.ts");
|
||||
assert.include(result.paths, "untracked.ts");
|
||||
assert.equal(result.truncated, false);
|
||||
assert.equal(result.freshness.source, "live-local");
|
||||
assert.isTrue(DateTime.isDateTime(result.freshness.observedAt));
|
||||
assert.isTrue(Option.isNone(result.freshness.expiresAt));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("excludes ignored files from workspace listing", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* VcsDriver;
|
||||
|
||||
yield* input.fixture.createRepo(cwd);
|
||||
yield* input.fixture.ignorePath(cwd, "*.log");
|
||||
yield* input.fixture.writeFile(cwd, "included.ts", "export const included = true;\n");
|
||||
yield* input.fixture.writeFile(cwd, "debug.log", "ignore me\n");
|
||||
yield* input.fixture.writeFile(cwd, "nested/error.log", "ignore me too\n");
|
||||
|
||||
const result = yield* driver.listWorkspaceFiles(cwd);
|
||||
|
||||
assert.include(result.paths, "included.ts");
|
||||
assert.notInclude(result.paths, "debug.log");
|
||||
assert.notInclude(result.paths, "nested/error.log");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("ignored path filtering", () => {
|
||||
it.effect("filters ignored paths", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* VcsDriver;
|
||||
|
||||
yield* input.fixture.createRepo(cwd);
|
||||
yield* input.fixture.ignorePath(cwd, "*.log");
|
||||
|
||||
const result = yield* driver.filterIgnoredPaths(cwd, [
|
||||
"keep.ts",
|
||||
"debug.log",
|
||||
"nested/error.log",
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(result, ["keep.ts"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns empty input unchanged", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const driver = yield* VcsDriver;
|
||||
|
||||
yield* input.fixture.createRepo(cwd);
|
||||
|
||||
assert.deepStrictEqual(yield* driver.filterIgnoredPaths(cwd, []), []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -5,8 +5,8 @@ import { it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
@@ -14,8 +14,7 @@ import { WorkspacePathsLive } from "./WorkspacePaths.ts";
|
||||
const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-workspace-entries-test-",
|
||||
@@ -26,11 +25,12 @@ const TestLayer = Layer.empty.pipe(
|
||||
|
||||
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const gitCore = yield* GitCore;
|
||||
const dir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: opts?.prefix ?? "t3code-workspace-entries-",
|
||||
});
|
||||
if (opts?.git) {
|
||||
yield* git(dir, ["init"]);
|
||||
yield* gitCore.initRepo({ cwd: dir });
|
||||
}
|
||||
return dir;
|
||||
});
|
||||
@@ -51,10 +51,9 @@ function writeTextFile(
|
||||
|
||||
const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const result = yield* process.run({
|
||||
const gitCore = yield* GitCore;
|
||||
const result = yield* gitCore.execute({
|
||||
operation: "WorkspaceEntries.test.git",
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env } : {}),
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as OS from "node:os";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
|
||||
import { Cache, DateTime, Duration, Effect, Exit, Layer, Path } from "effect";
|
||||
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
|
||||
|
||||
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
|
||||
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
type RankedSearchResult,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
|
||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
WorkspaceEntries,
|
||||
WorkspaceEntriesBrowseError,
|
||||
@@ -174,39 +174,38 @@ const resolveBrowseTarget = (
|
||||
|
||||
export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const vcsRegistry = yield* VcsDriverRegistry;
|
||||
const gitOption = yield* Effect.serviceOption(GitCore);
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
|
||||
const isInsideVcsWorkTree = (cwd: string): Effect.Effect<boolean> =>
|
||||
vcsRegistry.detect({ cwd }).pipe(
|
||||
Effect.map((handle) => handle !== null),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
const isInsideGitWorkTree = (cwd: string): Effect.Effect<boolean> =>
|
||||
Option.match(gitOption, {
|
||||
onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
|
||||
onNone: () => Effect.succeed(false),
|
||||
});
|
||||
|
||||
const filterVcsIgnoredPaths = (
|
||||
const filterGitIgnoredPaths = (
|
||||
cwd: string,
|
||||
relativePaths: string[],
|
||||
): Effect.Effect<string[], never> =>
|
||||
vcsRegistry.detect({ cwd }).pipe(
|
||||
Effect.flatMap((handle) =>
|
||||
handle
|
||||
? handle.driver.filterIgnoredPaths(cwd, relativePaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
)
|
||||
: Effect.succeed(relativePaths),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
);
|
||||
Option.match(gitOption, {
|
||||
onSome: (git) =>
|
||||
git.filterIgnoredPaths(cwd, relativePaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => Effect.succeed(relativePaths)),
|
||||
),
|
||||
onNone: () => Effect.succeed(relativePaths),
|
||||
});
|
||||
|
||||
const buildWorkspaceIndexFromVcs = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromVcs")(
|
||||
const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")(
|
||||
function* (cwd: string) {
|
||||
const vcs = yield* vcsRegistry.detect({ cwd }).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!vcs) {
|
||||
if (Option.isNone(gitOption)) {
|
||||
return null;
|
||||
}
|
||||
if (!(yield* isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = yield* vcs.driver
|
||||
const listedFiles = yield* gitOption.value
|
||||
.listWorkspaceFiles(cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
|
||||
@@ -217,10 +216,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const listedPaths = [...listedFiles.paths]
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = yield* vcs.driver.filterIgnoredPaths(cwd, listedPaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => filterVcsIgnoredPaths(cwd, listedPaths)),
|
||||
);
|
||||
const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
@@ -252,10 +248,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: now.epochMilliseconds,
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
@@ -293,7 +288,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const buildWorkspaceIndexFromFilesystem = Effect.fn(
|
||||
"WorkspaceEntries.buildWorkspaceIndexFromFilesystem",
|
||||
)(function* (cwd: string): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
|
||||
const shouldFilterWithGitIgnore = yield* isInsideVcsWorkTree(cwd);
|
||||
const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: SearchableWorkspaceEntry[] = [];
|
||||
@@ -341,7 +336,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(yield* filterVcsIgnoredPaths(cwd, candidatePaths))
|
||||
? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
@@ -373,9 +368,8 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
return {
|
||||
scannedAt: now.epochMilliseconds,
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
@@ -384,9 +378,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* (
|
||||
cwd: string,
|
||||
): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
|
||||
const vcsIndexed = yield* buildWorkspaceIndexFromVcs(cwd);
|
||||
if (vcsIndexed) {
|
||||
return vcsIndexed;
|
||||
const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
return yield* buildWorkspaceIndexFromFilesystem(cwd);
|
||||
});
|
||||
|
||||
@@ -3,8 +3,7 @@ import { it, describe, expect } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
|
||||
@@ -20,7 +19,7 @@ const TestLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProjectLayer),
|
||||
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-workspace-files-test-",
|
||||
|
||||
+515
-53
@@ -1,6 +1,28 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
copyFile,
|
||||
cp,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { arch, homedir, platform, tmpdir } from "node:os";
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
|
||||
import {
|
||||
type AuthAccessStreamEvent,
|
||||
AcpRegistryIndex,
|
||||
type AcpRegistryAgent,
|
||||
type AcpRegistryInstallBinaryResult,
|
||||
type AcpRegistryListResult,
|
||||
AuthSessionId,
|
||||
CommandId,
|
||||
EventId,
|
||||
@@ -29,6 +51,9 @@ import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitManager } from "./git/Services/GitManager.ts";
|
||||
import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster.ts";
|
||||
import { Keybindings } from "./keybindings.ts";
|
||||
import { Open, resolveAvailableEditors } from "./open.ts";
|
||||
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
||||
@@ -40,6 +65,7 @@ import {
|
||||
observeRpcStreamEffect,
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";
|
||||
import { AcpRegistryClientError } from "./provider/Services/AcpRegistryClient.ts";
|
||||
import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";
|
||||
import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";
|
||||
@@ -47,8 +73,6 @@ import { TerminalManager } from "./terminal/Services/Manager.ts";
|
||||
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";
|
||||
import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "./git/GitWorkflowService.ts";
|
||||
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
@@ -63,6 +87,8 @@ import {
|
||||
} from "./auth/Services/SessionCredentialService.ts";
|
||||
import { respondToAuthError } from "./auth/http.ts";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
@@ -86,6 +112,313 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
|
||||
}
|
||||
|
||||
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
|
||||
const ACP_BINARY_INSTALLS_DIR = "acp_agents";
|
||||
const ACP_BINARY_MANIFEST_FILE = "install.json";
|
||||
|
||||
type BinaryDistributionTarget = {
|
||||
readonly archive: string;
|
||||
readonly cmd: string;
|
||||
};
|
||||
|
||||
type AcpBinaryInstallManifest = {
|
||||
readonly layoutVersion: 2;
|
||||
readonly agentId: string;
|
||||
readonly version: string;
|
||||
readonly platformKey: string;
|
||||
readonly command: string;
|
||||
readonly archiveUrl: string;
|
||||
};
|
||||
|
||||
function getAcpBinaryPlatformKey(): string {
|
||||
const os = platform();
|
||||
const cpu = arch();
|
||||
const osKey =
|
||||
os === "darwin" ? "darwin" : os === "win32" ? "windows" : os === "linux" ? "linux" : os;
|
||||
const archKey = cpu === "arm64" ? "aarch64" : cpu === "x64" ? "x86_64" : cpu;
|
||||
return `${osKey}-${archKey}`;
|
||||
}
|
||||
|
||||
function getBinaryTarget(agent: AcpRegistryAgent): BinaryDistributionTarget | null {
|
||||
const binary = agent.distribution.binary;
|
||||
if (!binary || typeof binary !== "object" || globalThis.Array.isArray(binary)) return null;
|
||||
const target = (binary as Record<string, unknown>)[getAcpBinaryPlatformKey()];
|
||||
if (!target || typeof target !== "object" || globalThis.Array.isArray(target)) return null;
|
||||
const record = target as Record<string, unknown>;
|
||||
if (typeof record.archive !== "string" || typeof record.cmd !== "string") return null;
|
||||
return { archive: record.archive, cmd: record.cmd };
|
||||
}
|
||||
|
||||
async function fileExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeArchiveCommandPath(command: string): string {
|
||||
const trimmed = command.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error("Registry binary command must not be empty.");
|
||||
}
|
||||
if (isAbsolute(trimmed)) {
|
||||
throw new Error("Registry binary command must be a relative archive path.");
|
||||
}
|
||||
const withoutLeadingDot = trimmed.replace(/^(?:\.[/\\])+/u, "");
|
||||
const parts = withoutLeadingDot
|
||||
.split(/[/\\]+/u)
|
||||
.filter((part) => part.length > 0 && part !== ".");
|
||||
if (parts.length === 0 || parts.some((part) => part === "..")) {
|
||||
throw new Error("Registry binary command resolves outside the archive.");
|
||||
}
|
||||
return join(...parts);
|
||||
}
|
||||
|
||||
function resolveInstallRootFromBinaryPath(binaryPath: string, commandRelativePath: string): string {
|
||||
const depth = commandRelativePath.split(/[/\\]+/u).filter((part) => part.length > 0).length;
|
||||
let installRoot = binaryPath;
|
||||
for (let index = 0; index < depth; index += 1) {
|
||||
installRoot = dirname(installRoot);
|
||||
}
|
||||
return installRoot;
|
||||
}
|
||||
|
||||
function resolveAcpBinaryInstallPath(
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
) {
|
||||
const commandPath = normalizeArchiveCommandPath(getBinaryTarget(agent)?.cmd ?? agent.id);
|
||||
return join(config.stateDir, ACP_BINARY_INSTALLS_DIR, agent.id, agent.version, commandPath);
|
||||
}
|
||||
|
||||
function expandUserPath(path: string): string {
|
||||
if (path === "~") return homedir();
|
||||
if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2));
|
||||
return path;
|
||||
}
|
||||
|
||||
function normalizeAcpBinaryInstallPath(path: string): string {
|
||||
const expanded = expandUserPath(path.trim());
|
||||
return isAbsolute(expanded) ? expanded : resolve(expanded);
|
||||
}
|
||||
|
||||
function displayPath(path: string): string {
|
||||
const home = homedir();
|
||||
return path === home || path.startsWith(`${home}/`) || path.startsWith(`${home}\\`)
|
||||
? `~${path.slice(home.length)}`
|
||||
: path;
|
||||
}
|
||||
|
||||
function isPathInside(parent: string, child: string): boolean {
|
||||
const relativePath = relative(parent, child);
|
||||
return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath));
|
||||
}
|
||||
|
||||
function toBinaryInstallPreview(
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
target: BinaryDistributionTarget,
|
||||
) {
|
||||
const defaultInstallPath = resolveAcpBinaryInstallPath(config, agent);
|
||||
return {
|
||||
archiveUrl: target.archive,
|
||||
defaultInstallPath: displayPath(defaultInstallPath),
|
||||
platformKey: getAcpBinaryPlatformKey(),
|
||||
command: target.cmd,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAcpBinaryManifestPath(
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
) {
|
||||
return join(dirname(resolveAcpBinaryInstallPath(config, agent)), ACP_BINARY_MANIFEST_FILE);
|
||||
}
|
||||
|
||||
async function readAcpBinaryManifest(
|
||||
config: { readonly stateDir: string },
|
||||
agent: AcpRegistryAgent,
|
||||
): Promise<AcpBinaryInstallManifest | null> {
|
||||
const manifestPath = resolveAcpBinaryManifestPath(config, agent);
|
||||
try {
|
||||
const raw = await readFile(manifestPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<AcpBinaryInstallManifest>;
|
||||
if (
|
||||
parsed.layoutVersion === 2 &&
|
||||
parsed.agentId === agent.id &&
|
||||
parsed.version === agent.version &&
|
||||
parsed.platformKey === getAcpBinaryPlatformKey() &&
|
||||
typeof parsed.command === "string" &&
|
||||
(await fileExists(parsed.command))
|
||||
) {
|
||||
return parsed as AcpBinaryInstallManifest;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadFile(url: string, destination: string): Promise<void> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`Download failed with status ${response.status}`);
|
||||
}
|
||||
await pipeline(response.body, createWriteStream(destination));
|
||||
}
|
||||
|
||||
async function extractArchive(archivePath: string, destinationDir: string): Promise<void> {
|
||||
if (archivePath.endsWith(".tar.gz") || archivePath.endsWith(".tgz")) {
|
||||
await execFileAsync("tar", ["-xzf", archivePath, "-C", destinationDir]);
|
||||
return;
|
||||
}
|
||||
if (archivePath.endsWith(".zip")) {
|
||||
if (platform() === "win32") {
|
||||
await execFileAsync("powershell.exe", [
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"Expand-Archive",
|
||||
"-LiteralPath",
|
||||
archivePath,
|
||||
"-DestinationPath",
|
||||
destinationDir,
|
||||
"-Force",
|
||||
]);
|
||||
return;
|
||||
}
|
||||
await execFileAsync("unzip", ["-q", archivePath, "-d", destinationDir]);
|
||||
return;
|
||||
}
|
||||
throw new Error("Unsupported binary archive format.");
|
||||
}
|
||||
|
||||
async function installAcpBinaryAgent(input: {
|
||||
readonly config: { readonly stateDir: string };
|
||||
readonly agent: AcpRegistryAgent;
|
||||
readonly installPath?: string | undefined;
|
||||
}): Promise<BinaryDistributionTarget & { readonly command: string }> {
|
||||
const target = getBinaryTarget(input.agent);
|
||||
if (!target) {
|
||||
throw new Error(`No binary is available for ${getAcpBinaryPlatformKey()}.`);
|
||||
}
|
||||
const installPath = normalizeAcpBinaryInstallPath(
|
||||
input.installPath?.trim() || resolveAcpBinaryInstallPath(input.config, input.agent),
|
||||
);
|
||||
const commandPath = normalizeArchiveCommandPath(target.cmd);
|
||||
const installRoot = resolveInstallRootFromBinaryPath(installPath, commandPath);
|
||||
if (installRoot === dirname(installRoot)) {
|
||||
throw new Error(`Binary path is too shallow for registry command '${target.cmd}'.`);
|
||||
}
|
||||
const manifestPath = resolveAcpBinaryManifestPath(input.config, input.agent);
|
||||
const tempDir = await mkdtemp(join(tmpdir(), "t3-acp-agent-"));
|
||||
try {
|
||||
const archivePath = join(
|
||||
tempDir,
|
||||
basename(new URL(target.archive).pathname) || "agent.archive",
|
||||
);
|
||||
const extractDir = join(tempDir, "extract");
|
||||
await mkdir(extractDir, { recursive: true });
|
||||
await downloadFile(target.archive, archivePath);
|
||||
await extractArchive(archivePath, extractDir);
|
||||
|
||||
const extractedCommand = resolve(extractDir, commandPath);
|
||||
if (!isPathInside(extractDir, extractedCommand)) {
|
||||
throw new Error(`Registry binary command resolves outside the archive.`);
|
||||
}
|
||||
if (!(await fileExists(extractedCommand))) {
|
||||
throw new Error(`Installed archive did not contain expected command '${target.cmd}'.`);
|
||||
}
|
||||
await mkdir(installRoot, { recursive: true });
|
||||
await cp(extractDir, installRoot, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
errorOnExist: false,
|
||||
});
|
||||
if (!(await fileExists(installPath))) {
|
||||
await mkdir(dirname(installPath), { recursive: true });
|
||||
await copyFile(extractedCommand, installPath);
|
||||
}
|
||||
if (platform() !== "win32") {
|
||||
await chmod(installPath, 0o755);
|
||||
}
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
const manifest: AcpBinaryInstallManifest = {
|
||||
layoutVersion: 2,
|
||||
agentId: input.agent.id,
|
||||
version: input.agent.version,
|
||||
platformKey: getAcpBinaryPlatformKey(),
|
||||
command: installPath,
|
||||
archiveUrl: target.archive,
|
||||
};
|
||||
await mkdir(dirname(manifestPath), { recursive: true });
|
||||
await writeFile(manifestPath, JSON.stringify(manifest, null, 2));
|
||||
return { ...target, command: installPath };
|
||||
}
|
||||
|
||||
async function toAcpLaunchSpec(
|
||||
agent: AcpRegistryAgent,
|
||||
config: { readonly stateDir: string },
|
||||
): Promise<{
|
||||
readonly supported: boolean;
|
||||
readonly distributionType: "npx" | "uvx" | "binary" | "binaryUnsupported";
|
||||
readonly launch: {
|
||||
readonly command: string;
|
||||
readonly args: readonly string[];
|
||||
readonly env: Record<string, string>;
|
||||
} | null;
|
||||
readonly binaryInstall?: {
|
||||
readonly archiveUrl: string;
|
||||
readonly defaultInstallPath: string;
|
||||
readonly platformKey: string;
|
||||
readonly command: string;
|
||||
};
|
||||
}> {
|
||||
if (agent.distribution.npx) {
|
||||
return {
|
||||
supported: true as const,
|
||||
distributionType: "npx" as const,
|
||||
launch: {
|
||||
command: "npx",
|
||||
args: ["-y", agent.distribution.npx.package, ...(agent.distribution.npx.args ?? [])],
|
||||
env: agent.distribution.npx.env ?? {},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (agent.distribution.uvx) {
|
||||
return {
|
||||
supported: true as const,
|
||||
distributionType: "uvx" as const,
|
||||
launch: {
|
||||
command: "uvx",
|
||||
args: [agent.distribution.uvx.package, ...(agent.distribution.uvx.args ?? [])],
|
||||
env: agent.distribution.uvx.env ?? {},
|
||||
},
|
||||
};
|
||||
}
|
||||
const manifest = await readAcpBinaryManifest(config, agent);
|
||||
const target = getBinaryTarget(agent);
|
||||
if (manifest) {
|
||||
return {
|
||||
supported: true as const,
|
||||
distributionType: "binary" as const,
|
||||
launch: {
|
||||
command: manifest.command,
|
||||
args: [],
|
||||
env: {},
|
||||
},
|
||||
...(target ? { binaryInstall: toBinaryInstallPreview(config, agent, target) } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
supported: false as const,
|
||||
distributionType: "binaryUnsupported" as const,
|
||||
launch: null,
|
||||
...(target ? { binaryInstall: toBinaryInstallPreview(config, agent, target) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: BootstrapCredentialChange | SessionCredentialChange,
|
||||
@@ -135,8 +468,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const gitManager = yield* GitManager;
|
||||
const git = yield* GitCore;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
@@ -160,6 +494,110 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie),
|
||||
});
|
||||
|
||||
const loadAcpRegistryIndex = serverSettings.getSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const response = await fetch(settings.providers.acpRegistry.registryUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Registry request failed with status ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
catch: (cause) =>
|
||||
new AcpRegistryClientError({
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((raw) => Schema.decodeUnknownEffect(AcpRegistryIndex)(raw)),
|
||||
);
|
||||
|
||||
const listAcpRegistry = Effect.all({
|
||||
registry: loadAcpRegistryIndex,
|
||||
config: Effect.succeed(config),
|
||||
}).pipe(
|
||||
Effect.flatMap(({ registry, config }) =>
|
||||
Effect.tryPromise({
|
||||
try: async (): Promise<AcpRegistryListResult> => ({
|
||||
registryVersion: registry.version,
|
||||
agents: (
|
||||
await Promise.all(
|
||||
registry.agents.map(async (agent) => {
|
||||
const resolved = await toAcpLaunchSpec(agent, config);
|
||||
return {
|
||||
agent,
|
||||
supported: resolved.supported,
|
||||
distributionType: resolved.distributionType,
|
||||
launch: resolved.launch,
|
||||
...(resolved.binaryInstall ? { binaryInstall: resolved.binaryInstall } : {}),
|
||||
};
|
||||
}),
|
||||
)
|
||||
).toSorted((left, right) => left.agent.name.localeCompare(right.agent.name)),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new AcpRegistryClientError({
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const installAcpRegistryBinary = (input: {
|
||||
readonly agentId: string;
|
||||
readonly installPath?: string | undefined;
|
||||
}) =>
|
||||
Effect.all({
|
||||
registry: loadAcpRegistryIndex,
|
||||
config: Effect.succeed(config),
|
||||
}).pipe(
|
||||
Effect.flatMap(({ registry, config }) =>
|
||||
Effect.tryPromise({
|
||||
try: async (): Promise<AcpRegistryInstallBinaryResult> => {
|
||||
const agent = registry.agents.find((entry) => entry.id === input.agentId);
|
||||
if (!agent) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `No ACP registry agent found for '${input.agentId}'.`,
|
||||
};
|
||||
}
|
||||
const installed = await installAcpBinaryAgent({
|
||||
config,
|
||||
agent,
|
||||
installPath: input.installPath,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
agent: {
|
||||
agent,
|
||||
supported: true,
|
||||
distributionType: "binary",
|
||||
binaryInstall: toBinaryInstallPreview(config, agent, installed),
|
||||
launch: {
|
||||
command: installed.command,
|
||||
args: [],
|
||||
env: {},
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
catch: (cause): AcpRegistryInstallBinaryResult => ({
|
||||
ok: false,
|
||||
error: cause instanceof Error ? cause.message : String(cause),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((cause: unknown) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
error: cause instanceof Error ? cause.message : String(cause),
|
||||
} satisfies AcpRegistryInstallBinaryResult),
|
||||
),
|
||||
);
|
||||
|
||||
const appendSetupScriptActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
|
||||
@@ -451,10 +889,10 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}
|
||||
|
||||
if (bootstrap?.prepareWorktree) {
|
||||
const worktree = yield* gitWorkflow.createWorktree({
|
||||
const worktree = yield* git.createWorktree({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
refName: bootstrap.prepareWorktree.baseBranch,
|
||||
newRefName: bootstrap.prepareWorktree.branch,
|
||||
branch: bootstrap.prepareWorktree.baseBranch,
|
||||
newBranch: bootstrap.prepareWorktree.branch,
|
||||
path: null,
|
||||
});
|
||||
targetWorktreePath = worktree.worktree.path;
|
||||
@@ -462,7 +900,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("bootstrap-thread-meta-update"),
|
||||
threadId: command.threadId,
|
||||
branch: worktree.worktree.refName,
|
||||
branch: worktree.worktree.branch,
|
||||
worktreePath: targetWorktreePath,
|
||||
});
|
||||
yield* refreshGitStatus(targetWorktreePath);
|
||||
@@ -538,7 +976,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
});
|
||||
|
||||
const refreshGitStatus = (cwd: string) =>
|
||||
vcsStatusBroadcaster
|
||||
gitStatusBroadcaster
|
||||
.refreshStatus(cwd)
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
|
||||
|
||||
@@ -781,6 +1219,32 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverListAcpRegistry]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverListAcpRegistry,
|
||||
listAcpRegistry.pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("failed to list ACP registry agents", {
|
||||
error: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => ({
|
||||
registryVersion: "unavailable",
|
||||
agents: [],
|
||||
})),
|
||||
),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverInstallAcpRegistryBinary]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverInstallAcpRegistryBinary,
|
||||
installAcpRegistryBinary(input),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.projectsSearchEntries]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsSearchEntries,
|
||||
@@ -829,26 +1293,26 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.subscribeVcsStatus]: (input) =>
|
||||
[WS_METHODS.subscribeGitStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeVcsStatus,
|
||||
vcsStatusBroadcaster.streamStatus(input),
|
||||
WS_METHODS.subscribeGitStatus,
|
||||
gitStatusBroadcaster.streamStatus(input),
|
||||
{
|
||||
"rpc.aggregate": "vcs",
|
||||
"rpc.aggregate": "git",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.vcsRefreshStatus]: (input) =>
|
||||
[WS_METHODS.gitRefreshStatus]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsRefreshStatus,
|
||||
vcsStatusBroadcaster.refreshStatus(input.cwd),
|
||||
WS_METHODS.gitRefreshStatus,
|
||||
gitStatusBroadcaster.refreshStatus(input.cwd),
|
||||
{
|
||||
"rpc.aggregate": "vcs",
|
||||
"rpc.aggregate": "git",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.vcsPull]: (input) =>
|
||||
[WS_METHODS.gitPull]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsPull,
|
||||
gitWorkflow.pullCurrentBranch(input.cwd).pipe(
|
||||
WS_METHODS.gitPull,
|
||||
git.pullCurrentBranch(input.cwd).pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) => Effect.failCause(cause),
|
||||
onSuccess: (result) =>
|
||||
@@ -861,7 +1325,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.gitRunStackedAction,
|
||||
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
|
||||
gitWorkflow
|
||||
gitManager
|
||||
.runStackedAction(input, {
|
||||
actionId: input.actionId,
|
||||
progressReporter: {
|
||||
@@ -878,57 +1342,55 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.gitResolvePullRequest]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.gitResolvePullRequest,
|
||||
gitWorkflow.resolvePullRequest(input),
|
||||
{
|
||||
"rpc.aggregate": "git",
|
||||
},
|
||||
),
|
||||
observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.gitPreparePullRequestThread,
|
||||
gitWorkflow
|
||||
gitManager
|
||||
.preparePullRequestThread(input)
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.vcsListRefs]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.vcsListRefs, gitWorkflow.listRefs(input), {
|
||||
"rpc.aggregate": "vcs",
|
||||
[WS_METHODS.gitListBranches]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.vcsCreateWorktree]: (input) =>
|
||||
[WS_METHODS.gitCreateWorktree]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsCreateWorktree,
|
||||
gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
WS_METHODS.gitCreateWorktree,
|
||||
git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.vcsRemoveWorktree]: (input) =>
|
||||
[WS_METHODS.gitRemoveWorktree]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsRemoveWorktree,
|
||||
gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
WS_METHODS.gitRemoveWorktree,
|
||||
git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.vcsCreateRef]: (input) =>
|
||||
[WS_METHODS.gitCreateBranch]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsCreateRef,
|
||||
gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
WS_METHODS.gitCreateBranch,
|
||||
git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.vcsSwitchRef]: (input) =>
|
||||
[WS_METHODS.gitCheckout]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsSwitchRef,
|
||||
gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
WS_METHODS.gitCheckout,
|
||||
Effect.scoped(git.checkoutBranch(input)).pipe(
|
||||
Effect.tap(() => refreshGitStatus(input.cwd)),
|
||||
),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.vcsInit]: (input) =>
|
||||
[WS_METHODS.gitInit]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsInit,
|
||||
gitWorkflow.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
WS_METHODS.gitInit,
|
||||
git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "git" },
|
||||
),
|
||||
[WS_METHODS.terminalOpen]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
|
||||
import { EnvironmentId, type GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
@@ -28,7 +28,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
).toBe("local");
|
||||
});
|
||||
|
||||
it("keeps new-worktree mode when selecting a base ref before worktree creation", () => {
|
||||
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: null,
|
||||
@@ -38,7 +38,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("uses worktree mode when selecting a ref already attached to a worktree", () => {
|
||||
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
|
||||
expect(
|
||||
resolveDraftEnvModeAfterBranchChange({
|
||||
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
@@ -50,7 +50,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
});
|
||||
|
||||
describe("resolveBranchToolbarValue", () => {
|
||||
it("defaults new-worktree mode to current git ref when no explicit base ref is set", () => {
|
||||
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
@@ -61,7 +61,7 @@ describe("resolveBranchToolbarValue", () => {
|
||||
).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps an explicitly selected worktree base ref", () => {
|
||||
it("keeps an explicitly selected worktree base branch", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "worktree",
|
||||
@@ -72,7 +72,7 @@ describe("resolveBranchToolbarValue", () => {
|
||||
).toBe("feature/base");
|
||||
});
|
||||
|
||||
it("shows the actual checked-out ref when not selecting a new worktree base", () => {
|
||||
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
|
||||
expect(
|
||||
resolveBranchToolbarValue({
|
||||
envMode: "local",
|
||||
@@ -186,8 +186,8 @@ describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
});
|
||||
|
||||
describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
it("hides remote refs when the matching local ref exists", () => {
|
||||
const input: VcsRef[] = [
|
||||
it("hides remote refs when the matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
@@ -212,14 +212,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps all entries when no local match exists for a remote ref", () => {
|
||||
const input: VcsRef[] = [
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/local",
|
||||
current: false,
|
||||
@@ -236,14 +236,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/local",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps non-origin remote refs visible even when a matching local ref exists", () => {
|
||||
const input: VcsRef[] = [
|
||||
it("keeps non-origin remote refs visible even when a matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
@@ -260,14 +260,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"my-org/upstream/feature/demo",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps non-origin remote refs visible when git tracks with first-slash local naming", () => {
|
||||
const input: VcsRef[] = [
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "upstream/feature",
|
||||
current: false,
|
||||
@@ -284,7 +284,7 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"upstream/feature",
|
||||
"my-org/upstream/feature",
|
||||
]);
|
||||
@@ -292,12 +292,12 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
});
|
||||
|
||||
describe("resolveBranchSelectionTarget", () => {
|
||||
it("reuses an existing secondary worktree for the selected ref", () => {
|
||||
it("reuses an existing secondary worktree for the selected branch", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
refName: {
|
||||
branch: {
|
||||
isDefault: false,
|
||||
worktreePath: "/repo/.t3/worktrees/feature-b",
|
||||
},
|
||||
@@ -309,12 +309,12 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("switches back to the main repo when the ref already lives there", () => {
|
||||
it("switches back to the main repo when the branch already lives there", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
refName: {
|
||||
branch: {
|
||||
isDefault: true,
|
||||
worktreePath: "/repo",
|
||||
},
|
||||
@@ -326,12 +326,12 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("checks out the default ref in the main repo when leaving a secondary worktree", () => {
|
||||
it("checks out the default branch in the main repo when leaving a secondary worktree", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
refName: {
|
||||
branch: {
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
@@ -343,12 +343,12 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps checkout in the current worktree for non-default refs", () => {
|
||||
it("keeps checkout in the current worktree for non-default branches", () => {
|
||||
expect(
|
||||
resolveBranchSelectionTarget({
|
||||
activeProjectCwd: "/repo",
|
||||
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||
refName: {
|
||||
branch: {
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
@@ -373,7 +373,7 @@ describe("shouldIncludeBranchPickerItem", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the synthetic create-ref item visible for arbitrary ref input", () => {
|
||||
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__create_new_branch__:feature/demo",
|
||||
@@ -384,7 +384,7 @@ describe("shouldIncludeBranchPickerItem", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("still filters ordinary ref items by query text", () => {
|
||||
it("still filters ordinary branch items by query text", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "main",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, GitBranch, ProjectId } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
export {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
@@ -100,24 +100,24 @@ export function resolveBranchToolbarValue(input: {
|
||||
export function resolveBranchSelectionTarget(input: {
|
||||
activeProjectCwd: string;
|
||||
activeWorktreePath: string | null;
|
||||
refName: Pick<VcsRef, "isDefault" | "worktreePath">;
|
||||
branch: Pick<GitBranch, "isDefault" | "worktreePath">;
|
||||
}): {
|
||||
checkoutCwd: string;
|
||||
nextWorktreePath: string | null;
|
||||
reuseExistingWorktree: boolean;
|
||||
} {
|
||||
const { activeProjectCwd, activeWorktreePath, refName } = input;
|
||||
const { activeProjectCwd, activeWorktreePath, branch } = input;
|
||||
|
||||
if (refName.worktreePath) {
|
||||
if (branch.worktreePath) {
|
||||
return {
|
||||
checkoutCwd: refName.worktreePath,
|
||||
nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
|
||||
checkoutCwd: branch.worktreePath,
|
||||
nextWorktreePath: branch.worktreePath === activeProjectCwd ? null : branch.worktreePath,
|
||||
reuseExistingWorktree: true,
|
||||
};
|
||||
}
|
||||
|
||||
const nextWorktreePath =
|
||||
activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
|
||||
activeWorktreePath !== null && branch.isDefault ? null : activeWorktreePath;
|
||||
|
||||
return {
|
||||
checkoutCwd: nextWorktreePath ?? activeProjectCwd,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
@@ -23,7 +23,6 @@ import { cn } from "../lib/utils";
|
||||
import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import { useStore } from "../store";
|
||||
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { resolveVcsTerms } from "../vcsPresentation";
|
||||
import {
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveBranchSelectionTarget,
|
||||
@@ -54,7 +53,7 @@ interface BranchToolbarBranchSelectorProps {
|
||||
envLocked: boolean;
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -67,11 +66,10 @@ function getBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: "local" | "worktree";
|
||||
resolvedActiveBranch: string | null;
|
||||
refNoun: string;
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch, refNoun } = input;
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return `Select ${refNoun}`;
|
||||
return "Select branch";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
@@ -195,7 +193,7 @@ export function BranchToolbarBranchSelector({
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Git ref queries
|
||||
// Git branch queries
|
||||
// ---------------------------------------------------------------------------
|
||||
const queryClient = useQueryClient();
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
@@ -203,7 +201,6 @@ export function BranchToolbarBranchSelector({
|
||||
const deferredBranchQuery = useDeferredValue(branchQuery);
|
||||
|
||||
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
|
||||
const vcsTerms = resolveVcsTerms(branchStatusQuery.data?.kind);
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
|
||||
|
||||
@@ -227,22 +224,22 @@ export function BranchToolbarBranchSelector({
|
||||
query: deferredTrimmedBranchQuery,
|
||||
}),
|
||||
);
|
||||
const refs = useMemo(
|
||||
() => branchesSearchData?.pages.flatMap((page) => page.refs) ?? [],
|
||||
const branches = useMemo(
|
||||
() => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
|
||||
[branchesSearchData?.pages],
|
||||
);
|
||||
const currentGitBranch =
|
||||
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
|
||||
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
|
||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||
envMode: effectiveEnvMode,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
currentGitBranch,
|
||||
});
|
||||
const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchByName = useMemo(
|
||||
() => new Map(refs.map((refName) => [refName.name, refName] as const)),
|
||||
[refs],
|
||||
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||
[branches],
|
||||
);
|
||||
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
|
||||
const prReference = parsePullRequestReference(trimmedBranchQuery);
|
||||
@@ -292,11 +289,11 @@ export function BranchToolbarBranchSelector({
|
||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
|
||||
const branchStatusText = isBranchesSearchPending
|
||||
? `Loading ${vcsTerms.refNounPlural}...`
|
||||
? "Loading branches..."
|
||||
: isFetchingNextPage
|
||||
? `Loading more ${vcsTerms.refNounPlural}...`
|
||||
? "Loading more branches..."
|
||||
: hasNextPage
|
||||
? `Showing ${refs.length} of ${totalBranchCount} ${vcsTerms.refNounPlural}`
|
||||
? `Showing ${branches.length} of ${totalBranchCount} branches`
|
||||
: null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -306,17 +303,17 @@ export function BranchToolbarBranchSelector({
|
||||
startBranchActionTransition(async () => {
|
||||
await action().catch(() => undefined);
|
||||
await queryClient
|
||||
.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, branchCwd) })
|
||||
.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, branchCwd) })
|
||||
.catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (refName: VcsRef) => {
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
|
||||
|
||||
if (isSelectingWorktreeBase) {
|
||||
setThreadBranch(refName.name, null);
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
@@ -325,19 +322,19 @@ export function BranchToolbarBranchSelector({
|
||||
const selectionTarget = resolveBranchSelectionTarget({
|
||||
activeProjectCwd,
|
||||
activeWorktreePath,
|
||||
refName,
|
||||
branch,
|
||||
});
|
||||
|
||||
if (selectionTarget.reuseExistingWorktree) {
|
||||
setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
|
||||
setThreadBranch(branch.name, selectionTarget.nextWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = refName.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(refName.name)
|
||||
: refName.name;
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
@@ -346,12 +343,12 @@ export function BranchToolbarBranchSelector({
|
||||
const previousBranch = resolvedActiveBranch;
|
||||
setOptimisticBranch(selectedBranchName);
|
||||
try {
|
||||
const checkoutResult = await api.vcs.switchRef({
|
||||
const checkoutResult = await api.git.checkout({
|
||||
cwd: selectionTarget.checkoutCwd,
|
||||
refName: refName.name,
|
||||
branch: branch.name,
|
||||
});
|
||||
const nextBranchName = refName.isRemote
|
||||
? (checkoutResult.refName ?? selectedBranchName)
|
||||
const nextBranchName = branch.isRemote
|
||||
? (checkoutResult.branch ?? selectedBranchName)
|
||||
: selectedBranchName;
|
||||
setOptimisticBranch(nextBranchName);
|
||||
setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
|
||||
@@ -360,7 +357,7 @@ export function BranchToolbarBranchSelector({
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to switch ${vcsTerms.refNoun}.`,
|
||||
title: "Failed to checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
@@ -368,7 +365,7 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
const createRef = (rawName: string) => {
|
||||
const createBranch = (rawName: string) => {
|
||||
const name = rawName.trim();
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
||||
@@ -380,19 +377,19 @@ export function BranchToolbarBranchSelector({
|
||||
const previousBranch = resolvedActiveBranch;
|
||||
setOptimisticBranch(name);
|
||||
try {
|
||||
const createBranchResult = await api.vcs.createRef({
|
||||
const createBranchResult = await api.git.createBranch({
|
||||
cwd: branchCwd,
|
||||
refName: name,
|
||||
switchRef: true,
|
||||
branch: name,
|
||||
checkout: true,
|
||||
});
|
||||
setOptimisticBranch(createBranchResult.refName);
|
||||
setThreadBranch(createBranchResult.refName, activeWorktreePath);
|
||||
setOptimisticBranch(createBranchResult.branch);
|
||||
setThreadBranch(createBranchResult.branch, activeWorktreePath);
|
||||
} catch (error) {
|
||||
setOptimisticBranch(previousBranch);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Failed to create and switch ${vcsTerms.refNoun}.`,
|
||||
title: "Failed to create and checkout branch.",
|
||||
description: toBranchActionErrorMessage(error),
|
||||
}),
|
||||
);
|
||||
@@ -423,7 +420,7 @@ export function BranchToolbarBranchSelector({
|
||||
return;
|
||||
}
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: gitQueryKeys.refs(environmentId, branchCwd),
|
||||
queryKey: gitQueryKeys.branches(environmentId, branchCwd),
|
||||
});
|
||||
},
|
||||
[branchCwd, environmentId, queryClient],
|
||||
@@ -485,13 +482,12 @@ export function BranchToolbarBranchSelector({
|
||||
useEffect(() => {
|
||||
if (shouldVirtualizeBranchList) return;
|
||||
maybeFetchNextBranchPage();
|
||||
}, [refs.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
refNoun: vcsTerms.refNoun,
|
||||
});
|
||||
|
||||
function renderPickerItem(itemValue: string, index: number) {
|
||||
@@ -526,27 +522,25 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
onClick={() => createRef(trimmedBranchQuery)}
|
||||
onClick={() => createBranch(trimmedBranchQuery)}
|
||||
>
|
||||
<span className="truncate">
|
||||
Create new {vcsTerms.refNoun} "{trimmedBranchQuery}"
|
||||
</span>
|
||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||
</ComboboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
const refName = branchByName.get(itemValue);
|
||||
if (!refName) return null;
|
||||
const branch = branchByName.get(itemValue);
|
||||
if (!branch) return null;
|
||||
|
||||
const hasSecondaryWorktree =
|
||||
refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
|
||||
const badge = refName.current
|
||||
branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd;
|
||||
const badge = branch.current
|
||||
? "current"
|
||||
: hasSecondaryWorktree
|
||||
? "worktree"
|
||||
: refName.isRemote
|
||||
: branch.isRemote
|
||||
? "remote"
|
||||
: refName.isDefault
|
||||
: branch.isDefault
|
||||
? "default"
|
||||
: null;
|
||||
return (
|
||||
@@ -555,7 +549,7 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
onClick={() => selectBranch(refName)}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
@@ -587,7 +581,7 @@ export function BranchToolbarBranchSelector({
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)}
|
||||
disabled={(isBranchesSearchPending && refs.length === 0) || isBranchActionPending}
|
||||
disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
|
||||
>
|
||||
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon className="shrink-0" />
|
||||
@@ -597,14 +591,14 @@ export function BranchToolbarBranchSelector({
|
||||
<ComboboxInput
|
||||
className="[&_input]:font-sans rounded-md"
|
||||
inputClassName="ring-0"
|
||||
placeholder="Search refs..."
|
||||
placeholder="Search branches..."
|
||||
showTrigger={false}
|
||||
size="sm"
|
||||
value={branchQuery}
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<ComboboxEmpty>No refs found.</ComboboxEmpty>
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
{shouldVirtualizeBranchList ? (
|
||||
<ComboboxListVirtualized>
|
||||
|
||||
@@ -206,7 +206,6 @@ function createMockEnvironmentApi(input: {
|
||||
filesystem: {
|
||||
browse: input.browse,
|
||||
},
|
||||
vcs: {} as EnvironmentApi["vcs"],
|
||||
git: {} as EnvironmentApi["git"],
|
||||
orchestration: {
|
||||
dispatchCommand: input.dispatchCommand,
|
||||
@@ -952,13 +951,13 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.vcsListRefs) {
|
||||
if (tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
refs: [
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -2288,11 +2287,11 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
branchButton.click();
|
||||
|
||||
const branchInput = await waitForElement(
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search refs..."]'),
|
||||
"Unable to find ref search input.",
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
|
||||
"Unable to find branch search input.",
|
||||
);
|
||||
branchInput.focus();
|
||||
await page.getByPlaceholder("Search refs...").fill("1359");
|
||||
await page.getByPlaceholder("Search branches...").fill("1359");
|
||||
|
||||
const checkoutItem = await waitForElement(
|
||||
() =>
|
||||
@@ -2426,7 +2425,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.vcsCreateWorktree)).toBe(
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
@@ -2573,13 +2572,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
refs: [
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -2666,13 +2665,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 2,
|
||||
refs: [
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -2762,13 +2761,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: snapshotWithTwoThreads,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 2,
|
||||
refs: [
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -3022,13 +3021,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
initialPath: `/draft/${activeDraftId}`,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 2,
|
||||
refs: [
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
@@ -3147,13 +3146,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
initialPath: `/draft/${draftId}`,
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.vcsListRefs) {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: branches.length,
|
||||
refs: branches,
|
||||
branches,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
@@ -3171,8 +3170,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
branchButton.click();
|
||||
|
||||
await waitForElement(
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search refs..."]'),
|
||||
"Unable to find ref search input.",
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
|
||||
"Unable to find branch search input.",
|
||||
);
|
||||
|
||||
const popup = await waitForElement(
|
||||
|
||||
@@ -1458,8 +1458,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
? terminalLaunchContext
|
||||
: (storeServerTerminalLaunchContext ?? null);
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const vcsKind = gitStatusQuery.data?.kind ?? null;
|
||||
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const terminalShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
context: {
|
||||
@@ -2137,7 +2136,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
: (activeThread?.branch ?? null);
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo: isVcsRepo,
|
||||
isGitRepo,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -3298,8 +3297,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isVcsRepo={isVcsRepo}
|
||||
vcsKind={vcsKind}
|
||||
isGitRepo={isGitRepo}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
@@ -3379,7 +3377,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
<div
|
||||
className={cn(
|
||||
"pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-1.5 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-2",
|
||||
isVcsRepo
|
||||
isGitRepo
|
||||
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
|
||||
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
|
||||
)}
|
||||
@@ -3452,7 +3450,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
{isVcsRepo && (
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
|
||||
@@ -35,7 +35,6 @@ import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { resolveVcsTerms } from "../vcsPresentation";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
@@ -202,8 +201,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
cwd: activeCwd ?? null,
|
||||
});
|
||||
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const vcsTerms = resolveVcsTerms(gitStatusQuery.data?.kind);
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -280,7 +278,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
enabled: isVcsRepo,
|
||||
enabled: isGitRepo,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
@@ -563,9 +561,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : !isVcsRepo ? (
|
||||
) : !isGitRepo ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a {vcsTerms.repositoryNoun}.
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
|
||||
@@ -113,16 +113,7 @@ vi.mock("~/lib/gitStatusState", () => ({
|
||||
resetGitStatusStateForTests: () => undefined,
|
||||
useGitStatus: vi.fn(() => ({
|
||||
data: {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
kind: "github",
|
||||
name: "GitHub",
|
||||
baseUrl: "https://github.com",
|
||||
},
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: BRANCH_NAME,
|
||||
branch: BRANCH_NAME,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import type { GitStatusResult } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "vitest";
|
||||
import {
|
||||
buildGitActionProgressStages,
|
||||
@@ -11,13 +11,12 @@ import {
|
||||
resolveThreadBranchUpdate,
|
||||
} from "./GitActionsControl.logic";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
return {
|
||||
kind: "git",
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/test",
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "feature/test",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
@@ -32,7 +31,7 @@ function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
};
|
||||
}
|
||||
|
||||
describe("when: ref is clean and has an open PR", () => {
|
||||
describe("when: branch is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
@@ -40,8 +39,8 @@ describe("when: ref is clean and has an open PR", () => {
|
||||
number: 10,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/10",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -57,8 +56,8 @@ describe("when: ref is clean and has an open PR", () => {
|
||||
number: 11,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/11",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -151,7 +150,7 @@ describe("when: git status is unavailable", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean, ahead, and has an open PR", () => {
|
||||
describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
it("resolveQuickAction prefers push", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
@@ -160,8 +159,8 @@ describe("when: ref is clean, ahead, and has an open PR", () => {
|
||||
number: 13,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/13",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -178,8 +177,8 @@ describe("when: ref is clean, ahead, and has an open PR", () => {
|
||||
number: 12,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -213,7 +212,7 @@ describe("when: ref is clean, ahead, and has an open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean, ahead, and has no open PR", () => {
|
||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
it("resolveQuickAction pushes and creates a PR", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||
assert.deepInclude(quick, {
|
||||
@@ -254,7 +253,7 @@ describe("when: ref is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean, up to date, and has no open PR", () => {
|
||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
@@ -294,7 +293,7 @@ describe("when: ref is clean, up to date, and has no open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is behind upstream", () => {
|
||||
describe("when: branch is behind upstream", () => {
|
||||
it("resolveQuickAction returns pull", () => {
|
||||
const quick = resolveQuickAction(status({ behindCount: 2 }), false);
|
||||
assert.deepInclude(quick, { kind: "run_pull", label: "Pull", disabled: false });
|
||||
@@ -331,11 +330,11 @@ describe("when: ref is behind upstream", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref has diverged from upstream", () => {
|
||||
describe("when: branch has diverged from upstream", () => {
|
||||
it("resolveQuickAction returns a disabled sync hint", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, behindCount: 1 }), false);
|
||||
assert.deepEqual(quick, {
|
||||
label: "Sync ref",
|
||||
label: "Sync branch",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Branch has diverged from upstream. Rebase/merge first.",
|
||||
@@ -376,8 +375,8 @@ describe("when: working tree has local changes", () => {
|
||||
number: 16,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/16",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -421,10 +420,10 @@ describe("when: working tree has local changes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: on default ref without open PR", () => {
|
||||
describe("when: on default branch without open PR", () => {
|
||||
it("resolveQuickAction returns commit and push when local changes exist", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ refName: "main", hasWorkingTreeChanges: true }),
|
||||
status({ branch: "main", hasWorkingTreeChanges: true }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -436,9 +435,9 @@ describe("when: on default ref without open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction returns push when ref is ahead", () => {
|
||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ refName: "main", aheadCount: 2, pr: null }),
|
||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -451,7 +450,7 @@ describe("when: on default ref without open PR", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: working tree has local changes and ref is behind upstream", () => {
|
||||
describe("when: working tree has local changes and branch is behind upstream", () => {
|
||||
it("resolveQuickAction still prefers commit, push, and create PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasWorkingTreeChanges: true, behindCount: 1 }),
|
||||
@@ -498,14 +497,14 @@ describe("when: working tree has local changes and ref is behind upstream", () =
|
||||
describe("when: HEAD is detached and there are no local changes", () => {
|
||||
it("resolveQuickAction shows detached head hint", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ refName: null, hasWorkingTreeChanges: false, hasUpstream: false }),
|
||||
status({ branch: null, hasWorkingTreeChanges: false, hasUpstream: false }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||
});
|
||||
|
||||
it("buildMenuItems keeps commit, push, and PR disabled", () => {
|
||||
const items = buildMenuItems(status({ refName: null, hasWorkingTreeChanges: false }), false);
|
||||
const items = buildMenuItems(status({ branch: null, hasWorkingTreeChanges: false }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -535,7 +534,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref has no upstream configured", () => {
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
@@ -558,8 +557,8 @@ describe("when: ref has no upstream configured", () => {
|
||||
number: 14,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/14",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -581,8 +580,8 @@ describe("when: ref has no upstream configured", () => {
|
||||
number: 15,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/15",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
@@ -726,10 +725,10 @@ describe("when: ref has no upstream configured", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolveQuickAction is disabled on default ref when no upstream exists and no commits are ahead", () => {
|
||||
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
refName: "main",
|
||||
branch: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
pr: null,
|
||||
@@ -745,10 +744,10 @@ describe("when: ref has no upstream configured", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction uses push-only on default ref when no upstream exists and commits are ahead", () => {
|
||||
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
refName: "main",
|
||||
branch: "main",
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
pr: null,
|
||||
@@ -764,7 +763,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("buildMenuItems still disables push and create PR when ref is behind", () => {
|
||||
it("buildMenuItems still disables push and create PR when branch is behind", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
@@ -804,7 +803,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
});
|
||||
|
||||
describe("requiresDefaultBranchConfirmation", () => {
|
||||
it("requires confirmation for push actions on default ref", () => {
|
||||
it("requires confirmation for push actions on default branch", () => {
|
||||
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("push", true));
|
||||
assert.isTrue(requiresDefaultBranchConfirmation("create_pr", true));
|
||||
@@ -824,9 +823,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push to default ref?",
|
||||
title: "Push to default branch?",
|
||||
description:
|
||||
'This action will push local commits on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Push to main",
|
||||
});
|
||||
});
|
||||
@@ -839,9 +838,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Push & create PR from default ref?",
|
||||
title: "Push & create PR from default branch?",
|
||||
description:
|
||||
'This action will push local commits and create a PR on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Push & create PR",
|
||||
});
|
||||
});
|
||||
@@ -854,9 +853,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(copy, {
|
||||
title: "Commit, push & create PR from default ref?",
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
description:
|
||||
'This action will commit, push, and create a PR on "main". You can continue on this ref or create a feature ref and run the same action there.',
|
||||
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
|
||||
continueLabel: "Commit, push & create PR",
|
||||
});
|
||||
});
|
||||
@@ -945,7 +944,7 @@ describe("resolveThreadBranchUpdate", () => {
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
subject: "feat: add ref sync",
|
||||
subject: "feat: add branch sync",
|
||||
},
|
||||
push: { status: "pushed", branch: "feature/fix-toast-copy" },
|
||||
pr: { status: "skipped_not_requested" },
|
||||
@@ -969,7 +968,7 @@ describe("resolveThreadBranchUpdate", () => {
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "89abcdef01234567",
|
||||
subject: "feat: add ref sync",
|
||||
subject: "feat: add branch sync",
|
||||
},
|
||||
push: { status: "pushed", branch: "feature/fix-toast-copy" },
|
||||
pr: { status: "skipped_not_requested" },
|
||||
@@ -986,8 +985,8 @@ describe("resolveThreadBranchUpdate", () => {
|
||||
describe("resolveLiveThreadBranchUpdate", () => {
|
||||
it("returns a branch update when live git status differs from stored thread metadata", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "feature/old-ref",
|
||||
gitStatus: status({ refName: "effect-atom" }),
|
||||
threadBranch: "feature/old-branch",
|
||||
gitStatus: status({ branch: "effect-atom" }),
|
||||
});
|
||||
|
||||
assert.deepEqual(update, {
|
||||
@@ -997,35 +996,35 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
|
||||
it("returns null when live git status is unavailable", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "feature/old-ref",
|
||||
threadBranch: "feature/old-branch",
|
||||
gitStatus: null,
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("returns null when the stored thread ref already matches git status", () => {
|
||||
it("returns null when the stored thread branch already matches git status", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "effect-atom",
|
||||
gitStatus: status({ refName: "effect-atom" }),
|
||||
gitStatus: status({ branch: "effect-atom" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("returns null when git status is detached HEAD but the thread already has a ref", () => {
|
||||
it("returns null when git status is detached HEAD but the thread already has a branch", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "effect-atom",
|
||||
gitStatus: status({ refName: null }),
|
||||
gitStatus: status({ branch: null }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
});
|
||||
|
||||
it("does not regress a semantic thread ref back to a temporary worktree ref", () => {
|
||||
it("does not regress a semantic thread branch back to a temporary worktree branch", () => {
|
||||
const update = resolveLiveThreadBranchUpdate({
|
||||
threadBranch: "t3code/github-query-rate-limit",
|
||||
gitStatus: status({ refName: "t3code/bda76797" }),
|
||||
gitStatus: status({ branch: "t3code/bda76797" }),
|
||||
});
|
||||
|
||||
assert.equal(update, null);
|
||||
@@ -1033,31 +1032,31 @@ describe("resolveLiveThreadBranchUpdate", () => {
|
||||
});
|
||||
|
||||
describe("resolveAutoFeatureBranchName", () => {
|
||||
it("uses semantic preferred ref names when available", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(ref, "feature/fix-toast-copy");
|
||||
it("uses semantic preferred branch names when available", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||
assert.equal(branch, "feature/fix-toast-copy");
|
||||
});
|
||||
|
||||
it("normalizes preferred names that already include a ref namespace", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||
assert.equal(ref, "feature/refine-toolbar-actions");
|
||||
it("normalizes preferred names that already include a branch namespace", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||
assert.equal(branch, "feature/refine-toolbar-actions");
|
||||
});
|
||||
|
||||
it("increments suffix when the preferred ref name already exists", () => {
|
||||
const ref = resolveAutoFeatureBranchName(
|
||||
it("increments suffix when the preferred branch name already exists", () => {
|
||||
const branch = resolveAutoFeatureBranchName(
|
||||
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
|
||||
"fix toast copy",
|
||||
);
|
||||
assert.equal(ref, "feature/fix-toast-copy-3");
|
||||
assert.equal(branch, "feature/fix-toast-copy-3");
|
||||
});
|
||||
|
||||
it("treats existing ref names as case-insensitive for collision checks", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||
assert.equal(ref, "feature/ticket-1-2");
|
||||
it("treats existing branch names as case-insensitive for collision checks", () => {
|
||||
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||
assert.equal(branch, "feature/ticket-1-2");
|
||||
});
|
||||
|
||||
it("falls back to feature/update when no preferred name is provided", () => {
|
||||
const ref = resolveAutoFeatureBranchName(["main"]);
|
||||
assert.equal(ref, "feature/update");
|
||||
const branch = resolveAutoFeatureBranchName(["main"]);
|
||||
assert.equal(branch, "feature/update");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
VcsStatusResult,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
@@ -46,7 +46,7 @@ export function buildGitActionProgressStages(input: {
|
||||
featureBranch?: boolean;
|
||||
shouldPushBeforePr?: boolean;
|
||||
}): string[] {
|
||||
const branchStages = input.featureBranch ? ["Preparing feature ref..."] : [];
|
||||
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
|
||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||
const prStages = [
|
||||
"Preparing PR...",
|
||||
@@ -77,17 +77,17 @@ export function buildGitActionProgressStages(input: {
|
||||
}
|
||||
|
||||
export function buildMenuItems(
|
||||
gitStatus: VcsStatusResult | null,
|
||||
gitStatus: GitStatusResult | null,
|
||||
isBusy: boolean,
|
||||
hasPrimaryRemote = true,
|
||||
hasOriginRemote = true,
|
||||
): GitActionMenuItem[] {
|
||||
if (!gitStatus) return [];
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
|
||||
const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush =
|
||||
!isBusy &&
|
||||
@@ -143,10 +143,10 @@ export function buildMenuItems(
|
||||
}
|
||||
|
||||
export function resolveQuickAction(
|
||||
gitStatus: VcsStatusResult | null,
|
||||
gitStatus: GitStatusResult | null,
|
||||
isBusy: boolean,
|
||||
isDefaultRef = false,
|
||||
hasPrimaryRemote = true,
|
||||
isDefaultBranch = false,
|
||||
hasOriginRemote = true,
|
||||
): GitQuickAction {
|
||||
if (isBusy) {
|
||||
return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
|
||||
@@ -161,7 +161,7 @@ export function resolveQuickAction(
|
||||
};
|
||||
}
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
@@ -173,15 +173,15 @@ export function resolveQuickAction(
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Create and checkout a ref before pushing or opening a PR.",
|
||||
hint: "Create and checkout a branch before pushing or opening a PR.",
|
||||
};
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
|
||||
}
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
@@ -193,7 +193,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (!gitStatus.hasUpstream) {
|
||||
if (!hasPrimaryRemote) {
|
||||
if (!hasOriginRemote) {
|
||||
if (hasOpenPr && !isAhead) {
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
@@ -215,12 +215,12 @@ export function resolveQuickAction(
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: isDefaultRef ? "commit_push" : "push",
|
||||
action: isDefaultBranch ? "commit_push" : "push",
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -233,7 +233,7 @@ export function resolveQuickAction(
|
||||
|
||||
if (isDiverged) {
|
||||
return {
|
||||
label: "Sync ref",
|
||||
label: "Sync branch",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: "Branch has diverged from upstream. Rebase/merge first.",
|
||||
@@ -249,12 +249,12 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (isAhead) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
kind: "run_action",
|
||||
action: isDefaultRef ? "commit_push" : "push",
|
||||
action: isDefaultBranch ? "commit_push" : "push",
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -279,9 +279,9 @@ export function resolveQuickAction(
|
||||
|
||||
export function requiresDefaultBranchConfirmation(
|
||||
action: GitStackedAction,
|
||||
isDefaultRef: boolean,
|
||||
isDefaultBranch: boolean,
|
||||
): boolean {
|
||||
if (!isDefaultRef) return false;
|
||||
if (!isDefaultBranch) return false;
|
||||
return (
|
||||
action === "push" ||
|
||||
action === "create_pr" ||
|
||||
@@ -296,18 +296,18 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
includesCommit: boolean;
|
||||
}): DefaultBranchActionDialogCopy {
|
||||
const branchLabel = input.branchName;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
|
||||
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
|
||||
|
||||
if (input.action === "push" || input.action === "commit_push") {
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit & push to default ref?",
|
||||
title: "Commit & push to default branch?",
|
||||
description: `This action will commit and push changes${suffix}`,
|
||||
continueLabel: `Commit & push to ${branchLabel}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push to default ref?",
|
||||
title: "Push to default branch?",
|
||||
description: `This action will push local commits${suffix}`,
|
||||
continueLabel: `Push to ${branchLabel}`,
|
||||
};
|
||||
@@ -315,13 +315,13 @@ export function resolveDefaultBranchActionDialogCopy(input: {
|
||||
|
||||
if (input.includesCommit) {
|
||||
return {
|
||||
title: "Commit, push & create PR from default ref?",
|
||||
title: "Commit, push & create PR from default branch?",
|
||||
description: `This action will commit, push, and create a PR${suffix}`,
|
||||
continueLabel: `Commit, push & create PR`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: "Push & create PR from default ref?",
|
||||
title: "Push & create PR from default branch?",
|
||||
description: `This action will push local commits and create a PR${suffix}`,
|
||||
continueLabel: "Push & create PR",
|
||||
};
|
||||
@@ -341,31 +341,31 @@ export function resolveThreadBranchUpdate(
|
||||
|
||||
export function resolveLiveThreadBranchUpdate(input: {
|
||||
threadBranch: string | null;
|
||||
gitStatus: VcsStatusResult | null;
|
||||
gitStatus: GitStatusResult | null;
|
||||
}): { branch: string | null } | null {
|
||||
if (!input.gitStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (input.gitStatus.refName === null && input.threadBranch !== null) {
|
||||
if (input.gitStatus.branch === null && input.threadBranch !== null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (input.threadBranch === input.gitStatus.refName) {
|
||||
if (input.threadBranch === input.gitStatus.branch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
input.threadBranch !== null &&
|
||||
input.gitStatus.refName !== null &&
|
||||
input.gitStatus.branch !== null &&
|
||||
!isTemporaryWorktreeBranch(input.threadBranch) &&
|
||||
isTemporaryWorktreeBranch(input.gitStatus.refName)
|
||||
isTemporaryWorktreeBranch(input.gitStatus.branch)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
branch: input.gitStatus.refName,
|
||||
branch: input.gitStatus.branch,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import type {
|
||||
GitActionProgressEvent,
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
VcsStatusResult,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
@@ -54,7 +54,6 @@ import { readEnvironmentApi } from "~/environmentApi";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { useStore } from "~/store";
|
||||
import { createThreadSelectorByRef } from "~/storeSelectors";
|
||||
import { resolveVcsActionPresentation, resolveVcsTerms } from "~/vcsPresentation";
|
||||
|
||||
interface GitActionsControlProps {
|
||||
gitCwd: string | null;
|
||||
@@ -90,7 +89,7 @@ interface RunGitActionWithToastInput {
|
||||
commitMessage?: string;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: VcsStatusResult | null;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
@@ -122,18 +121,18 @@ function getMenuActionDisabledReason({
|
||||
item,
|
||||
gitStatus,
|
||||
isBusy,
|
||||
hasPrimaryRemote,
|
||||
hasOriginRemote,
|
||||
}: {
|
||||
item: GitActionMenuItem;
|
||||
gitStatus: VcsStatusResult | null;
|
||||
gitStatus: GitStatusResult | null;
|
||||
isBusy: boolean;
|
||||
hasPrimaryRemote: boolean;
|
||||
hasOriginRemote: boolean;
|
||||
}): string | null {
|
||||
if (!item.disabled) return null;
|
||||
if (isBusy) return "Git action in progress.";
|
||||
if (!gitStatus) return "Git status is unavailable.";
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
@@ -148,7 +147,7 @@ function getMenuActionDisabledReason({
|
||||
|
||||
if (item.id === "push") {
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a refName before pushing.";
|
||||
return "Detached HEAD: checkout a branch before pushing.";
|
||||
}
|
||||
if (hasChanges) {
|
||||
return "Commit or stash local changes before pushing.";
|
||||
@@ -156,7 +155,7 @@ function getMenuActionDisabledReason({
|
||||
if (isBehind) {
|
||||
return "Branch is behind upstream. Pull/rebase before pushing.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
return 'Add an "origin" remote before pushing.';
|
||||
}
|
||||
if (!isAhead) {
|
||||
@@ -169,12 +168,12 @@ function getMenuActionDisabledReason({
|
||||
return "View PR is currently unavailable.";
|
||||
}
|
||||
if (!hasBranch) {
|
||||
return "Detached HEAD: checkout a refName before creating a PR.";
|
||||
return "Detached HEAD: checkout a branch before creating a PR.";
|
||||
}
|
||||
if (hasChanges) {
|
||||
return "Commit local changes before creating a PR.";
|
||||
}
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
return 'Add an "origin" remote before creating a PR.';
|
||||
}
|
||||
if (!isAhead) {
|
||||
@@ -325,12 +324,8 @@ export default function GitActionsControl({
|
||||
});
|
||||
// Default to true while loading so we don't flash init controls.
|
||||
const isRepo = gitStatus?.isRepo ?? true;
|
||||
const vcsKind = gitStatus?.kind ?? null;
|
||||
const vcsTerms = resolveVcsTerms(vcsKind);
|
||||
const vcsActionPresentation = resolveVcsActionPresentation(vcsKind);
|
||||
const supportsGitWorkflowActions = !isRepo || vcsActionPresentation.supportsGitWorkflowActions;
|
||||
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
|
||||
const gitStatusForActions = supportsGitWorkflowActions ? gitStatus : null;
|
||||
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
|
||||
const gitStatusForActions = gitStatus;
|
||||
|
||||
const allFiles = gitStatusForActions?.workingTree.files ?? [];
|
||||
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
|
||||
@@ -387,18 +382,18 @@ export default function GitActionsControl({
|
||||
persistThreadBranchSync,
|
||||
]);
|
||||
|
||||
const isDefaultRef = useMemo(() => {
|
||||
return gitStatusForActions?.isDefaultRef ?? false;
|
||||
}, [gitStatusForActions?.isDefaultRef]);
|
||||
const isDefaultBranch = useMemo(() => {
|
||||
return gitStatusForActions?.isDefaultBranch ?? false;
|
||||
}, [gitStatusForActions?.isDefaultBranch]);
|
||||
|
||||
const gitActionMenuItems = useMemo(
|
||||
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasPrimaryRemote),
|
||||
[gitStatusForActions, hasPrimaryRemote, isGitActionRunning],
|
||||
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
|
||||
[gitStatusForActions, hasOriginRemote, isGitActionRunning],
|
||||
);
|
||||
const quickAction = useMemo(
|
||||
() =>
|
||||
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultRef, hasPrimaryRemote),
|
||||
[gitStatusForActions, hasPrimaryRemote, isDefaultRef, isGitActionRunning],
|
||||
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch, hasOriginRemote),
|
||||
[gitStatusForActions, hasOriginRemote, isDefaultBranch, isGitActionRunning],
|
||||
);
|
||||
const quickActionDisabledReason = quickAction.disabled
|
||||
? (quickAction.hint ?? "This action is currently unavailable.")
|
||||
@@ -502,8 +497,8 @@ export default function GitActionsControl({
|
||||
filePaths,
|
||||
}: RunGitActionWithToastInput) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionBranch = actionStatus?.refName ?? null;
|
||||
const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch;
|
||||
const actionCanCommit =
|
||||
action === "commit" || action === "commit_push" || action === "commit_push_pr";
|
||||
const includesCommit =
|
||||
@@ -780,8 +775,8 @@ export default function GitActionsControl({
|
||||
title: result.status === "pulled" ? "Pulled" : "Already up to date",
|
||||
description:
|
||||
result.status === "pulled"
|
||||
? `Updated ${result.refName} from ${result.upstreamRef ?? "upstream"}`
|
||||
: `${result.refName} is already synchronized.`,
|
||||
? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
|
||||
: `${result.branch} is already synchronized.`,
|
||||
data: threadToastData,
|
||||
}),
|
||||
error: (err) => ({
|
||||
@@ -879,25 +874,6 @@ export default function GitActionsControl({
|
||||
>
|
||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</Button>
|
||||
) : !supportsGitWorkflowActions ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
render={
|
||||
<Button
|
||||
aria-disabled="true"
|
||||
className="cursor-not-allowed opacity-70"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{vcsTerms.systemName} {vcsTerms.repositoryNoun}
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup tooltipStyle side="bottom" align="end">
|
||||
{vcsActionPresentation.unsupportedGitWorkflowDescription}
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
) : (
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
{quickActionDisabledReason ? (
|
||||
@@ -958,7 +934,7 @@ export default function GitActionsControl({
|
||||
item,
|
||||
gitStatus: gitStatusForActions,
|
||||
isBusy: isGitActionRunning,
|
||||
hasPrimaryRemote,
|
||||
hasOriginRemote,
|
||||
});
|
||||
if (item.disabled && disabledReason) {
|
||||
return (
|
||||
@@ -993,13 +969,13 @@ export default function GitActionsControl({
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{gitStatusForActions?.refName === null && (
|
||||
{gitStatusForActions?.branch === null && (
|
||||
<p className="px-2 py-1.5 text-xs text-warning">
|
||||
Detached HEAD: create and checkout a refName to enable push and PR actions.
|
||||
Detached HEAD: create and checkout a branch to enable push and PR actions.
|
||||
</p>
|
||||
)}
|
||||
{gitStatusForActions &&
|
||||
gitStatusForActions.refName !== null &&
|
||||
gitStatusForActions.branch !== null &&
|
||||
!gitStatusForActions.hasWorkingTreeChanges &&
|
||||
gitStatusForActions.behindCount > 0 &&
|
||||
gitStatusForActions.aheadCount === 0 && (
|
||||
@@ -1037,12 +1013,10 @@ export default function GitActionsControl({
|
||||
<span className="text-muted-foreground">Branch</span>
|
||||
<span className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium">
|
||||
{gitStatusForActions?.refName ?? "(detached HEAD)"}
|
||||
{gitStatusForActions?.branch ?? "(detached HEAD)"}
|
||||
</span>
|
||||
{isDefaultRef && (
|
||||
<span className="text-right text-warning text-xs">
|
||||
Warning: default refName
|
||||
</span>
|
||||
{isDefaultBranch && (
|
||||
<span className="text-right text-warning text-xs">Warning: default branch</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -1175,7 +1149,7 @@ export default function GitActionsControl({
|
||||
disabled={noneSelected}
|
||||
onClick={runDialogActionOnNewBranch}
|
||||
>
|
||||
Commit on new refName
|
||||
Commit on new branch
|
||||
</Button>
|
||||
<Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
|
||||
Commit
|
||||
@@ -1195,32 +1169,18 @@ export default function GitActionsControl({
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default refName?"}
|
||||
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="sm:flex-wrap sm:items-center">
|
||||
<Button
|
||||
className="w-full sm:mr-auto sm:w-auto"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPendingDefaultBranchAction(null)}
|
||||
>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
|
||||
Abort
|
||||
</Button>
|
||||
<Button
|
||||
className="min-h-8 w-full max-w-full whitespace-normal py-1.5 leading-snug sm:min-h-7 sm:w-auto"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={continuePendingDefaultBranchAction}
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
|
||||
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
|
||||
</Button>
|
||||
<Button
|
||||
className="min-h-8 w-full max-w-full whitespace-normal py-1.5 leading-snug sm:min-h-7 sm:w-auto"
|
||||
size="sm"
|
||||
onClick={checkoutFeatureBranchAndContinuePendingAction}
|
||||
>
|
||||
<Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
|
||||
Checkout feature branch & continue
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -103,6 +103,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
enabled: true,
|
||||
binaryPath: "",
|
||||
@@ -256,13 +257,13 @@ function resolveWsRpc(tag: string): unknown {
|
||||
if (tag === WS_METHODS.serverGetConfig) {
|
||||
return fixture.serverConfig;
|
||||
}
|
||||
if (tag === WS_METHODS.vcsListRefs) {
|
||||
if (tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
refs: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
|
||||
branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.projectsSearchEntries) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeProjectRef, scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import type { GitStatusResult } from "@t3tools/contracts";
|
||||
import { CloudIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { usePrimaryEnvironmentId } from "../environments/primary";
|
||||
@@ -28,7 +28,7 @@ export interface TerminalStatusIndicator {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
export type ThreadPr = VcsStatusResult["pr"];
|
||||
export type ThreadPr = GitStatusResult["pr"];
|
||||
|
||||
export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
@@ -62,9 +62,9 @@ export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
|
||||
export function resolveThreadPr(
|
||||
threadBranch: string | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
gitStatus: GitStatusResult | null,
|
||||
): ThreadPr | null {
|
||||
if (threadBranch === null || gitStatus === null || gitStatus.refName !== threadBranch) {
|
||||
if (threadBranch === null || gitStatus === null || gitStatus.branch !== threadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ import { proposedPlanTitle } from "../../proposedPlan";
|
||||
import { getProviderInteractionModeToggle } from "../../providerModels";
|
||||
import {
|
||||
deriveProviderInstanceEntries,
|
||||
isModelPickerProviderInstanceEntry,
|
||||
resolveProviderDriverKindForInstanceSelection,
|
||||
sortProviderInstanceEntries,
|
||||
type ProviderInstanceEntry,
|
||||
@@ -574,7 +575,12 @@ export const ChatComposer = memo(
|
||||
// configured instance (default built-in + any custom `providerInstances.*`),
|
||||
// sorted default-first per driver kind for a stable picker order.
|
||||
const providerInstanceEntries = useMemo<ReadonlyArray<ProviderInstanceEntry>>(
|
||||
() => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerStatuses)),
|
||||
() =>
|
||||
sortProviderInstanceEntries(
|
||||
deriveProviderInstanceEntries(providerStatuses).filter(
|
||||
isModelPickerProviderInstanceEntry,
|
||||
),
|
||||
),
|
||||
[providerStatuses],
|
||||
);
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
|
||||
@@ -17,8 +17,6 @@ import { Toggle } from "../ui/toggle";
|
||||
import { SidebarTrigger } from "../ui/sidebar";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../environments/primary";
|
||||
import { resolveVcsTerms } from "../../vcsPresentation";
|
||||
import type { VcsDriverKind } from "@t3tools/contracts";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
@@ -26,8 +24,7 @@ interface ChatHeaderProps {
|
||||
draftId?: DraftId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isVcsRepo: boolean;
|
||||
vcsKind: VcsDriverKind | null;
|
||||
isGitRepo: boolean;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ProjectScript[] | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -53,8 +50,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
draftId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isVcsRepo,
|
||||
vcsKind,
|
||||
isGitRepo,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -76,7 +72,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const isRemoteEnvironment =
|
||||
primaryEnvironmentId !== null && activeThreadEnvironmentId !== primaryEnvironmentId;
|
||||
const vcsTerms = resolveVcsTerms(vcsKind);
|
||||
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
|
||||
@@ -93,9 +88,9 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isVcsRepo && (
|
||||
{activeProjectName && !isGitRepo && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
|
||||
No repository
|
||||
No Git
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
@@ -159,15 +154,15 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!isVcsRepo && !diffOpen}
|
||||
disabled={!isGitRepo && !diffOpen}
|
||||
>
|
||||
<DiffIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{!isVcsRepo && !diffOpen
|
||||
? `Diff panel is unavailable because this project is not a supported ${vcsTerms.repositoryNoun}.`
|
||||
{!isGitRepo && !diffOpen
|
||||
? "Diff panel is unavailable because this project is not a git repository."
|
||||
: diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
getDisplayModelName,
|
||||
getTriggerDisplayModelLabel,
|
||||
type ModelEsque,
|
||||
PROVIDER_ICON_BY_PROVIDER,
|
||||
} from "./providerIconUtils";
|
||||
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
|
||||
import { ComboboxItem } from "../ui/combobox";
|
||||
import { Kbd } from "../ui/kbd";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -26,6 +26,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
*/
|
||||
providerDisplayName: string;
|
||||
providerAccentColor?: string | undefined;
|
||||
providerIconUrl?: string | undefined;
|
||||
isFavorite: boolean;
|
||||
showProvider: boolean;
|
||||
preferShortName?: boolean;
|
||||
@@ -34,7 +35,6 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
jumpLabel?: string | null;
|
||||
onToggleFavorite: () => void;
|
||||
}) {
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null;
|
||||
const providerLabel = props.model.subProvider
|
||||
? `${props.providerDisplayName} · ${props.model.subProvider}`
|
||||
: props.providerDisplayName;
|
||||
@@ -104,7 +104,13 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
</div>
|
||||
{props.showProvider && (
|
||||
<div className="flex items-center gap-1 mt-0.5">
|
||||
{ProviderIcon ? <ProviderIcon className="size-3 shrink-0" /> : null}
|
||||
<ProviderInstanceIcon
|
||||
driverKind={props.driverKind}
|
||||
displayName={props.providerDisplayName}
|
||||
iconUrl={props.providerIconUrl}
|
||||
className="size-3"
|
||||
iconClassName="size-3 text-muted-foreground/70"
|
||||
/>
|
||||
{props.providerAccentColor ? (
|
||||
<span
|
||||
className="size-1.5 shrink-0 rounded-full"
|
||||
|
||||
@@ -11,7 +11,8 @@ import { ModelPickerSidebar } from "./ModelPickerSidebar";
|
||||
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
|
||||
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
|
||||
import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxList } from "../ui/combobox";
|
||||
import { ModelEsque, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils";
|
||||
import { ModelEsque } from "./providerIconUtils";
|
||||
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
|
||||
import {
|
||||
modelPickerJumpCommandForIndex,
|
||||
modelPickerJumpIndexFromCommand,
|
||||
@@ -33,6 +34,7 @@ type ModelPickerItem = {
|
||||
driverKind: ProviderDriverKind;
|
||||
instanceDisplayName: string;
|
||||
instanceAccentColor?: string | undefined;
|
||||
instanceIconUrl?: string | undefined;
|
||||
continuationGroupKey?: string | undefined;
|
||||
};
|
||||
|
||||
@@ -202,6 +204,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
driverKind: entry.driverKind,
|
||||
instanceDisplayName: entry.displayName,
|
||||
...(entry.accentColor ? { instanceAccentColor: entry.accentColor } : {}),
|
||||
...(entry.iconUrl ? { instanceIconUrl: entry.iconUrl } : {}),
|
||||
...(entry.continuationGroupKey
|
||||
? { continuationGroupKey: entry.continuationGroupKey }
|
||||
: {}),
|
||||
@@ -363,18 +366,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
[favorites, updateSettings],
|
||||
);
|
||||
|
||||
const LockedProviderIcon =
|
||||
isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null;
|
||||
// Header label for locked mode. Use the active instance's displayName
|
||||
// when the lock narrows to exactly one instance (so "Codex Personal"
|
||||
// shows instead of the generic driver label); fall back to the first
|
||||
// matching entry otherwise.
|
||||
const lockedHeaderLabel = useMemo(() => {
|
||||
const lockedHeaderEntry = useMemo(() => {
|
||||
if (!isLocked || !props.lockedProvider) return null;
|
||||
const matches = instanceEntries.filter((entry) => matchesLockedProvider(entry));
|
||||
if (matches.length === 0) return null;
|
||||
const active = matches.find((entry) => entry.instanceId === props.activeInstanceId);
|
||||
return (active ?? matches[0])?.displayName ?? null;
|
||||
return active ?? matches[0] ?? null;
|
||||
}, [
|
||||
isLocked,
|
||||
matchesLockedProvider,
|
||||
@@ -524,12 +525,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
)}
|
||||
>
|
||||
{/* Locked provider header (only shown in locked mode) */}
|
||||
{isLocked && !showLockedInstanceSidebar && LockedProviderIcon && lockedHeaderLabel && (
|
||||
{isLocked && !showLockedInstanceSidebar && lockedHeaderEntry ? (
|
||||
<div className="flex items-center gap-2 px-4 py-3 border-b">
|
||||
<LockedProviderIcon className="size-5 shrink-0" />
|
||||
<span className="font-medium text-sm">{lockedHeaderLabel}</span>
|
||||
<ProviderInstanceIcon
|
||||
driverKind={lockedHeaderEntry.driverKind}
|
||||
displayName={lockedHeaderEntry.displayName}
|
||||
iconUrl={lockedHeaderEntry.iconUrl}
|
||||
className="size-5"
|
||||
iconClassName="size-5"
|
||||
/>
|
||||
<span className="font-medium text-sm">{lockedHeaderEntry.displayName}</span>
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
|
||||
{/* Sidebar (only in unlocked mode) */}
|
||||
{showSidebar && (
|
||||
@@ -626,6 +633,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
driverKind={model.driverKind}
|
||||
providerDisplayName={model.instanceDisplayName}
|
||||
providerAccentColor={model.instanceAccentColor}
|
||||
providerIconUrl={model.instanceIconUrl}
|
||||
isFavorite={favoritesSet.has(modelKey)}
|
||||
showProvider={!isLocked || showLockedInstanceSidebar}
|
||||
preferShortName={!isLocked}
|
||||
|
||||
@@ -158,6 +158,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
driverKind={entry.driverKind}
|
||||
displayName={entry.displayName}
|
||||
accentColor={entry.accentColor}
|
||||
iconUrl={entry.iconUrl}
|
||||
showBadge={showInstanceBadge}
|
||||
className="size-6"
|
||||
iconClassName="size-5"
|
||||
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user