Merge pull requests: PR view, comments and reviews, merge, links, watch, prepare

# Conflicts:
#	README.md
#	src/ui/App.tsx
This commit is contained in:
Callum Alpass committed 2026-11-02 20:52:08 +11:00
commit fbdfb5c3e0
8 files changed
+1466 -16

No files matched your search

+63 -7
View File
@@ -15,7 +15,7 @@ import { type ChatAttachment, type ContextMenuItem, type DiscoveredLocalServer,
import { homedir } from "node:os";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { OrchestrationMessageContext, ProjectEntry, ThreadContextRecord } from "@t3tools/contracts";
import type { ComposerContextRecord, OrchestrationMessageContext, ProjectEntry } from "@t3tools/contracts";
import type { FeedState, ServerConfigState, ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts";
import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
@@ -24,6 +24,7 @@ import { draftDefaults, lockedProviderInstance, modelSummary, optionDescriptors,
import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts";
import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts";
import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type Picker, type PickerItem } from "../model/palette.ts";
import { pullRequestRepository } from "../model/pullRequests.ts";
import { serverSettingLines, settingRows } from "../model/settings.ts";
import { resetCreditOutcome, usageLimits, usageSummaryLines } from "../model/usage.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts";
@@ -38,8 +39,10 @@ import { Palette } from "./Palette.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx";
import { QueuePanel } from "./QueuePanel.tsx";
import { SecretPanel } from "./SecretPanel.tsx";
import { PullRequestView } from "./PullRequestView.tsx";
import { SettingsView } from "./SettingsView.tsx";
import { useWorkspace } from "./useWorkspace.ts";
import { useComposerPullRequests, usePullRequests } from "./usePullRequests.ts";
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx";
@@ -62,7 +65,7 @@ import { useUsageSummary } from "./useUsage.ts";
* "details": j/k move through the details panel. "settings": j/k move through settings.
* The rest are overlays with their own input.
*/
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find";
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request";
/** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120;
@@ -137,8 +140,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
/** The trigger esc closed the menu for; typing on reopens it. */
const [menuDismissed, setMenuDismissed] = useState<string | null>(null);
const [pathResults, setPathResults] = useState<{ key: string; entries: readonly ProjectEntry[] } | null>(null);
/** Thread mentions per composer, sent as the message's context. */
const mentions = useRef(new Map<string, Map<string, ThreadContextRecord>>());
/** Mentions per composer (threads, pull requests), sent as the message's context. */
const mentions = useRef(new Map<string, Map<string, ComposerContextRecord>>());
const [questionDrafts, setQuestionDrafts] = useState<ReadonlyMap<string, QuestionDraft>>(new Map());
const [now, setNow] = useState(Date.now());
const scrollRef = useRef<ScrollBoxRenderable | null>(null);
@@ -204,7 +207,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setSettingsIndex(null);
setDraft(null);
setDetailsSelected(null);
setMode((current) => (current === "details" || current === "settings" ? "nav" : current));
setMode((current) => (current === "details" || current === "settings" || current === "pull-request" ? "nav" : current));
}, []);
const [watchedId, setWatchedId] = useState(threadId);
@@ -971,6 +974,41 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
},
});
// Pull requests: the P view, link/unlink/watch, a draft checked out from one.
const pullRequests = usePullRequests({
session,
renderer,
threadShell,
project: draft ? draftProject : project,
projects: shell.snapshot?.projects ?? [],
serverConfig: providerConfig,
confirm,
openPicker,
say,
run,
showView: () => {
setDiff(null);
setSettingsIndex(null);
setMode("pull-request");
},
hideView: () => setMode("nav"),
startDraftFromPullRequest: (targetProject, prepared) => {
setDraft({
...draftDefaults({
config: providerConfig,
project: targetProject,
currentModel: threadShell?.modelSelection ?? null,
projectHasThreads: shell.snapshot?.threads.some((candidate) => candidate.projectId === targetProject.id) ?? false,
}),
envMode: prepared.worktreePath ? "worktree" : "local",
...(prepared.worktreePath ? { existingWorktree: { path: prepared.worktreePath, branch: prepared.branch } } : {}),
});
setDiff(null);
setSettingsIndex(null);
setMode("input");
},
});
// The command palette: everything the keys do, plus what the details panel offers.
const commands: (PaletteCommand & { readonly run: () => void })[] = [...turns.commands];
const command = (id: string, label: string, action: () => void, extra: Omit<PaletteCommand, "id" | "title"> = {}) => commands.push({ id, title: label, run: action, ...extra });
@@ -1019,6 +1057,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
if (threadId || draft) commands.push(...attach.commands);
command("new-automation", "New automation", automationEditing.newAutomation, { keywords: ["scheduled", "task", "create", "editor"] });
usageInfo.credits.forEach((credit, index) => command(`reset-credit:${index}`, `Use reset credit: ${credit.label}`, () => useResetCredit(credit), { keywords: ["usage", "limit", "reset", "credit"] }));
for (const prCommand of pullRequests.commands) commands.push(prCommand);
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] });
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
@@ -1060,7 +1099,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return false;
};
// The / $ @ menu: the web composer's suggestions for the trigger under the cursor.
// The / $ @ # menu: the web composer's suggestions for the trigger under the cursor.
const composerCwd = draft ? (draftProject?.workspaceRoot ?? null) : (threadShell?.worktreePath ?? project?.workspaceRoot ?? null);
const composerProvider = currentModel ? providerConfig?.providers.find((candidate) => candidate.instanceId === currentModel.instanceId) : undefined;
const trigger = mode === "input" && (threadId || draft) ? composerTrigger(composerState.text, composerState.cursor) : null;
@@ -1078,6 +1117,13 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}, 120);
return () => clearTimeout(timer);
}, [session, pathKey]);
const composerPullRequests = useComposerPullRequests({
session,
query: trigger?.kind === "pull-request" ? trigger.query : null,
projectId: providerConfig ? (draft ? draft.projectId : (threadShell?.projectId ?? null)) : null,
repository: providerConfig ? pullRequestRepository(draft ? draftProject : project) : null,
links: threadShell?.pullRequests,
});
const menu = ((): { items: ComposerItem[]; empty: string; loading: boolean } | null => {
if (!trigger || triggerKey === menuDismissed) return null;
switch (trigger.kind) {
@@ -1092,6 +1138,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const fresh = pathResults?.key === pathKey;
return { items: [...threads, ...(fresh ? pathItems(pathResults.entries) : [])], empty: fresh ? "No matching files or folders." : "Searching…", loading: !fresh };
}
case "pull-request":
return composerPullRequests;
default:
return null;
}
@@ -1120,7 +1168,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const at = cursorAtIndex(next.text, next.cursor);
composer.setCursor(at.row, at.col);
if (item.record) {
const records = mentions.current.get(composerKey) ?? new Map<string, ThreadContextRecord>();
const records = mentions.current.get(composerKey) ?? new Map<string, ComposerContextRecord>();
records.set(item.record.contextId, item.record);
mentions.current.set(composerKey, records);
}
@@ -1201,6 +1249,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return;
}
const scroll = scrollRef.current;
if (mode === "pull-request") {
if (pullRequests.handleKey(key, scroll)) return key.preventDefault();
return;
}
if (mode === "settings") {
const index = settingsIndex ?? 0;
switch (key.name) {
@@ -1273,6 +1325,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
case ".":
return openSelectedThreadMenu();
case "p":
if (key.shift) return pullRequests.open();
if (draft) openProjectPicker();
return;
case "w":
@@ -1439,6 +1492,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
cycleSetting(index);
}}
/>
) : mode === "pull-request" && pullRequests.view ? (
<PullRequestView view={pullRequests.view} scrollRef={scrollRef} />
) : diff ? (
<DiffView diff={diff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} />
) : draft ? (
@@ -1612,6 +1667,7 @@ function hints(
if (mode === "confirm") return "enter confirm · esc cancel";
if (mode === "details") return "j/k move · enter open · t toggle automation · esc back";
if (mode === "settings") return "j/k move · enter change · esc close";
if (mode === "pull-request") return "j/k scroll · o open · r refresh · c comment · R review · a actions · w watch · u unlink · esc close";
if (mode === "input") {
const send = state.config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
const other = state.config.followUpBehavior === "steer" ? "queue" : "steer";
+66
View File
@@ -0,0 +1,66 @@
import type { ScrollBoxRenderable } from "@opentui/core";
import type { RefObject } from "react";
import type { PullRequestLine } from "../model/pullRequests.ts";
import { colors } from "./theme.ts";
export interface PullRequestViewState {
readonly status: "loading" | "ready" | "error";
readonly lines: readonly PullRequestLine[];
readonly watching: boolean;
readonly error?: string;
}
const LINE_COLORS: Record<PullRequestLine["kind"], string> = {
title: colors.accent,
meta: colors.muted,
body: colors.text,
check: colors.text,
review: colors.text,
comment: colors.muted,
guide: colors.text,
faint: colors.faint,
};
/** A linked pull request in place of the conversation: j/k scroll, o opens it, esc closes. */
export function PullRequestView(props: { readonly view: PullRequestViewState; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
const { view } = props;
return (
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
<box flexDirection="row" flexShrink={0} height={1}>
<text fg={colors.text}>
<strong>Pull request</strong>
</text>
{view.watching ? <text fg={colors.good}>{" watching"}</text> : null}
<box flexGrow={1} />
<text fg={colors.faint}>esc close</text>
</box>
{view.status === "loading" ? <text fg={colors.muted}>Loading pull request…</text> : null}
{view.status === "error" ? <text fg={colors.bad}>{`Could not load the pull request: ${view.error ?? "unknown error"}`}</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
{view.lines.map((line, index) =>
line.kind === "title" && index > 0 ? (
<text key={index} fg={LINE_COLORS[line.kind]} marginTop={1}>
<strong>{line.text}</strong>
</text>
) : line.kind === "title" ? (
<text key={index} fg={colors.text}>
<strong>{line.text}</strong>
</text>
) : (
<text key={index} fg={line.kind === "check" ? checkColor(line.text) : LINE_COLORS[line.kind]}>
{line.text || " "}
</text>
),
)}
</scrollbox>
</box>
);
}
function checkColor(text: string): string {
if (text.startsWith("✓")) return colors.good;
if (text.startsWith("✕")) return colors.bad;
if (text.startsWith("◐")) return colors.warn;
return colors.text;
}
+538
View File
@@ -0,0 +1,538 @@
import type { CliRenderer, KeyEvent, ScrollBoxRenderable } from "@opentui/core";
import type {
GitPreparePullRequestThreadResult,
OrchestrationProjectShell,
OrchestrationV2ThreadShell,
ProjectId,
PullRequestActivity,
PullRequestMergeMethod,
PullRequestDetail,
PullRequestRef,
PullRequestReviewGuideResult,
PullRequestReviewVerdict,
ServerConfig,
ThreadPullRequestLink,
} from "@t3tools/contracts";
import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-link-input";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { planThreadPullRequestMutation, threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
import { useEffect, useMemo, useRef, useState } from "react";
import type { T3Session } from "../client/session.ts";
import { pullRequestItems, type ComposerItem } from "../model/composerMenu.ts";
import type { PaletteCommand, Picker } from "../model/palette.ts";
import {
COMPOSER_PULL_REQUEST_LIST_LIMIT,
MERGE_METHOD_LABELS,
exactPullRequestNumber,
linkKey,
offeredActions,
offeredMergeMethods,
pullRequestLines,
rankComposerPullRequests,
referenceForLink,
resolveLinkInput,
visibleLinks,
} from "../model/pullRequests.ts";
import type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts";
import type { PullRequestViewState } from "./PullRequestView.tsx";
export interface PullRequestDeps {
readonly session: T3Session;
readonly renderer: CliRenderer;
readonly threadShell: OrchestrationV2ThreadShell | undefined;
readonly project: OrchestrationProjectShell | undefined;
readonly projects: readonly OrchestrationProjectShell[];
readonly serverConfig: ServerConfig | null;
readonly confirm: (next: Confirmation) => void;
readonly openPicker: (next: Picker) => void;
readonly say: (text: string, bad?: boolean) => void;
readonly run: (label: string, action: () => Promise<unknown>) => void;
/** Shows the PR view (App's mode and render slot). */
readonly showView: () => void;
readonly hideView: () => void;
/** Opens a draft in the prepared checkout, as the web's draft thread does. */
readonly startDraftFromPullRequest: (project: OrchestrationProjectShell, prepared: GitPreparePullRequestThreadResult) => void;
}
interface Loaded {
readonly link: ThreadPullRequestLink;
readonly reference: PullRequestRef;
readonly status: "loading" | "ready" | "error";
readonly detail: PullRequestDetail | null;
readonly activity: PullRequestActivity | null;
readonly guide: PullRequestReviewGuideResult | null;
readonly error?: string;
}
const VERDICTS: readonly { value: PullRequestReviewVerdict; label: string; sent: string }[] = [
{ value: "comment", label: "Comment", sent: "Review submitted" },
{ value: "approve", label: "Approve", sent: "Approved" },
{ value: "request-changes", label: "Request changes", sent: "Changes requested" },
];
/**
* The thread's linked pull requests: the `P` view with its comment, review and host actions,
* link / unlink / watch, a new thread checked out from a pull request, and the composer's `#`.
*/
export function usePullRequests(deps: PullRequestDeps) {
const { session, threadShell, project, serverConfig } = deps;
const [loaded, setLoaded] = useState<Loaded | null>(null);
const loadedRef = useRef<Loaded | null>(null);
loadedRef.current = loaded;
const links = threadShell ? visibleLinks(threadShell) : [];
const capabilities = serverConfig?.environment.capabilities;
const linkMode = threadPullRequestLinkMode(capabilities);
const supportsWatch = capabilities?.threadPullRequestWatch === true;
const guidesEnabled = serverConfig?.settings.reviewGuidesEnabled === true;
const load = async (link: ThreadPullRequestLink, reference: PullRequestRef) => {
const token = { link, reference };
try {
const [detail, activity] = await Promise.all([session.pullRequestDetail(reference), session.pullRequestActivity(reference)]);
let merged = detail;
if (capabilities?.pullRequestChecks === true) {
const checks = await session.pullRequestChecks(reference).catch(() => null);
merged = resolvePullRequestDetailChecks(detail, checks, true) ?? detail;
}
const guide = guidesEnabled ? await session.pullRequestReviewGuide(reference).catch(() => null) : null;
if (loadedRef.current?.link !== token.link) return;
setLoaded({ link, reference, status: "ready", detail: merged, activity, guide });
} catch (error) {
if (loadedRef.current?.link !== token.link) return;
setLoaded({ link, reference, status: "error", detail: null, activity: null, guide: null, error: messageOf(error) });
}
};
const openLink = (link: ThreadPullRequestLink) => {
if (!threadShell) return;
const reference = referenceForLink(link, threadShell.projectId);
setLoaded({ link, reference, status: "loading", detail: null, activity: null, guide: null });
deps.showView();
void load(link, reference);
};
const open = () => {
if (!threadShell) return deps.say("Open a thread first.", true);
if (links.length === 0) return deps.say("This thread has no linked pull requests. Link one from the palette.", true);
if (links.length === 1) return openLink(links[0]!);
deps.openPicker({
placeholder: "Linked pull requests",
groups: [
{
label: "Pull requests",
items: links.map((link) => ({
id: `pr:${link.host}/${link.repository}#${link.number}`,
title: `#${link.number} ${link.snapshot?.title ?? link.repository}`,
...(link.snapshot ? { hint: link.snapshot.state } : {}),
run: () => openLink(link),
})),
},
],
});
};
const close = () => {
setLoaded(null);
deps.hideView();
};
const refresh = () => {
const current = loadedRef.current;
if (!current) return;
deps.say("Refreshing…");
void (async () => {
await session.invalidatePullRequest(current.reference).catch(() => {});
await load(current.link, current.reference);
deps.say("Refreshed");
})();
};
const openInBrowser = () => {
const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url;
if (!url) return;
try {
Bun.spawn([process.platform === "darwin" ? "open" : "xdg-open", url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
} catch {
deps.say(`Could not open ${url}`, true);
}
};
const reloadQuietly = () => {
const current = loadedRef.current;
if (current) void load(current.link, current.reference);
};
const comment = () => {
const current = loadedRef.current;
if (!current?.detail || !current.detail.capabilities.comment || !current.detail.viewerPermissions.comment) return deps.say("Commenting is not available on this pull request.", true);
const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; nothing was posted.", true);
const body = edited.trim();
if (!body) return deps.say("Nothing to post.", true);
const number = current.detail.number;
deps.confirm({
title: `Comment on #${number}?`,
detail: firstLine(body),
confirmLabel: "comment",
run: () =>
deps.run("Comment posted", async () => {
await session.commentOnPullRequest(current.reference, body);
reloadQuietly();
}),
});
};
const review = () => {
const current = loadedRef.current;
const detail = current?.detail;
if (!current || !detail) return;
const offered = VERDICTS.filter((verdict) => detail.capabilities.review.verdicts.includes(verdict.value) && detail.viewerPermissions.verdicts.includes(verdict.value));
if (offered.length === 0) return deps.say("Reviewing is not available on this pull request.", true);
deps.openPicker({
placeholder: "Review verdict",
groups: [
{
label: "Verdict",
items: offered.map((verdict) => ({
id: `verdict:${verdict.value}`,
title: verdict.label,
run: () => {
const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; the review was not submitted.", true);
const body = edited;
const summaryRequired = sourceControlClients.get(detail.provider).reviewSummaryRequired("request-changes");
const canSubmit =
verdict.value === "request-changes" && summaryRequired ? body.trim().length > 0 : verdict.value === "approve" || body.trim().length > 0;
if (!canSubmit) return deps.say(verdict.value === "request-changes" && summaryRequired ? "Summarize your review (required to request changes)." : "Summarize your review or approve without one.", true);
deps.confirm({
title: `${verdict.label} #${detail.number}?`,
...(body.trim() ? { detail: firstLine(body) } : {}),
confirmLabel: "submit review",
run: () =>
deps.run(verdict.sent, async () => {
await session.submitPullRequestReview(current.reference, verdict.value, body);
reloadQuietly();
}),
});
},
})),
},
],
});
};
const actions = () => {
const current = loadedRef.current;
const detail = current?.detail;
if (!current || !detail) return;
const host = offeredActions(detail).map(({ action, label }) => ({
id: `pr-action:${action}`,
title: label,
run: () => {
const finish = (mergeMethod?: PullRequestMergeMethod) =>
deps.confirm({
title: `${label} #${detail.number}?`,
detail: detail.title,
confirmLabel: label.toLowerCase(),
run: () =>
deps.run(label === "Merge" ? "Merge requested" : label, async () => {
await session.runPullRequestAction(current.reference, action, mergeMethod);
await session.invalidatePullRequest(current.reference).catch(() => {});
reloadQuietly();
}),
});
if (action !== "merge") return finish();
const methods = offeredMergeMethods(detail);
if (methods.length <= 1) return finish(methods[0]);
const preferred = serverConfig ? preferredMergeMethod(serverConfig, detail.projectId) : undefined;
deps.openPicker({
placeholder: "Merge method",
groups: [
{
label: "Merge method",
items: methods.map((method) => ({
id: `merge:${method}`,
title: MERGE_METHOD_LABELS[method],
...(method === preferred ? { hint: "default" } : {}),
run: () => finish(method),
})),
},
],
});
},
}));
const guideItems =
guidesEnabled && current.guide?.run?._tag !== "Running"
? [
{
id: "pr-guide",
title: current.guide?.guide ? "Rewrite review guide" : "Write review guide",
run: () =>
deps.run("Review guide started", async () => {
const guide = await session.generatePullRequestReviewGuide(current.reference);
setLoaded((value) => (value?.link === current.link ? { ...value, guide } : value));
}),
},
]
: [];
if (host.length === 0 && guideItems.length === 0) return deps.say("No actions are available on this pull request.", true);
deps.openPicker({
placeholder: `#${detail.number} actions`,
groups: [
...(host.length > 0 ? [{ label: "Pull request", items: host }] : []),
...(guideItems.length > 0 ? [{ label: "Review guide", items: guideItems }] : []),
],
});
};
const unlink = (link: ThreadPullRequestLink) => {
if (!threadShell) return;
const id = threadShell.id;
deps.confirm({
title: `${link.source === "stack" ? "Dismiss" : "Unlink"} #${link.number} from this thread?`,
...(link.snapshot?.title ? { detail: link.snapshot.title } : {}),
confirmLabel: link.source === "stack" ? "dismiss" : "unlink",
run: () =>
deps.run("Unlinked", async () => {
await session.unlinkPullRequest(id, linkKey(link));
if (loadedRef.current?.link === link) close();
}),
});
};
const setWatching = (link: ThreadPullRequestLink, watching: boolean) => {
if (!threadShell) return;
deps.run(watching ? "Watching for changes" : "Stopped watching", () => session.watchPullRequest(threadShell.id, linkKey(link), watching));
};
const linkDialog = () => {
if (!threadShell) return deps.say("Open a thread first.", true);
if (linkMode === "unsupported") return deps.say("Server details are still loading.", true);
const id = threadShell.id;
deps.confirm({
title: "Link pull request",
detail: "Attach a pull request to this thread by its URL, or by its number for this thread's repository.",
message: { placeholder: "Pull request URL or #42" },
confirmLabel: "link",
run: (text) => {
if (!text.trim()) return deps.say("Paste a pull request URL or enter 123 / #123.", true);
const resolved = resolveLinkInput({ reference: text, project, projects: deps.projects });
if (resolved === null) return deps.say("Use a pull request URL, 123, or #123.", true);
if ("error" in resolved) return deps.say(resolved.error, true);
const mutation = planThreadPullRequestMutation({ capabilities, threadId: id, reference: resolved.link, linked: true });
if (mutation === null || mutation.type !== "thread.pull-request.link") return deps.say("This environment does not support linking this pull request.", true);
const { threadId: _threadId, source: _source, url, ...key } = mutation.input;
deps.run(`Linked #${key.number}`, () => session.linkPullRequest(id, key, url));
},
});
};
const newThreadFromPullRequest = () => {
const target = project ?? deps.projects[0];
if (!target) return deps.say("No projects on this server yet; add one in T3 Code.", true);
const cwd = target.workspaceRoot;
deps.confirm({
title: "New thread from pull request",
detail: `Resolve a pull request, then create the draft thread in ${target.title} or in a dedicated worktree.`,
message: { placeholder: "Pull request URL, checkout command, or #42" },
confirmLabel: "resolve",
run: (text) => {
if (!text.trim()) return deps.say("Paste a pull request URL, checkout command, or enter 123 / #123.", true);
const parsed = parsePullRequestReference(text);
if (parsed === null) return deps.say("Use a pull request URL, checkout command, 123, or #123.", true);
deps.say("Resolving…");
session.resolvePullRequest(cwd, parsed).then(
({ pullRequest }) => {
const prepare = (mode: "local" | "worktree") => {
deps.say(mode === "worktree" ? "Preparing worktree…" : "Preparing local…");
session.preparePullRequestThread(cwd, parsed, mode).then(
(prepared) => {
deps.startDraftFromPullRequest(target, prepared);
deps.say(prepared.isOnPullRequestHead ? `Draft on ${prepared.branch}` : `Draft on ${prepared.branch} (not on the pull request head)`);
},
(error) => deps.say(`Could not prepare the pull request thread: ${messageOf(error)}`, true),
);
};
deps.openPicker({
placeholder: `#${pullRequest.number} ${pullRequest.title} · ${pullRequest.headBranch} to ${pullRequest.baseBranch} · ${pullRequest.state}`,
groups: [
{
label: "Runs in",
items: [
{ id: "pr-thread:worktree", title: "Worktree", hint: "a dedicated worktree", run: () => prepare("worktree") },
{ id: "pr-thread:local", title: "Local", hint: "the project folder", run: () => prepare("local") },
],
},
],
});
},
(error) => deps.say(messageOf(error), true),
);
},
});
};
const watchingCurrent = loaded ? links.some((link) => link.host === loaded.link.host && link.repository === loaded.link.repository && link.number === loaded.link.number && link.watch !== undefined) : false;
const view: PullRequestViewState | null = loaded
? {
status: loaded.status,
lines: loaded.detail ? pullRequestLines(loaded.detail, loaded.activity, loaded.guide) : [],
watching: watchingCurrent,
...(loaded.error ? { error: loaded.error } : {}),
}
: null;
/** Keys inside the PR view. Returns true when handled. */
const handleKey = (key: KeyEvent, scroll: ScrollBoxRenderable | null): boolean => {
if (!loadedRef.current) return false;
const current = loadedRef.current;
switch (key.name) {
case "j":
case "down":
scroll?.scrollBy(1);
return true;
case "k":
case "up":
scroll?.scrollBy(-1);
return true;
case "g":
if (key.shift) scroll?.scrollTo(scroll.scrollHeight);
else scroll?.scrollTo(0);
return true;
case "o":
openInBrowser();
return true;
case "r":
if (key.shift) review();
else refresh();
return true;
case "c":
comment();
return true;
case "a":
actions();
return true;
case "w":
if (supportsWatch && (current.link.snapshot === null || current.link.snapshot.state === "open")) setWatching(current.link, !watchingCurrent);
return true;
case "u":
unlink(current.link);
return true;
case "escape":
case "q":
close();
return true;
default:
return false;
}
};
const commands: (PaletteCommand & { run: () => void })[] = [];
if (threadShell && links.length > 0) {
commands.push({ id: "pull-requests", title: "Show linked pull requests", shortcut: "P", keywords: ["pull requests", "linked", "stack", "prs"], run: open });
}
if (threadShell && linkMode !== "unsupported") {
commands.push({ id: "link-pull-request", title: "Link pull request to thread", keywords: ["link", "pull request", "pr", "attach", "stack"], run: linkDialog });
}
if (threadShell) {
for (const link of links) {
commands.push({ id: `unlink-pull-request:${link.number}`, title: `${link.source === "stack" ? "Dismiss" : "Unlink"} pull request #${link.number} from thread`, keywords: ["unlink", "pull request", "pr"], run: () => unlink(link) });
if (supportsWatch && (link.snapshot === null || link.snapshot.state === "open")) {
const watching = link.watch !== undefined;
commands.push({
id: `watch-pull-request:${link.number}`,
title: watching ? `Stop watching pull request #${link.number}` : `Watch pull request #${link.number} for changes`,
keywords: ["watch", "pull request", "pr"],
run: () => setWatching(link, !watching),
});
}
}
}
commands.push({ id: "new-thread-from-pull-request", title: "New thread from pull request…", keywords: ["checkout", "pull request", "pr", "worktree"], run: newThreadFromPullRequest });
if (loaded?.detail) {
const number = loaded.detail.number;
commands.push({ id: "pr-comment", title: `Comment on pull request #${number}`, shortcut: "c", keywords: ["comment", "pull request"], run: comment });
commands.push({ id: "pr-review", title: `Review pull request #${number}…`, shortcut: "R", keywords: ["review", "approve", "request changes"], run: review });
commands.push({ id: "pr-actions", title: `Pull request #${number} actions…`, shortcut: "a", keywords: ["merge", "close", "ready", "draft"], run: actions });
commands.push({ id: "pr-open", title: `Open pull request #${number} in browser`, shortcut: "o", keywords: ["open", "browser"], run: openInBrowser });
commands.push({ id: "pr-refresh", title: "Refresh pull request", shortcut: "r", keywords: ["refresh", "reload"], run: refresh });
}
return { view, isOpen: loaded !== null, open, close, handleKey, commands };
}
/** The project's configured merge method, as the web pre-selects it. */
function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) {
return resolveProjectSettings(config.settings, projectId).settings.pullRequestMergeMethod ?? undefined;
}
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
function firstLine(text: string): string {
const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ");
return line.length > 100 ? `${line.slice(0, 99)}…` : line;
}
/**
* The composer's `#` search, debounced as the web's (180ms): the recent list (host-searched for
* words), plus the exact pull request a typed number names when the list lacks it.
*/
export function useComposerPullRequests(input: {
readonly session: T3Session;
readonly query: string | null;
readonly projectId: ProjectId | null;
readonly repository: string | null;
readonly links: readonly ThreadPullRequestLink[] | undefined;
}): { items: ComposerItem[]; empty: string; loading: boolean } {
const { session, query, projectId, repository } = input;
const [result, setResult] = useState<{ key: string; items: ComposerItem[]; failed: boolean } | null>(null);
const textQuery = query !== null && query.length > 0 && !/^\d+$/u.test(query) ? query : null;
const key = query !== null && projectId !== null && repository !== null ? `${projectId}\u0000${repository}\u0000${query}` : null;
const linksRef = useRef(input.links);
linksRef.current = input.links;
useEffect(() => {
if (key === null || projectId === null || repository === null || query === null) return;
let cancelled = false;
const timer = setTimeout(() => {
void (async () => {
try {
const list = await session.pullRequestsList({ state: "all", projectId, limit: COMPOSER_PULL_REQUEST_LIST_LIMIT, ...(textQuery === null ? {} : { query: textQuery }) });
const number = exactPullRequestNumber(query);
const hasExact =
number !== null &&
list.entries.some((entry) => entry.projectId === projectId && entry.repository.trim().toLowerCase() === repository.trim().toLowerCase() && entry.number === number);
const exact = number !== null && !hasExact ? await session.pullRequestDetail({ projectId, repository, number }).catch(() => null) : null;
const exactDetail = exact?.number === number ? exact : null;
if (cancelled) return;
const matches = rankComposerPullRequests({ result: list, exact: exactDetail, links: linksRef.current, projectId, repository, query });
setResult({ key, items: pullRequestItems(matches, repository), failed: list.errors.some((error) => error.projectId === projectId) });
} catch {
if (!cancelled) setResult({ key, items: [], failed: true });
}
})();
}, 180);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [session, key, projectId, repository, query, textQuery]);
return useMemo(() => {
if (query === null) return { items: [], empty: "", loading: false };
if (projectId === null || repository === null) return { items: [], empty: "Pull requests are not available for this project.", loading: false };
const fresh = result?.key === key;
if (fresh && result.failed && result.items.length === 0) return { items: [], empty: "Pull requests could not be read for this project.", loading: false };
return {
items: fresh ? result.items : [],
empty: fresh ? (query ? `No pull request matches ${query}.` : "No pull requests found in this repository.") : "Searching…",
loading: !fresh,
};
}, [query, projectId, repository, result, key]);
}