Merge branch 'main' into t3code/fix-lightmode-sidebar
This commit is contained in:
19 files changed
+640
-253
No files matched your search
@@ -50,6 +50,8 @@ interface FakeGhScenario {
|
||||
};
|
||||
repositoryCloneUrls?: Record<string, { url: string; sshUrl: string }>;
|
||||
failWith?: GitHubCli.GitHubCliError;
|
||||
/** Let this many gh calls succeed before failWith kicks in (default 0 = fail immediately). */
|
||||
failAfterCalls?: number;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
@@ -382,7 +384,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const args = [...input.args];
|
||||
ghCalls.push(args.join(" "));
|
||||
|
||||
if (scenario.failWith) {
|
||||
if (scenario.failWith && ghCalls.length > (scenario.failAfterCalls ?? 0)) {
|
||||
return Effect.fail(scenario.failWith);
|
||||
}
|
||||
|
||||
@@ -1336,6 +1338,230 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when a later lookup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 214,
|
||||
title: "Sticky PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-sticky",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(214);
|
||||
|
||||
// An explicit invalidation (user refresh, git action) bypasses the PR
|
||||
// cache and forces a live lookup — which now fails. The badge must keep
|
||||
// the last known PR instead of blanking out.
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(214);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"status does not reuse a stale PR after the branch is retargeted to a different upstream",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-retarget"]);
|
||||
|
||||
const originRemote = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originRemote]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-retarget"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 214,
|
||||
title: "Sticky PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-retarget",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(214);
|
||||
|
||||
// Retarget the branch to a different remote/upstream (e.g. the PR was
|
||||
// reopened against a fork). The previously cached PR belonged to the
|
||||
// old upstream and must not be shown against the new one.
|
||||
const forkRemote = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork", forkRemote]);
|
||||
yield* runGit(repoDir, ["push", "fork", "feature/pr-retarget"]);
|
||||
yield* runGit(repoDir, [
|
||||
"branch",
|
||||
"--set-upstream-to=fork/feature/pr-retarget",
|
||||
"feature/pr-retarget",
|
||||
]);
|
||||
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when the branch gains its first upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky-first-push"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
|
||||
const existingPr = {
|
||||
number: 215,
|
||||
title: "Sticky first-push PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/215",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-sticky-first-push",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(215);
|
||||
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky-first-push"]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(215);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status drops the last known PR when the tracked remote is repointed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]);
|
||||
const originalRemoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 216,
|
||||
title: "Old remote PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/216",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-repointed",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(216);
|
||||
|
||||
const replacementRemoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]);
|
||||
yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]);
|
||||
yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status keeps the last known PR when the current remote URL can't be resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-config-hiccup"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-config-hiccup"]);
|
||||
|
||||
const existingPr = {
|
||||
number: 217,
|
||||
title: "Config hiccup PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/217",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-config-hiccup",
|
||||
};
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
prListSequence: [JSON.stringify([existingPr])],
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("rate limited"),
|
||||
}),
|
||||
failAfterCalls: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* manager.status({ cwd: repoDir });
|
||||
expect(first.pr?.number).toBe(217);
|
||||
|
||||
// `remote.origin.url` reads go through readConfigValueNullable, which
|
||||
// maps ANY failed read (a real "no remote configured" state or a
|
||||
// transient git-config hiccup) to null the same way. Unsetting the
|
||||
// key here reproduces that ambiguity without touching branch
|
||||
// tracking (refs/remotes/origin/* and branch.<b>.remote are
|
||||
// untouched) — the remote identity has not actually changed, so the
|
||||
// sticky PR must survive even though the current lookup can no
|
||||
// longer resolve a remote URL to compare against.
|
||||
yield* runGit(repoDir, ["config", "--unset", "remote.origin.url"]);
|
||||
yield* manager.invalidateStatus(repoDir);
|
||||
|
||||
const second = yield* manager.status({ cwd: repoDir });
|
||||
expect(second.pr?.number).toBe(217);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates a commit when working tree is dirty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
mergeGitStatusParts,
|
||||
normalizeGitRemoteUrl,
|
||||
resolveAutoFeatureBranchName,
|
||||
sanitizeBranchFragment,
|
||||
sanitizeFeatureBranchName,
|
||||
@@ -95,6 +96,9 @@ const SHORT_SHA_LENGTH = 7;
|
||||
const TOAST_DESCRIPTION_MAX = 72;
|
||||
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
|
||||
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
|
||||
const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
|
||||
const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20);
|
||||
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
|
||||
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
|
||||
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
|
||||
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
|
||||
@@ -142,6 +146,7 @@ interface BranchHeadContext {
|
||||
headSelectors: ReadonlyArray<string>;
|
||||
preferredHeadSelector: string;
|
||||
remoteName: string | null;
|
||||
headRemoteUrlKey: string | null;
|
||||
headRepositoryNameWithOwner: string | null;
|
||||
headRepositoryOwnerLogin: string | null;
|
||||
isCrossRepository: boolean;
|
||||
@@ -768,6 +773,154 @@ export const make = Effect.gen(function* () {
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
||||
);
|
||||
// PR lookups hit the hosting provider's API (gh/glab/...), so they refresh
|
||||
// on their own, slower cadence: ahead/behind counts stay fresh on every
|
||||
// status poll while the PR association is re-fetched at most once per
|
||||
// PR_LOOKUP_CACHE_TTL per branch. Git actions and user-driven refreshes bump
|
||||
// the epoch (invalidateStatus) to bypass the cache immediately.
|
||||
const prLookupEpochByCwd = new Map<string, number>();
|
||||
const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;
|
||||
const bumpPrLookupEpoch = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.map((cacheKey) => {
|
||||
prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);
|
||||
}),
|
||||
);
|
||||
// Cache keys are NUL-joined [cwd, branch, upstreamRef, epoch] — none of the
|
||||
// segments can contain a NUL byte, and refs are never empty, so "" decodes
|
||||
// back to a null upstreamRef.
|
||||
const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
|
||||
[cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000");
|
||||
const prLookupCache = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
|
||||
const details = {
|
||||
branch,
|
||||
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
|
||||
};
|
||||
return resolveBranchHeadContext(cwd, details).pipe(
|
||||
Effect.flatMap((headContext) =>
|
||||
findLatestPrForHeadContext(cwd, headContext).pipe(
|
||||
Effect.map((latest) => ({ latest, headContext })),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
{
|
||||
capacity: PR_LOOKUP_CACHE_CAPACITY,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL),
|
||||
},
|
||||
);
|
||||
// A transient lookup failure (rate limit, network blip) must not clear an
|
||||
// already-known PR badge, so the last successful answer per branch sticks
|
||||
// around as the fallback. Keep the resolved head context with it so a
|
||||
// branch retargeted to another remote/fork cannot inherit the old badge.
|
||||
interface LastKnownPr {
|
||||
readonly pr: ReturnType<typeof toStatusPr> | null;
|
||||
readonly upstreamRef: string | null;
|
||||
readonly headBranch: string;
|
||||
readonly remoteName: string | null;
|
||||
readonly headRemoteUrlKey: string | null;
|
||||
}
|
||||
const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
|
||||
const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
|
||||
if (
|
||||
!lastKnownPrByBranchKey.has(branchKey) &&
|
||||
lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
|
||||
) {
|
||||
const oldestKey = lastKnownPrByBranchKey.keys().next().value;
|
||||
if (oldestKey !== undefined) {
|
||||
lastKnownPrByBranchKey.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
lastKnownPrByBranchKey.set(branchKey, entry);
|
||||
};
|
||||
const resolveLastKnownPr = (
|
||||
branchKey: string,
|
||||
current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
|
||||
): ReturnType<typeof toStatusPr> | null => {
|
||||
const lastKnown = lastKnownPrByBranchKey.get(branchKey);
|
||||
if (!lastKnown) return null;
|
||||
if (lastKnown.headBranch !== current.headBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The normalized URL catches both remote-alias changes and an existing
|
||||
// alias being repointed. Both sides must be resolved before treating a
|
||||
// mismatch as real: `readConfigValueNullable` swallows any git-config
|
||||
// read failure into `null`, so a transient failure to resolve the
|
||||
// *current* remote URL must read as "unknown", not as "no remote" — the
|
||||
// latter would otherwise drop an already-known PR badge on every hiccup.
|
||||
if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {
|
||||
return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown.pr : null;
|
||||
}
|
||||
|
||||
// If the remote URL can't be compared, fall back to the remote identity
|
||||
// encoded by tracked branches — same "both sides known" requirement, for
|
||||
// the same reason. A null-to-non-null transition (upstream/remoteName)
|
||||
// is allowed because that is the expected first-push case.
|
||||
if (
|
||||
lastKnown.upstreamRef !== null &&
|
||||
current.upstreamRef !== null &&
|
||||
lastKnown.remoteName !== null &&
|
||||
current.remoteName !== null
|
||||
) {
|
||||
return lastKnown.remoteName === current.remoteName ? lastKnown.pr : null;
|
||||
}
|
||||
return lastKnown.pr;
|
||||
};
|
||||
const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
|
||||
cwd: string,
|
||||
details: { branch: string; upstreamRef: string | null; isDefaultBranch: boolean },
|
||||
) {
|
||||
// Keyed by (cwd, branch) only: the upstream ref changing (e.g. a first
|
||||
// `push -u`) must not orphan the fallback value for the same branch.
|
||||
const branchKey = `${cwd}\u0000${details.branch}`;
|
||||
return yield* Cache.get(prLookupCache, prLookupCacheKey(cwd, details)).pipe(
|
||||
Effect.map(({ latest, headContext }) => {
|
||||
if (!latest) return { pr: null, headContext };
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") {
|
||||
return { pr: null, headContext };
|
||||
}
|
||||
return { pr: toStatusPr(latest), headContext };
|
||||
}),
|
||||
Effect.tap(({ pr, headContext }) =>
|
||||
Effect.sync(() =>
|
||||
rememberLastKnownPr(branchKey, {
|
||||
pr,
|
||||
upstreamRef: details.upstreamRef,
|
||||
headBranch: headContext.headBranch,
|
||||
remoteName: headContext.remoteName,
|
||||
headRemoteUrlKey: headContext.headRemoteUrlKey,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(({ pr }) => pr),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("PR lookup failed; keeping last known PR state.").pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: "lookupStatusPr",
|
||||
branch: details.branch,
|
||||
errorTag:
|
||||
typeof error === "object" && error !== null && "_tag" in error
|
||||
? String(error._tag)
|
||||
: typeof error,
|
||||
}),
|
||||
Effect.andThen(resolveBranchHeadContext(cwd, details)),
|
||||
Effect.map((headContext) =>
|
||||
resolveLastKnownPr(branchKey, {
|
||||
upstreamRef: details.upstreamRef,
|
||||
headBranch: headContext.headBranch,
|
||||
remoteName: headContext.remoteName,
|
||||
headRemoteUrlKey: headContext.headRemoteUrlKey,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (
|
||||
cwd: string,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
@@ -781,19 +934,11 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(cwd, {
|
||||
? yield* lookupStatusPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.map((latest) => {
|
||||
if (!latest) return null;
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
||||
return toStatusPr(latest);
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
isDefaultBranch: details.isDefaultBranch,
|
||||
})
|
||||
: null;
|
||||
|
||||
return {
|
||||
@@ -837,6 +982,7 @@ export const make = Effect.gen(function* () {
|
||||
) {
|
||||
if (!remoteName) {
|
||||
return {
|
||||
remoteUrlKey: null,
|
||||
repositoryNameWithOwner: null,
|
||||
ownerLogin: null,
|
||||
};
|
||||
@@ -845,6 +991,7 @@ export const make = Effect.gen(function* () {
|
||||
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
|
||||
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
|
||||
return {
|
||||
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
|
||||
repositoryNameWithOwner,
|
||||
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
|
||||
};
|
||||
@@ -915,6 +1062,9 @@ export const make = Effect.gen(function* () {
|
||||
preferredHeadSelector:
|
||||
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
|
||||
remoteName,
|
||||
headRemoteUrlKey:
|
||||
remoteRepository.remoteUrlKey ??
|
||||
(remoteName === null ? originRepository.remoteUrlKey : null),
|
||||
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
|
||||
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
|
||||
isCrossRepository,
|
||||
@@ -960,11 +1110,10 @@ export const make = Effect.gen(function* () {
|
||||
return null;
|
||||
});
|
||||
|
||||
const findLatestPr = Effect.fn("findLatestPr")(function* (
|
||||
const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* (
|
||||
cwd: string,
|
||||
details: { branch: string; upstreamRef: string | null },
|
||||
headContext: BranchHeadContext,
|
||||
) {
|
||||
const headContext = yield* resolveBranchHeadContext(cwd, details);
|
||||
const parsedByNumber = new Map<number, PullRequestInfo>();
|
||||
|
||||
for (const headSelector of headContext.headSelectors) {
|
||||
@@ -991,7 +1140,6 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
|
||||
cwd: string,
|
||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||
@@ -1442,6 +1590,10 @@ export const make = Effect.gen(function* () {
|
||||
function* (cwd) {
|
||||
yield* invalidateLocalStatusResultCache(cwd);
|
||||
yield* invalidateRemoteStatusResultCache(cwd);
|
||||
// Full invalidation is the explicit-freshness path (git actions, user
|
||||
// refresh); it also bypasses the slow PR-lookup cache. The periodic
|
||||
// status poll only invalidates local/remote and keeps the PR cache warm.
|
||||
yield* bumpPrLookupEpoch(cwd);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -5285,6 +5285,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
invalidateStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
@@ -5331,6 +5332,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
invalidateStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
@@ -5407,6 +5409,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
invalidateStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Deferred.succeed(localRefreshStarted, undefined).pipe(
|
||||
Effect.ignore,
|
||||
|
||||
@@ -208,6 +208,61 @@ describe("GitHubCli.layer", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps pull requests from gh versions without headRepository.nameWithOwner", () =>
|
||||
// gh < 2.47 (e.g. Ubuntu-packaged 2.46) exports headRepository as
|
||||
// {id, name} only. These entries must decode instead of being dropped,
|
||||
// with nameWithOwner rebuilt from the owner login.
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 2829,
|
||||
title: "Codex turn mapping",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
|
||||
baseRefName: "main",
|
||||
headRefName: "t3code/codex-turn-mapping",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: false,
|
||||
headRepository: {
|
||||
id: "R_kgDORLtfbQ",
|
||||
name: "codething-mvp",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
id: "MDEyOk9yZ2FuaXphdGlvbjg5MTkxNzI3",
|
||||
login: "pingdotgg",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "t3code/codex-turn-mapping",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 2829,
|
||||
title: "Codex turn mapping",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
|
||||
baseRefName: "main",
|
||||
headRefName: "t3code/codex-turn-mapping",
|
||||
state: "open",
|
||||
isCrossRepository: false,
|
||||
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
|
||||
headRepositoryOwnerLogin: "pingdotgg",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
|
||||
@@ -30,17 +30,21 @@ const GitHubPullRequestSchema = Schema.Struct({
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
// gh < 2.47 exports headRepository as {id, name} only; nameWithOwner was
|
||||
// added later. Both fields stay optional so a version-drifted gh CLI can
|
||||
// never fail the decode and silently drop the PR from the list.
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
nameWithOwner: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
login: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -71,11 +75,15 @@ function normalizeGitHubPullRequestState(input: {
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const explicitNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryName = trimOptionalString(raw.headRepository?.name);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
(explicitNameWithOwner?.includes("/") ? (explicitNameWithOwner.split("/")[0] ?? null) : null);
|
||||
const headRepositoryNameWithOwner =
|
||||
explicitNameWithOwner ??
|
||||
(headRepositoryOwnerLogin && headRepositoryName
|
||||
? `${headRepositoryOwnerLogin}/${headRepositoryName}`
|
||||
: null);
|
||||
|
||||
return {
|
||||
|
||||
@@ -690,6 +690,47 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("remote operations", () => {
|
||||
it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
yield* git(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]);
|
||||
|
||||
const reusedForSsh = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "[email protected]:pingdotgg/t3code.git",
|
||||
});
|
||||
assert.equal(reusedForSsh, "origin");
|
||||
|
||||
const reusedForSshScheme = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://[email protected]/pingdotgg/t3code",
|
||||
});
|
||||
assert.equal(reusedForSshScheme, "origin");
|
||||
|
||||
const reusedForSshWithPort = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "pingdotgg",
|
||||
url: "ssh://[email protected]:22/pingdotgg/t3code.git",
|
||||
});
|
||||
assert.equal(reusedForSshWithPort, "origin");
|
||||
|
||||
const addedForFork = yield* driver.ensureRemote({
|
||||
cwd,
|
||||
preferredName: "octocat",
|
||||
url: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
assert.equal(addedForFork, "octocat");
|
||||
assert.equal(yield* git(cwd, ["remote"]), "octocat\norigin");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("commit context", () => {
|
||||
it.effect("stages selected files and commits only those files", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
type ReviewDiffPreviewSource,
|
||||
type VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3tools/shared/git";
|
||||
import { compactTraceAttributes } from "@t3tools/shared/observability";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
|
||||
@@ -235,14 +235,6 @@ function sanitizeRemoteName(value: string): string {
|
||||
return sanitized.length > 0 ? sanitized : "fork";
|
||||
}
|
||||
|
||||
function normalizeRemoteUrl(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.replace(/\/+$/g, "")
|
||||
.replace(/\.git$/i, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function parseRemoteFetchUrls(stdout: string): Map<string, string> {
|
||||
const remotes = new Map<string, string>();
|
||||
for (const line of stdout.split("\n")) {
|
||||
@@ -1092,7 +1084,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
"ensureRemote",
|
||||
)(function* (input) {
|
||||
const preferredName = sanitizeRemoteName(input.preferredName);
|
||||
const normalizedTargetUrl = normalizeRemoteUrl(input.url);
|
||||
const normalizedTargetUrl = normalizeGitRemoteUrl(input.url);
|
||||
const remoteFetchUrls = yield* runGitStdout(
|
||||
"GitVcsDriver.ensureRemote.listRemoteUrls",
|
||||
input.cwd,
|
||||
@@ -1100,7 +1092,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
|
||||
|
||||
for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
|
||||
if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) {
|
||||
if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) {
|
||||
return remoteName;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,11 @@ function makeTestLayer(state: {
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -206,6 +211,11 @@ describe("VcsStatusBroadcaster", () => {
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -366,10 +366,9 @@ export const make = Effect.gen(function* () {
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
yield* Effect.all([workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)], {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
// invalidateStatus (not the two partial invalidations) so an explicit
|
||||
// refresh also bypasses GitManager's slow PR-lookup cache.
|
||||
yield* workflow.invalidateStatus(cwd);
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
{ concurrency: "unbounded" },
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Tiny event bus allowing components to programmatically open the command palette
|
||||
// without owning its React state.
|
||||
const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";
|
||||
|
||||
export interface CommandPaletteOpenDetail {
|
||||
readonly open?: "add-project" | "new-thread-in";
|
||||
}
|
||||
|
||||
export function openCommandPalette(detail?: CommandPaletteOpenDetail): void {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent(COMMAND_PALETTE_OPEN_EVENT, detail ? { detail } : undefined),
|
||||
);
|
||||
}
|
||||
|
||||
export function onOpenCommandPalette(
|
||||
listener: (detail: CommandPaletteOpenDetail) => void,
|
||||
): () => void {
|
||||
const handler = (event: Event) => {
|
||||
listener((event as CustomEvent<CommandPaletteOpenDetail>).detail ?? {});
|
||||
};
|
||||
window.addEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
|
||||
return () => window.removeEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
|
||||
}
|
||||
|
||||
/** Read at event time so consumers do not subscribe to transient dialog state. */
|
||||
export function isCommandPaletteOpen(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { createContext, use, type ReactNode } from "react";
|
||||
|
||||
const OpenAddProjectCommandPaletteContext = createContext<(() => void) | null>(null);
|
||||
|
||||
export function OpenAddProjectCommandPaletteProvider(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly openAddProject: () => void;
|
||||
}) {
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteContext value={props.openAddProject}>
|
||||
{props.children}
|
||||
</OpenAddProjectCommandPaletteContext>
|
||||
);
|
||||
}
|
||||
|
||||
export function useOpenAddProjectCommandPalette(): () => void {
|
||||
const openAddProject = use(OpenAddProjectCommandPaletteContext);
|
||||
if (!openAddProject) {
|
||||
throw new Error("Command palette actions must be used inside CommandPalette");
|
||||
}
|
||||
return openAddProject;
|
||||
}
|
||||
|
||||
/** Read at event time so the chat tree does not subscribe to transient dialog state. */
|
||||
export function isCommandPaletteOpen(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
|
||||
);
|
||||
}
|
||||
@@ -112,7 +112,7 @@ import {
|
||||
} from "../types";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteContext";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
|
||||
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
|
||||
|
||||
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
|
||||
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
@@ -77,6 +77,7 @@ import {
|
||||
isUnsupportedWindowsProjectPath,
|
||||
resolveProjectPathForDispatch,
|
||||
} from "../lib/projectPaths";
|
||||
import { onOpenCommandPalette } from "../commandPaletteBus";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { getLatestThreadForProject } from "../lib/threadSort";
|
||||
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
|
||||
@@ -334,7 +335,7 @@ function errorMessage(error: unknown): string {
|
||||
}
|
||||
|
||||
interface CommandPaletteOpenIntent {
|
||||
readonly kind: "add-project";
|
||||
readonly kind: "add-project" | "new-thread-in";
|
||||
}
|
||||
|
||||
interface CommandPaletteUiState {
|
||||
@@ -346,6 +347,7 @@ type CommandPaletteUiAction =
|
||||
| { readonly _tag: "SetOpen"; readonly open: boolean }
|
||||
| { readonly _tag: "Toggle" }
|
||||
| { readonly _tag: "OpenAddProject" }
|
||||
| { readonly _tag: "OpenNewThreadIn" }
|
||||
| { readonly _tag: "ClearOpenIntent" };
|
||||
|
||||
function reduceCommandPaletteUiState(
|
||||
@@ -362,6 +364,8 @@ function reduceCommandPaletteUiState(
|
||||
return { open: !state.open, openIntent: null };
|
||||
case "OpenAddProject":
|
||||
return { open: true, openIntent: { kind: "add-project" } };
|
||||
case "OpenNewThreadIn":
|
||||
return { open: true, openIntent: { kind: "new-thread-in" } };
|
||||
case "ClearOpenIntent":
|
||||
return state.openIntent ? { ...state, openIntent: null } : state;
|
||||
}
|
||||
@@ -375,6 +379,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
|
||||
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
|
||||
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
|
||||
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
|
||||
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
@@ -409,20 +414,32 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
onOpenCommandPalette((detail) => {
|
||||
if (detail.open === "new-thread-in") {
|
||||
openNewThreadIn();
|
||||
} else if (detail.open === "add-project") {
|
||||
openAddProject();
|
||||
} else {
|
||||
setOpen(true);
|
||||
}
|
||||
}),
|
||||
[openAddProject, openNewThreadIn, setOpen],
|
||||
);
|
||||
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteProvider openAddProject={openAddProject}>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog
|
||||
open={state.open}
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
</OpenAddProjectCommandPaletteProvider>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog
|
||||
open={state.open}
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -960,6 +977,36 @@ function OpenCommandPaletteDialog(props: {
|
||||
openAddProjectFlow();
|
||||
}, [clearOpenIntent, openAddProjectFlow, openIntent]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (openIntent?.kind !== "new-thread-in" || projectThreadItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
clearOpenIntent();
|
||||
setAddProjectCloneFlow(null);
|
||||
setViewStack([]);
|
||||
setQuery("");
|
||||
const currentPrefix =
|
||||
currentProjectEnvironmentId && currentProjectId
|
||||
? `new-thread-in:${currentProjectEnvironmentId}:${currentProjectId}`
|
||||
: null;
|
||||
const prioritized = currentPrefix
|
||||
? [
|
||||
...projectThreadItems.filter((item) => item.value === currentPrefix),
|
||||
...projectThreadItems.filter((item) => item.value !== currentPrefix),
|
||||
]
|
||||
: projectThreadItems;
|
||||
pushPaletteView({
|
||||
addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [{ value: "projects", label: "Projects", items: prioritized }],
|
||||
});
|
||||
}, [
|
||||
clearOpenIntent,
|
||||
currentProjectEnvironmentId,
|
||||
currentProjectId,
|
||||
openIntent,
|
||||
projectThreadItems,
|
||||
]);
|
||||
|
||||
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (projects.length > 0) {
|
||||
|
||||
@@ -177,7 +177,7 @@ import {
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import {
|
||||
archiveSelectedThreadEntries,
|
||||
buildMultiSelectThreadContextMenuItems,
|
||||
@@ -3086,7 +3086,10 @@ export default function Sidebar() {
|
||||
: false,
|
||||
);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const openAddProjectCommandPalette = useOpenAddProjectCommandPalette();
|
||||
const openAddProjectCommandPalette = useCallback(
|
||||
() => openCommandPalette({ open: "add-project" }),
|
||||
[],
|
||||
);
|
||||
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
|
||||
ReadonlySet<string>
|
||||
>(() => new Set());
|
||||
|
||||
@@ -57,14 +57,8 @@ import { useUiStateStore } from "../uiStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import { onOpenNewThreadPicker } from "../newThreadPickerBus";
|
||||
import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "./ui/dialog";
|
||||
import {
|
||||
resolveThreadActionProjectRef,
|
||||
startNewThreadFromContext,
|
||||
startNewThreadInProjectFromContext,
|
||||
} from "../lib/chatThreadActions";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { startNewThreadFromContext } from "../lib/chatThreadActions";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
@@ -634,7 +628,10 @@ export default function SidebarV2() {
|
||||
reportFailure: false,
|
||||
});
|
||||
const newThreadContext = useHandleNewThread();
|
||||
const openAddProjectCommandPalette = useOpenAddProjectCommandPalette();
|
||||
const openAddProjectCommandPalette = useCallback(
|
||||
() => openCommandPalette({ open: "add-project" }),
|
||||
[],
|
||||
);
|
||||
const { environments } = useEnvironments();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
|
||||
@@ -1305,12 +1302,8 @@ export default function SidebarV2() {
|
||||
|
||||
// New thread defaults to the project you're in (active thread's project,
|
||||
// falling back to the top project) — same resolution the command palette
|
||||
// uses. The chevron menu is the explicit project picker the flat list no
|
||||
// longer gets from per-project headers.
|
||||
const [newThreadPickerOpen, setNewThreadPickerOpen] = useState(false);
|
||||
// chat.new (mod+shift+o / mod+n) is handled by the _chat route layout; in
|
||||
// v2 with multiple projects it opens this picker via the event bus.
|
||||
useEffect(() => onOpenNewThreadPicker(() => setNewThreadPickerOpen(true)), []);
|
||||
// uses. The command palette already offers a "New thread in..." submenu
|
||||
// for multi-project setups.
|
||||
const handleNewThreadClick = useCallback(() => {
|
||||
// One project: nothing to pick, create immediately.
|
||||
if (projects.length <= 1) {
|
||||
@@ -1323,57 +1316,9 @@ export default function SidebarV2() {
|
||||
});
|
||||
return;
|
||||
}
|
||||
setNewThreadPickerOpen(true);
|
||||
if (isMobile) setOpenMobile(false);
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
}, [isMobile, newThreadContext, projects.length, setOpenMobile]);
|
||||
const createThreadInProject = useCallback(
|
||||
(environmentId: (typeof projects)[number]["environmentId"], projectId: string) => {
|
||||
setNewThreadPickerOpen(false);
|
||||
if (isMobile) setOpenMobile(false);
|
||||
const project = projects.find(
|
||||
(candidate) => candidate.environmentId === environmentId && candidate.id === projectId,
|
||||
);
|
||||
if (!project) return;
|
||||
void startNewThreadInProjectFromContext(
|
||||
{
|
||||
activeDraftThread: newThreadContext.activeDraftThread,
|
||||
activeThread: newThreadContext.activeThread ?? undefined,
|
||||
defaultProjectRef: newThreadContext.defaultProjectRef,
|
||||
handleNewThread: newThreadContext.handleNewThread,
|
||||
},
|
||||
scopeProjectRef(project.environmentId, project.id),
|
||||
);
|
||||
},
|
||||
[isMobile, newThreadContext, projects, setOpenMobile],
|
||||
);
|
||||
const contextualProjectRef = resolveThreadActionProjectRef({
|
||||
activeDraftThread: newThreadContext.activeDraftThread,
|
||||
activeThread: newThreadContext.activeThread ?? undefined,
|
||||
defaultProjectRef: newThreadContext.defaultProjectRef,
|
||||
handleNewThread: newThreadContext.handleNewThread,
|
||||
});
|
||||
const newThreadTargetRef = scopedProject
|
||||
? scopeProjectRef(scopedProject.environmentId, scopedProject.id)
|
||||
: contextualProjectRef;
|
||||
const newThreadTargetProject = newThreadTargetRef
|
||||
? (projects.find(
|
||||
(project) =>
|
||||
project.environmentId === newThreadTargetRef.environmentId &&
|
||||
project.id === newThreadTargetRef.projectId,
|
||||
) ?? null)
|
||||
: null;
|
||||
// Picker order: the contextual default first (preselected), everything else
|
||||
// after — the common case is Enter/click on the top row.
|
||||
const newThreadPickerProjects = useMemo(() => {
|
||||
if (!newThreadTargetProject) return projects;
|
||||
return [
|
||||
newThreadTargetProject,
|
||||
...projects.filter(
|
||||
(project) =>
|
||||
project.environmentId !== newThreadTargetProject.environmentId ||
|
||||
project.id !== newThreadTargetProject.id,
|
||||
),
|
||||
];
|
||||
}, [newThreadTargetProject, projects]);
|
||||
|
||||
const commandPaletteShortcutLabel = shortcutLabelForCommand(keybindings, "commandPalette.toggle");
|
||||
// Same resolution as v1: prefer the local-thread binding, fall back to
|
||||
@@ -1643,87 +1588,6 @@ export default function SidebarV2() {
|
||||
</SidebarContent>
|
||||
<SidebarSeparator className="bg-border/80" />
|
||||
<SidebarChromeFooter />
|
||||
<Dialog open={newThreadPickerOpen} onOpenChange={setNewThreadPickerOpen}>
|
||||
<DialogPopup className="max-w-sm p-0">
|
||||
<DialogHeader className="px-4 pb-2 pt-4">
|
||||
<DialogTitle className="text-sm">New thread in…</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div
|
||||
className="flex flex-col gap-0.5 px-2 pb-3"
|
||||
role="listbox"
|
||||
aria-label="Choose a project for the new thread"
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key !== "ArrowDown" &&
|
||||
event.key !== "ArrowUp" &&
|
||||
event.key !== "Home" &&
|
||||
event.key !== "End"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const container = event.currentTarget;
|
||||
const options = [...container.querySelectorAll<HTMLButtonElement>("button")];
|
||||
if (options.length === 0) return;
|
||||
const currentIndex = options.findIndex((option) => option === document.activeElement);
|
||||
const nextIndex =
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? options.length - 1
|
||||
: event.key === "ArrowDown"
|
||||
? (currentIndex + 1) % options.length
|
||||
: (currentIndex - 1 + options.length) % options.length;
|
||||
event.preventDefault();
|
||||
options[nextIndex]?.focus();
|
||||
}}
|
||||
>
|
||||
{newThreadPickerProjects.map((project, index) => {
|
||||
const isDefault = index === 0 && newThreadTargetProject !== null;
|
||||
return (
|
||||
<button
|
||||
key={`${project.environmentId}:${project.id}`}
|
||||
type="button"
|
||||
autoFocus={isDefault}
|
||||
onClick={() => createThreadInProject(project.environmentId, project.id)}
|
||||
className={cn(
|
||||
"flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-left transition-colors",
|
||||
"hover:bg-accent focus:bg-accent focus:outline-none",
|
||||
isDefault && "bg-accent/50",
|
||||
)}
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-4"
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13px] font-medium text-foreground">
|
||||
{project.title}
|
||||
</span>
|
||||
<span className="block truncate font-mono text-[10px] text-muted-foreground/60">
|
||||
{project.workspaceRoot}
|
||||
</span>
|
||||
</span>
|
||||
{isDefault ? (
|
||||
<Kbd className="h-4 shrink-0 rounded-sm px-1.5 text-[10px]">↵</Kbd>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setNewThreadPickerOpen(false);
|
||||
openAddProjectCommandPalette();
|
||||
}}
|
||||
className="mt-1 flex items-center gap-2.5 rounded-lg border border-dashed border-border px-2.5 py-2 text-left text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent focus:text-foreground focus:outline-none"
|
||||
>
|
||||
<PlusIcon className="size-4" />
|
||||
Add project
|
||||
</button>
|
||||
</div>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { ScopedProjectRef } from "@t3tools/contracts";
|
||||
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { FolderPlusIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { useOpenAddProjectCommandPalette } from "~/commandPaletteContext";
|
||||
import { openCommandPalette } from "~/commandPaletteBus";
|
||||
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
|
||||
import { useProjects, useThreadShells } from "~/state/entities";
|
||||
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
|
||||
@@ -29,7 +29,7 @@ export function DraftHeroHeadline({
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const openAddProject = useOpenAddProjectCommandPalette();
|
||||
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
|
||||
|
||||
const orderedProjects = useMemo(
|
||||
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// Tiny event bus connecting the global chat.new shortcut (handled in the
|
||||
// _chat route layout) to SidebarV2's project picker dialog. The route layer
|
||||
// can't render the picker itself — it lives with the sidebar — and the
|
||||
// sidebar can't own the window keydown handler without racing the layout's.
|
||||
const NEW_THREAD_PICKER_EVENT = "t3code:open-new-thread-picker";
|
||||
|
||||
export function openNewThreadPicker(): void {
|
||||
window.dispatchEvent(new CustomEvent(NEW_THREAD_PICKER_EVENT));
|
||||
}
|
||||
|
||||
export function onOpenNewThreadPicker(listener: () => void): () => void {
|
||||
window.addEventListener(NEW_THREAD_PICKER_EVENT, listener);
|
||||
return () => window.removeEventListener(NEW_THREAD_PICKER_EVENT, listener);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
|
||||
@@ -105,7 +105,7 @@ function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {
|
||||
}
|
||||
|
||||
function NoProjectsHero() {
|
||||
const openAddProject = useOpenAddProjectCommandPalette();
|
||||
const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
|
||||
@@ -2,9 +2,9 @@ import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { isCommandPaletteOpen } from "../commandPaletteContext";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteBus";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { openNewThreadPicker } from "../newThreadPickerBus";
|
||||
import { openCommandPalette } from "../commandPaletteBus";
|
||||
import { useProjects } from "../state/entities";
|
||||
import { dispatchPreviewAction } from "../components/preview/previewActionBus";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
@@ -80,11 +80,11 @@ function ChatRouteGlobalShortcuts() {
|
||||
if (command === "chat.new") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// Sidebar v2 routes creation through its project picker whenever
|
||||
// Sidebar v2 routes creation through the command palette whenever
|
||||
// there is a real choice to make; v1 (and single-project setups)
|
||||
// keep the immediate contextual create.
|
||||
if (sidebarV2Enabled && projectCount > 1) {
|
||||
openNewThreadPicker();
|
||||
openCommandPalette({ open: "new-thread-in" });
|
||||
return;
|
||||
}
|
||||
void startNewThreadFromContext({
|
||||
|
||||
Reference in new issue
Block a user