Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] fc3a47a64f fix(acp): start the optional scan budget with the listing 2026-11-24 08:45:19 +00:00
paseo-bot[bot] 5e80c6b4f0 test(server): wait for the watcher before deleting a file
The native macOS watcher starts delivering events after subscription returns. Use the existing liveness canary before removing the file under test.
2026-11-24 05:12:15 +00:00
paseo-bot[bot] c3f9dba40f test(website): check plugin search parameters by name
Native GET form submission and hydrated navigation serialize the same filters in different orders. Verify the term and ranking window in both flows.
2026-11-24 05:05:04 +00:00
paseo-bot[bot] 5e4d27f4d2 fix(acp): keep import results when extra pages stall
Once the provider supplies enough sessions, bound the time spent looking for newer ones. Return the rows already collected and close the listing connection when the extra scan ends.
2026-11-24 04:52:27 +00:00
paseo-bot[bot] 18004b5419 fix(acp): show the latest sessions in Import Session
ACP peers can return sessions in storage order. Applying the result limit before sorting discards newer sessions before the daemon receives them.
2026-11-24 04:45:45 +00:00
39 changed files with 976 additions and 2260 deletions
@@ -1,5 +1,4 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { type Locator, type Page } from "@playwright/test";
@@ -499,56 +498,6 @@ test("Changes offers Push for a branch that was never pushed and the push sets i
});
});
test("Changes pushes and pulls a branch whose only remote is not named origin", async ({
page,
}) => {
const workspace = await createWorkspaceWithRemote((repoPath) => {
execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath });
// git pull stops on a branch that is both ahead and behind until it is told how to combine them.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath });
});
await openWorkspaceChangesSurface(page, workspace);
const primary = page.getByTestId("changes-primary-cta");
await test.step("a branch that is ahead offers Push and the push updates the remote", async () => {
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
commitAllWithGit(workspace.repoPath, "Local work");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]");
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toContain("Local work");
await expectNoGitActionLeft(page);
});
await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => {
pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(localBranchSubjects(workspace)).toEqual(
expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]),
);
await expectNoGitActionLeft(page);
});
await test.step("a branch that is ahead and behind pulls and then pushes", async () => {
await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n");
commitAllWithGit(workspace.repoPath, "More local work");
pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await page.getByTestId("changes-primary-cta-caret").click();
await page.getByTestId("changes-menu-pull-and-push").click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toEqual(
expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]),
);
await expectNoGitActionLeft(page);
});
});
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
page,
}, testInfo) => {
@@ -2253,79 +2202,6 @@ function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string |
return line ? (line.split("\t")[0] ?? null) : null;
}
// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]".
function trackingStatus(workspace: RemoteWorkspace): string {
const status = execFileSync("git", ["status", "-sb"], {
cwd: workspace.repoPath,
encoding: "utf8",
});
return status.split("\n")[0] ?? "";
}
// Neither ahead nor behind, which a push reaches only after the remote accepted it.
async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void> {
await expect
.poll(() => trackingStatus(workspace), { timeout: 30_000 })
.toMatch(/^## [^ ]+\.\.\.[^ ]+$/);
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
function localBranchSubjects(workspace: RemoteWorkspace): string[] {
return commitSubjects(workspace.repoPath, "HEAD");
}
function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] {
return commitSubjects(workspace.remotePath, branch);
}
function commitSubjects(repoPath: string, revision: string): string[] {
const log = execFileSync("git", ["log", "--format=%s", revision], {
cwd: repoPath,
encoding: "utf8",
});
return log.trim().split("\n");
}
// Paseo fetches only origin in the background, so the checkout learns about another remote's
// commits when the user fetches it.
function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void {
execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath });
}
// Lands commits on the remote's main from a second clone, as a teammate's push does.
function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void {
const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-"));
try {
execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]);
for (const subject of subjects) {
execFileSync(
"git",
[
"-c",
"user.name=Teammate",
"-c",
"user.email=teammate@paseo.test",
"-c",
"commit.gpgsign=false",
"commit",
"--quiet",
"--allow-empty",
"-m",
subject,
],
{ cwd: clonePath },
);
}
execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath });
} finally {
rmSync(clonePath, { recursive: true, force: true });
}
}
// Empty until the branch has an upstream.
function branchUpstream(workspace: RemoteWorkspace, branch: string): string {
return execFileSync(
+6 -142
View File
@@ -7,7 +7,6 @@ import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
} from "./policy";
@@ -61,11 +60,9 @@ function githubStatus(overrides: Partial<GithubMergeFactsFixture> = {}): GithubM
function createInput(
overrides: Partial<Omit<BuildGitActionsInput, "mergeCapability">> & {
pullRequestGithub?: unknown;
// Shorthand for a branch that both Pull and Push have a remote for.
hasRemote?: boolean;
} = {},
): BuildGitActionsInput {
const { pullRequestGithub = null, hasRemote = false, ...rest } = overrides;
const { pullRequestGithub = null, ...rest } = overrides;
return {
isGit: true,
githubFeaturesEnabled: true,
@@ -79,8 +76,8 @@ function createInput(
pullRequestIsMerged: false,
pullRequestMergeable: "UNKNOWN",
mergeCapability: deriveMergeCapability(pullRequestGithub),
hasPullRemote: hasRemote,
hasPushRemote: hasRemote,
hasRemote: false,
hasFirstPushRemote: rest.hasRemote ?? false,
upstream: "tracked",
isPaseoOwnedWorktree: false,
isOnBaseBranch: true,
@@ -179,10 +176,6 @@ function pushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "push");
}
function pullAndPushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "pull-and-push");
}
describe("git-actions-policy", () => {
afterEach(async () => {
await i18n.changeLanguage("en");
@@ -440,7 +433,7 @@ describe("git-actions-policy", () => {
});
it("does not offer Push when Git pushes the branch to another remote", () => {
const actions = buildGitActions(createInput({ ...neverPushed, hasPushRemote: false }));
const actions = buildGitActions(createInput({ ...neverPushed, hasFirstPushRemote: false }));
const pushAction = pushActionOf(actions);
expect(actions.primary?.id).not.toBe("push");
@@ -448,142 +441,13 @@ describe("git-actions-policy", () => {
"Push isn't available here because this branch is not connected to a remote yet",
);
});
});
// The daemon reports where Pull and Push go for the branch, so the remote's name never matters.
describe("a branch that tracks a remote other than origin", () => {
const tracksDorasMono = readSyncRemotes({
hasRemote: false,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("offers Push when the branch is ahead", () => {
it("keeps offering Push in a Paseo worktree when Git pushes the branch to another remote", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }),
createInput({ ...neverPushed, hasFirstPushRemote: false, isPaseoOwnedWorktree: true }),
);
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
expect(pushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
});
it("offers Pull when the branch is behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 0, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
});
it("offers Pull first and Pull and push when the branch is ahead and behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available yet because there are newer changes to bring in first",
);
});
// `feature` tracking `upstream/main`: the daemon reports a pull remote and no push remote.
const pullOnly = readSyncRemotes({
hasRemote: false,
pullRemote: "upstream",
pushRemote: null,
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("does not offer Push when it would land on a differently named upstream branch", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary?.id).not.toBe("push");
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available here because this branch is not connected to a remote yet",
);
});
it("still offers Pull for that branch, and not Pull and push", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)?.unavailableMessage).toBe(
"Pull and push isn't available here because this branch is not connected to a remote yet",
);
});
});
describe("readSyncRemotes", () => {
it("uses the remotes the daemon reports", () => {
expect(
readSyncRemotes({
hasRemote: true,
pullRemote: null,
pushRemote: "origin",
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
).toEqual({ hasPullRemote: false, hasPushRemote: true });
});
// The rest covers a daemon that predates pullRemote and pushRemote.
const tracked = {
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
} as const;
const neverPushed = {
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
} as const;
it("pulls and pushes a tracked branch on an older daemon only when the checkout has origin", () => {
expect(readSyncRemotes({ ...tracked, hasRemote: true })).toEqual({
hasPullRemote: true,
hasPushRemote: true,
});
expect(readSyncRemotes({ ...tracked, hasRemote: false })).toEqual({
hasPullRemote: false,
hasPushRemote: false,
});
});
it("makes a regular checkout's first push only where an older daemon confirmed it", () => {
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: "origin" }),
).toMatchObject({ hasPushRemote: true });
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: null }),
).toMatchObject({ hasPushRemote: false });
});
it("keeps a Paseo worktree's first push on an older daemon that reports no first push remote", () => {
expect(
readSyncRemotes({
...neverPushed,
hasRemote: true,
firstPushRemote: null,
isPaseoOwnedWorktree: true,
}),
).toMatchObject({ hasPushRemote: true });
});
});
+15 -41
View File
@@ -96,41 +96,7 @@ export function readUpstreamState(
return status.isPaseoOwnedWorktree ? "none" : "unknown";
}
export interface SyncRemotes {
/** Pull has a remote to fetch the branch from. Not limited to origin. */
hasPullRemote: boolean;
/** Push has a remote to send the branch to. Not limited to origin. */
hasPushRemote: boolean;
}
export function readSyncRemotes(
status: Pick<
CheckoutStatusPayload,
| "pullRemote"
| "pushRemote"
| "hasRemote"
| "firstPushRemote"
| "upstreamState"
| "aheadOfOrigin"
| "isPaseoOwnedWorktree"
>,
): SyncRemotes {
if (status.pullRemote !== undefined && status.pushRemote !== undefined) {
return { hasPullRemote: status.pullRemote !== null, hasPushRemote: status.pushRemote !== null };
}
// COMPAT(checkoutSyncRemotes): added in v0.17.5, remove after 2027-05-24 once the daemon floor
// reports pullRemote and pushRemote. Older daemons pull and push only in checkouts that have
// origin. They make a first push from a Paseo worktree, and from a regular checkout only where
// they report firstPushRemote.
const isFirstPush = readUpstreamState(status) === "none";
const canFirstPush = status.isPaseoOwnedWorktree || (status.firstPushRemote ?? null) !== null;
return {
hasPullRemote: status.hasRemote,
hasPushRemote: status.hasRemote && (!isFirstPush || canFirstPush),
};
}
export interface BuildGitActionsInput extends SyncRemotes {
export interface BuildGitActionsInput {
isGit: boolean;
githubFeaturesEnabled: boolean;
/** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */
@@ -145,6 +111,9 @@ export interface BuildGitActionsInput extends SyncRemotes {
pullRequestIsMerged: boolean;
pullRequestMergeable: PullRequestMergeable;
mergeCapability: MergeCapability | null;
hasRemote: boolean;
/** The daemon confirmed where a first push publishes the branch. */
hasFirstPushRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
@@ -603,11 +572,11 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable
}
function canPull(input: BuildGitActionsInput): boolean {
return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
}
function canPush(input: BuildGitActionsInput): boolean {
return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
}
function hasPushableCommits(input: BuildGitActionsInput): boolean {
@@ -616,7 +585,9 @@ function hasPushableCommits(input: BuildGitActionsInput): boolean {
return (input.aheadOfOrigin ?? 0) > 0;
case "none":
// A first push, which sets the upstream. The commits to send are the ones ahead of the base.
return input.aheadCount > 0;
// Paseo worktrees always publish to origin. A regular checkout publishes only where the
// daemon confirmed Git would push the branch too, so a fork setup is not sent to origin.
return input.aheadCount > 0 && (input.isPaseoOwnedWorktree || input.hasFirstPushRemote);
case "gone":
case "unknown":
// The branch has an upstream that is deleted or unreadable, so nothing counts the commits
@@ -707,7 +678,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean {
}
function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPullRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pullNoRemote");
}
if (input.hasUncommittedChanges) {
@@ -723,7 +694,7 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi
}
function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPushRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
if ((input.behindOfOrigin ?? 0) > 0) {
@@ -735,11 +706,14 @@ function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefi
if (input.upstream === "gone") {
return i18n.t("workspace.git.actions.unavailable.pushUpstreamGone");
}
if (input.upstream === "none" && input.aheadCount > 0) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
return i18n.t("workspace.git.actions.unavailable.pushNothing");
}
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPullRemote || !input.hasPushRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote");
}
if (input.hasUncommittedChanges) {
+11 -12
View File
@@ -15,13 +15,11 @@ import {
isCurrentBranchBase,
canMergeIntoLocalBase,
narrowPullRequestState,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
type GitAction,
type GitActions,
type GitUpstreamState,
type SyncRemotes,
} from "@/git/policy";
import { deriveMergeCapability } from "@/git/merge-capability";
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
@@ -125,15 +123,15 @@ interface DeriveGitActionsStateArgs {
baseRef: string | undefined;
}
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
interface DerivedGitActionsState extends SyncRemotes {
interface DerivedGitActionsState {
actionsDisabled: boolean;
aheadCount: number;
behindBaseCount: number;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
hasPullRequest: boolean;
hasRemote: boolean;
hasFirstPushRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
@@ -185,7 +183,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
actionsDisabled,
...extractGitCommitCounts(gitStatus),
hasPullRequest: Boolean(prStatus?.url),
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
hasRemote: gitStatus?.hasRemote ?? false,
hasFirstPushRemote: (gitStatus?.firstPushRemote ?? null) !== null,
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
isPaseoOwnedWorktree,
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
@@ -674,8 +673,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
aheadOfOrigin,
behindOfOrigin,
hasPullRequest,
hasPullRemote,
hasPushRemote,
hasRemote,
hasFirstPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
@@ -707,8 +706,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
pullRequestIsMerged: prStatus?.isMerged ?? false,
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
hasPullRemote,
hasPushRemote,
hasRemote,
hasFirstPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
@@ -817,8 +816,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
};
}, [
isGit,
hasPullRemote,
hasPushRemote,
hasRemote,
hasFirstPushRemote,
upstream,
hasPullRequest,
prStatus?.url,
@@ -291,6 +291,7 @@ async function listSessions(
input: Extract<ProviderInput, { type: "sessions" }>,
state: AcpConnectionState,
): Promise<void> {
const extraScanDeadline = performance.now() + EXTRA_SESSION_SCAN_BUDGET_MS;
const runtime = await AcpRuntime.start({
options: state.options,
launch: state.launch,
@@ -299,7 +300,11 @@ async function listSessions(
emit: state.emit,
});
try {
const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit });
const selected = await runtime.listSessions({
cwd: input.cwd,
limit: input.limit,
extraScanDeadline,
});
state.emit({
type: "sessions",
requestId: input.requestId,
@@ -315,6 +320,10 @@ async function listSessions(
}
}
function sessionUpdatedAt(session: SessionInfo): number {
return Date.parse(session.updatedAt ?? "") || 0;
}
function retireSession(state: AcpConnectionState, sessionId: string): void {
if (state.sessions.delete(sessionId)) {
state.emit({ type: "session.closed", sessionId });
@@ -411,6 +420,7 @@ interface ActivePrompt {
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
const SESSION_SCAN_LIMIT = 500;
const EXTRA_SESSION_SCAN_BUDGET_MS = 2_000;
// COMPAT(acpAutoAccept): added in v0.17.4, remove after 2027-05-23. The generic ACP adapter saves
// its Auto Accept toggle as this setting on agents that later moved to a bundled ACP provider.
const LEGACY_AUTO_ACCEPT_SETTING = "auto_accept";
@@ -918,17 +928,38 @@ class AcpRuntime {
return true;
}
/** Follows `nextCursor` until `limit` sessions, the last page, or the scan cap. */
async listSessions({ cwd, limit }: { cwd?: string; limit?: number }): Promise<SessionInfo[]> {
/** Selects the most recent sessions from a bounded scan of the provider's pages. */
async listSessions({
cwd,
limit,
extraScanDeadline,
}: {
cwd?: string;
limit?: number;
extraScanDeadline: number;
}): Promise<SessionInfo[]> {
const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT);
const sessions: SessionInfo[] = [];
let cursor: string | undefined;
do {
const page = await this.call(this.connection.listSessions({ cwd, cursor }));
sessions.push(...page.sessions);
// ACP does not guarantee that sessions arrive in recency order.
for (let pages = 0; pages < SESSION_SCAN_LIMIT; pages += 1) {
// Once we have enough rows, pages can improve the order only within the original budget.
const remainingMs =
cursor && sessions.length >= wanted ? extraScanDeadline - performance.now() : undefined;
if (remainingMs !== undefined && remainingMs <= 0) break;
const request = this.call(this.connection.listSessions({ cwd, cursor }));
const page =
remainingMs === undefined
? await request
: await withTimeout(request, remainingMs, "ACP listing scan budget expired").catch(
() => undefined,
);
if (!page) break;
sessions.push(...page.sessions.slice(0, SESSION_SCAN_LIMIT - sessions.length));
cursor = page.nextCursor ?? undefined;
} while (cursor && sessions.length < wanted);
return sessions.slice(0, wanted);
if (!cursor || sessions.length === SESSION_SCAN_LIMIT) break;
}
return sessions.sort((a, b) => sessionUpdatedAt(b) - sessionUpdatedAt(a)).slice(0, wanted);
}
async drainNotifications(): Promise<void> {
+36
View File
@@ -7038,6 +7038,42 @@ describe("ACP tool call rows", () => {
}
});
it("returns enough sessions and closes the connection when another page stalls", async () => {
const harness = connectorHarness({
capabilities: { sessionCapabilities: { list: {} } },
handleRequest(runtime, request) {
if (request.method !== "session/list") return false;
const { cursor } = request.params as { cursor?: string };
if (!cursor) {
runtime.respond(request, {
sessions: [{ sessionId: "s1", cwd: "/repo", title: "First page" }],
nextCursor: "stalled",
});
}
return true;
},
});
const connection = await runAcpProvider({
id: "stalled-listing",
label: "Stalled listing",
connector: harness.connector,
}).connect({ versions: [1], capabilities: ["prompt.message", "session.list"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send({ type: "sessions", requestId: "list", limit: 1 });
await expect.poll(() => countRequests(harness.instances[1], "session/list")).toBe(2);
const listed = await waitForEvent(events, (event) => event.type === "sessions");
expect(listed).toMatchObject({ sessions: [{ title: "First page" }] });
await expect.poll(() => harness.instances[1].readsCanceled).toBe(true);
expect(harness.instances[1].writesClosed).toBe(true);
} finally {
const listing = harness.instances[1];
if (listing && !listing.readsCanceled) listing.closeFromAgent();
await connection.close();
}
});
it("resumes the generic ACP adapter's saved Auto Accept toggle in the unattended mode", async () => {
const harness = connectorHarness({
configOptions: [
+4 -14
View File
@@ -5824,20 +5824,10 @@ const CheckoutStatusCommonSchema = z.object({
// as when the clone keeps no remote-tracking ref for the upstream). Absent from daemons that
// predate it, which report all but "tracked" as a null upstreamRef.
upstreamState: z.enum(["tracked", "none", "gone", "unknown"]).optional(),
// The remote Pull fetches currentBranch from, as git names it: the remote of the branch's
// configured upstream, which is not necessarily origin, or "." when the upstream is a local
// branch. Null when the branch has no upstream. Absent from daemons that predate it, which
// pull only in checkouts that have origin (hasRemote).
pullRemote: z.string().nullable().optional(),
// The remote Push sends currentBranch to, resolved as the daemon's push resolves it. It is not
// necessarily origin. Null when Push has nowhere to send the branch, as when it has no upstream
// and origin is missing, or git is set to push it to another remote (branch.<name>.pushRemote,
// remote.pushDefault). Absent from daemons that predate it, which push only in checkouts that
// have origin (hasRemote).
pushRemote: z.string().nullable().optional(),
// "origin" when Push sends currentBranch to origin, and null otherwise. Clients that predate
// pushRemote read it to offer a first push; newer clients read pushRemote instead. Absent from
// daemons that predate it.
// The remote a first push publishes currentBranch to, when the daemon can confirm git would
// push the branch there too. Null when there is no such remote, as when origin is missing or
// git is set to push the branch to another remote (branch.<name>.pushRemote,
// remote.pushDefault). Absent from daemons that predate it.
firstPushRemote: z.string().nullable().optional(),
forgeWeb: ForgeWebSchema.optional(),
});
@@ -72,41 +72,6 @@ test("base selection RPCs are correlated while older checkout and branch message
expect(WorkspaceBaseBranchSetResponseSchema.parse(response)).toEqual(response);
});
test("checkout status stays valid without pull and push remotes and retains them when sent", () => {
const olderDaemonPayload = {
cwd: "/repo",
requestId: "status",
error: null,
isGit: true,
isPaseoOwnedWorktree: false,
repoRoot: "/repo",
currentBranch: "main",
isDirty: false,
baseRef: "main",
aheadBehind: null,
aheadOfOrigin: 1,
behindOfOrigin: 2,
hasRemote: false,
remoteUrl: null,
upstreamRef: "refs/remotes/doras-mono/main",
upstreamState: "tracked",
firstPushRemote: null,
};
const parse = (payload: Record<string, unknown>) =>
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload;
const older = parse(olderDaemonPayload);
expect(older.pullRemote).toBeUndefined();
expect(older.pushRemote).toBeUndefined();
expect(
parse({ ...olderDaemonPayload, pullRemote: "doras-mono", pushRemote: "doras-mono" }),
).toMatchObject({ pullRemote: "doras-mono", pushRemote: "doras-mono" });
expect(parse({ ...olderDaemonPayload, pullRemote: "upstream", pushRemote: null })).toMatchObject({
pullRemote: "upstream",
pushRemote: null,
});
});
test("terminal listings accept older rows and retain new per-terminal directories", () => {
const response = {
type: "list_terminals_response",
@@ -74,19 +74,6 @@ describe("findExecutable", () => {
await expect(findExecutable("foo")).resolves.toBe(executable);
});
test("ignores relative PATH entries when resolving a bare command name", async () => {
const dir = makeTempDir();
const previousCwd = process.cwd();
writeExecutable(path.join(dir, "rel-only-cmd"), "#!/bin/sh\necho 0.1\n");
process.chdir(dir);
try {
process.env.PATH = [".", originalEnv.PATH].filter(Boolean).join(path.delimiter);
await expect(findExecutable("rel-only-cmd")).resolves.toBeNull();
} finally {
process.chdir(previousCwd);
}
});
});
describe.runIf(isPlatform("win32"))("Windows", () => {
@@ -155,21 +142,6 @@ describe("findExecutable", () => {
process.env.LOCALAPPDATA = originalLocalAppData;
}
});
test("ignores commands in the current working directory when not explicitly on PATH", async () => {
const repoDir = makeTempDir();
const emptyPathDir = makeTempDir();
const previousCwd = process.cwd();
process.env.PATHEXT = [".EXE", ".CMD"].join(path.delimiter);
writeExecutable(path.join(repoDir, "cwd-only-cmd.cmd"), "@echo off\r\necho 0.1\r\n");
process.chdir(repoDir);
try {
process.env.PATH = emptyPathDir;
await expect(findExecutable("cwd-only-cmd")).resolves.toBeNull();
} finally {
process.chdir(previousCwd);
}
});
});
test("returns an invokable absolute path", async () => {
@@ -1,5 +1,5 @@
import { existsSync } from "node:fs";
import { delimiter, dirname, isAbsolute, resolve } from "node:path";
import { delimiter, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
import which from "which";
@@ -11,46 +11,11 @@ function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
function stripWindowsPathQuotes(entry: string): string {
return process.platform === "win32" &&
entry.length >= 2 &&
entry.startsWith('"') &&
entry.endsWith('"')
? entry.slice(1, -1)
: entry;
}
function normalizeDirectory(dir: string): string {
const resolved = resolve(dir);
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
}
function extractAbsolutePathDirs(rawPath: string | undefined): string[] {
if (!rawPath) {
return [];
}
return rawPath
.split(delimiter)
.map(stripWindowsPathQuotes)
.filter((entry) => entry.length > 0 && isAbsolute(entry));
}
async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise<string[]> {
const rawPath = env?.PATH !== undefined ? env.PATH : process.env.PATH;
const absolutePathDirs = extractAbsolutePathDirs(rawPath);
if (absolutePathDirs.length === 0) {
return [];
if (process.platform !== "win32" && existsSync("/usr/bin/which")) {
return enumerateCandidatesViaSystemWhich(name, env);
}
const filteredEnv: ProcessEnvRecord = {
...(env ?? process.env),
PATH: absolutePathDirs.join(delimiter),
};
const allowedDirs = new Set(absolutePathDirs.map(normalizeDirectory));
const candidates =
process.platform !== "win32" && existsSync("/usr/bin/which")
? await enumerateCandidatesViaSystemWhich(name, filteredEnv)
: await enumerateCandidatesViaLibrary(name, filteredEnv);
return candidates.filter((candidate) => allowedDirs.has(normalizeDirectory(dirname(candidate))));
return enumerateCandidatesViaLibrary(name, env);
}
async function enumerateCandidatesViaSystemWhich(
@@ -69,8 +69,6 @@ export function buildCheckoutStatusPayloadFromSnapshot({
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
upstreamState: snapshot.git.upstreamState,
hasRemote: snapshot.git.hasRemote,
pullRemote: snapshot.git.pullRemote,
pushRemote: snapshot.git.pushRemote,
firstPushRemote: snapshot.git.firstPushRemote,
remoteUrl: snapshot.git.remoteUrl,
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
@@ -96,8 +94,6 @@ export function buildCheckoutStatusPayloadFromSnapshot({
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
upstreamState: snapshot.git.upstreamState,
hasRemote: snapshot.git.hasRemote,
pullRemote: snapshot.git.pullRemote,
pushRemote: snapshot.git.pushRemote,
firstPushRemote: snapshot.git.firstPushRemote,
remoteUrl: snapshot.git.remoteUrl,
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
@@ -0,0 +1,68 @@
// An ACP peer that returns sessions in storage order, with an optional page boundary.
const readline = require("node:readline");
const { existsSync, renameSync, writeFileSync } = require("node:fs");
const path = require("node:path");
const stalledListing = process.argv.indexOf("--stall-after-first-page");
const controlDir = stalledListing === -1 ? null : process.argv[stalledListing + 1];
if (process.argv.includes("--version")) {
process.stdout.write("1.5.13\n");
process.exit(0);
}
const sessions = Array.from({ length: 317 }, (_, index) => ({
sessionId: `session-${index}`,
cwd: process.cwd(),
title: `September session ${index}`,
updatedAt: "2026-09-08T11:36:19Z",
}));
sessions[42] = {
...sessions[42],
title: "Latest November session",
updatedAt: "2026-11-23T04:07:46Z",
};
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
if (id === undefined) return;
let response;
if (method === "initialize") {
response = {
result: { protocolVersion: 1, agentCapabilities: { sessionCapabilities: { list: {} } } },
};
} else if (method === "session/list") {
if (controlDir) {
if (params.cursor) {
writeFileSync(path.join(controlDir, "second-page"), "");
return;
}
const marker = path.join(controlDir, "first-page");
writeFileSync(marker + ".tmp", String(process.pid));
renameSync(marker + ".tmp", marker);
const gate = setInterval(() => {
if (!existsSync(path.join(controlDir, "release-first-page"))) return;
clearInterval(gate);
process.stdout.write(
JSON.stringify({
jsonrpc: "2.0",
id,
result: { sessions: sessions.slice(0, 42), nextCursor: "next" },
}) + "\n",
);
}, 10);
return;
}
const pageSize = process.argv.includes("--paginated") ? 42 : sessions.length;
response = {
result: params.cursor
? { sessions: sessions.slice(pageSize) }
: {
sessions: sessions.slice(0, pageSize),
nextCursor: pageSize < sessions.length ? "next" : null,
},
};
} else {
response = { error: { code: -32601, message: `Unsupported method ${method}` } };
}
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, ...response }) + "\n");
});
@@ -1,5 +1,7 @@
import { describe, test, expect } from "vitest";
import { describe, test, expect, vi } from "vitest";
import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import os from "node:os";
import path from "node:path";
import { loadConfig } from "../config.js";
@@ -165,6 +167,122 @@ test("Antigravity creates an agent and answers a prompt with real agy", async ({
}
}, 120000);
test.each(["one page", "two pages"])(
"Antigravity lists the latest importable sessions from %s in storage order",
async (pages) => {
const command = [
process.execPath,
path.resolve(import.meta.dirname, "antigravity-session-list-fixture.cjs"),
];
if (pages === "two pages") command.push("--paginated");
const daemon = await createTestPaseoDaemon({
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: { antigravity: { command, paseoTools: { enabled: false } } },
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.17.3",
});
const providers = ["antigravity"];
try {
await client.connect();
await client.refreshProvidersSnapshot({ cwd: daemon.paseoHome, providers });
const search = await client.fetchRecentProviderSessions({
providers,
limit: 5,
query: "November",
});
expect(search.entries.map((session) => session.title)).toEqual(["Latest November session"]);
const wide = await client.fetchRecentProviderSessions({ providers, limit: 100 });
expect(wide.entries[0]?.title).toBe("Latest November session");
const recent = await client.fetchRecentProviderSessions({ providers });
expect(recent.entries).toHaveLength(20);
expect(recent.entries[0]?.title).toBe("Latest November session");
} finally {
await client.close();
await daemon.close();
}
},
30_000,
);
test("Antigravity returns a late full page before Import Session times out", async () => {
const controlDir = await mkdtemp(path.join(os.tmpdir(), "paseo-antigravity-listing-"));
const command = [
process.execPath,
path.resolve(import.meta.dirname, "antigravity-session-list-fixture.cjs"),
"--stall-after-first-page",
controlDir,
];
const daemon = await createTestPaseoDaemon({
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: { antigravity: { command, paseoTools: { enabled: false } } },
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.17.3",
});
const providers = ["antigravity"];
try {
await client.connect();
await client.refreshProvidersSnapshot({ cwd: daemon.paseoHome, providers });
vi.useFakeTimers({ toFake: ["performance", "setTimeout", "clearTimeout"] });
const result = client.fetchRecentProviderSessions({ providers });
let returned = false;
const markReturned = () => {
returned = true;
};
void result.then(markReturned, markReturned);
const firstPage = path.join(controlDir, "first-page");
await waitForFixture(() => existsSync(firstPage), "first page requested");
const pid = Number(await readFile(firstPage, "utf8"));
await vi.advanceTimersByTimeAsync(59_000);
await writeFile(path.join(controlDir, "release-first-page"), "");
// Let real I/O deliver the page before advancing to the client deadline.
// The provider signals a second request but never answers it.
const secondPage = path.join(controlDir, "second-page");
await waitForFixture(() => returned || existsSync(secondPage), "result or second page request");
await vi.advanceTimersByTimeAsync(1_000);
const recent = await result;
expect(recent.entries.map((session) => session.title)).toEqual(
Array.from({ length: 20 }, (_, index) => `September session ${index}`),
);
await waitForFixture(() => {
try {
process.kill(pid, 0);
return false;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ESRCH") return true;
throw error;
}
}, "listing process exited");
} finally {
if (vi.isFakeTimers()) {
await vi.advanceTimersByTimeAsync(2_000);
vi.useRealTimers();
}
await client.close();
await daemon.close();
await rm(controlDir, { recursive: true, force: true });
}
});
async function waitForFixture(condition: () => boolean, description: string): Promise<void> {
// Use real timers for subprocess I/O while the RPC clock is paused.
const deadline = Date.now() + 10_000;
while (!condition()) {
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
await delay(10);
}
}
test("bundled fx requires a config entry and lists models instead of its providers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-fx-optin-"));
const record = path.join(root, "launches.txt");
@@ -194,12 +194,14 @@ test("classifies a removed file as deleted", async () => {
const root = await createRoot();
const target = join(root, "removed.txt");
await writeFile(target, "before");
const canary = createWatcherLivenessCanary(root);
const events: FileChange[] = [];
const subscription = await subscribeToFileChanges(root, (error, batch) => {
expect(error).toBeNull();
events.push(...batch);
events.push(...canary.filterEvents(batch));
});
await canary.verify();
await rm(target);
// macOS FSEvents can replay the write above as a create after the subscription starts,
// so the delete is the latest event for the path, not the first. Native recursive delivery
@@ -10050,7 +10050,7 @@ test("workspace PR status survives session cleanup and reconnect", async () => {
branchRemoteName: "origin",
branchMergeRef: "refs/heads/feature",
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "feature" },
};
const githubStub = {
@@ -248,8 +248,6 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna
behindOfOrigin: null,
upstreamState: "none",
hasRemote: false,
pullRemote: null,
pushRemote: null,
firstPushRemote: null,
diffStat: null,
},
@@ -42,7 +42,7 @@ function createFacts(cwd: string): CheckoutSnapshotFacts {
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -73,7 +73,7 @@ function createCheckoutFacts(cwd: string): CheckoutSnapshotFacts {
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -1020,7 +1020,7 @@ describe("WorkspaceGitService checkout observation", () => {
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
};
});
const runGitFetch = vi.fn(async () => ({
@@ -1164,7 +1164,7 @@ describe("WorkspaceGitService checkout observation", () => {
branchRemoteName: "origin",
branchMergeRef: `refs/heads/${branch}`,
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
} satisfies CheckoutSnapshotFacts;
});
const getCheckoutStatus = vi.fn(async (cwd: string) =>
@@ -81,7 +81,7 @@ function createCheckoutFacts(
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
...overrides,
};
@@ -172,7 +172,7 @@ function createCheckoutSnapshotFacts(cwd: string): CheckoutSnapshotFacts {
branchRemoteName: "origin",
branchMergeRef: "refs/heads/main",
upstreamStatus: { state: "none" },
pushTarget: null,
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -185,8 +185,6 @@ export interface WorkspaceGitRuntimeSnapshot {
behindOfOrigin: number | null;
upstreamState: UpstreamState;
hasRemote: boolean;
pullRemote: string | null;
pushRemote: string | null;
firstPushRemote: string | null;
diffStat: { additions: number; deletions: number } | null;
};
@@ -3787,8 +3785,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
behindOfOrigin: checkoutStatus.behindOfOrigin,
upstreamState: checkoutStatus.upstreamState,
hasRemote: checkoutStatus.hasRemote,
pullRemote: checkoutStatus.pullRemote,
pushRemote: checkoutStatus.pushRemote,
firstPushRemote: checkoutStatus.firstPushRemote,
diffStat,
};
@@ -4446,8 +4442,6 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot {
behindOfOrigin: null,
upstreamState: "none",
hasRemote: false,
pullRemote: null,
pushRemote: null,
firstPushRemote: null,
diffStat: null,
},
@@ -1,6 +1,6 @@
import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { delimiter, join } from "node:path";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
createCachedCliPathResolver,
@@ -70,44 +70,6 @@ exit 1
}),
).resolves.toBe(false);
});
it("invokes the resolved executable path instead of re-searching PATH by bare name", async () => {
const originalPath = process.env.PATH;
const earlierDir = join(tempDir, "earlier-bin");
const workingDir = join(tempDir, "working-bin");
mkdirSync(earlierDir);
mkdirSync(workingDir);
const shadowingCli = join(earlierDir, "forge-probe-cli");
const workingCli = join(workingDir, "forge-probe-cli");
writeFileSync(
workingCli,
`#!/bin/sh
if [ "$1" = "--version" ]; then
printf '#!/bin/sh\\nexit 1\\n' > "${shadowingCli}"
chmod 755 "${shadowingCli}"
exit 0
fi
if [ "$1" = "auth" ] && [ "$2" = "status" ] && [ "$3" = "--hostname" ] && [ "$4" = "git.acme.internal" ]; then
exit 0
fi
exit 1
`,
);
chmodSync(workingCli, 0o755);
process.env.PATH = [earlierDir, workingDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(
probeHostViaCliAuthStatus({
cli: "forge-probe-cli",
host: "git.acme.internal",
}),
).resolves.toBe(true);
} finally {
process.env.PATH = originalPath;
}
});
});
describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => {
@@ -176,264 +138,6 @@ describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => {
expect(normalized).toBeInstanceOf(FakeCommandError);
expect((normalized as FakeCommandError).stderr).toMatch(/timed out after 100ms/);
});
it("executes the provided executablePath instead of re-resolving binary from PATH", async () => {
const originalPath = process.env.PATH;
const pathDir = join(tempDir, "path-bin");
const resolvedDir = join(tempDir, "resolved-bin");
mkdirSync(pathDir);
mkdirSync(resolvedDir);
const pathCli = join(pathDir, "forge-cli-test");
writeFileSync(pathCli, "#!/bin/sh\necho from-path\n");
chmodSync(pathCli, 0o755);
const resolvedCli = join(resolvedDir, "forge-cli-test");
writeFileSync(resolvedCli, "#!/bin/sh\necho from-resolved\n");
chmodSync(resolvedCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-test",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [pathDir, originalPath].filter(Boolean).join(delimiter);
try {
const result = await runner.run(["status"], {
cwd: tempDir,
executablePath: resolvedCli,
});
expect(result.stdout.trim()).toBe("from-resolved");
} finally {
process.env.PATH = originalPath;
}
});
it("resolves a bare binary via resolveExecutablePath when executablePath is omitted", async () => {
const originalPath = process.env.PATH;
const pathDir = join(tempDir, "path-bin");
const resolvedDir = join(tempDir, "resolved-bin");
mkdirSync(pathDir);
mkdirSync(resolvedDir);
const pathCli = join(pathDir, "forge-cli-default");
writeFileSync(pathCli, "#!/bin/sh\necho from-path\n");
chmodSync(pathCli, 0o755);
const resolvedCli = join(resolvedDir, "forge-cli-default");
writeFileSync(resolvedCli, "#!/bin/sh\necho from-resolver\n");
chmodSync(resolvedCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-default",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
resolveExecutablePath: async () => resolvedCli,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [pathDir, originalPath].filter(Boolean).join(delimiter);
try {
const result = await runner.run(["status"], { cwd: tempDir });
expect(result.stdout.trim()).toBe("from-resolver");
} finally {
process.env.PATH = originalPath;
}
});
it("throws createMissingError when a bare binary cannot be resolved", async () => {
const runner = createForgeCliRunner({
binary: "forge-cli-uninstalled",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
resolveExecutablePath: async () => null,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("forge-cli-missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
await expect(runner.run(["status"], { cwd: tempDir })).rejects.toThrow("forge-cli-missing");
});
it("re-resolves and retries once when the cached executable is removed from PATH", async () => {
const originalPath = process.env.PATH;
const firstDir = join(tempDir, "first-bin");
const secondDir = join(tempDir, "second-bin");
mkdirSync(firstDir);
mkdirSync(secondDir);
const firstCli = join(firstDir, "forge-cli-fallback");
writeFileSync(firstCli, "#!/bin/sh\necho from-first\n");
chmodSync(firstCli, 0o755);
const secondCli = join(secondDir, "forge-cli-fallback");
writeFileSync(secondCli, "#!/bin/sh\necho from-second\n");
chmodSync(secondCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-fallback",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [firstDir, secondDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-first\n",
});
rmSync(firstCli);
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-second\n",
});
} finally {
process.env.PATH = originalPath;
}
});
it("re-resolves and retries once when the cached executable loses execute permission", async () => {
const originalPath = process.env.PATH;
const firstDir = join(tempDir, "first-perm-bin");
const secondDir = join(tempDir, "second-perm-bin");
mkdirSync(firstDir);
mkdirSync(secondDir);
const firstCli = join(firstDir, "forge-cli-perm");
writeFileSync(firstCli, "#!/bin/sh\necho from-first\n");
chmodSync(firstCli, 0o755);
const secondCli = join(secondDir, "forge-cli-perm");
writeFileSync(secondCli, "#!/bin/sh\necho from-second\n");
chmodSync(secondCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-perm",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [firstDir, secondDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-first\n",
});
chmodSync(firstCli, 0o644);
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-second\n",
});
} finally {
process.env.PATH = originalPath;
}
});
});
describe.runIf(isPlatform("win32"))("createForgeCliRunner (Windows)", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "forge-cli-win-"));
});
afterEach(() => {
rmSync(tempDir, { recursive: true, force: true });
});
class FakeCommandError extends Error {
readonly stderr: string;
constructor(params: { stderr: string }) {
super("command failed");
this.stderr = params.stderr;
}
}
it("runs the resolved executable instead of a cwd-local script and preserves percent-delimited args", async () => {
const originalPath = process.env.PATH;
const originalVar = process.env.PASEO_FORGE_ARG_LITERAL;
const binDir = join(tempDir, "bin");
const repoDir = join(tempDir, "repo");
mkdirSync(binDir);
mkdirSync(repoDir);
const installedExe = join(binDir, "forge-win-cli.exe");
copyFileSync(process.execPath, installedExe);
writeFileSync(join(repoDir, "forge-win-cli.cmd"), "@echo off\r\necho from-cwd\r\n");
const runner = createForgeCliRunner({
binary: "forge-win-cli",
envOverlay: {},
timeoutMs: 5_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [binDir, originalPath].filter(Boolean).join(delimiter);
process.env.PASEO_FORGE_ARG_LITERAL = "expanded-env-value";
try {
const result = await runner.run(
[
"-e",
"process.stdout.write(JSON.stringify(process.argv.slice(1)))",
"--",
"%PASEO_FORGE_ARG_LITERAL%",
"query=query Test {\n viewer { login }\n}",
],
{ cwd: repoDir },
);
expect(JSON.parse(result.stdout)).toEqual([
"%PASEO_FORGE_ARG_LITERAL%",
"query=query Test {\n viewer { login }\n}",
]);
} finally {
process.env.PATH = originalPath;
if (originalVar === undefined) {
delete process.env.PASEO_FORGE_ARG_LITERAL;
} else {
process.env.PASEO_FORGE_ARG_LITERAL = originalVar;
}
}
});
});
describe("createCachedCliPathResolver", () => {
@@ -471,21 +175,4 @@ describe("createCachedCliPathResolver", () => {
await Promise.all([resolveCliPath(), resolveCliPath(), resolveCliPath()]);
expect(calls).toBe(1);
});
it("re-resolves after invalidate matches the cached path and ignores mismatched paths", async () => {
let calls = 0;
const resolveCliPath = createCachedCliPathResolver(async () => {
calls += 1;
return calls === 1 ? "/first/bin/forge-cli" : "/second/bin/forge-cli";
});
await expect(resolveCliPath()).resolves.toBe("/first/bin/forge-cli");
resolveCliPath.invalidate("/other/bin/forge-cli");
await expect(resolveCliPath()).resolves.toBe("/first/bin/forge-cli");
expect(calls).toBe(1);
resolveCliPath.invalidate("/first/bin/forge-cli");
await expect(resolveCliPath()).resolves.toBe("/second/bin/forge-cli");
expect(calls).toBe(2);
});
});
+11 -135
View File
@@ -1,4 +1,3 @@
import { access } from "node:fs/promises";
import { z } from "zod";
import { findExecutable } from "../executable-resolution/executable-resolution.js";
import { runGitCommand } from "../utils/run-git-command.js";
@@ -60,7 +59,6 @@ interface ProbeHostViaCliAuthStatusOptions {
export interface ForgeCliRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface ForgeCliRunnerResult {
@@ -87,7 +85,6 @@ export interface CreateForgeCliRunnerOptions {
timeoutMs: number;
isAuthFailureText: (text: string) => boolean;
errorClasses: ForgeCliRunnerErrorClasses;
resolveExecutablePath?: () => Promise<string | null>;
}
export interface ForgeCliRunnerFactory {
@@ -98,48 +95,6 @@ export interface ForgeCliRunnerFactory {
) => Error;
}
function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
const UNLAUNCHABLE_EXECUTABLE_ERROR_CODES = new Set<unknown>([
"ENOENT",
"EACCES",
"ENOEXEC",
"UNKNOWN",
]);
function isWindowsBatchScript(executablePath: string): boolean {
if (process.platform !== "win32") {
return false;
}
const lower = executablePath.toLowerCase();
return lower.endsWith(".cmd") || lower.endsWith(".bat");
}
async function isUnlaunchableExecutableError(
error: unknown,
executablePath: string,
): Promise<boolean> {
if (
typeof error === "object" &&
error !== null &&
"code" in error &&
UNLAUNCHABLE_EXECUTABLE_ERROR_CODES.has((error as { code?: unknown }).code)
) {
return true;
}
if (!isWindowsBatchScript(executablePath)) {
return false;
}
try {
await access(executablePath);
return false;
} catch {
return true;
}
}
/**
* Shared shape behind the gh/glab/tea CLI adapters: an exec wrapper (10MB
* maxBuffer, per-call env overlay merged over the binary's defaults, a
@@ -147,41 +102,13 @@ async function isUnlaunchableExecutableError(
* trio. The three adapters differ only in the params passed here.
*/
export function createForgeCliRunner(options: CreateForgeCliRunnerOptions): ForgeCliRunnerFactory {
const resolveBinaryPath = createCachedCliPathResolver(
options.resolveExecutablePath ?? (() => findExecutable(options.binary)),
);
function execResolved(
command: string,
args: string[],
runOptions: ForgeCliRunnerOptions,
): Promise<ForgeCliRunnerResult> {
return execCommand(command, args, {
const run: ForgeCliRunner = (args, runOptions) =>
execCommand(options.binary, args, {
cwd: runOptions.cwd,
envOverlay: { ...options.envOverlay, ...runOptions.envOverlay },
maxBuffer: 10 * 1024 * 1024,
timeout: options.timeoutMs,
});
}
const run: ForgeCliRunner = async (args, runOptions) => {
const candidate = runOptions.executablePath ?? options.binary;
if (hasPathSeparator(candidate)) {
return execResolved(candidate, args, runOptions);
}
if (candidate === options.binary) {
return runWithResolvedCliPath({
resolvePath: resolveBinaryPath,
createMissingError: options.errorClasses.createMissingError,
run: (command) => execResolved(command, args, runOptions),
});
}
const resolved = await findExecutable(candidate);
if (!resolved) {
throw options.errorClasses.createMissingError();
}
return execResolved(resolved, args, runOptions);
};
function normalizeError(
error: unknown,
@@ -252,88 +179,37 @@ export class ForgeCommandError extends Error {
}
}
export interface CachedCliPathResolver {
(): Promise<string | null>;
invalidate(expectedPath?: string): void;
}
/**
* Memoize a CLI path resolver (`findExecutable`) for the lifetime of a service
* instance. A found path stays cached until invalidated (for example, when the
* binary disappears at launch time); a miss or rejected probe evicts the cache
* so a CLI installed after the daemon started is picked up on the next call.
* Concurrent callers during resolution share the same in-flight promise.
* instance. A found path is cached permanently; a miss (or a rejected probe)
* evicts the cache so a CLI installed after the daemon started is picked up
* on the next call instead of requiring a restart. Concurrent callers during
* resolution share the same in-flight promise.
*/
export function createCachedCliPathResolver(
resolve: () => Promise<string | null>,
): CachedCliPathResolver {
): () => Promise<string | null> {
let pending: Promise<string | null> | null = null;
let resolvedPath: string | null = null;
const resolveCliPath = function resolveCliPath(): Promise<string | null> {
return function resolveCliPath(): Promise<string | null> {
if (pending) {
return pending;
}
const current: Promise<string | null> = resolve()
.then((path) => {
if (pending === current) {
resolvedPath = path;
if (path === null) {
pending = null;
}
if (path === null && pending === current) {
pending = null;
}
return path;
})
.catch((error: unknown) => {
if (pending === current) {
resolvedPath = null;
pending = null;
}
throw error;
});
pending = current;
return current;
} as CachedCliPathResolver;
resolveCliPath.invalidate = (expectedPath?: string) => {
if (expectedPath === undefined || resolvedPath === expectedPath) {
resolvedPath = null;
pending = null;
}
};
return resolveCliPath;
}
/**
* Execute an operation with a cached CLI executable path, invalidating and
* re-resolving once if the previously resolved executable disappeared from disk.
*/
export async function runWithResolvedCliPath<T>(options: {
resolvePath: CachedCliPathResolver;
createMissingError: () => Error;
run: (executablePath: string) => Promise<T>;
}): Promise<T> {
const executablePath = await options.resolvePath();
if (!executablePath) {
throw options.createMissingError();
}
try {
return await options.run(executablePath);
} catch (error) {
if (!(await isUnlaunchableExecutableError(error, executablePath))) {
throw error;
}
options.resolvePath.invalidate(executablePath);
const refreshedPath = await options.resolvePath();
if (!refreshedPath) {
throw options.createMissingError();
}
if (refreshedPath === executablePath) {
throw error;
}
return options.run(refreshedPath);
}
}
export function bufferOrStringToString(value: unknown): string {
@@ -428,7 +304,7 @@ export async function probeHostViaCliAuthStatus(
return false;
}
try {
await execCommand(cliPath, ["auth", "status", "--hostname", options.host], {
await execCommand(options.cli, ["auth", "status", "--hostname", options.host], {
envOverlay: options.envOverlay,
timeout: CLI_AUTH_PROBE_TIMEOUT_MS,
});
@@ -1,6 +1,3 @@
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { delimiter, join } from "node:path";
import { describe, expect, it } from "vitest";
import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js";
@@ -8,13 +5,11 @@ import {
type CreateGiteaServiceOptions,
createGiteaService,
detectGiteaFamilySoftware,
probeGiteaHost,
TeaAuthenticationError,
TeaCommandError,
type TeaCommandResult,
type TeaCommandRunner,
} from "./gitea-service.js";
import { isPlatform } from "../test-utils/platform.js";
type Responder = (args: string[]) => TeaCommandResult | Promise<TeaCommandResult>;
@@ -3309,95 +3304,3 @@ describe("detectGiteaFamilySoftware", () => {
expect(software).toBe("gitea");
});
});
describe("Gitea CLI executable resolution", () => {
it("forwards the resolved tea executablePath to the command runner", async () => {
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGiteaService({
resolveTeaPath: async () => "/opt/tea-cli/bin/tea",
resolveRemoteUrl: async () => "https://gitea.com/example-user/sample-repo.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
return ok("[]");
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "sample", kinds: ["github-pr"] });
expect(seenExecutablePaths).toEqual(["/opt/tea-cli/bin/tea"]);
});
it("re-resolves tea and retries when the previously cached executable disappears", async () => {
let availablePath = "/first/bin/tea";
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGiteaService({
resolveTeaPath: async () => availablePath,
resolveRemoteUrl: async () => "https://gitea.com/example-user/sample-repo.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
if (options.executablePath !== availablePath) {
const error = new Error("spawn ENOENT") as NodeJS.ErrnoException;
error.code = "ENOENT";
throw error;
}
return ok("[]");
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-pr"] });
availablePath = "/second/bin/tea";
const secondResult = await service.searchIssuesAndPrs({
cwd: "/repo",
query: "second",
kinds: ["github-pr"],
});
expect(secondResult.featuresEnabled).toBe(true);
expect(seenExecutablePaths).toEqual(["/first/bin/tea", "/first/bin/tea", "/second/bin/tea"]);
});
it.skipIf(isPlatform("win32"))(
"probeGiteaHost and detectGiteaFamilySoftware invoke the resolved tea executable",
async () => {
const originalPath = process.env.PATH;
const tempDir = mkdtempSync(join(tmpdir(), "gitea-probe-cli-"));
const earlierDir = join(tempDir, "earlier-bin");
const workingDir = join(tempDir, "working-bin");
mkdirSync(earlierDir);
mkdirSync(workingDir);
const shadowingTea = join(earlierDir, "tea");
const workingTea = join(workingDir, "tea");
writeFileSync(
workingTea,
`#!/bin/sh
if [ "$1" = "--version" ]; then
printf '#!/bin/sh\\nexit 1\\n' > "${shadowingTea}"
chmod 755 "${shadowingTea}"
exit 0
fi
if [ "$1" = "login" ] && [ "$2" = "list" ]; then
printf '[{"name":"forge.acme.it","url":"https://forge.acme.it"}]'
exit 0
fi
if [ "$1" = "api" ]; then
printf '{"version":"1.0+gitea"}'
printf 'HTTP/1.1 200 OK\\n' >&2
exit 0
fi
exit 1
`,
);
chmodSync(workingTea, 0o755);
process.env.PATH = [earlierDir, workingDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(probeGiteaHost("forge.acme.it")).resolves.toBe(true);
rmSync(shadowingTea, { force: true });
await expect(detectGiteaFamilySoftware("forge.acme.it")).resolves.toBe("forgejo");
} finally {
process.env.PATH = originalPath;
rmSync(tempDir, { recursive: true, force: true });
}
},
);
});
+13 -22
View File
@@ -18,7 +18,6 @@ import {
CLI_AUTH_PROBE_TIMEOUT_MS,
defaultResolveRemoteUrl,
parseCliJsonOutput,
runWithResolvedCliPath,
ForgeCommandError,
type ForgeCommandFailureParams,
} from "./forge-cli-command.js";
@@ -138,7 +137,6 @@ export class TeaCommandError extends ForgeCommandError {
export interface TeaCommandRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface TeaCommandResult {
@@ -1032,7 +1030,7 @@ export async function probeGiteaHost(host: string): Promise<boolean> {
return false;
}
try {
const { stdout } = await execCommand(teaPath, ["login", "list", "-o", "json"], {
const { stdout } = await execCommand("tea", ["login", "list", "-o", "json"], {
envOverlay: TEA_ENV,
timeout: CLI_AUTH_PROBE_TIMEOUT_MS,
});
@@ -1063,19 +1061,12 @@ export interface DetectGiteaFamilyOptions {
runTea?: TeaApiRunner;
}
function createDefaultRunTea(): TeaApiRunner {
const resolveTea = createCachedCliPathResolver(resolveTeaPath);
return async (args: string[]): Promise<{ stdout: string; stderr: string }> => {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
const { stdout, stderr } = await execCommand(teaPath, args, {
envOverlay: TEA_ENV,
timeout: GITEA_SOFTWARE_PROBE_TIMEOUT_MS,
});
return { stdout, stderr };
};
async function defaultRunTea(args: string[]): Promise<{ stdout: string; stderr: string }> {
const { stdout, stderr } = await execCommand("tea", args, {
envOverlay: TEA_ENV,
timeout: GITEA_SOFTWARE_PROBE_TIMEOUT_MS,
});
return { stdout, stderr };
}
const HTTP_STATUS_LINE = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/m;
@@ -1138,7 +1129,7 @@ export async function detectGiteaFamilySoftware(
host: string,
options: DetectGiteaFamilyOptions = {},
): Promise<GiteaFamilySoftware> {
const runTea = options.runTea ?? createDefaultRunTea();
const runTea = options.runTea ?? defaultRunTea;
const viaTea = await probeForgejoNamespaceByTea(host, runTea);
if (viaTea !== null) {
@@ -1217,12 +1208,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
args: string[],
runOptions: TeaCommandRunnerOptions,
): Promise<TeaCommandResult> {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
try {
return await runWithResolvedCliPath({
resolvePath: resolveTea,
createMissingError: () => new TeaCliMissingError(),
run: (teaPath) => runner(args, { ...runOptions, executablePath: teaPath }),
});
return await runner(args, runOptions);
} catch (error) {
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
}
@@ -66,11 +66,11 @@ describe("GitHub repository search", () => {
"--limit",
"8",
],
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
options: { cwd: "/tmp" },
},
{
args: ["config", "get", "git_protocol", "--host", "github.com"],
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
options: { cwd: "/tmp" },
},
]);
});
@@ -123,11 +123,11 @@ describe("GitHub repository search", () => {
"--order",
"desc",
],
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
options: { cwd: "/tmp" },
},
{
args: ["config", "get", "git_protocol", "--host", "github.com"],
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
options: { cwd: "/tmp" },
},
]);
});
@@ -5341,47 +5341,3 @@ it("skips pagination after the last exact observer releases its PR", async () =>
vi.useRealTimers();
}
});
it("forwards the resolved gh executablePath to the command runner", async () => {
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitHubService({
resolveGhPath: async () => "/opt/github-cli/bin/gh",
resolveRepoHost: async () => null,
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
return { stdout: "[]", stderr: "" };
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "test", kinds: ["github-issue"] });
expect(seenExecutablePaths).toEqual(["/opt/github-cli/bin/gh"]);
});
it("re-resolves gh and retries when the previously cached executable disappears", async () => {
let availablePath = "/first/bin/gh";
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitHubService({
resolveGhPath: async () => availablePath,
resolveRepoHost: async () => null,
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
if (options.executablePath !== availablePath) {
const error = new Error("spawn ENOENT") as NodeJS.ErrnoException;
error.code = "ENOENT";
throw error;
}
return { stdout: "[]", stderr: "" };
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-issue"] });
availablePath = "/second/bin/gh";
const secondResult = await service.searchIssuesAndPrs({
cwd: "/repo",
query: "second",
kinds: ["github-issue"],
});
expect(secondResult.featuresEnabled).toBe(true);
expect(seenExecutablePaths).toEqual(["/first/bin/gh", "/first/bin/gh", "/second/bin/gh"]);
});
+7 -16
View File
@@ -22,15 +22,12 @@ import {
import { execCommand } from "../utils/spawn.js";
import { resolveSshHostname } from "../utils/ssh-hostname.js";
import {
type CachedCliPathResolver,
CLI_AUTH_PROBE_TIMEOUT_MS,
createCachedCliPathResolver,
createForgeCliRunner,
ForgeAuthenticationError,
ForgeCliMissingError,
parseCliJsonOutput,
probeHostViaCliAuthStatus,
runWithResolvedCliPath,
ForgeCommandError,
type ForgeCommandFailureParams,
} from "./forge-cli-command.js";
@@ -969,7 +966,7 @@ interface CacheEntry {
interface GitHubServiceDependencies {
runner: GitHubCommandRunner;
resolveGhPath: CachedCliPathResolver;
resolveGhPath: () => Promise<string | null>;
now: () => number;
/**
* GitHub Enterprise host for a workspace, or null for github.com (where `gh`
@@ -994,7 +991,6 @@ interface GitHubServiceDependencies {
export interface GitHubCommandRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface GitHubCommandResult {
@@ -1152,7 +1148,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
const ttlMs = options.ttlMs ?? DEFAULT_GITHUB_CACHE_TTL_MS;
const deps: GitHubServiceDependencies = {
runner: options.runner ?? runGhCommand,
resolveGhPath: createCachedCliPathResolver(options.resolveGhPath ?? resolveGhPath),
resolveGhPath: options.resolveGhPath ?? resolveGhPath,
now: options.now ?? Date.now,
resolveRepoHost: options.resolveRepoHost ?? resolveGitHubEnterpriseHost,
resolveRepoSlug: options.resolveRepoSlug ?? resolveGitHubSlugFromOrigin,
@@ -1371,8 +1367,8 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
runOptions: GitHubCommandRunnerOptions,
explicitHost?: string,
): Promise<string> {
const initialGhPath = await deps.resolveGhPath();
if (!initialGhPath) {
const ghPath = await deps.resolveGhPath();
if (!ghPath) {
throw new GitHubCliMissingError();
}
// Route every gh invocation to the workspace's host. `gh api`/`graphql`
@@ -1380,15 +1376,11 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
// which silently queries the wrong server on GitHub Enterprise. GH_HOST is
// safe even for auto-routing subcommands because it matches the repo's host.
const host = explicitHost ?? (await resolveRepoHostCached(runOptions.cwd));
const baseOptions: GitHubCommandRunnerOptions = host
const effectiveOptions: GitHubCommandRunnerOptions = host
? { ...runOptions, envOverlay: { ...runOptions.envOverlay, GH_HOST: host } }
: runOptions;
try {
const result = await runWithResolvedCliPath({
resolvePath: deps.resolveGhPath,
createMissingError: () => new GitHubCliMissingError(),
run: (ghPath) => deps.runner(args, { ...baseOptions, executablePath: ghPath }),
});
const result = await deps.runner(args, effectiveOptions);
return result.stdout.trim();
} catch (error) {
throw githubCliRunner.normalizeError(error, {
@@ -3177,8 +3169,7 @@ const githubCliRunner = createForgeCliRunner({
timeoutMs: GITHUB_COMMAND_TIMEOUT_MS,
isAuthFailureText,
errorClasses: {
isAlreadyClassified: (candidate) =>
candidate instanceof GitHubAuthenticationError || candidate instanceof GitHubCliMissingError,
isAlreadyClassified: (candidate) => candidate instanceof GitHubAuthenticationError,
isCommandError: (candidate): candidate is GitHubCommandError =>
candidate instanceof GitHubCommandError,
createAuthError: (stderr) => new GitHubAuthenticationError({ stderr }),
@@ -1654,49 +1654,4 @@ describe("createGitLabService", () => {
GlabCommandError,
);
});
it("forwards the resolved glab executablePath to the command runner", async () => {
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitLabService({
resolveGlabPath: async () => "/opt/gitlab-cli/bin/glab",
resolveRemoteUrl: async () => "git@gitlab.example.com:example-group/example-project.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
return ok("[]");
},
});
await expect(service.isAuthenticated({ cwd: "/repo" })).resolves.toBe(true);
await service.searchIssuesAndPrs({ cwd: "/repo", query: "release", kinds: ["github-pr"] });
expect(seenExecutablePaths).toEqual(["/opt/gitlab-cli/bin/glab", "/opt/gitlab-cli/bin/glab"]);
});
it("re-resolves glab and retries when the previously cached executable disappears", async () => {
let availablePath = "/first/bin/glab";
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitLabService({
resolveGlabPath: async () => availablePath,
resolveRemoteUrl: async () => "git@gitlab.example.com:example-group/example-project.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
if (options.executablePath !== availablePath) {
const error = new Error("spawn ENOENT") as NodeJS.ErrnoException;
error.code = "ENOENT";
throw error;
}
return ok("[]");
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-pr"] });
availablePath = "/second/bin/glab";
const secondResult = await service.searchIssuesAndPrs({
cwd: "/repo",
query: "second",
kinds: ["github-pr"],
});
expect(secondResult.featuresEnabled).toBe(true);
expect(seenExecutablePaths).toEqual(["/first/bin/glab", "/first/bin/glab", "/second/bin/glab"]);
});
});
+6 -16
View File
@@ -9,7 +9,6 @@ import {
defaultResolveRemoteUrl,
parseCliJsonOutput,
probeHostViaCliAuthStatus,
runWithResolvedCliPath,
ForgeCommandError,
type ForgeCommandFailureParams,
} from "./forge-cli-command.js";
@@ -98,7 +97,6 @@ export class GlabCommandError extends ForgeCommandError {
export interface GlabCommandRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface GlabCommandResult {
@@ -935,12 +933,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
args: string[],
runOptions: GlabCommandRunnerOptions,
): Promise<GlabCommandResult> {
const glabPath = await resolveGlab();
if (!glabPath) {
throw new GlabCliMissingError();
}
try {
return await runWithResolvedCliPath({
resolvePath: resolveGlab,
createMissingError: () => new GlabCliMissingError(),
run: (glabPath) => runner(args, { ...runOptions, executablePath: glabPath }),
});
return await runner(args, runOptions);
} catch (error) {
throw glabCliRunner.normalizeError(error, { args, cwd: runOptions.cwd });
}
@@ -1193,15 +1191,7 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
return false;
}
try {
await runWithResolvedCliPath({
resolvePath: resolveGlab,
createMissingError: () => new GlabCliMissingError(),
run: (resolvedPath) =>
runner(["auth", "status", "--hostname", host], {
cwd: input.cwd,
executablePath: resolvedPath,
}),
});
await runner(["auth", "status", "--hostname", host], { cwd: input.cwd });
return true;
} catch {
return false;
@@ -67,7 +67,7 @@ function seedFeatureCheckout(): {
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 0, behind: 0 },
},
pushTarget: { kind: "upstream", remoteName: "origin", headRef: "main" },
firstPushRemote: "origin",
pullRequestLookupTarget: { headRef: "feature" },
},
};
@@ -111,7 +111,7 @@ function seedMainCheckout(): {
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 1, behind: 0 },
},
pushTarget: { kind: "upstream", remoteName: "origin", headRef: "main" },
firstPushRemote: "origin",
pullRequestLookupTarget: { headRef: "main" },
},
};
+3 -264
View File
@@ -251,13 +251,12 @@ function getBranchUpstream(cwd: string): string | null {
function setupRemoteTrackingMain(
repoDir: string,
tempDir: string,
remoteName = "origin",
): { remoteDir: string; cloneDir: string } {
const remoteDir = join(tempDir, "remote.git");
const cloneDir = join(tempDir, "upstream-clone");
execFileSync("git", ["init", "--bare", "-b", "main", remoteDir]);
execFileSync("git", ["remote", "add", remoteName, remoteDir], { cwd: repoDir });
execFileSync("git", ["push", "-u", remoteName, "main"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir });
execFileSync("git", ["push", "-u", "origin", "main"], { cwd: repoDir });
execFileSync("git", ["clone", remoteDir, cloneDir]);
execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: cloneDir });
execFileSync("git", ["config", "user.name", "Test"], { cwd: cloneDir });
@@ -1029,7 +1028,6 @@ const x = 1;
return;
}
expect(status.upstreamRef).toBe("refs/remotes/origin/other-name");
expect(status).toMatchObject({ pullRemote: "origin", pushRemote: "origin" });
});
it("reports the upstream when the repo's only remote is not origin", async () => {
@@ -1056,31 +1054,7 @@ const x = 1;
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({
upstreamState: "none",
pullRemote: null,
pushRemote: "origin",
firstPushRemote: "origin",
});
});
// Apps that predate pushRemote offer a regular checkout's first push from firstPushRemote.
it("reports origin as the first push remote when a push refspec names the branch on origin", async () => {
setupRemoteTrackingMain(repoDir, tempDir);
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["config", "branch.feature.pushRemote", "origin"], { cwd: repoDir });
execFileSync("git", ["config", "remote.origin.push", "HEAD:refs/heads/published"], {
cwd: repoDir,
});
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({
upstreamState: "none",
pushRemote: "origin",
firstPushRemote: "origin",
});
expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: "origin" });
});
// The daemon's first push goes to origin. When git would send the branch to a fork instead,
@@ -1105,7 +1079,6 @@ const x = 1;
expect(status).toMatchObject({
upstreamState: "none",
hasRemote: true,
pushRemote: null,
firstPushRemote: null,
});
const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"])
@@ -1119,10 +1092,8 @@ const x = 1;
execFileSync("git", ["checkout", "-b", "feature", "--track", "main"], { cwd: repoDir });
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
await pushCurrentBranch(repoDir);
expect(status).toMatchObject({ pullRemote: ".", pushRemote: "origin" });
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir })
.toString()
.trim();
@@ -1224,11 +1195,8 @@ const x = 1;
const worktreeDir = worktree.worktreePath;
commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(worktreeDir, { paseoHome });
await pushCurrentBranch(worktreeDir, undefined, { paseoHome });
expect(status).toMatchObject({ upstreamState: "none", pushRemote: "origin" });
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir })
.toString()
.trim();
@@ -1257,238 +1225,9 @@ const x = 1;
isGit: true,
upstreamState: "none",
hasRemote: false,
pullRemote: null,
pushRemote: null,
firstPushRemote: null,
});
await expect(pushCurrentBranch(repoDir)).rejects.toThrow("Remote 'origin' is not configured.");
await expect(pullCurrentBranch(repoDir)).rejects.toThrow(
"There is no tracking information for the current branch.",
);
});
// Git decides whether a pull has something to pull. In a single-branch clone it pulls the one
// fetched branch into a branch that has no upstream.
it("pulls a branch with no upstream where git itself can pull", async () => {
const { remoteDir, cloneDir } = setupRemoteTrackingMain(repoDir, tempDir);
const singleBranchDir = join(tempDir, "single-branch");
execFileSync("git", [
"clone",
"--single-branch",
"--branch",
"main",
remoteDir,
singleBranchDir,
]);
execFileSync("git", ["checkout", "-b", "local"], { cwd: singleBranchDir });
commitFile(cloneDir, "remote.txt", "remote\n", "remote commit");
execFileSync("git", ["push"], { cwd: cloneDir });
const status = await getCheckoutStatus(singleBranchDir);
await pullCurrentBranch(singleBranchDir);
expect(status).toMatchObject({ upstreamState: "none", pullRemote: null });
const pulledHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: singleBranchDir });
const remoteHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: cloneDir });
expect(pulledHead.toString()).toBe(remoteHead.toString());
});
// A checkout does not need a remote named origin. Pull and Push follow the branch's upstream.
describe("a checkout whose only remote is not origin", () => {
function headOf(cwd: string, ref = "HEAD"): string {
return execFileSync("git", ["rev-parse", ref], { cwd }).toString().trim();
}
function branchesOf(gitDir: string): string {
return execFileSync("git", ["--git-dir", gitDir, "branch", "--list"]).toString().trim();
}
function pushRemoteCommits(cloneDir: string, count: number): void {
for (let index = 1; index <= count; index += 1) {
commitFile(cloneDir, `remote-${index}.txt`, "remote\n", `remote commit ${index}`);
}
execFileSync("git", ["push"], { cwd: cloneDir });
}
it("pushes a branch that is ahead to its upstream", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
commitFile(repoDir, "local.txt", "local\n", "local commit");
const status = await getCheckoutStatus(repoDir);
await pushCurrentBranch(repoDir);
expect(status).toMatchObject({
upstreamRef: "refs/remotes/doras-mono/main",
upstreamState: "tracked",
aheadOfOrigin: 1,
behindOfOrigin: 0,
hasRemote: false,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
});
expect(headOf(remoteDir, "refs/heads/main")).toBe(headOf(repoDir));
});
it("pulls a branch that is behind from its upstream", async () => {
const { cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
pushRemoteCommits(cloneDir, 2);
execFileSync("git", ["fetch", "doras-mono"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
await pullCurrentBranch(repoDir);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 0,
behindOfOrigin: 2,
pullRemote: "doras-mono",
});
expect(headOf(repoDir)).toBe(headOf(cloneDir));
});
it("pulls and then pushes a branch that is both ahead and behind", async () => {
const { remoteDir, cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
// Git refuses to pull a diverged branch until it is told how to reconcile it.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoDir });
pushRemoteCommits(cloneDir, 2);
commitFile(repoDir, "local.txt", "local\n", "local commit");
const localCommit = headOf(repoDir);
execFileSync("git", ["fetch", "doras-mono"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
await pullCurrentBranch(repoDir);
await pushCurrentBranch(repoDir);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 1,
behindOfOrigin: 2,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
});
expect(headOf(remoteDir, "refs/heads/main")).toBe(headOf(repoDir));
execFileSync("git", ["merge-base", "--is-ancestor", localCommit, "refs/heads/main"], {
cwd: remoteDir,
});
execFileSync("git", ["merge-base", "--is-ancestor", headOf(cloneDir), "refs/heads/main"], {
cwd: remoteDir,
});
expect(await getCheckoutStatus(repoDir)).toMatchObject({
aheadOfOrigin: 0,
behindOfOrigin: 0,
});
});
// Git's default refuses this push. In a checkout that has origin Paseo has always made it,
// which is how a PR checkout reaches the contributor's branch. It is not extended to
// checkouts without origin, where the upstream is often a shared base branch.
it("does not push a branch to a differently named upstream branch", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
execFileSync("git", ["checkout", "-b", "feature", "--track", "upstream/main"], {
cwd: repoDir,
});
const remoteMainBefore = headOf(remoteDir, "refs/heads/main");
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
await expect(pushCurrentBranch(repoDir)).rejects.toThrow(
"Push did not send 'feature' to 'upstream/main'",
);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 1,
pullRemote: "upstream",
pushRemote: null,
});
expect(headOf(remoteDir, "refs/heads/main")).toBe(remoteMainBefore);
});
// Push follows the upstream only when `git push` would update it too.
it.each([
{
name: "the branch's pushRemote names a fork",
config: [["branch.main.pushRemote", "fork"]],
},
{ name: "remote.pushDefault names a fork", config: [["remote.pushDefault", "fork"]] },
{
name: "the branch's pushRemote has a push refspec",
config: [
["branch.main.pushRemote", "fork"],
["remote.fork.push", "HEAD:refs/heads/published"],
],
},
{
name: "the upstream remote has a push refspec",
config: [["remote.upstream.push", "HEAD:refs/heads/other"]],
},
{
name: "the push remote shares the upstream's remote-tracking refs",
config: [
["branch.main.pushRemote", "fork"],
["remote.fork.fetch", "+refs/heads/*:refs/remotes/upstream/*"],
],
},
{ name: "push.default is nothing", config: [["push.default", "nothing"]] },
// Matching mode sends a branch only when the remote still has it, which the checkout
// cannot know.
{ name: "push.default is matching", config: [["push.default", "matching"]] },
])("does not push when $name", async ({ config }) => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir });
for (const [key, value] of config) {
execFileSync("git", ["config", key, value], { cwd: repoDir });
}
const remoteMainBefore = headOf(remoteDir, "refs/heads/main");
commitFile(repoDir, "local.txt", "local\n", "local commit");
const status = await getCheckoutStatus(repoDir);
await expect(pushCurrentBranch(repoDir)).rejects.toThrow(
"Push did not send 'main' to 'upstream/main' because Git's push settings do not confirm",
);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 1,
pullRemote: "upstream",
pushRemote: null,
});
expect(branchesOf(remoteDir)).toBe("* main");
expect(headOf(remoteDir, "refs/heads/main")).toBe(remoteMainBefore);
expect(branchesOf(forkDir)).toBe("");
});
// Paseo writes this configuration for a PR checkout, so that its push reaches the
// contributor's branch.
it("pushes a Paseo worktree to the push refspec Paseo configured for it", async () => {
setupRemoteTrackingMain(repoDir, tempDir, "upstream");
const prRemoteDir = join(tempDir, "pr-remote.git");
execFileSync("git", ["init", "--bare", "-b", "main", prRemoteDir]);
const worktree = await createLegacyWorktreeForTest({
branchName: "contributor/feature",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "contributor-feature",
paseoHome,
});
const worktreeDir = worktree.worktreePath;
execFileSync("git", ["remote", "add", "paseo-pr-7", prRemoteDir], { cwd: worktreeDir });
execFileSync("git", ["config", "branch.contributor/feature.pushRemote", "paseo-pr-7"], {
cwd: worktreeDir,
});
execFileSync("git", ["config", "remote.paseo-pr-7.push", "HEAD:refs/heads/feature"], {
cwd: worktreeDir,
});
commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(worktreeDir, { paseoHome });
await pushCurrentBranch(worktreeDir, undefined, { paseoHome });
expect(status).toMatchObject({ hasRemote: false, pushRemote: "paseo-pr-7" });
expect(headOf(prRemoteDir, "refs/heads/feature")).toBe(headOf(worktreeDir));
});
});
// A legal local branch named "origin/main" shadows the short form "origin/main" in git's
+100 -244
View File
@@ -909,14 +909,7 @@ export interface CheckoutStatusGitNonPaseo {
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
upstreamState: UpstreamState;
// Whether origin is configured. Pull and Push do not need it; see pullRemote and pushRemote.
hasRemote: boolean;
// The remote Pull fetches currentBranch from, as git names it: the remote of the branch's
// configured upstream, or "." when the upstream is a local branch. Null without an upstream.
pullRemote: string | null;
// The remote Push sends currentBranch to, resolved as pushCurrentBranch resolves it. Null when
// Push has nowhere to send the branch.
pushRemote: string | null;
firstPushRemote: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: false;
@@ -937,8 +930,6 @@ export interface CheckoutStatusGitPaseo {
behindOfOrigin: number | null;
upstreamState: UpstreamState;
hasRemote: boolean;
pullRemote: string | null;
pushRemote: string | null;
firstPushRemote: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: true;
@@ -976,9 +967,6 @@ export interface CheckoutContext {
logger?: Pick<Logger, "trace" | "warn">;
facts?: CheckoutSnapshotFacts | null;
runGitCommand?: RunGitCommand;
// `git config --get` results shared by the lookups of one snapshot, keyed by config key.
// Several lookups read the same keys; this keeps each to one process.
gitConfigReads?: Map<string, Promise<string | null>>;
}
export type CheckoutSnapshotFacts =
@@ -1000,8 +988,7 @@ export type CheckoutSnapshotFacts =
branchRemoteName: string | null;
branchMergeRef: string | null;
upstreamStatus: UpstreamStatus;
// Where Push sends the current branch. Null when Push has nowhere to send it.
pushTarget: PushTarget | null;
firstPushRemote: string | null;
pullRequestLookupTarget: PullRequestStatusLookupTarget | null;
};
@@ -1454,7 +1441,16 @@ export async function getOriginRemoteUrl(
cwd: string,
context?: CheckoutContext,
): Promise<string | null> {
return getGitConfigValue(cwd, "remote.origin.url", context);
try {
const { stdout } = await getRunGitCommand(context)(["config", "--get", "remote.origin.url"], {
cwd,
envOverlay: READ_ONLY_GIT_ENV,
});
const url = stdout.trim();
return url.length > 0 ? url : null;
} catch {
return null;
}
}
export async function hasOriginRemote(cwd: string): Promise<boolean> {
@@ -1466,23 +1462,6 @@ async function getGitConfigValue(
cwd: string,
key: string,
context?: CheckoutContext,
): Promise<string | null> {
const reads = context?.gitConfigReads;
if (!reads) {
return readGitConfigValue(cwd, key, context);
}
let read = reads.get(key);
if (!read) {
read = readGitConfigValue(cwd, key, context);
reads.set(key, read);
}
return read;
}
async function readGitConfigValue(
cwd: string,
key: string,
context?: CheckoutContext,
): Promise<string | null> {
try {
const { stdout } = await getRunGitCommand(context)(["config", "--get", key], {
@@ -2050,6 +2029,32 @@ async function readGitPushRemote(input: {
return branchPushRemote ?? pushDefault ?? input.branchRemoteName ?? "origin";
}
// pushCurrentBranch publishes a branch with no upstream here.
const FIRST_PUSH_REMOTE = "origin";
// Where a first push publishes the branch, when the daemon can confirm git would push it there
// too. When git picks another remote, as in a fork setup, this is null so that clients do not
// offer a first push that lands in a different repository than `git push` would use.
async function readFirstPushRemote(input: {
cwd: string;
storedBranchName: string | null;
branchRemoteName: string | null;
hasOrigin: boolean;
context?: CheckoutContext;
}): Promise<string | null> {
const { cwd, storedBranchName, branchRemoteName, context } = input;
if (!storedBranchName || !input.hasOrigin) {
return null;
}
const gitPushRemote = await readGitPushRemote({
cwd,
storedBranchName,
branchRemoteName,
context,
});
return gitPushRemote === FIRST_PUSH_REMOTE ? FIRST_PUSH_REMOTE : null;
}
interface CheckoutInspectionContext {
worktreeRoot: string;
currentBranch: string | null;
@@ -2309,13 +2314,7 @@ export async function getCheckoutSnapshotFacts(
if (context?.facts) {
return context.facts;
}
return collectCheckoutSnapshotFacts(cwd, { ...context, gitConfigReads: new Map() });
}
async function collectCheckoutSnapshotFacts(
cwd: string,
context: CheckoutContext,
): Promise<CheckoutSnapshotFacts> {
const inspected = await inspectCheckoutContext(cwd, context);
if (!inspected) {
return { isGit: false };
@@ -2361,14 +2360,13 @@ async function collectCheckoutSnapshotFacts(
]);
}
}
const pushTargetPromise = storedBranchName
? resolvePushTarget({
cwd,
storedBranchName,
paseoWorktree: inspected.paseoWorktree,
context,
})
: null;
const firstPushRemotePromise = readFirstPushRemote({
cwd,
storedBranchName,
branchRemoteName,
hasOrigin: inspected.remoteUrl !== null,
context,
});
let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
cwd,
inspected,
@@ -2404,7 +2402,7 @@ async function collectCheckoutSnapshotFacts(
branchRemoteName,
branchMergeRef,
upstreamStatus,
pushTarget: pushTargetOrNull(await pushTargetPromise),
firstPushRemote: await firstPushRemotePromise,
pullRequestLookupTarget,
};
}
@@ -2582,16 +2580,6 @@ export async function getCheckoutStatus(
// comparisons and actions read it.
const displayBaseRef = baseRef ? branchNameFromRef(baseRef) : null;
const upstream = projectUpstreamStatus(facts.upstreamStatus);
const pushRemote = facts.pushTarget?.remoteName ?? null;
const remotes = {
hasRemote,
pullRemote: resolvePullRemote(facts.branchRemoteName, facts.branchMergeRef),
pushRemote,
// COMPAT(checkoutFirstPushRemote): added in v0.17.5, remove after 2027-05-24 once the app
// floor reads pushRemote. v0.17.4 apps offer a regular checkout's first push only when this
// is set, and the daemon they shipped with set it when the push went to origin.
firstPushRemote: pushRemote === PUBLISH_REMOTE ? pushRemote : null,
};
if (paseoWorktree.isPaseoOwnedWorktree && baseRef) {
return {
@@ -2605,7 +2593,8 @@ export async function getCheckoutStatus(
comparisonBaseRef,
aheadBehind,
...upstream,
...remotes,
hasRemote,
firstPushRemote: facts.firstPushRemote,
remoteUrl,
isPaseoOwnedWorktree: true,
};
@@ -2623,7 +2612,8 @@ export async function getCheckoutStatus(
comparisonBaseRef,
aheadBehind,
...upstream,
...remotes,
hasRemote,
firstPushRemote: facts.firstPushRemote,
remoteUrl,
isPaseoOwnedWorktree: false,
};
@@ -4329,8 +4319,10 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService
if (!currentBranch || currentBranch === "HEAD") {
throw new Error("Unable to determine current branch for pull");
}
// Git decides whether there is something to pull from. It does not need origin, and it can
// pull some branches that have no upstream, as in a single-branch clone.
const hasRemote = await hasOriginRemote(cwd);
if (!hasRemote) {
throw new Error("Remote 'origin' is not configured.");
}
try {
await runGitCommand(["pull"], { cwd, timeout: 120_000 });
forgeService?.invalidate({ cwd });
@@ -4340,16 +4332,6 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService
}
}
// The remote `git pull` fetches a branch from when the branch has a configured upstream, which
// git names "." when the upstream is a local branch. Checkout status reports it so that clients
// offer Pull for any upstream, not only one on origin.
function resolvePullRemote(
branchRemoteName: string | null,
branchMergeRef: string | null,
): string | null {
return branchMergeRef === null ? null : branchRemoteName;
}
export async function pushCurrentBranch(
cwd: string,
forgeService?: ForgeService,
@@ -4361,175 +4343,55 @@ export async function pushCurrentBranch(
throw new Error("Unable to determine current branch for push");
}
const storedBranchName = await readStoredBranchName(cwd, currentBranch, context);
// The status a client acted on can be older than the git configuration, so the destination is
// resolved again before anything is sent.
const target = await resolvePushTarget({ cwd, storedBranchName, context });
switch (target.kind) {
case "refused":
throw new Error(target.reason);
case "configured":
await runGitCommand(["push", target.remoteName, `HEAD:refs/heads/${target.headRef}`], {
cwd,
timeout: 120_000,
});
await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, target);
break;
case "upstream":
await runGitCommand(["push", "-u", target.remoteName, `HEAD:refs/heads/${target.headRef}`], {
cwd,
timeout: 120_000,
});
break;
case "publish":
await runGitCommand(["push", "-u", target.remoteName, currentBranch], {
cwd,
timeout: 120_000,
});
break;
const configuredPushTarget = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName);
if (configuredPushTarget) {
await runGitCommand(
["push", configuredPushTarget.remoteName, `HEAD:refs/heads/${configuredPushTarget.headRef}`],
{ cwd, timeout: 120_000 },
);
await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, configuredPushTarget);
forgeService?.invalidate({ cwd });
return;
}
const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName);
if (upstreamTarget) {
await runGitCommand(
["push", "-u", upstreamTarget.remoteName, `HEAD:refs/heads/${upstreamTarget.headRef}`],
{ cwd, timeout: 120_000 },
);
forgeService?.invalidate({ cwd });
return;
}
const hasRemote = await hasOriginRemote(cwd);
if (!hasRemote) {
throw new Error("Remote 'origin' is not configured.");
}
await requireFirstPushAgreesWithGit(cwd, storedBranchName, context);
await runGitCommand(["push", "-u", FIRST_PUSH_REMOTE, currentBranch], { cwd, timeout: 120_000 });
forgeService?.invalidate({ cwd });
}
// A branch with no upstream on a remote is published here.
const PUBLISH_REMOTE = "origin";
// Where Push sends the current branch. In a checkout that has origin, in order: the branch's push
// remote with a HEAD push refspec, then its upstream, then origin under the branch's own name,
// which sets the upstream. Without origin, see resolvePushWithoutOrigin. Checkout status reports
// the remote of this target, so the Push offer and the push cannot disagree.
export type PushTarget =
| { kind: "configured"; remoteName: string; headRef: string }
| { kind: "upstream"; remoteName: string; headRef: string }
| { kind: "publish"; remoteName: typeof PUBLISH_REMOTE };
// Push has nowhere to send the branch. The reason is written for the user.
interface PushRefusal {
kind: "refused";
reason: string;
}
function pushTargetOrNull(resolved: PushTarget | PushRefusal | null): PushTarget | null {
return resolved === null || resolved.kind === "refused" ? null : resolved;
}
interface ResolvePushTargetInput {
cwd: string;
storedBranchName: string;
// Known by the caller. Looked up when absent.
paseoWorktree?: PaseoWorktreeForCwd;
context?: CheckoutContext;
}
async function resolvePushTarget(input: ResolvePushTargetInput): Promise<PushTarget | PushRefusal> {
const { cwd, storedBranchName, context } = input;
if ((await getOriginRemoteUrl(cwd, context)) === null) {
return resolvePushWithoutOrigin(input);
}
const configured = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName, context);
if (configured) {
return { kind: "configured", ...configured };
}
// In a checkout that has origin, Push has always followed the upstream, whatever the upstream
// branch is called.
const upstream = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName, context);
if (upstream) {
return { kind: "upstream", ...upstream };
}
return resolvePublish(input);
}
// Without origin, Push follows the upstream only when the upstream branch has the branch's own
// name and plain `git push` would update that same branch. A differently named upstream is often
// a shared base branch, as with `feature` tracking `upstream/main`. Git's own push settings
// (branch.<name>.pushRemote, remote.pushDefault, remote.<name>.push, push.default) can send the
// branch elsewhere, and then the push is left to the user.
async function resolvePushWithoutOrigin(
input: ResolvePushTargetInput,
): Promise<PushTarget | PushRefusal> {
const { cwd, storedBranchName, context } = input;
const paseoWorktree = input.paseoWorktree ?? (await getPaseoWorktreeForCwd(cwd, { context }));
if (paseoWorktree.isPaseoOwnedWorktree) {
// Paseo writes this configuration for a PR checkout, so its push reaches the PR's branch.
const configured = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName, context);
if (configured) {
return { kind: "configured", ...configured };
}
}
const upstream = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName, context);
if (!upstream) {
return { kind: "refused", reason: `Remote '${PUBLISH_REMOTE}' is not configured.` };
}
const upstreamName = `${upstream.remoteName}/${upstream.headRef}`;
if (upstream.headRef !== storedBranchName) {
return {
kind: "refused",
reason: `Push did not send '${storedBranchName}' to '${upstreamName}' because the branch names differ. Push it from a terminal instead.`,
};
}
const gitPushUpdatesUpstream = await doesGitPushUpdateUpstream({
cwd,
storedBranchName,
upstreamRemoteName: upstream.remoteName,
context,
});
if (!gitPushUpdatesUpstream) {
return {
kind: "refused",
reason: `Push did not send '${storedBranchName}' to '${upstreamName}' because Git's push settings do not confirm that destination. Push it from a terminal instead.`,
};
}
return { kind: "upstream", ...upstream };
}
// Whether plain `git push` on this branch updates the branch's upstream. Git resolves its push
// destination from its own settings and reports none when it cannot name a single one. The
// remote is compared by name as well, because two remotes can map onto one remote-tracking ref.
// Matching mode is left to the user: Git then sends the branch only when the remote still has
// it, and the checkout's remote-tracking refs can outlive a branch deleted on the remote.
async function doesGitPushUpdateUpstream(input: {
cwd: string;
storedBranchName: string;
upstreamRemoteName: string;
context?: CheckoutContext;
}): Promise<boolean> {
if ((await getGitConfigValue(input.cwd, "push.default", input.context)) === "matching") {
return false;
}
try {
const { stdout } = await getRunGitCommand(input.context)(
[
"for-each-ref",
"--format=%(push:remotename)%00%(push)%00%(upstream)",
`refs/heads/${input.storedBranchName}`,
],
{ cwd: input.cwd, envOverlay: READ_ONLY_GIT_ENV },
);
const [pushRemoteName, pushRef, upstreamRef] = stdout.trim().split("\0");
return (
pushRemoteName === input.upstreamRemoteName && Boolean(pushRef) && pushRef === upstreamRef
);
} catch {
return false;
}
}
// Publishing sends the branch to origin. A regular checkout needs git to push the branch there
// too, so that a fork setup is not published to origin. Paseo worktrees always publish to origin.
async function resolvePublish(input: ResolvePushTargetInput): Promise<PushTarget | PushRefusal> {
const { cwd, storedBranchName, context } = input;
const publish: PushTarget = { kind: "publish", remoteName: PUBLISH_REMOTE };
// The status a client acted on can be older than the git configuration, so a first push checks
// the destination again before it sends anything. Paseo worktrees always publish to origin.
async function requireFirstPushAgreesWithGit(
cwd: string,
storedBranchName: string,
context?: CheckoutContext,
): Promise<void> {
const [branchRemoteName, branchMergeRef] = await Promise.all([
getGitConfigValue(cwd, `branch.${storedBranchName}.remote`, context),
getGitConfigValue(cwd, `branch.${storedBranchName}.merge`, context),
]);
// A branch with a configured upstream gets here when that upstream is not a remote branch, as
// when it tracks a local branch. It goes to origin as before.
// when it tracks a local branch. That is not a first push, and it goes to origin as before.
if (branchRemoteName !== null && branchMergeRef !== null) {
return publish;
return;
}
const paseoWorktree = input.paseoWorktree ?? (await getPaseoWorktreeForCwd(cwd, { context }));
const paseoWorktree = await getPaseoWorktreeForCwd(cwd, { context });
if (paseoWorktree.isPaseoOwnedWorktree) {
return publish;
return;
}
const gitPushRemote = await readGitPushRemote({
cwd,
@@ -4537,29 +4399,24 @@ async function resolvePublish(input: ResolvePushTargetInput): Promise<PushTarget
branchRemoteName,
context,
});
if (gitPushRemote !== PUBLISH_REMOTE) {
return {
kind: "refused",
reason: `Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${PUBLISH_REMOTE}'. Push it from a terminal instead.`,
};
if (gitPushRemote !== FIRST_PUSH_REMOTE) {
throw new Error(
`Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${FIRST_PUSH_REMOTE}'. Push it from a terminal instead.`,
);
}
return publish;
}
async function getCurrentBranchConfiguredPushTarget(
cwd: string,
currentBranch: string,
context?: CheckoutContext,
): Promise<{ remoteName: string; headRef: string } | null> {
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.pushRemote`, context);
const pushRefspec = remoteName
? await getGitConfigValue(cwd, `remote.${remoteName}.push`, context)
: null;
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.pushRemote`);
const pushRefspec = remoteName ? await getGitConfigValue(cwd, `remote.${remoteName}.push`) : null;
const headRef = parseHeadPushRefspec(pushRefspec);
if (!remoteName || !headRef) {
return null;
}
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`, context);
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`);
return remoteUrl ? { remoteName, headRef } : null;
}
@@ -4626,17 +4483,16 @@ async function updateRemoteTrackingRef(
async function getCurrentBranchUpstreamPushTarget(
cwd: string,
currentBranch: string,
context?: CheckoutContext,
): Promise<{ remoteName: string; headRef: string } | null> {
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.remote`, context);
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.remote`);
const mergeRef = remoteName
? await getGitConfigValue(cwd, `branch.${currentBranch}.merge`, context)
? await getGitConfigValue(cwd, `branch.${currentBranch}.merge`)
: null;
const headRef = parseBranchMergeHeadRef(mergeRef);
if (!remoteName || !headRef) {
return null;
}
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`, context);
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`);
return remoteUrl ? { remoteName, headRef } : null;
}
+17 -2
View File
@@ -177,7 +177,7 @@ test("filters by search and clears to all plugins", async ({ page }) => {
test("keeps the directory's ranking window when searching", async ({ page }) => {
await page.goto("/plugins?window=month");
await submitSearch(page, "graphite");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite&window=month$/);
await expectDirectorySearch(page, "graphite", "month");
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
@@ -358,10 +358,16 @@ test.describe("search engine visits without JavaScript", () => {
});
test("renders search results and submits the search form", async ({ page }) => {
await page.goto("/plugins/all?q=graphite");
await page.goto("/plugins?window=month");
await submitSearch(page, "graphite");
await expectDirectorySearch(page, "graphite", "month");
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible();
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
);
await expect(page.getByRole("main").getByRole("link", { name: /Graphite/ })).toBeVisible();
await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0);
@@ -459,6 +465,15 @@ async function submitSearch(page: Page, term: string) {
await page.keyboard.press("Enter");
}
async function expectDirectorySearch(page: Page, term: string, window: string) {
await expect(page).toHaveURL(
(url) =>
url.pathname === "/plugins/all" &&
url.searchParams.get("q") === term &&
url.searchParams.get("window") === window,
);
}
async function typeSearch(page: Page, term: string) {
await page.getByRole("searchbox", { name: "Search plugins" }).pressSequentially(term);
}
@@ -1,152 +0,0 @@
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { z } from "zod";
import { execCommand } from "@getpaseo/plugin/server";
import type { Input } from "../shared/input.js";
/** The OpenCode installed for the daemon's user. */
export interface OpenCodeInstall {
command: string;
args: string[];
env: NodeJS.ProcessEnv;
/** Where OpenCode 1 keeps its logins. */
authFile: string;
}
/** A credential OpenCode can serve Go with. Anything else on the integration is ignored. */
export type GoCredential =
| { type: "key"; key: string }
| { type: "console"; access: string; expires: number; orgID: string };
/** The selected credential on each integration that can carry OpenCode Go. */
export interface Logins {
/** OpenCode binds Go to this integration when the Console workspace has Go. */
opencode: GoCredential | null;
go: GoCredential | null;
}
const CONSOLE_SERVER = "https://opencode.ai/console";
const ORGANIZATION_ID = /^(?:org|wrk)_[A-Za-z0-9]+$/;
const VERSION = /^(?:opencode\s+)?v?(\d+)\./i;
const fileSchema = z.object({
"opencode-go": z.object({ type: z.literal("api"), key: z.string().min(1) }).optional(),
});
const exportSchema = z.array(
z.object({ integrationID: z.string(), active: z.boolean(), value: z.unknown() }),
);
/** The error of a process that Node stopped at its timeout. */
const stoppedSchema = z.object({ killed: z.literal(true) });
const metadataSchema = z
.object({ server: z.string().optional(), orgID: z.string().optional() })
.optional();
const credentialSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("key"), key: z.string().min(1), metadata: metadataSchema }),
z.object({
type: z.literal("oauth"),
access: z.string().min(1),
expires: z.number(),
metadata: metadataSchema,
}),
]);
export function installedOpenCode(env: NodeJS.ProcessEnv = process.env): OpenCodeInstall {
const dataHome = env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share");
return { command: "opencode", args: [], env, authFile: join(dataHome, "opencode", "auth.json") };
}
/**
* Where the installed OpenCode keeps its logins. OpenCode 2 keeps them behind its own credential
* listing, and `readLogins` adds the auth.json Go key to it. OpenCode 1 keeps them in auth.json
* only, even though its database has a credential table too.
*/
export async function loginStore(install: OpenCodeInstall): Promise<Input["store"]> {
let version: string;
try {
const { stdout } = await run(install, ["--version"], { timeout: 5_000 });
version = stdout.trim();
} catch (error) {
// A check that was cut off does not show which store OpenCode uses.
if (stoppedSchema.safeParse(error).success)
throw new Error("OpenCode did not report its version in time.", { cause: error });
// The daemon treats a missing or failing OpenCode as OpenCode 1 too.
return "file";
}
return Number(VERSION.exec(version)?.[1] ?? 1) >= 2 ? "credentials" : "file";
}
/**
* Re-reads the store. OpenCode 2 imports auth.json only once, so a Go key saved there later is in
* no other place: the file's key stands in when OpenCode 2 has no `opencode-go` login. A stale key
* in the file never replaces a login OpenCode 2 has. A failed OpenCode 2 read throws, because it
* does not show which logins OpenCode 2 has.
*/
export async function readLogins(install: OpenCodeInstall, store: Input["store"]): Promise<Logins> {
if (store === "file") return { opencode: null, go: await readFileLogin(install.authFile) };
const credentials = await exportCredentials(install);
const selected = (integrationID: string) => {
const entry = credentials.find((item) => item.integrationID === integrationID && item.active);
return entry ? goCredential(integrationID, entry.value) : null;
};
return {
opencode: selected("opencode"),
go: selected("opencode-go") ?? (await readFileLogin(install.authFile)),
};
}
/** Runs OpenCode for plain output. OpenCode 2 colors it when the environment forces colors. */
function run(
install: OpenCodeInstall,
args: string[],
options: { timeout: number; maxBuffer?: number },
) {
return execCommand(install.command, [...install.args, ...args], {
...options,
env: { ...install.env, NO_COLOR: "1" },
});
}
async function readFileLogin(path: string): Promise<GoCredential | null> {
try {
const auth = fileSchema.parse(JSON.parse(await readFile(path, "utf8")));
const key = auth["opencode-go"]?.key;
return key ? { type: "key", key } : null;
} catch {
return null;
}
}
async function exportCredentials(install: OpenCodeInstall) {
try {
// Without --standalone the command starts OpenCode's background service and leaves it running.
const { stdout } = await run(install, ["auth", "export", "--standalone"], {
timeout: 10_000,
maxBuffer: 16 * 1024 * 1024,
});
return exportSchema.parse(JSON.parse(stdout));
} catch {
// The command's output holds every secret, so its error is not passed on.
throw new Error("OpenCode could not list its logins. OpenCode 2.0.20 or newer is required.");
}
}
function goCredential(integrationID: string, value: unknown): GoCredential | null {
const parsed = credentialSchema.safeParse(value);
if (!parsed.success) return null;
const { data } = parsed;
// A credential for another Console never goes to opencode.ai.
if (consoleServer(data.metadata?.server) !== CONSOLE_SERVER) return null;
if (data.type === "key") return { type: "key", key: data.key };
const orgID = data.metadata?.orgID;
if (integrationID !== "opencode" || !orgID || !ORGANIZATION_ID.test(orgID)) return null;
return { type: "console", access: data.access, expires: data.expires, orgID };
}
// OpenCode defaults a missing server to the Console and maps the retired host onto it.
function consoleServer(server: string | undefined): string {
return (server ?? CONSOLE_SERVER).replace(
/^https:\/\/console\.opencode\.ai(?=\/|$)/,
CONSOLE_SERVER,
);
}
@@ -0,0 +1,122 @@
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { z } from "zod";
interface Database {
prepare(sql: string): { all(...args: string[]): unknown[] };
close(): void;
}
interface Sqlite {
DatabaseSync: new (path: string, options: { readOnly: boolean }) => Database;
}
export interface StorePaths {
file: string;
database: string;
}
/** A credential OpenCode can serve Go with. Anything else on the integration is ignored. */
export type GoCredential =
| { type: "key"; key: string }
| { type: "console"; access: string; expires: number; orgID: string };
/** The selected credential on each integration that can carry OpenCode Go. */
export interface DatabaseLogins {
/** OpenCode binds Go to this integration when the Console workspace has Go. */
opencode: GoCredential | null;
go: GoCredential | null;
}
const CONSOLE_SERVER = "https://opencode.ai/console";
const ORGANIZATION_ID = /^(?:org|wrk)_[A-Za-z0-9]+$/;
const fileSchema = z.object({
"opencode-go": z.object({ type: z.literal("api"), key: z.string().min(1) }).optional(),
});
const rowSchema = z.object({ value: z.string() });
const metadataSchema = z
.object({ server: z.string().optional(), orgID: z.string().optional() })
.optional();
const credentialSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("key"), key: z.string().min(1), metadata: metadataSchema }),
z.object({
type: z.literal("oauth"),
access: z.string().min(1),
expires: z.number(),
metadata: metadataSchema,
}),
]);
export function defaultStorePaths(env: NodeJS.ProcessEnv = process.env): StorePaths {
const dataHome = env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share");
const directory = join(dataHome, "opencode");
const database = resolve(directory, env.OPENCODE_DB || "opencode.db");
return { file: join(directory, "auth.json"), database };
}
export async function readFileKey(path: string): Promise<string | null> {
try {
const auth = fileSchema.parse(JSON.parse(await readFile(path, "utf8")));
return auth["opencode-go"]?.key ?? null;
} catch {
return null;
}
}
/** Null when the path is not an OpenCode v2 credential store. */
export function readDatabaseLogins(path: string): DatabaseLogins | null {
// Keep the legacy source loadable on Node versions without node:sqlite.
const sqlite = z
.object({
DatabaseSync: z.custom<Sqlite["DatabaseSync"]>((value) => typeof value === "function"),
})
.safeParse(process.getBuiltinModule?.("node:sqlite"));
if (!sqlite.success || !existsSync(path)) return null;
const db = new sqlite.data.DatabaseSync(path, { readOnly: true });
try {
// V1 also has opencode.db, but only v2 has the credential table.
const tables = db
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'credential'")
.all();
if (!tables.length) return null;
return { opencode: selected(db, "opencode"), go: selected(db, "opencode-go") };
} finally {
db.close();
}
}
function selected(db: Database, integrationID: string): GoCredential | null {
const [value] = db
.prepare(
// OpenCode also selects migrated rows with no active flag, ordered by creation time.
"SELECT value FROM credential WHERE integration_id = ? ORDER BY active DESC, time_created DESC, id DESC LIMIT 1",
)
.all(integrationID);
const row = rowSchema.safeParse(value);
if (!row.success) return null;
let credential: unknown;
try {
credential = JSON.parse(row.data.value);
} catch (error) {
if (error instanceof SyntaxError) return null;
throw error;
}
const parsed = credentialSchema.safeParse(credential);
if (!parsed.success) return null;
const { data } = parsed;
// A credential for another Console never goes to opencode.ai.
if (consoleServer(data.metadata?.server) !== CONSOLE_SERVER) return null;
if (data.type === "key") return { type: "key", key: data.key };
const orgID = data.metadata?.orgID;
if (integrationID !== "opencode" || !orgID || !ORGANIZATION_ID.test(orgID)) return null;
return { type: "console", access: data.access, expires: data.expires, orgID };
}
// OpenCode defaults a missing server to the Console and maps the retired host onto it.
function consoleServer(server: string | undefined): string {
return (server ?? CONSOLE_SERVER).replace(
/^https:\/\/console\.opencode\.ai(?=\/|$)/,
CONSOLE_SERVER,
);
}
@@ -1,113 +1,42 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, expect, test } from "vitest";
import { inputSchema } from "../shared/input.js";
import { installedOpenCode, type OpenCodeInstall } from "./opencode.js";
import { discover, fetchUsage } from "./usage.js";
import { defaultStorePaths } from "./stores.js";
// Stands in for the OpenCode CLI: it answers the two commands the source runs, the way the real
// OpenCode 1.19.5 and 2.4.1 answer them, and logs every call.
const OPENCODE_CLI = `
import { appendFileSync, readFileSync } from "node:fs";
const state = JSON.parse(readFileSync(new URL("./opencode-state.json", import.meta.url), "utf8"));
const command = process.argv.slice(2).join(" ");
const colors = process.env.FORCE_COLOR && !process.env.NO_COLOR;
appendFileSync(new URL("./opencode-calls.log", import.meta.url), command + "\\n");
if (command === "--version" && state.hangs) setInterval(() => {}, 60_000);
else if (command === "--version" && state.version)
console.log(colors && state.coloredVersion ? state.coloredVersion : state.version);
else if (command === "auth export --standalone" && state.exported !== undefined)
process.stdout.write(state.exported);
else {
console.error("opencode providers");
process.exit(1);
}
`;
import { inputSchema } from "../shared/input.js";
interface Credential {
integrationID: string;
value: unknown;
active?: boolean;
}
let fixtureDirectory: string;
let authFile: string;
let install: OpenCodeInstall;
function installState(state: {
version?: string;
coloredVersion?: string;
exported?: string;
hangs?: boolean;
}) {
return writeFile(join(fixtureDirectory, "opencode-state.json"), JSON.stringify(state));
let fixturePath: string;
function stores(path: string) {
return { file: path, database: join(dirname(path), "opencode.db") };
}
/** OpenCode 1 keeps logins in auth.json and has no `auth export`. */
function openCode1() {
return installState({ version: "1.19.5" });
}
/** OpenCode 2 lists its own logins and never reads auth.json. */
function openCode2(credentials: Credential[]) {
const exported = credentials.map((credential, index) => ({
id: `cred_${index}`,
label: "API key",
active: true,
...credential,
}));
return installState({
version: "opencode v2.4.1",
coloredVersion: "\u001b[1mopencode\u001b[0m \u001b[2mv\u001b[0m\u001b[1m2.4.1\u001b[0m",
exported: JSON.stringify(exported),
});
}
async function openCodeCalls() {
const log = await readFile(join(fixtureDirectory, "opencode-calls.log"), "utf8");
return log.trimEnd().split("\n");
}
/** The database OpenCode creates next to auth.json, with OpenCode's credential table. */
async function database(credentials: Array<{ integration: string; label: string }> | null) {
async function database() {
const { DatabaseSync } = await import("node:sqlite");
const db = new DatabaseSync(join(fixtureDirectory, "opencode.db"));
db.exec("CREATE TABLE session (id TEXT PRIMARY KEY)");
if (credentials) {
db.exec(
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, label TEXT NOT NULL, value TEXT NOT NULL, connector_id TEXT, method_id TEXT, active INTEGER, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)",
);
const insert = db.prepare(
"INSERT INTO credential (id, integration_id, label, value, time_created, time_updated) VALUES (?, ?, ?, ?, 1, 1)",
);
for (const { integration, label } of credentials)
insert.run(integration, integration, label, JSON.stringify({ type: "key", key: "other" }));
}
db.close();
db.exec(
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, value TEXT, active INTEGER, time_updated INTEGER, time_created INTEGER DEFAULT 0)",
);
return db;
}
const account = (store: "file" | "credentials") => ({
key: expect.stringMatching(/^[a-f0-9]{64}$/),
input: { store },
});
const goKey = (key: string, active = true): Credential => ({
integrationID: "opencode-go",
value: { type: "key", key },
active,
});
beforeEach(async () => {
fixtureDirectory = await mkdtemp(join(tmpdir(), "go-default-"));
authFile = join(fixtureDirectory, "auth.json");
await writeFile(authFile, JSON.stringify({ "opencode-go": { type: "api", key: "file-key" } }));
const cli = join(fixtureDirectory, "opencode.mjs");
await writeFile(cli, OPENCODE_CLI);
install = { command: process.execPath, args: [cli], env: process.env, authFile };
await openCode1();
fixturePath = join(fixtureDirectory, "auth.json");
await writeFile(
fixturePath,
JSON.stringify({ "opencode-go": { type: "api", key: "fixture-secret" } }),
);
});
afterEach(async () => {
await rm(fixtureDirectory, { recursive: true, force: true });
});
test("discovery input holds no path and no API key", () => {
test("discovery input rejects an explicit API key", () => {
expect(inputSchema.safeParse({ apiKey: "unused" }).success).toBe(false);
expect(inputSchema.safeParse({ store: "credentials", apiKey: "unused" }).success).toBe(false);
expect(inputSchema.safeParse({ store: "file", path: authFile }).success).toBe(false);
expect(
inputSchema.safeParse({ store: "database", path: "opencode.db", apiKey: "unused" }).success,
).toBe(false);
expect(() => inputSchema.parse({})).toThrow();
});
@@ -120,280 +49,287 @@ const upstreamResponse = {
monthly: { status: "rate-limited", percent: 100, resetsAt: "2026-10-01T00:00:00.000Z" },
},
};
const bearer = (init?: RequestInit) => new Headers(init?.headers).get("Authorization");
// OpenCode 1.17.5 and newer creates the credential table too, and keeps every login in auth.json.
// OpenCode 2 fills that table when it opens the same directory, and OpenCode 1 keeps using the file.
test.each([
["no credential table", null],
["an empty credential table", []],
[
"only an unrelated credential that OpenCode 2 imported",
[{ integration: "manifest", label: "API key" }],
],
[
"a Go credential that OpenCode 2 imported before the key changed",
[{ integration: "opencode-go", label: "API key" }],
],
])("reads OpenCode 1's Go key from auth.json next to a database with %s", async (_name, rows) => {
await database(rows);
const accounts = await discover(install);
expect(accounts).toEqual([account("file")]);
const report = await fetchUsage(
inputSchema.parse(accounts[0]!.input),
async (_url, init) => {
expect(bearer(init)).toBe("Bearer file-key");
return Response.json(upstreamResponse);
},
install,
test("uses the active v2 Go key instead of a stale legacy key without writing either store", async () => {
const databasePath = join(fixtureDirectory, "opencode.db");
const db = await database();
const insert = db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
);
expect(report.status).toBe("available");
// OpenCode 1 has no login listing, so it is never asked for one.
expect(await openCodeCalls()).toEqual(["--version"]);
});
test("reads auth.json when OpenCode is not installed", async () => {
const absent = { ...install, command: join(fixtureDirectory, "absent-opencode"), args: [] };
expect(await discover(absent)).toEqual([account("file")]);
});
test("reads auth.json when OpenCode fails its version check", async () => {
await installState({});
expect(await discover(install)).toEqual([account("file")]);
});
// A check that is cut off does not show which store OpenCode uses. Reading auth.json here would
// drop the card of a login that only OpenCode 2 has.
test("fails instead of reading auth.json when OpenCode does not answer its version check", async () => {
await installState({ hangs: true });
await expect(discover(install)).rejects.toThrow("OpenCode did not report its version in time");
}, 15_000);
test("uses the Go key OpenCode 2 marks active instead of a stale auth.json key", async () => {
await openCode2([goKey("inactive-key", false), goKey("active-key")]);
const beforeFile = await readFile(authFile);
const accounts = await discover(install);
expect(accounts).toEqual([account("credentials")]);
expect(JSON.stringify(accounts)).not.toContain("active-key");
const report = await fetchUsage(
inputSchema.parse(accounts[0]!.input),
async (_url, init) => {
expect(bearer(init)).toBe("Bearer active-key");
return Response.json(upstreamResponse);
insert.run("inactive", "opencode-go", JSON.stringify({ type: "key", key: "inactive-key" }), 0, 3);
insert.run("active", "opencode-go", JSON.stringify({ type: "key", key: "active-key" }), 1, 1);
db.close();
const beforeDatabase = await readFile(databasePath);
const beforeFile = await readFile(fixturePath);
const accounts = await discover(stores(fixturePath));
expect(accounts).toEqual([
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
input: { store: "database", path: databasePath },
},
install,
);
]);
const input = inputSchema.parse(accounts[0]!.input);
const report = await fetchUsage(input, async (_url, init) => {
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer active-key");
return Response.json(upstreamResponse);
});
expect(report.status).toBe("available");
expect(report.windows.map((window) => window.usedPct)).toEqual([21, 42, 100]);
expect(await readFile(authFile)).toEqual(beforeFile);
// --standalone keeps the listing from starting OpenCode's background service.
expect(await openCodeCalls()).toEqual([
"--version",
"auth export --standalone",
"auth export --standalone",
expect(await readFile(databasePath)).toEqual(beforeDatabase);
expect(await readFile(fixturePath)).toEqual(beforeFile);
});
test("discovers v2 Go usage without a legacy auth.json", async () => {
const db = await database();
db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
).run("go", "opencode-go", JSON.stringify({ type: "key", key: "database-key" }), 1, 1);
db.close();
await rm(fixturePath);
const accounts = await discover(stores(fixturePath));
expect(accounts).toEqual([
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
input: { store: "database", path: join(fixtureDirectory, "opencode.db") },
},
]);
});
// OpenCode 2 colors its version when the environment forces colors, even into a pipe.
test("recognizes OpenCode 2 when the daemon's environment forces terminal colors", async () => {
await openCode2([goKey("listed-key")]);
const { NO_COLOR: _unset, ...env } = process.env;
const colored = { ...install, env: { ...env, FORCE_COLOR: "1" } };
expect(await discover(colored)).toEqual([account("credentials")]);
});
test("discovers OpenCode 2 Go usage without an auth.json", async () => {
await openCode2([goKey("listed-key")]);
await rm(authFile);
const accounts = await discover(install);
expect(accounts).toEqual([account("credentials")]);
expect(JSON.stringify(accounts)).not.toContain("listed-key");
expect(JSON.stringify(accounts)).not.toContain("database-key");
});
test("refresh follows the active Go account and re-reads its rotated key", async () => {
await openCode2([goKey("first-key"), goKey("second-key", false)]);
const accounts = await discover(install);
await openCode2([goKey("first-key", false), goKey("rotated-key")]);
expect(await discover(install)).toEqual(accounts);
const report = await fetchUsage(
inputSchema.parse(accounts[0]!.input),
async (_url, init) => {
expect(bearer(init)).toBe("Bearer rotated-key");
return Response.json(upstreamResponse);
},
install,
const db = await database();
const insert = db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
);
insert.run("first", "opencode-go", JSON.stringify({ type: "key", key: "first-key" }), 1, 1);
insert.run("second", "opencode-go", JSON.stringify({ type: "key", key: "second-key" }), 0, 2);
db.close();
const paths = stores(fixturePath);
const accounts = await discover(paths);
const input = inputSchema.parse(accounts[0]!.input);
const { DatabaseSync } = await import("node:sqlite");
const writer = new DatabaseSync(paths.database);
writer.exec("UPDATE credential SET active = CASE id WHEN 'second' THEN 1 ELSE 0 END");
writer
.prepare("UPDATE credential SET value = ? WHERE id = 'second'")
.run(JSON.stringify({ type: "key", key: "rotated-key" }));
writer.close();
expect(await discover(paths)).toEqual(accounts);
const before = await readFile(paths.database);
const report = await fetchUsage(input, async (_url, init) => {
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer rotated-key");
return Response.json(upstreamResponse);
});
expect(report.status).toBe("available");
expect(JSON.stringify(report)).not.toContain("rotated-key");
expect(await readFile(paths.database)).toEqual(before);
});
// The state in #10659: OpenCode 2 opened the directory once and imported an unrelated login, and
// the Go key is only in auth.json.
test("reads the auth.json Go key when OpenCode 2 holds only an unrelated login", async () => {
await database([{ integration: "manifest", label: "API key" }]);
await openCode2([{ integrationID: "manifest", value: { type: "key", key: "other" } }]);
const accounts = await discover(install);
expect(accounts).toEqual([account("credentials")]);
const requests: Array<string | null> = [];
const report = await fetchUsage(
inputSchema.parse(accounts[0]!.input),
async (_url, init) => {
requests.push(bearer(init));
return Response.json(upstreamResponse);
},
install,
);
expect(report.status).toBe("available");
expect(requests).toEqual(["Bearer file-key", "Bearer file-key"]);
});
// A login OpenCode 2 cannot serve Go with from opencode.ai counts as no login.
test.each<[string, Credential[]]>([
["no logins", []],
["an unrelated login", [{ integrationID: "manifest", value: { type: "key", key: "other" } }]],
["a Go key that is not the active one", [goKey("inactive-key", false)]],
[
"a Console sign-in on another server",
[
{
integrationID: "opencode",
value: {
type: "oauth",
access: "staging-token",
expires: 0,
metadata: { server: "https://staging.example.com/console", orgID: "org_TEST" },
},
},
],
],
[
"a Console key on another server",
[
{
integrationID: "opencode",
value: {
type: "key",
key: "staging-key",
metadata: { server: "https://staging.example.com/console" },
},
},
],
],
[
"a sign-in on opencode-go",
[{ integrationID: "opencode-go", value: { type: "oauth", access: "token", expires: 0 } }],
],
["an unreadable Go login", [{ integrationID: "opencode-go", value: "invalid" }]],
["an empty Go key", [goKey("")]],
])("reads the auth.json Go key when OpenCode 2 has %s", async (_name, credentials) => {
await openCode2(credentials);
expect(await discover(install)).toEqual([account("credentials")]);
const report = await fetchUsage(
{ store: "credentials" },
async (_url, init) => {
expect(bearer(init)).toBe("Bearer file-key");
return Response.json(upstreamResponse);
},
install,
);
expect(report.status).toBe("available");
});
test("discovers no account when neither OpenCode 2 nor auth.json has a Go login", async () => {
await openCode2([{ integrationID: "manifest", value: { type: "key", key: "other" } }]);
await rm(authFile);
expect(await discover(install)).toEqual([]);
await expect(
fetchUsage(
{ store: "credentials" },
async () => {
throw new Error("must not fetch");
},
install,
),
).rejects.toThrow("login no longer exists");
});
// A failed listing does not show that OpenCode 2 has no Go login, so auth.json is not read.
test.each([
["has no login listing", { version: "opencode v2.0.10" }],
["answers with something else", { version: "opencode v2.4.1", exported: "not JSON" }],
[
"lists logins in another shape",
{ version: "opencode v2.4.1", exported: JSON.stringify({ "opencode-go": "listed-secret" }) },
],
])("fails instead of reading auth.json when OpenCode 2 %s", async (_name, state) => {
await installState(state);
const failure = await discover(install).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(Error);
expect(String(failure)).toContain("OpenCode could not list its logins");
expect(JSON.stringify(failure, Object.getOwnPropertyNames(failure))).not.toContain(
"listed-secret",
);
});
test("resolves OpenCode and its auth.json from the daemon environment", () => {
expect(installedOpenCode({ HOME: fixtureDirectory })).toEqual({
command: "opencode",
args: [],
env: { HOME: fixtureDirectory },
authFile: join(fixtureDirectory, ".local", "share", "opencode", "auth.json"),
});
expect(installedOpenCode({ XDG_DATA_HOME: fixtureDirectory }).authFile).toBe(
join(fixtureDirectory, "opencode", "auth.json"),
);
});
test("discovers and fetches the key from read-only auth.json", async () => {
const content = await readFile(authFile, "utf8");
expect(await discover(install)).toEqual([account("file")]);
const requests: Array<{ url: string; authorization: string | null }> = [];
const fetchApi = async (url: string | URL | Request, init?: RequestInit) => {
requests.push({ url: String(url), authorization: bearer(init) });
[null, false],
[null, true],
[0, false],
[0, true],
])("discovers a selected Go key with active=%s and legacy file=%s", async (active, legacy) => {
const db = await database();
db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
).run("migrated", "opencode-go", JSON.stringify({ type: "key", key: "migrated-key" }), active, 1);
db.close();
if (!legacy) await rm(fixturePath);
const accounts = await discover(stores(fixturePath));
expect(accounts).toEqual([
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
input: { store: "database", path: join(fixtureDirectory, "opencode.db") },
},
]);
const report = await fetchUsage(inputSchema.parse(accounts[0]!.input), async (_url, init) => {
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer migrated-key");
return Response.json(upstreamResponse);
};
const report = await fetchUsage({ store: "file" }, fetchApi, install);
expect(requests).toEqual([
{ url: CONSOLE_STATUS_URL, authorization: "Bearer file-key" },
{ url: USAGE_URL, authorization: "Bearer file-key" },
]);
});
expect(report.status).toBe("available");
expect(report.windows.map((window) => [window.id, window.usedPct, window.resetsAt])).toEqual([
["rolling", 21, "2026-09-26T20:00:00.000Z"],
["weekly", 42, "2026-09-28T00:00:00.000Z"],
["monthly", 100, "2026-10-01T00:00:00.000Z"],
]);
// The rolling window's length is not reported, so its percent stands without a name.
expect(report.windows.map((window) => window.shortLabel)).toEqual(["", "wk", "mo"]);
// The current upstream endpoint returns windows only; do not invent balances.
expect(report.balances).toBeUndefined();
expect(await readFile(authFile, "utf8")).toBe(content);
});
test("selects the newest created Go key when no explicit active key exists", async () => {
const db = await database();
const insert = db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_created, time_updated) VALUES (?, ?, ?, ?, ?, ?)",
);
insert.run("older", "opencode-go", JSON.stringify({ type: "key", key: "older-key" }), null, 1, 9);
insert.run("newer-a", "opencode-go", JSON.stringify({ type: "key", key: "tie-key" }), null, 2, 8);
insert.run(
"newer-b",
"opencode-go",
JSON.stringify({ type: "key", key: "selected-key" }),
null,
2,
1,
);
db.close();
const accounts = await discover(stores(fixturePath));
expect(accounts).toHaveLength(1);
await fetchUsage(inputSchema.parse(accounts[0]!.input), async (_url, init) => {
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer selected-key");
return Response.json(upstreamResponse);
});
});
test.each([
["has another provider's login", JSON.stringify({ openai: { type: "oauth", access: "token" } })],
["is empty", "{}"],
["is missing", null],
])("discovers no account when auth.json %s", async (_name, content) => {
if (content === null) await rm(authFile);
else await writeFile(authFile, content);
expect(await discover(install)).toEqual([]);
["unrelated provider", "anthropic", 1, JSON.stringify({ type: "key", key: "other-key" })],
[
"Console sign-in on another server",
"opencode",
1,
JSON.stringify({
type: "oauth",
access: "staging-token",
expires: 0,
metadata: { server: "https://staging.example.com/console", orgID: "org_TEST" },
}),
],
[
"Console key on another server",
"opencode",
1,
JSON.stringify({
type: "key",
key: "staging-key",
metadata: { server: "https://staging.example.com/console" },
}),
],
["Console OAuth", "opencode-go", 1, JSON.stringify({ type: "oauth", access: "oauth-token" })],
["malformed credential", "opencode-go", 1, "invalid JSON"],
["empty key", "opencode-go", 1, JSON.stringify({ type: "key", key: "" })],
])(
"does not revive a legacy key for a v2 store with %s",
async (_name, provider, active, value) => {
const db = await database();
db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
).run("credential", provider, value, active, 1);
db.close();
expect(await discover(stores(fixturePath))).toEqual([]);
},
);
test("keeps legacy discovery when the v1 session database has no credential table", async () => {
const { DatabaseSync } = await import("node:sqlite");
const db = new DatabaseSync(join(fixtureDirectory, "opencode.db"));
db.exec("CREATE TABLE session (id TEXT PRIMARY KEY)");
db.close();
expect(await discover(stores(fixturePath))).toEqual([
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
input: { store: "file", path: fixturePath },
},
]);
});
test("fails before fetching when the selected database disappears", async () => {
await expect(
fetchUsage(
{ store: "file" },
async () => {
fetchUsage({ store: "database", path: join(fixtureDirectory, "missing.db") }, async () => {
throw new Error("must not fetch");
}),
).rejects.toThrow("login store no longer exists");
});
test("resolves default and overridden OpenCode store paths", () => {
expect(defaultStorePaths({ HOME: fixtureDirectory })).toEqual({
file: join(fixtureDirectory, ".local", "share", "opencode", "auth.json"),
database: join(fixtureDirectory, ".local", "share", "opencode", "opencode.db"),
});
const customDatabase = join(fixtureDirectory, "custom.db");
expect(
defaultStorePaths({ XDG_DATA_HOME: fixtureDirectory, OPENCODE_DB: customDatabase }),
).toEqual({
file: join(fixtureDirectory, "opencode", "auth.json"),
database: customDatabase,
});
});
test("discovers a relative OPENCODE_DB under the OpenCode data directory", async () => {
const paths = defaultStorePaths({
XDG_DATA_HOME: fixtureDirectory,
OPENCODE_DB: "go.db",
});
const databasePath = join(fixtureDirectory, "opencode", "go.db");
await mkdir(dirname(databasePath));
const { DatabaseSync } = await import("node:sqlite");
const db = new DatabaseSync(databasePath);
db.exec(
"CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, value TEXT, active INTEGER, time_updated INTEGER, time_created INTEGER DEFAULT 0)",
);
db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
).run("go", "opencode-go", JSON.stringify({ type: "key", key: "relative-key" }), 1, 1);
db.close();
expect(await discover(paths)).toEqual([
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
input: { store: "database", path: databasePath },
},
]);
});
test("discovers and fetches the default key from read-only auth.json", async () => {
const directory = await mkdtemp(join(tmpdir(), "paseo-go-usage-"));
const path = join(directory, "auth.json");
const content = JSON.stringify({ "opencode-go": { type: "api", key: "fixture-key" } });
try {
await writeFile(path, content);
expect(await discover(stores(path))).toEqual([
{ key: expect.stringMatching(/^[a-f0-9]{64}$/), input: { store: "file", path } },
]);
const requests: Array<{ url: string; authorization: string | null }> = [];
const fetchApi = async (url: string | URL | Request, init?: RequestInit) => {
requests.push({
url: String(url),
authorization: new Headers(init?.headers).get("Authorization"),
});
return Response.json(upstreamResponse);
};
const report = await fetchUsage({ store: "file", path }, fetchApi);
expect(requests).toEqual([
{ url: CONSOLE_STATUS_URL, authorization: "Bearer fixture-key" },
{ url: USAGE_URL, authorization: "Bearer fixture-key" },
]);
expect(report.status).toBe("available");
expect(report.windows.map((window) => [window.id, window.usedPct, window.resetsAt])).toEqual([
["rolling", 21, "2026-09-26T20:00:00.000Z"],
["weekly", 42, "2026-09-28T00:00:00.000Z"],
["monthly", 100, "2026-10-01T00:00:00.000Z"],
]);
// The rolling window's length is not reported, so its percent stands without a name.
expect(report.windows.map((window) => window.shortLabel)).toEqual(["", "wk", "mo"]);
// The current upstream endpoint returns windows only; do not invent balances.
expect(report.balances).toBeUndefined();
expect(await readFile(path, "utf8")).toBe(content);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("omits default discovery when auth.json lacks an OpenCode Go API key", async () => {
const directory = await mkdtemp(join(tmpdir(), "paseo-go-usage-"));
const path = join(directory, "auth.json");
try {
await writeFile(path, JSON.stringify({ openai: { type: "oauth", access: "other-token" } }));
expect(await discover(stores(path))).toEqual([]);
await expect(
fetchUsage({ store: "file", path }, async () => {
throw new Error("must not fetch");
},
install,
),
).rejects.toThrow("login no longer exists");
}),
).rejects.toThrow("login store no longer exists");
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test.each([401, 403])("maps HTTP %i to unavailable", async (status) => {
const report = await fetchUsage(
{ store: "file" },
{ store: "file", path: fixturePath },
async () => new Response(null, { status }),
install,
);
expect(report).toEqual({
status: "unavailable",
@@ -401,18 +337,28 @@ test.each([401, 403])("maps HTTP %i to unavailable", async (status) => {
});
});
test("keeps the account identity when OpenCode 2 imports the auth.json Go login", async () => {
const [legacy] = await discover(install);
await openCode2([goKey("file-key")]);
const [migrated] = await discover(install);
expect(migrated!.input).toEqual({ store: "credentials" });
test.each(["missing file", "unrelated file"])("discovers no accounts for %s", async (scenario) => {
const path = join(fixtureDirectory, "missing.json");
if (scenario === "unrelated file") await writeFile(path, "{}");
expect(await discover(stores(path))).toEqual([]);
});
test("keeps the account identity when OpenCode v2 imports the legacy Go login", async () => {
const paths = stores(fixturePath);
const [legacy] = await discover(paths);
const db = await database();
db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
).run("imported", "opencode-go", JSON.stringify({ type: "key", key: "fixture-secret" }), null, 1);
db.close();
const [migrated] = await discover(paths);
expect(migrated!.input).toEqual({ store: "database", path: paths.database });
// Usage settings are saved per account, so the card keeps its visibility and position.
expect(migrated!.key).toBe(legacy!.key);
});
const consoleSignIn = (overrides: { expires?: number; server?: string } = {}): Credential => ({
integrationID: "opencode",
value: {
const consoleSignIn = (overrides: { expires?: number; server?: string } = {}) =>
JSON.stringify({
type: "oauth",
methodID: "device",
access: "console-token",
@@ -423,12 +369,7 @@ const consoleSignIn = (overrides: { expires?: number; server?: string } = {}): C
orgID: "org_TESTORG123",
orgName: "Team",
},
},
});
const consoleKey = (key: string): Credential => ({
integrationID: "opencode",
value: { type: "key", key },
});
});
const goStatus = (
access: unknown = {
meters: {
@@ -474,19 +415,27 @@ function upstream(answers: Record<string, () => Response>) {
};
return { requests, fetchApi: fetchApi as typeof fetch };
}
async function storeWith(credentials: Credential[]) {
await openCode2(credentials);
await rm(authFile, { force: true });
const [found] = await discover(install);
return inputSchema.parse(found!.input);
async function storeWith(rows: Array<[string, string]>) {
const db = await database();
const insert = db.prepare(
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
);
for (const [integration, value] of rows) insert.run(integration, integration, value, 1, 1);
db.close();
await rm(fixturePath);
const [account] = await discover(stores(fixturePath));
return inputSchema.parse(account!.input);
}
test("reads Go from the Console sign-in OpenCode serves it with, ahead of the opencode-go key", async () => {
const input = await storeWith([consoleSignIn(), goKey("go-key")]);
const input = await storeWith([
["opencode", consoleSignIn()],
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
]);
const { requests, fetchApi } = upstream({
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus()),
});
const report = await fetchUsage(input, fetchApi, install);
const report = await fetchUsage(input, fetchApi);
expect(requests).toEqual([
{
url: CONSOLE_STATUS_URL,
@@ -503,34 +452,39 @@ test("reads Go from the Console sign-in OpenCode serves it with, ahead of the op
});
test("discovers a Console sign-in on its own, including one saved for the retired host", async () => {
const input = await storeWith([consoleSignIn({ server: "https://console.opencode.ai" })]);
const input = await storeWith([
["opencode", consoleSignIn({ server: "https://console.opencode.ai" })],
]);
const { fetchApi } = upstream({
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus()),
});
expect((await fetchUsage(input, fetchApi, install)).status).toBe("available");
expect((await fetchUsage(input, fetchApi)).status).toBe("available");
});
test.each([
["another product", { product: "zen", access: null }],
["an ended subscription", goStatus(null)],
])("falls back to the opencode-go key when the sign-in's workspace has %s", async (_, body) => {
const input = await storeWith([consoleSignIn(), goKey("go-key")]);
const input = await storeWith([
["opencode", consoleSignIn()],
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
]);
const { fetchApi } = upstream({
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(body),
[`${USAGE_URL} Bearer go-key`]: () => Response.json(upstreamResponse),
});
const report = await fetchUsage(input, fetchApi, install);
const report = await fetchUsage(input, fetchApi);
expect(report.status === "available" && report.windows.map((w) => w.usedPct)).toEqual([
21, 42, 100,
]);
});
test("reports the absent subscription for a Console sign-in without Go", async () => {
const input = await storeWith([consoleSignIn()]);
const input = await storeWith([["opencode", consoleSignIn()]]);
const { fetchApi } = upstream({
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus(null)),
});
expect(await fetchUsage(input, fetchApi, install)).toEqual({
expect(await fetchUsage(input, fetchApi)).toEqual({
status: "unavailable",
problem: { kind: "no_quota", detail: "No active OpenCode Go subscription" },
});
@@ -538,7 +492,7 @@ test("reports the absent subscription for a Console sign-in without Go", async (
test("reports an expired sign-in without a request, and keeps it over a rejected fallback key", async () => {
const expires = Date.now() - 1000;
const alone = await storeWith([consoleSignIn({ expires })]);
const alone = await storeWith([["opencode", consoleSignIn({ expires })]]);
const { requests, fetchApi } = upstream({});
const expired = {
status: "unavailable",
@@ -548,18 +502,26 @@ test("reports an expired sign-in without a request, and keeps it over a rejected
refreshedBy: "opencode",
},
};
expect(await fetchUsage(alone, fetchApi, install)).toEqual(expired);
expect(await fetchUsage(alone, fetchApi)).toEqual(expired);
expect(requests).toEqual([]);
const withKey = await storeWith([consoleSignIn({ expires }), goKey("expired-go-key")]);
expect(await fetchUsage(withKey, fetchApi, install)).toEqual(expired);
await rm(join(fixtureDirectory, "opencode.db"));
await writeFile(fixturePath, "{}");
const withKey = await storeWith([
["opencode", consoleSignIn({ expires })],
["opencode-go", JSON.stringify({ type: "key", key: "expired-go-key" })],
]);
expect(await fetchUsage(withKey, fetchApi)).toEqual(expired);
});
test("reads Go with a key on the opencode integration and falls back when its workspace lacks Go", async () => {
const input = await storeWith([consoleKey("workspace-key"), goKey("go-key")]);
const input = await storeWith([
["opencode", JSON.stringify({ type: "key", key: "workspace-key" })],
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
]);
const served = upstream({
[`${CONSOLE_STATUS_URL} Bearer workspace-key`]: () => Response.json(goStatus()),
});
const report = await fetchUsage(input, served.fetchApi, install);
const report = await fetchUsage(input, served.fetchApi);
expect(report.status).toBe("available");
expect(served.requests.map((request) => [request.authorization, request.orgID])).toEqual([
["Bearer workspace-key", null],
@@ -568,82 +530,43 @@ test("reads Go with a key on the opencode integration and falls back when its wo
[`${USAGE_URL} Bearer workspace-key`]: () => new Response(null, { status: 403 }),
[`${USAGE_URL} Bearer go-key`]: () => Response.json(upstreamResponse),
});
expect((await fetchUsage(input, refused.fetchApi, install)).status).toBe("available");
expect((await fetchUsage(input, refused.fetchApi)).status).toBe("available");
expect(refused.requests.at(-1)).toMatchObject({ url: USAGE_URL, authorization: "Bearer go-key" });
});
test("reports a key on the opencode integration without Go as the absent subscription", async () => {
const input = await storeWith([consoleKey("zen-key")]);
const input = await storeWith([["opencode", JSON.stringify({ type: "key", key: "zen-key" })]]);
const { fetchApi } = upstream({
[`${USAGE_URL} Bearer zen-key`]: () => new Response(null, { status: 403 }),
});
expect(await fetchUsage(input, fetchApi, install)).toEqual({
expect(await fetchUsage(input, fetchApi)).toEqual({
status: "unavailable",
problem: { kind: "no_quota", detail: "No active OpenCode Go subscription" },
});
});
// The auth.json key stands in for a Go login that OpenCode 2 never imported.
test.each<[string, Credential, Record<string, () => Response>]>([
[
"key",
consoleKey("workspace-key"),
{ [`${USAGE_URL} Bearer workspace-key`]: () => new Response(null, { status: 403 }) },
],
[
"sign-in",
consoleSignIn(),
{ [`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus(null)) },
],
])(
"reads the auth.json Go key when the workspace of OpenCode 2's opencode %s has no Go",
async (_name, login, refusal) => {
await openCode2([login]);
const [found] = await discover(install);
const { requests, fetchApi } = upstream({
...refusal,
[`${USAGE_URL} Bearer file-key`]: () => Response.json(upstreamResponse),
});
const report = await fetchUsage(inputSchema.parse(found!.input), fetchApi, install);
expect(report.status).toBe("available");
expect(requests.at(-1)).toMatchObject({ url: USAGE_URL, authorization: "Bearer file-key" });
},
);
test("keeps the card on OpenCode 2's opencode key ahead of the auth.json Go key", async () => {
await openCode2([consoleKey("workspace-key")]);
const [found] = await discover(install);
const input = inputSchema.parse(found!.input);
const served = upstream({
[`${CONSOLE_STATUS_URL} Bearer workspace-key`]: () => Response.json(goStatus()),
[`${USAGE_URL} Bearer file-key`]: () => Response.json(upstreamResponse),
});
expect((await fetchUsage(input, served.fetchApi, install)).status).toBe("available");
const failing = upstream({
[`${USAGE_URL} Bearer workspace-key`]: () => new Response(null, { status: 503 }),
[`${USAGE_URL} Bearer file-key`]: () => Response.json(upstreamResponse),
});
await expect(fetchUsage(input, failing.fetchApi, install)).rejects.toThrow("returned 503");
const asked = [...served.requests, ...failing.requests].map((request) => request.authorization);
expect(asked).not.toContain("Bearer file-key");
});
test("keeps the card on the opencode key through a temporary failure", async () => {
const input = await storeWith([consoleKey("workspace-key"), goKey("go-key")]);
const input = await storeWith([
["opencode", JSON.stringify({ type: "key", key: "workspace-key" })],
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
]);
const { requests, fetchApi } = upstream({
[`${USAGE_URL} Bearer workspace-key`]: () => new Response(null, { status: 503 }),
});
await expect(fetchUsage(input, fetchApi, install)).rejects.toThrow("returned 503");
await expect(fetchUsage(input, fetchApi)).rejects.toThrow("returned 503");
expect(requests.some((request) => request.authorization === "Bearer go-key")).toBe(false);
});
test("keeps the card on the Console sign-in through a temporary failure", async () => {
const input = await storeWith([consoleSignIn(), goKey("go-key")]);
const input = await storeWith([
["opencode", consoleSignIn()],
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
]);
const { requests, fetchApi } = upstream({
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => new Response(null, { status: 503 }),
[`${USAGE_URL} Bearer go-key`]: () => Response.json(upstreamResponse),
});
await expect(fetchUsage(input, fetchApi, install)).rejects.toThrow("returned 503");
await expect(fetchUsage(input, fetchApi)).rejects.toThrow("returned 503");
expect(requests.some((request) => request.authorization === "Bearer go-key")).toBe(false);
});
@@ -656,7 +579,7 @@ test("reads a key's usage within the refresh deadline when the Console does not
});
}) as typeof fetch;
const started = Date.now();
const report = await fetchUsage({ store: "file" }, fetchApi, install);
const report = await fetchUsage({ store: "file", path: fixturePath }, fetchApi);
expect(report.status).toBe("available");
// The daemon gives a usage refresh 20 seconds, and the usage API keeps 15 of them.
expect(Date.now() - started).toBeLessThan(5_000);
@@ -9,7 +9,7 @@ import {
} from "@getpaseo/plugin/server/usage";
import type { Input } from "../shared/input.js";
import { NO_SUBSCRIPTION, readConsoleGo } from "./console.js";
import { installedOpenCode, loginStore, readLogins, type GoCredential } from "./opencode.js";
import { defaultStorePaths, readDatabaseLogins, readFileKey, type GoCredential } from "./stores.js";
const windowSchema = z.object({
status: z.enum(["ok", "rate-limited"]),
@@ -20,23 +20,38 @@ const responseSchema = z.object({
usage: z.object({ rolling: windowSchema, weekly: windowSchema, monthly: windowSchema }),
});
export async function discover(install = installedOpenCode()): Promise<UsageAccount[]> {
const store = await loginStore(install);
const logins = await readLogins(install, store);
if (!logins.opencode && !logins.go) return [];
export async function discover(paths = defaultStorePaths()): Promise<UsageAccount[]> {
// One OpenCode data directory holds one Go login, whichever store it lives in. Usage settings
// are saved per account, so a login OpenCode 2 imports keeps the identity it had in auth.json.
return [{ key: hashAccountKey(install.authFile), input: { store } }];
// are saved per account, so a login OpenCode v2 imports keeps the identity it had in auth.json.
const key = hashAccountKey(paths.file);
const logins = readDatabaseLogins(paths.database);
if (logins) {
return logins.opencode || logins.go
? [
{
key,
input: { store: "database", path: paths.database },
},
]
: [];
}
return (await readFileKey(paths.file))
? [{ key, input: { store: "file", path: paths.file } }]
: [];
}
export async function fetchUsage(
input: Input,
fetchApi: typeof fetch = fetch,
install = installedOpenCode(),
): Promise<UsageReport> {
const logins = await readLogins(install, input.store);
const only = logins.opencode ?? logins.go;
if (!only) throw new Error("OpenCode Go login no longer exists");
if (input.store === "file") {
const key = await readFileKey(input.path);
if (!key) throw new Error("OpenCode Go login store no longer exists");
return readKey(key, fetchApi);
}
const logins = readDatabaseLogins(input.path);
const only = logins?.opencode ?? logins?.go;
if (!logins || !only) throw new Error("OpenCode Go login store no longer exists");
if (logins.opencode && logins.go) return readEitherLogin(logins.opencode, logins.go, fetchApi);
return readCredential(only, fetchApi, { workspaceKey: only === logins.opencode });
}
@@ -1,4 +1,5 @@
import { z } from "zod";
/** `credentials` is OpenCode 2's own login listing with auth.json behind it; `file` is auth.json only. */
export const inputSchema = z.object({ store: z.enum(["file", "credentials"]) }).strict();
export const inputSchema = z
.object({ store: z.enum(["file", "database"]), path: z.string().min(1) })
.strict();
export type Input = z.infer<typeof inputSchema>;