style: readability pass on delegate-written hooks and models
This commit is contained in:
1 parent
a6cfb9a2cd
commit
d5b6406cae
9 files changed
+844
-309
No files matched your search
+107
-56
@@ -47,16 +47,17 @@ export function newAutomationTemplate(projects: readonly OrchestrationProjectShe
|
|||||||
/** The $EDITOR template for an existing automation, its fields filled in. */
|
/** The $EDITOR template for an existing automation, its fields filled in. */
|
||||||
export function automationTemplate(task: ScheduledTask, projects: readonly OrchestrationProjectShell[]): string {
|
export function automationTemplate(task: ScheduledTask, projects: readonly OrchestrationProjectShell[]): string {
|
||||||
const project = projects.find((candidate) => candidate.id === task.projectId);
|
const project = projects.find((candidate) => candidate.id === task.projectId);
|
||||||
|
const strategy = task.workspaceStrategy;
|
||||||
return template({
|
return template({
|
||||||
title: task.title,
|
title: task.title,
|
||||||
enabled: task.enabled,
|
enabled: task.enabled,
|
||||||
schedule: scheduleText(task),
|
schedule: scheduleText(task),
|
||||||
project: project?.title ?? task.projectId,
|
project: project?.title ?? task.projectId,
|
||||||
thread: task.threadId ?? "",
|
thread: task.threadId ?? "",
|
||||||
workspace: task.workspaceStrategy.type,
|
workspace: strategy.type,
|
||||||
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
|
baseRef: strategy.type === "worktree" ? strategy.baseRef : "main",
|
||||||
startFromOrigin: task.workspaceStrategy.type === "worktree" ? (task.workspaceStrategy.startFromOrigin ?? false) : true,
|
startFromOrigin: strategy.type === "worktree" ? (strategy.startFromOrigin ?? false) : true,
|
||||||
checkoutPath: task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath : "",
|
checkoutPath: strategy.type === "existing_worktree" ? strategy.worktreePath : "",
|
||||||
model: `${task.modelSelection.instanceId}:${task.modelSelection.model}`,
|
model: `${task.modelSelection.instanceId}:${task.modelSelection.model}`,
|
||||||
mode: task.runtimeMode,
|
mode: task.runtimeMode,
|
||||||
prompt: task.prompt,
|
prompt: task.prompt,
|
||||||
@@ -107,10 +108,13 @@ function scheduleText(task: ScheduledTask): string {
|
|||||||
switch (schedule.type) {
|
switch (schedule.type) {
|
||||||
case "interval": {
|
case "interval": {
|
||||||
const minutes = schedule.everyMs / 60_000;
|
const minutes = schedule.everyMs / 60_000;
|
||||||
return Number.isInteger(minutes) && minutes % 60 === 0 ? `interval ${minutes / 60}h` : `interval ${Math.max(1, Math.round(minutes))}m`;
|
const wholeHours = Number.isInteger(minutes) && minutes % 60 === 0;
|
||||||
|
return wholeHours ? `interval ${minutes / 60}h` : `interval ${Math.max(1, Math.round(minutes))}m`;
|
||||||
}
|
}
|
||||||
case "fixed_time": {
|
case "fixed_time": {
|
||||||
const days = schedule.weekdays && schedule.weekdays.length > 0 && schedule.weekdays.length < 7 ? ` ${schedule.weekdays.map((day) => WEEKDAY_NAMES[day]).join(",")}` : "";
|
// No days, or every day, both read as plain "every day at HH:MM".
|
||||||
|
const weekdayNames = (schedule.weekdays ?? []).map((day) => WEEKDAY_NAMES[day]);
|
||||||
|
const days = weekdayNames.length > 0 && weekdayNames.length < 7 ? ` ${weekdayNames.join(",")}` : "";
|
||||||
return `fixed ${schedule.timeOfDay}${days}`;
|
return `fixed ${schedule.timeOfDay}${days}`;
|
||||||
}
|
}
|
||||||
case "webhook":
|
case "webhook":
|
||||||
@@ -127,6 +131,58 @@ export type AutomationParse = { readonly ok: true; readonly input: ScheduledTask
|
|||||||
* its signature, dedupe and filters, as the template says.
|
* its signature, dedupe and filters, as the template says.
|
||||||
*/
|
*/
|
||||||
export function parseAutomation(text: string, projects: readonly OrchestrationProjectShell[], existing?: ScheduledTask): AutomationParse {
|
export function parseAutomation(text: string, projects: readonly OrchestrationProjectShell[], existing?: ScheduledTask): AutomationParse {
|
||||||
|
const { fields, prompt } = readTemplate(text);
|
||||||
|
const get = (key: string) => fields.get(key) ?? "";
|
||||||
|
|
||||||
|
const title = get("title");
|
||||||
|
const projectText = get("project");
|
||||||
|
const byTitle = projects.find((candidate) => candidate.title === projectText);
|
||||||
|
const project = byTitle ?? projects.find((candidate) => candidate.id === projectText);
|
||||||
|
const model = parseModel(get("model"), existing?.modelSelection);
|
||||||
|
if (!title || !prompt || !project || !model) {
|
||||||
|
return { ok: false, error: "Scheduled task is incomplete: add a title, prompt, project, and model." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const schedule = parseSchedule(get("schedule"), existing);
|
||||||
|
if (!schedule.ok) return schedule;
|
||||||
|
|
||||||
|
const workspace = get("workspace") || "worktree";
|
||||||
|
const checkoutPath = get("checkout path");
|
||||||
|
if (workspace === "existing_worktree" && !checkoutPath) {
|
||||||
|
return { ok: false, error: "Checkout path is required: enter the path of the checkout to run in." };
|
||||||
|
}
|
||||||
|
const workspaceStrategy = workspaceStrategyFor(workspace, checkoutPath, get);
|
||||||
|
if (workspaceStrategy === null) {
|
||||||
|
return { ok: false, error: `Workspace must be worktree, root, or existing_worktree, not "${workspace}".` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const mode = get("mode");
|
||||||
|
if (!(RUNTIME_MODES as readonly string[]).includes(mode)) {
|
||||||
|
return { ok: false, error: `Mode must be one of ${RUNTIME_MODES.join(", ")}, not "${mode}".` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const threadId = get("thread");
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
input: {
|
||||||
|
...(existing ? { id: existing.id, requireExisting: true } : {}),
|
||||||
|
title,
|
||||||
|
prompt,
|
||||||
|
enabled: get("enabled").toLowerCase() !== "false",
|
||||||
|
schedule: schedule.schedule,
|
||||||
|
projectId: ProjectId.make(project.id),
|
||||||
|
threadId: threadId ? ThreadId.make(threadId) : null,
|
||||||
|
workspaceStrategy,
|
||||||
|
modelSelection: model,
|
||||||
|
runtimeMode: mode as RuntimeMode,
|
||||||
|
interactionMode: existing?.interactionMode ?? "default",
|
||||||
|
creationSource: "web",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The template's `Key: value` lines, plus everything after `Prompt:` as the prompt. */
|
||||||
|
function readTemplate(text: string): { fields: Map<string, string>; prompt: string } {
|
||||||
const fields = new Map<string, string>();
|
const fields = new Map<string, string>();
|
||||||
const promptLines: string[] = [];
|
const promptLines: string[] = [];
|
||||||
let inPrompt = false;
|
let inPrompt = false;
|
||||||
@@ -146,48 +202,29 @@ export function parseAutomation(text: string, projects: readonly OrchestrationPr
|
|||||||
}
|
}
|
||||||
fields.set(key, match[2]!.trim());
|
fields.set(key, match[2]!.trim());
|
||||||
}
|
}
|
||||||
const get = (key: string) => fields.get(key) ?? "";
|
return { fields, prompt: promptLines.join("\n").trim() };
|
||||||
const title = get("title");
|
}
|
||||||
const prompt = promptLines.join("\n").trim();
|
|
||||||
const projectText = get("project");
|
|
||||||
const project = projects.find((candidate) => candidate.title === projectText) ?? projects.find((candidate) => candidate.id === projectText);
|
|
||||||
const model = parseModel(get("model"), existing?.modelSelection);
|
|
||||||
if (!title || !prompt || !project || !model) return { ok: false, error: "Scheduled task is incomplete: add a title, prompt, project, and model." };
|
|
||||||
|
|
||||||
const schedule = parseSchedule(get("schedule"), existing);
|
/** The workspace a template names, or null when it names none of the three. */
|
||||||
if (!schedule.ok) return schedule;
|
function workspaceStrategyFor(
|
||||||
|
workspace: string,
|
||||||
const workspace = get("workspace") || "worktree";
|
checkoutPath: string,
|
||||||
const checkoutPath = get("checkout path");
|
get: (key: string) => string,
|
||||||
if (workspace === "existing_worktree" && !checkoutPath) return { ok: false, error: "Checkout path is required: enter the path of the checkout to run in." };
|
): ScheduledTaskUpsertInput["workspaceStrategy"] | null {
|
||||||
if (workspace !== "root" && workspace !== "worktree" && workspace !== "existing_worktree") return { ok: false, error: `Workspace must be worktree, root, or existing_worktree, not "${workspace}".` };
|
switch (workspace) {
|
||||||
|
case "root":
|
||||||
const mode = get("mode");
|
return { type: "root" };
|
||||||
if (!(RUNTIME_MODES as readonly string[]).includes(mode)) return { ok: false, error: `Mode must be one of ${RUNTIME_MODES.join(", ")}, not "${mode}".` };
|
case "existing_worktree":
|
||||||
|
return { type: "existing_worktree", worktreePath: checkoutPath };
|
||||||
const threadId = get("thread");
|
case "worktree":
|
||||||
return {
|
return {
|
||||||
ok: true,
|
type: "worktree",
|
||||||
input: {
|
baseRef: get("base ref") || "main",
|
||||||
...(existing ? { id: existing.id, requireExisting: true } : {}),
|
startFromOrigin: get("start from origin").toLowerCase() !== "false",
|
||||||
title,
|
};
|
||||||
prompt,
|
default:
|
||||||
enabled: get("enabled").toLowerCase() !== "false",
|
return null;
|
||||||
schedule: schedule.schedule,
|
}
|
||||||
projectId: ProjectId.make(project.id),
|
|
||||||
threadId: threadId ? ThreadId.make(threadId) : null,
|
|
||||||
workspaceStrategy:
|
|
||||||
workspace === "root"
|
|
||||||
? { type: "root" }
|
|
||||||
: workspace === "existing_worktree"
|
|
||||||
? { type: "existing_worktree", worktreePath: checkoutPath }
|
|
||||||
: { type: "worktree", baseRef: get("base ref") || "main", startFromOrigin: get("start from origin").toLowerCase() !== "false" },
|
|
||||||
modelSelection: model,
|
|
||||||
runtimeMode: mode as RuntimeMode,
|
|
||||||
interactionMode: existing?.interactionMode ?? "default",
|
|
||||||
creationSource: "web",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseModel(text: string, base?: ModelSelection): ModelSelection | null {
|
function parseModel(text: string, base?: ModelSelection): ModelSelection | null {
|
||||||
@@ -207,32 +244,46 @@ function parseSchedule(text: string, existing?: ScheduledTask): ScheduleParse {
|
|||||||
const [kind = "", ...rest] = text.trim().split(/\s+/);
|
const [kind = "", ...rest] = text.trim().split(/\s+/);
|
||||||
if (kind === "interval") {
|
if (kind === "interval") {
|
||||||
const match = /^(\d+)\s*(m|h)?$/.exec(rest.join(" "));
|
const match = /^(\d+)\s*(m|h)?$/.exec(rest.join(" "));
|
||||||
const everyMs = match ? Number(match[1]) * (match[2] === "h" ? 3_600_000 : 60_000) : Number.NaN;
|
const unitMs = match?.[2] === "h" ? 3_600_000 : 60_000;
|
||||||
if (!Number.isSafeInteger(everyMs) || everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS) return { ok: false, error: "Invalid interval: enter an interval of at least one minute." };
|
const everyMs = match ? Number(match[1]) * unitMs : Number.NaN;
|
||||||
|
if (!Number.isSafeInteger(everyMs) || everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS) {
|
||||||
|
return { ok: false, error: "Invalid interval: enter an interval of at least one minute." };
|
||||||
|
}
|
||||||
return { ok: true, schedule: { type: "interval", everyMs } };
|
return { ok: true, schedule: { type: "interval", everyMs } };
|
||||||
}
|
}
|
||||||
if (kind === "fixed") {
|
if (kind === "fixed") {
|
||||||
const timeOfDay = rest[0] ?? "";
|
const timeOfDay = rest[0] ?? "";
|
||||||
if (!/^([01]?\d|2[0-3]):([0-5]\d)$/.test(timeOfDay)) return { ok: false, error: `Invalid schedule: "${text}" — use fixed HH:MM, interval 15m, or webhook.` };
|
if (!/^([01]?\d|2[0-3]):([0-5]\d)$/.test(timeOfDay)) {
|
||||||
const days = rest.slice(1).join(" ").split(/[,\s]+/).filter(Boolean);
|
return { ok: false, error: `Invalid schedule: "${text}" — use fixed HH:MM, interval 15m, or webhook.` };
|
||||||
|
}
|
||||||
|
const dayNames = rest.slice(1).join(" ").split(/[,\s]+/).filter(Boolean);
|
||||||
const weekdays: number[] = [];
|
const weekdays: number[] = [];
|
||||||
for (const day of days) {
|
for (const day of dayNames) {
|
||||||
const index = WEEKDAY_BY_NAME.get(day.toLowerCase());
|
const index = WEEKDAY_BY_NAME.get(day.toLowerCase());
|
||||||
if (index === undefined) return { ok: false, error: `Unknown weekday "${day}": use ${WEEKDAY_NAMES.join(", ")}.` };
|
if (index === undefined) {
|
||||||
|
return { ok: false, error: `Unknown weekday "${day}": use ${WEEKDAY_NAMES.join(", ")}.` };
|
||||||
|
}
|
||||||
weekdays.push(index);
|
weekdays.push(index);
|
||||||
}
|
}
|
||||||
const everyDay = weekdays.length === 0 || new Set(weekdays).size === 7;
|
const uniqueWeekdays = [...new Set(weekdays)].sort((a, b) => a - b);
|
||||||
return { ok: true, schedule: { type: "fixed_time", timeOfDay, ...(everyDay ? {} : { weekdays: [...new Set(weekdays)].sort((a, b) => a - b) }) } };
|
const everyDay = weekdays.length === 0 || uniqueWeekdays.length === 7;
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
schedule: { type: "fixed_time", timeOfDay, ...(everyDay ? {} : { weekdays: uniqueWeekdays }) },
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if (kind === "webhook") {
|
if (kind === "webhook") {
|
||||||
const current = existing?.schedule.type === "webhook" ? existing.schedule : null;
|
const current = existing?.schedule.type === "webhook" ? existing.schedule : null;
|
||||||
if (!current) return { ok: true, schedule: { type: "webhook", signature: null, dedupe: {} } };
|
if (!current) return { ok: true, schedule: { type: "webhook", signature: null, dedupe: {} } };
|
||||||
// Filters stay stored when left out; a signature without a secret keeps the stored one.
|
// Filters stay stored when left out; a signature without a secret keeps the stored one.
|
||||||
|
const signature = current.signature
|
||||||
|
? { header: current.signature.header, encoding: current.signature.encoding, prefix: current.signature.prefix }
|
||||||
|
: null;
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
schedule: {
|
schedule: {
|
||||||
type: "webhook",
|
type: "webhook",
|
||||||
signature: current.signature ? { header: current.signature.header, encoding: current.signature.encoding, prefix: current.signature.prefix } : null,
|
signature,
|
||||||
...(current.maxDeliveryAgeMinutes !== undefined ? { maxDeliveryAgeMinutes: current.maxDeliveryAgeMinutes } : {}),
|
...(current.maxDeliveryAgeMinutes !== undefined ? { maxDeliveryAgeMinutes: current.maxDeliveryAgeMinutes } : {}),
|
||||||
dedupe: current.dedupe ?? {},
|
dedupe: current.dedupe ?? {},
|
||||||
},
|
},
|
||||||
|
|||||||
+184
-88
@@ -77,51 +77,61 @@ export function rankComposerPullRequests(input: {
|
|||||||
const { projectId, repository, query } = input;
|
const { projectId, repository, query } = input;
|
||||||
const linked = composerPullRequestsFromLinks(input.links ?? [], projectId);
|
const linked = composerPullRequestsFromLinks(input.links ?? [], projectId);
|
||||||
const entries = input.result?.entries ?? [];
|
const entries = input.result?.entries ?? [];
|
||||||
const exactEntry: PullRequestListEntry[] = input.exact
|
const exactEntry: PullRequestListEntry[] = input.exact ? [listEntryFromDetail(input.exact)] : [];
|
||||||
? [
|
|
||||||
{
|
|
||||||
provider: input.exact.provider,
|
|
||||||
host: input.exact.capabilities ? "" : "",
|
|
||||||
projectId: input.exact.projectId,
|
|
||||||
projectTitle: input.exact.projectTitle,
|
|
||||||
repository: input.exact.repository,
|
|
||||||
number: input.exact.number,
|
|
||||||
title: input.exact.title,
|
|
||||||
url: input.exact.url,
|
|
||||||
author: input.exact.author,
|
|
||||||
headBranch: input.exact.headBranch,
|
|
||||||
baseBranch: input.exact.baseBranch,
|
|
||||||
state: input.exact.state,
|
|
||||||
isDraft: input.exact.isDraft,
|
|
||||||
mergeability: input.exact.mergeability,
|
|
||||||
additions: input.exact.additions,
|
|
||||||
deletions: input.exact.deletions,
|
|
||||||
createdAt: input.exact.createdAt,
|
|
||||||
updatedAt: input.exact.updatedAt,
|
|
||||||
viewerReviewRequested: false,
|
|
||||||
labels: input.exact.labels,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: [];
|
|
||||||
if (/^\d*$/u.test(query)) {
|
if (/^\d*$/u.test(query)) {
|
||||||
return filterComposerPullRequestMatches({
|
const filtered = filterComposerPullRequestMatches({
|
||||||
entries: [...exactEntry, ...entries],
|
entries: [...exactEntry, ...entries],
|
||||||
linked,
|
linked,
|
||||||
projectId,
|
projectId,
|
||||||
repository,
|
repository,
|
||||||
query,
|
query,
|
||||||
limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
|
limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
|
||||||
}).map(toComposerPullRequest);
|
});
|
||||||
|
return filtered.map(toComposerPullRequest);
|
||||||
}
|
}
|
||||||
const matches = rankPullRequestMatches(
|
|
||||||
entries.filter((entry) => {
|
const inRepository = entries.filter((entry) => {
|
||||||
if (entry.projectId !== projectId || entry.repository.trim().toLowerCase() !== repository.trim().toLowerCase()) return false;
|
if (entry.projectId !== projectId) return false;
|
||||||
const provider = input.result?.providers.find((candidate) => candidate.host === entry.host);
|
if (entry.repository.trim().toLowerCase() !== repository.trim().toLowerCase()) return false;
|
||||||
return provider?.searchesOnHost === true || matchesPullRequestQuery(entry, query);
|
// Host-searched results already matched on the host; the rest match here.
|
||||||
}),
|
const provider = input.result?.providers.find((candidate) => candidate.host === entry.host);
|
||||||
|
return provider?.searchesOnHost === true || matchesPullRequestQuery(entry, query);
|
||||||
|
});
|
||||||
|
const matches = rankPullRequestMatches(inRepository, query);
|
||||||
|
const ranked = withLinkedComposerPullRequestsFirst({
|
||||||
|
matches,
|
||||||
|
linked,
|
||||||
query,
|
query,
|
||||||
);
|
limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
|
||||||
return withLinkedComposerPullRequestsFirst({ matches, linked, query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT }).map(toComposerPullRequest);
|
});
|
||||||
|
return ranked.map(toComposerPullRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A detail reshaped as a list entry, so an exact lookup ranks alongside the recent list. */
|
||||||
|
function listEntryFromDetail(detail: PullRequestDetail): PullRequestListEntry {
|
||||||
|
return {
|
||||||
|
provider: detail.provider,
|
||||||
|
host: detail.capabilities ? "" : "",
|
||||||
|
projectId: detail.projectId,
|
||||||
|
projectTitle: detail.projectTitle,
|
||||||
|
repository: detail.repository,
|
||||||
|
number: detail.number,
|
||||||
|
title: detail.title,
|
||||||
|
url: detail.url,
|
||||||
|
author: detail.author,
|
||||||
|
headBranch: detail.headBranch,
|
||||||
|
baseBranch: detail.baseBranch,
|
||||||
|
state: detail.state,
|
||||||
|
isDraft: detail.isDraft,
|
||||||
|
mergeability: detail.mergeability,
|
||||||
|
additions: detail.additions,
|
||||||
|
deletions: detail.deletions,
|
||||||
|
createdAt: detail.createdAt,
|
||||||
|
updatedAt: detail.updatedAt,
|
||||||
|
viewerReviewRequested: false,
|
||||||
|
labels: detail.labels,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function toComposerPullRequest(entry: {
|
function toComposerPullRequest(entry: {
|
||||||
@@ -151,7 +161,8 @@ export function exactPullRequestNumber(query: string): number | null {
|
|||||||
* buildPullRequestReferenceContext + reviewCommentContextRecord build it.
|
* buildPullRequestReferenceContext + reviewCommentContextRecord build it.
|
||||||
*/
|
*/
|
||||||
export function pullRequestContextRecord(meta: PullRequestContextMetadata): { record: ReviewCommentContextRecord; replacement: string } {
|
export function pullRequestContextRecord(meta: PullRequestContextMetadata): { record: ReviewCommentContextRecord; replacement: string } {
|
||||||
const term = (sourceControlClients.findByChangeRequestUrl(meta.url) ?? sourceControlClients.get(undefined)).changeRequest.singular;
|
const client = sourceControlClients.findByChangeRequestUrl(meta.url) ?? sourceControlClients.get(undefined);
|
||||||
|
const term = client.changeRequest.singular;
|
||||||
const comment = {
|
const comment = {
|
||||||
id: `pr-reference:${meta.url}`,
|
id: `pr-reference:${meta.url}`,
|
||||||
sectionId: `pull-request:${meta.number}`,
|
sectionId: `pull-request:${meta.number}`,
|
||||||
@@ -189,7 +200,8 @@ export function pullRequestContextRecord(meta: PullRequestContextMetadata): { re
|
|||||||
diff: "",
|
diff: "",
|
||||||
pullRequest: comment.pullRequest,
|
pullRequest: comment.pullRequest,
|
||||||
};
|
};
|
||||||
return { record, replacement: `${formatComposerContextReference({ kind: "review-comment", contextId, label: `#${meta.number}` })} ` };
|
const reference = formatComposerContextReference({ kind: "review-comment", contextId, label: `#${meta.number}` });
|
||||||
|
return { record, replacement: `${reference} ` };
|
||||||
}
|
}
|
||||||
|
|
||||||
function boundedField(value: string): string {
|
function boundedField(value: string): string {
|
||||||
@@ -203,16 +215,21 @@ export function resolveLinkInput(input: {
|
|||||||
readonly project: OrchestrationProjectShell | undefined;
|
readonly project: OrchestrationProjectShell | undefined;
|
||||||
readonly projects: readonly OrchestrationProjectShell[];
|
readonly projects: readonly OrchestrationProjectShell[];
|
||||||
}): { link: ThreadPullRequestKey & { url: string } } | { error: string } | null {
|
}): { link: ThreadPullRequestKey & { url: string } } | { error: string } | null {
|
||||||
const resolved = resolveLinkPullRequestInput({
|
const hasProject = (reference: { host: string; repository: string; url: string }): boolean => {
|
||||||
|
const known = input.projects.some((project) => {
|
||||||
|
const identity = pullRequestLinkProject(project.repositoryIdentity);
|
||||||
|
if (identity === null) return false;
|
||||||
|
const sameHost = identity.host === reference.host;
|
||||||
|
const sameRepository = identity.repository.toLowerCase() === reference.repository.toLowerCase();
|
||||||
|
return sameHost && sameRepository;
|
||||||
|
});
|
||||||
|
return known || sourceControlClients.parseChangeRequestUrl(reference.url) !== null;
|
||||||
|
};
|
||||||
|
return resolveLinkPullRequestInput({
|
||||||
reference: input.reference,
|
reference: input.reference,
|
||||||
project: pullRequestLinkProject(input.project?.repositoryIdentity),
|
project: pullRequestLinkProject(input.project?.repositoryIdentity),
|
||||||
hasProject: (reference) =>
|
hasProject,
|
||||||
input.projects.some((project) => {
|
|
||||||
const identity = pullRequestLinkProject(project.repositoryIdentity);
|
|
||||||
return identity !== null && identity.host === reference.host && identity.repository.toLowerCase() === reference.repository.toLowerCase();
|
|
||||||
}) || sourceControlClients.parseChangeRequestUrl(reference.url) !== null,
|
|
||||||
});
|
});
|
||||||
return resolved;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PullRequestLineKind = "title" | "meta" | "body" | "check" | "review" | "comment" | "guide" | "faint";
|
export type PullRequestLineKind = "title" | "meta" | "body" | "check" | "review" | "comment" | "guide" | "faint";
|
||||||
@@ -223,75 +240,135 @@ export interface PullRequestLine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The PR view's lines: what the web's summary and timeline tabs lead with, in terminal order. */
|
/** The PR view's lines: what the web's summary and timeline tabs lead with, in terminal order. */
|
||||||
export function pullRequestLines(detail: PullRequestDetail, activity: PullRequestActivity | null, guide: PullRequestReviewGuideResult | null, now = Date.now()): PullRequestLine[] {
|
export function pullRequestLines(
|
||||||
|
detail: PullRequestDetail,
|
||||||
|
activity: PullRequestActivity | null,
|
||||||
|
guide: PullRequestReviewGuideResult | null,
|
||||||
|
now = Date.now(),
|
||||||
|
): PullRequestLine[] {
|
||||||
const lines: PullRequestLine[] = [];
|
const lines: PullRequestLine[] = [];
|
||||||
|
pushHeaderLines(lines, detail, now);
|
||||||
|
pushCheckLines(lines, detail);
|
||||||
|
pushCommentLines(lines, activity, now);
|
||||||
|
pushCommitLines(lines, activity);
|
||||||
|
lines.push(...guideLines(guide));
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Title, state and description: the summary the view leads with. */
|
||||||
|
function pushHeaderLines(lines: PullRequestLine[], detail: PullRequestDetail, now: number): void {
|
||||||
const state = detail.state === "open" && detail.isDraft ? "draft" : detail.state;
|
const state = detail.state === "open" && detail.isDraft ? "draft" : detail.state;
|
||||||
|
const fileCount = `${detail.changedFiles} ${detail.changedFiles === 1 ? "file" : "files"}`;
|
||||||
|
const meta = [
|
||||||
|
state,
|
||||||
|
detail.author ? `by ${detail.author.login}` : "",
|
||||||
|
`${detail.headBranch} → ${detail.baseBranch}`,
|
||||||
|
`+${detail.additions} −${detail.deletions} · ${fileCount}`,
|
||||||
|
detail.mergeability !== "unknown" ? detail.mergeability : "",
|
||||||
|
`updated ${ago(detail.updatedAt, now)}`,
|
||||||
|
];
|
||||||
|
|
||||||
lines.push({ kind: "title", text: `#${detail.number} ${detail.title}` });
|
lines.push({ kind: "title", text: `#${detail.number} ${detail.title}` });
|
||||||
lines.push({
|
lines.push({ kind: "meta", text: meta.filter(Boolean).join(" · ") });
|
||||||
kind: "meta",
|
|
||||||
text: [
|
|
||||||
state,
|
|
||||||
detail.author ? `by ${detail.author.login}` : "",
|
|
||||||
`${detail.headBranch} → ${detail.baseBranch}`,
|
|
||||||
`+${detail.additions} −${detail.deletions} · ${detail.changedFiles} ${detail.changedFiles === 1 ? "file" : "files"}`,
|
|
||||||
detail.mergeability !== "unknown" ? detail.mergeability : "",
|
|
||||||
`updated ${ago(detail.updatedAt, now)}`,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" · "),
|
|
||||||
});
|
|
||||||
lines.push({ kind: "faint", text: detail.url });
|
lines.push({ kind: "faint", text: detail.url });
|
||||||
if (detail.labels.length > 0) lines.push({ kind: "meta", text: `Labels: ${detail.labels.map((label) => label.name).join(", ")}` });
|
|
||||||
if (detail.reviewers.length > 0) lines.push({ kind: "meta", text: `Reviewers: ${detail.reviewers.map((actor) => actor.login).join(", ")}` });
|
if (detail.labels.length > 0) {
|
||||||
|
const names = detail.labels.map((label) => label.name);
|
||||||
|
lines.push({ kind: "meta", text: `Labels: ${names.join(", ")}` });
|
||||||
|
}
|
||||||
|
if (detail.reviewers.length > 0) {
|
||||||
|
const logins = detail.reviewers.map((actor) => actor.login);
|
||||||
|
lines.push({ kind: "meta", text: `Reviewers: ${logins.join(", ")}` });
|
||||||
|
}
|
||||||
if (detail.body.trim()) {
|
if (detail.body.trim()) {
|
||||||
lines.push({ kind: "title", text: "Description" });
|
lines.push({ kind: "title", text: "Description" });
|
||||||
for (const text of wrapBody(detail.body)) lines.push({ kind: "body", text });
|
for (const text of wrapBody(detail.body)) lines.push({ kind: "body", text });
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One line per check, or a note that the host reported none. */
|
||||||
|
function pushCheckLines(lines: PullRequestLine[], detail: PullRequestDetail): void {
|
||||||
lines.push({ kind: "title", text: `Checks (${detail.checks.length})` });
|
lines.push({ kind: "title", text: `Checks (${detail.checks.length})` });
|
||||||
if (detail.checks.length === 0) lines.push({ kind: "faint", text: "No checks reported." });
|
if (detail.checks.length === 0) lines.push({ kind: "faint", text: "No checks reported." });
|
||||||
for (const check of detail.checks) {
|
for (const check of detail.checks) {
|
||||||
lines.push({ kind: "check", text: `${checkGlyph(check.status)} ${check.name}${check.description ? ` — ${check.description}` : ""}${check.required ? " (required)" : ""}` });
|
const description = check.description ? ` — ${check.description}` : "";
|
||||||
|
const required = check.required ? " (required)" : "";
|
||||||
|
lines.push({ kind: "check", text: `${checkGlyph(check.status)} ${check.name}${description}${required}` });
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reviews, then the newest comments and review threads, as the timeline tab shows them. */
|
||||||
|
function pushCommentLines(lines: PullRequestLine[], activity: PullRequestActivity | null, now: number): void {
|
||||||
const reviews = latestReviews(activity);
|
const reviews = latestReviews(activity);
|
||||||
lines.push({ kind: "title", text: "Reviews" });
|
lines.push({ kind: "title", text: "Reviews" });
|
||||||
if (reviews.length === 0) lines.push({ kind: "faint", text: "No reviews yet." });
|
if (reviews.length === 0) lines.push({ kind: "faint", text: "No reviews yet." });
|
||||||
for (const review of reviews) lines.push({ kind: "review", text: review });
|
for (const review of reviews) lines.push({ kind: "review", text: review });
|
||||||
|
|
||||||
const comments = activity?.comments ?? [];
|
const comments = activity?.comments ?? [];
|
||||||
lines.push({ kind: "title", text: `Comments (${activity?.commentCount ?? comments.length}${activity?.commentsTruncated ? ", cut short" : ""})` });
|
const commentCount = activity?.commentCount ?? comments.length;
|
||||||
|
const cutShort = activity?.commentsTruncated ? ", cut short" : "";
|
||||||
|
lines.push({ kind: "title", text: `Comments (${commentCount}${cutShort})` });
|
||||||
if (comments.length === 0) lines.push({ kind: "faint", text: "No comments yet." });
|
if (comments.length === 0) lines.push({ kind: "faint", text: "No comments yet." });
|
||||||
for (const comment of comments.slice(-20)) {
|
for (const comment of comments.slice(-20)) {
|
||||||
const who = comment.author?.login ?? "ghost";
|
const who = comment.author?.login ?? "ghost";
|
||||||
const kind = comment.kind === "review" ? `review${comment.reviewState ? ` · ${comment.reviewState}` : ""}` : comment.path ? `on ${comment.path}` : "comment";
|
lines.push({ kind: "comment", text: `${who} · ${commentKindLabel(comment)} · ${ago(comment.createdAt, now)}` });
|
||||||
lines.push({ kind: "comment", text: `${who} · ${kind} · ${ago(comment.createdAt, now)}` });
|
|
||||||
for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` });
|
for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
const threads = activity?.reviewThreads ?? [];
|
const threads = activity?.reviewThreads ?? [];
|
||||||
if (threads.length > 0) {
|
if (threads.length === 0) return;
|
||||||
lines.push({ kind: "title", text: `Review threads (${threads.length})` });
|
lines.push({ kind: "title", text: `Review threads (${threads.length})` });
|
||||||
for (const thread of threads.slice(-20)) {
|
for (const thread of threads.slice(-20)) {
|
||||||
lines.push({ kind: "comment", text: `${thread.isResolved ? "✓ resolved" : "● open"} ${thread.path}${thread.line ? `:${thread.line}` : ""}` });
|
const state = thread.isResolved ? "✓ resolved" : "● open";
|
||||||
for (const comment of thread.comments.slice(-3)) {
|
const atLine = thread.line ? `:${thread.line}` : "";
|
||||||
lines.push({ kind: "comment", text: ` ${comment.author?.login ?? "ghost"} · ${ago(comment.createdAt, now)}` });
|
lines.push({ kind: "comment", text: `${state} ${thread.path}${atLine}` });
|
||||||
for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` });
|
for (const comment of thread.comments.slice(-3)) {
|
||||||
}
|
const who = comment.author?.login ?? "ghost";
|
||||||
|
lines.push({ kind: "comment", text: ` ${who} · ${ago(comment.createdAt, now)}` });
|
||||||
|
for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a comment is, in the timeline's words: a review, a note on a file, or plain talk. */
|
||||||
|
function commentKindLabel(comment: PullRequestActivity["comments"][number]): string {
|
||||||
|
if (comment.kind === "review") {
|
||||||
|
return comment.reviewState ? `review · ${comment.reviewState}` : "review";
|
||||||
|
}
|
||||||
|
if (comment.path) return `on ${comment.path}`;
|
||||||
|
return "comment";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The newest commits, short hash first as in a log. */
|
||||||
|
function pushCommitLines(lines: PullRequestLine[], activity: PullRequestActivity | null): void {
|
||||||
const commits = activity?.commits ?? [];
|
const commits = activity?.commits ?? [];
|
||||||
if (commits.length > 0) {
|
if (commits.length === 0) return;
|
||||||
lines.push({ kind: "title", text: `Commits (${commits.length})` });
|
lines.push({ kind: "title", text: `Commits (${commits.length})` });
|
||||||
for (const commit of commits.slice(-10)) lines.push({ kind: "meta", text: `${commit.oid.slice(0, 7)} ${commit.messageHeadline}` });
|
for (const commit of commits.slice(-10)) {
|
||||||
|
lines.push({ kind: "meta", text: `${commit.oid.slice(0, 7)} ${commit.messageHeadline}` });
|
||||||
}
|
}
|
||||||
lines.push(...guideLines(guide));
|
|
||||||
return lines;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The review guide's lines, or its run state, as the web's guide tab leads with. */
|
/** The review guide's lines, or its run state, as the web's guide tab leads with. */
|
||||||
export function guideLines(guide: PullRequestReviewGuideResult | null): PullRequestLine[] {
|
export function guideLines(guide: PullRequestReviewGuideResult | null): PullRequestLine[] {
|
||||||
if (!guide) return [];
|
if (!guide) return [];
|
||||||
if (guide.run?._tag === "Running") return [{ kind: "title", text: "Review guide" }, { kind: "guide", text: "Writing the review guide…" }];
|
if (guide.run?._tag === "Running") {
|
||||||
if (guide.run?._tag === "Failed" && !guide.guide) return [{ kind: "title", text: "Review guide" }, { kind: "guide", text: `The review guide failed: ${guide.run.detail}` }];
|
return [
|
||||||
|
{ kind: "title", text: "Review guide" },
|
||||||
|
{ kind: "guide", text: "Writing the review guide…" },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (guide.run?._tag === "Failed" && !guide.guide) {
|
||||||
|
return [
|
||||||
|
{ kind: "title", text: "Review guide" },
|
||||||
|
{ kind: "guide", text: `The review guide failed: ${guide.run.detail}` },
|
||||||
|
];
|
||||||
|
}
|
||||||
if (!guide.guide) return [];
|
if (!guide.guide) return [];
|
||||||
const lines: PullRequestLine[] = [{ kind: "title", text: guide.currentHeadSha && guide.guide.headSha !== guide.currentHeadSha ? "Review guide (out of date)" : "Review guide" }];
|
const outOfDate = guide.currentHeadSha && guide.guide.headSha !== guide.currentHeadSha;
|
||||||
|
const lines: PullRequestLine[] = [
|
||||||
|
{ kind: "title", text: outOfDate ? "Review guide (out of date)" : "Review guide" },
|
||||||
|
];
|
||||||
for (const stop of guide.guide.stops) {
|
for (const stop of guide.guide.stops) {
|
||||||
lines.push({ kind: "guide", text: stop.title });
|
lines.push({ kind: "guide", text: stop.title });
|
||||||
for (const text of wrapBody(stop.summary)) lines.push({ kind: "body", text: ` ${text}` });
|
for (const text of wrapBody(stop.summary)) lines.push({ kind: "body", text: ` ${text}` });
|
||||||
@@ -310,9 +387,12 @@ export function latestReviews(activity: PullRequestActivity | null): string[] {
|
|||||||
if (comment.kind !== "review" || !comment.reviewState) continue;
|
if (comment.kind !== "review" || !comment.reviewState) continue;
|
||||||
const who = comment.author?.login ?? "ghost";
|
const who = comment.author?.login ?? "ghost";
|
||||||
const held = latest.get(who);
|
const held = latest.get(who);
|
||||||
if (!held || comment.createdAt.localeCompare(held.at) >= 0) latest.set(who, { at: comment.createdAt, text: `${who}: ${comment.reviewState}` });
|
if (!held || comment.createdAt.localeCompare(held.at) >= 0) {
|
||||||
|
latest.set(who, { at: comment.createdAt, text: `${who}: ${comment.reviewState}` });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return [...latest.values()].sort((a, b) => b.at.localeCompare(a.at)).map((entry) => entry.text);
|
const newestFirst = [...latest.values()].sort((a, b) => b.at.localeCompare(a.at));
|
||||||
|
return newestFirst.map((entry) => entry.text);
|
||||||
}
|
}
|
||||||
|
|
||||||
const ACTION_LABELS: Record<PullRequestAction, string> = {
|
const ACTION_LABELS: Record<PullRequestAction, string> = {
|
||||||
@@ -337,19 +417,32 @@ export const MERGE_METHOD_LABELS: Record<PullRequestMergeMethod, string> = {
|
|||||||
|
|
||||||
/** The runAction actions to offer: what the host can do and the viewer may, for this state. */
|
/** The runAction actions to offer: what the host can do and the viewer may, for this state. */
|
||||||
export function offeredActions(detail: PullRequestDetail): readonly { action: PullRequestAction; label: string }[] {
|
export function offeredActions(detail: PullRequestDetail): readonly { action: PullRequestAction; label: string }[] {
|
||||||
const allowed = new Set(detail.capabilities.actions.filter((action) => detail.viewerPermissions.actions.includes(action)));
|
const allowed = new Set(
|
||||||
|
detail.capabilities.actions.filter((action) => detail.viewerPermissions.actions.includes(action)),
|
||||||
|
);
|
||||||
const byState: readonly PullRequestAction[] =
|
const byState: readonly PullRequestAction[] =
|
||||||
detail.state === "merged"
|
detail.state === "merged"
|
||||||
? ["revert", "delete-branch"]
|
? ["revert", "delete-branch"]
|
||||||
: detail.state === "closed"
|
: detail.state === "closed"
|
||||||
? ["reopen", "delete-branch"]
|
? ["reopen", "delete-branch"]
|
||||||
: ["merge", detail.isDraft ? "ready" : "draft", "close", "update-branch", detail.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge", "approve-workflows"];
|
: [
|
||||||
return byState.filter((action) => allowed.has(action)).map((action) => ({ action, label: ACTION_LABELS[action] }));
|
"merge",
|
||||||
|
detail.isDraft ? "ready" : "draft",
|
||||||
|
"close",
|
||||||
|
"update-branch",
|
||||||
|
detail.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge",
|
||||||
|
"approve-workflows",
|
||||||
|
];
|
||||||
|
const offered = byState.filter((action) => allowed.has(action));
|
||||||
|
return offered.map((action) => ({ action, label: ACTION_LABELS[action] }));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Merge methods to offer, from the host's capabilities as the detail reports them. */
|
/** Merge methods to offer, from the host's capabilities as the detail reports them. */
|
||||||
export function offeredMergeMethods(detail: PullRequestDetail): readonly PullRequestMergeMethod[] {
|
export function offeredMergeMethods(detail: PullRequestDetail): readonly PullRequestMergeMethod[] {
|
||||||
return (["merge", "squash", "rebase"] as const).filter((method) => detail.capabilities.mergeMethods.includes(method) && detail.mergeCapabilities[method]);
|
const methods: readonly PullRequestMergeMethod[] = ["merge", "squash", "rebase"];
|
||||||
|
return methods.filter((method) => {
|
||||||
|
return detail.capabilities.mergeMethods.includes(method) && detail.mergeCapabilities[method];
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkGlyph(status: string): string {
|
function checkGlyph(status: string): string {
|
||||||
@@ -370,7 +463,10 @@ function checkGlyph(status: string): string {
|
|||||||
|
|
||||||
/** Body text as plain lines: blank runs collapse, very long bodies stop. */
|
/** Body text as plain lines: blank runs collapse, very long bodies stop. */
|
||||||
export function wrapBody(body: string, maxLines = 60): string[] {
|
export function wrapBody(body: string, maxLines = 60): string[] {
|
||||||
const lines = body.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd());
|
const lines = body
|
||||||
|
.replace(/\r\n/g, "\n")
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.trimEnd());
|
||||||
const out: string[] = [];
|
const out: string[] = [];
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
if (line === "" && out.at(-1) === "") continue;
|
if (line === "" && out.at(-1) === "") continue;
|
||||||
|
|||||||
+28
-7
@@ -1,14 +1,31 @@
|
|||||||
import { EDITORS, worktreeSetupStageLabel, type EditorId, type TerminalOpenInput, type TerminalSummary, type ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
|
import {
|
||||||
|
EDITORS,
|
||||||
|
worktreeSetupStageLabel,
|
||||||
|
type EditorId,
|
||||||
|
type TerminalOpenInput,
|
||||||
|
type TerminalSummary,
|
||||||
|
type ThreadId,
|
||||||
|
type WorktreeSetupSnapshot,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
import { projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
import { projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||||
import { nextTerminalId } from "@t3tools/shared/terminalLabels";
|
import { nextTerminalId } from "@t3tools/shared/terminalLabels";
|
||||||
|
|
||||||
export { resolveBranchSelectionTarget } from "../../vendor/t3code/apps/web/src/components/BranchToolbar.logic.ts";
|
export { resolveBranchSelectionTarget } from "../../vendor/t3code/apps/web/src/components/BranchToolbar.logic.ts";
|
||||||
|
|
||||||
/** Allocate and launch shells with the web's project environment and terminal numbering. */
|
/** Allocate and launch shells with the web's project environment and terminal numbering. */
|
||||||
export function newTerminalInput(threadId: ThreadId, projectRoot: string, worktreePath: string | null, terminals: readonly TerminalSummary[], metadataLive: boolean): TerminalOpenInput {
|
export function newTerminalInput(
|
||||||
|
threadId: ThreadId,
|
||||||
|
projectRoot: string,
|
||||||
|
worktreePath: string | null,
|
||||||
|
terminals: readonly TerminalSummary[],
|
||||||
|
metadataLive: boolean,
|
||||||
|
): TerminalOpenInput {
|
||||||
|
const existingIds = terminals.map((terminal) => terminal.terminalId);
|
||||||
|
// Without live metadata the next number is unknowable, so fall back to a fresh id.
|
||||||
|
const terminalId = nextTerminalId(existingIds, metadataLive ? undefined : crypto.randomUUID());
|
||||||
return {
|
return {
|
||||||
threadId,
|
threadId,
|
||||||
terminalId: nextTerminalId(terminals.map((terminal) => terminal.terminalId), metadataLive ? undefined : crypto.randomUUID()),
|
terminalId,
|
||||||
cwd: worktreePath ?? projectRoot,
|
cwd: worktreePath ?? projectRoot,
|
||||||
worktreePath,
|
worktreePath,
|
||||||
env: projectScriptRuntimeEnv({ project: { cwd: projectRoot }, worktreePath }),
|
env: projectScriptRuntimeEnv({ project: { cwd: projectRoot }, worktreePath }),
|
||||||
@@ -23,11 +40,15 @@ export function preferredEditor(available: readonly EditorId[]): EditorId | null
|
|||||||
/** Show the active preparation stage without hiding failures after setup stops. */
|
/** Show the active preparation stage without hiding failures after setup stops. */
|
||||||
export function worktreeSetupNote(snapshot: WorktreeSetupSnapshot | null): string | null {
|
export function worktreeSetupNote(snapshot: WorktreeSetupSnapshot | null): string | null {
|
||||||
if (!snapshot || snapshot.phase === "done") return null;
|
if (!snapshot || snapshot.phase === "done") return null;
|
||||||
const stage = snapshot.stages.find((stage) => stage.status === "running") ?? snapshot.stages.find((stage) => stage.status === "failed");
|
const running = snapshot.stages.find((stage) => stage.status === "running");
|
||||||
return [
|
const failed = snapshot.stages.find((stage) => stage.status === "failed");
|
||||||
|
const stage = running ?? failed;
|
||||||
|
const percent = stage?.percent !== null && stage?.percent !== undefined ? `${stage.percent}%` : null;
|
||||||
|
const parts = [
|
||||||
`Worktree setup: ${snapshot.phase}`,
|
`Worktree setup: ${snapshot.phase}`,
|
||||||
stage ? worktreeSetupStageLabel(stage.id) : null,
|
stage ? worktreeSetupStageLabel(stage.id) : null,
|
||||||
stage?.percent !== null && stage?.percent !== undefined ? `${stage.percent}%` : null,
|
percent,
|
||||||
snapshot.error ?? stage?.detail,
|
snapshot.error ?? stage?.detail,
|
||||||
].filter(Boolean).join(" · ");
|
];
|
||||||
|
return parts.filter(Boolean).join(" · ");
|
||||||
}
|
}
|
||||||
@@ -40,12 +40,27 @@ export function useAttachments(deps: {
|
|||||||
const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map());
|
const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map());
|
||||||
const pending = byComposer.get(composerKey) ?? [];
|
const pending = byComposer.get(composerKey) ?? [];
|
||||||
|
|
||||||
const add = (attachment: ChatAttachment) =>
|
// Lists are replaced whole, per composer, so switching threads never mixes them.
|
||||||
setByComposer((previous) => new Map(previous).set(composerKey, [...(previous.get(composerKey) ?? []), attachment]));
|
const setPending = (attachments: readonly ChatAttachment[]) => {
|
||||||
|
setByComposer((previous) => new Map(previous).set(composerKey, attachments));
|
||||||
|
};
|
||||||
|
|
||||||
|
const add = (attachment: ChatAttachment) => {
|
||||||
|
setByComposer((previous) => {
|
||||||
|
const current = previous.get(composerKey) ?? [];
|
||||||
|
return new Map(previous).set(composerKey, [...current, attachment]);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const upload = (name: string, bytes: Uint8Array, mimeType?: string) => {
|
const upload = (name: string, bytes: Uint8Array, mimeType?: string) => {
|
||||||
if (maxFileBytes === undefined) return say("Still loading the server's attachment limits.", true);
|
if (maxFileBytes === undefined) return say("Still loading the server's attachment limits.", true);
|
||||||
const checked = checkAttachment({ name, sizeBytes: bytes.length, ...(mimeType ? { mimeType } : {}), pending: byComposer.get(composerKey) ?? [], maxFileBytes });
|
const checked = checkAttachment({
|
||||||
|
name,
|
||||||
|
sizeBytes: bytes.length,
|
||||||
|
...(mimeType ? { mimeType } : {}),
|
||||||
|
pending: byComposer.get(composerKey) ?? [],
|
||||||
|
maxFileBytes,
|
||||||
|
});
|
||||||
if (!checked.ok) return say(checked.error, true);
|
if (!checked.ok) return say(checked.error, true);
|
||||||
say(`Uploading ${checked.upload.name}…`);
|
say(`Uploading ${checked.upload.name}…`);
|
||||||
session.uploadAttachment(checked.upload, bytes).then(
|
session.uploadAttachment(checked.upload, bytes).then(
|
||||||
@@ -91,7 +106,11 @@ export function useAttachments(deps: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const remove = (attachment: ChatAttachment) => {
|
const remove = (attachment: ChatAttachment) => {
|
||||||
setByComposer((previous) => new Map(previous).set(composerKey, (previous.get(composerKey) ?? []).filter((candidate) => candidate.id !== attachment.id)));
|
setByComposer((previous) => {
|
||||||
|
const current = previous.get(composerKey) ?? [];
|
||||||
|
const kept = current.filter((candidate) => candidate.id !== attachment.id);
|
||||||
|
return new Map(previous).set(composerKey, kept);
|
||||||
|
});
|
||||||
session.deleteAttachment(attachment.id).then(
|
session.deleteAttachment(attachment.id).then(
|
||||||
() => say(`Removed ${attachment.name}`),
|
() => say(`Removed ${attachment.name}`),
|
||||||
(error) => say(`Removed ${attachment.name}; deleting the upload failed: ${messageOf(error)}`, true),
|
(error) => say(`Removed ${attachment.name}; deleting the upload failed: ${messageOf(error)}`, true),
|
||||||
@@ -117,7 +136,7 @@ export function useAttachments(deps: {
|
|||||||
remove,
|
remove,
|
||||||
take: () => {
|
take: () => {
|
||||||
const taken = byComposer.get(composerKey) ?? [];
|
const taken = byComposer.get(composerKey) ?? [];
|
||||||
if (taken.length > 0) setByComposer((previous) => new Map(previous).set(composerKey, []));
|
if (taken.length > 0) setPending([]);
|
||||||
return taken;
|
return taken;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,17 +10,37 @@ export function usePaletteSearch(session: T3Session, snapshot: OrchestrationV2Sh
|
|||||||
const before = snapshot?.olderSettled?.before;
|
const before = snapshot?.olderSettled?.before;
|
||||||
const [result, setResult] = useState<{ query: string; value: OrchestrationV2SearchThreadsResult } | null>(null);
|
const [result, setResult] = useState<{ query: string; value: OrchestrationV2SearchThreadsResult } | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setError(null);
|
setError(null);
|
||||||
if (!normalized) return;
|
if (!normalized) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
session.searchThreads({ query: normalized, ...(before ? { olderSettledBefore: before, ...(messageSearchTokens(normalized).long.length ? {} : { titlesOnly: true }) } : {}) }).then(
|
// Beyond the live shelf a query with no searchable words can only match titles.
|
||||||
(value) => { if (!cancelled) setResult({ query: normalized, value }); },
|
const titlesOnly = before ? messageSearchTokens(normalized).long.length === 0 : false;
|
||||||
(error) => { if (!cancelled) setError(`Could not search messages: ${String(error)}`); },
|
const search = {
|
||||||
|
query: normalized,
|
||||||
|
...(before ? { olderSettledBefore: before, ...(titlesOnly ? { titlesOnly: true } : {}) } : {}),
|
||||||
|
};
|
||||||
|
session.searchThreads(search).then(
|
||||||
|
(value) => {
|
||||||
|
if (!cancelled) setResult({ query: normalized, value });
|
||||||
|
},
|
||||||
|
(searchError) => {
|
||||||
|
if (!cancelled) setError(`Could not search messages: ${String(searchError)}`);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}, 120);
|
}, 120);
|
||||||
return () => { cancelled = true; clearTimeout(timer); };
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
}, [session, normalized, before]);
|
}, [session, normalized, before]);
|
||||||
return { result: normalized && result?.query === normalized ? result.value : null, pending: normalized !== null && result?.query !== normalized && !error, error };
|
|
||||||
|
const fresh = normalized !== null && result?.query === normalized;
|
||||||
|
return {
|
||||||
|
result: fresh ? result.value : null,
|
||||||
|
pending: normalized !== null && result?.query !== normalized && !error,
|
||||||
|
error,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+95
-33
@@ -93,7 +93,10 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
const load = async (link: ThreadPullRequestLink, reference: PullRequestRef) => {
|
const load = async (link: ThreadPullRequestLink, reference: PullRequestRef) => {
|
||||||
const token = { link, reference };
|
const token = { link, reference };
|
||||||
try {
|
try {
|
||||||
const [detail, activity] = await Promise.all([session.pullRequestDetail(reference), session.pullRequestActivity(reference)]);
|
const [detail, activity] = await Promise.all([
|
||||||
|
session.pullRequestDetail(reference),
|
||||||
|
session.pullRequestActivity(reference),
|
||||||
|
]);
|
||||||
let merged = detail;
|
let merged = detail;
|
||||||
if (capabilities?.pullRequestChecks === true) {
|
if (capabilities?.pullRequestChecks === true) {
|
||||||
const checks = await session.pullRequestChecks(reference).catch(() => null);
|
const checks = await session.pullRequestChecks(reference).catch(() => null);
|
||||||
@@ -169,7 +172,10 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
|
|
||||||
const comment = () => {
|
const comment = () => {
|
||||||
const current = loadedRef.current;
|
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 canComment = current?.detail?.capabilities.comment && current.detail.viewerPermissions.comment;
|
||||||
|
if (!current?.detail || !canComment) {
|
||||||
|
return deps.say("Commenting is not available on this pull request.", true);
|
||||||
|
}
|
||||||
const edited = editInEditor(deps.renderer, "");
|
const edited = editInEditor(deps.renderer, "");
|
||||||
if (edited === null) return deps.say("The editor exited with an error; nothing was posted.", true);
|
if (edited === null) return deps.say("The editor exited with an error; nothing was posted.", true);
|
||||||
const body = edited.trim();
|
const body = edited.trim();
|
||||||
@@ -191,8 +197,39 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
const current = loadedRef.current;
|
const current = loadedRef.current;
|
||||||
const detail = current?.detail;
|
const detail = current?.detail;
|
||||||
if (!current || !detail) return;
|
if (!current || !detail) return;
|
||||||
const offered = VERDICTS.filter((verdict) => detail.capabilities.review.verdicts.includes(verdict.value) && detail.viewerPermissions.verdicts.includes(verdict.value));
|
const offered = VERDICTS.filter((verdict) => {
|
||||||
|
const hostOffers = detail.capabilities.review.verdicts.includes(verdict.value);
|
||||||
|
const viewerMay = detail.viewerPermissions.verdicts.includes(verdict.value);
|
||||||
|
return hostOffers && viewerMay;
|
||||||
|
});
|
||||||
if (offered.length === 0) return deps.say("Reviewing is not available on this pull request.", true);
|
if (offered.length === 0) return deps.say("Reviewing is not available on this pull request.", true);
|
||||||
|
|
||||||
|
const writeReview = (verdict: (typeof VERDICTS)[number]) => {
|
||||||
|
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");
|
||||||
|
// Requesting changes can demand a summary; approving never does.
|
||||||
|
const needsSummary = verdict.value === "request-changes" && summaryRequired;
|
||||||
|
const canSubmit = needsSummary ? body.trim().length > 0 : verdict.value === "approve" || body.trim().length > 0;
|
||||||
|
if (!canSubmit) {
|
||||||
|
const message = needsSummary
|
||||||
|
? "Summarize your review (required to request changes)."
|
||||||
|
: "Summarize your review or approve without one.";
|
||||||
|
return deps.say(message, 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();
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
deps.openPicker({
|
deps.openPicker({
|
||||||
placeholder: "Review verdict",
|
placeholder: "Review verdict",
|
||||||
groups: [
|
groups: [
|
||||||
@@ -201,25 +238,7 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
items: offered.map((verdict) => ({
|
items: offered.map((verdict) => ({
|
||||||
id: `verdict:${verdict.value}`,
|
id: `verdict:${verdict.value}`,
|
||||||
title: verdict.label,
|
title: verdict.label,
|
||||||
run: () => {
|
run: () => writeReview(verdict),
|
||||||
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();
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -307,7 +326,8 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
|
|
||||||
const setWatching = (link: ThreadPullRequestLink, watching: boolean) => {
|
const setWatching = (link: ThreadPullRequestLink, watching: boolean) => {
|
||||||
if (!threadShell) return;
|
if (!threadShell) return;
|
||||||
deps.run(watching ? "Watching for changes" : "Stopped watching", () => session.watchPullRequest(threadShell.id, linkKey(link), watching));
|
const label = watching ? "Watching for changes" : "Stopped watching";
|
||||||
|
deps.run(label, () => session.watchPullRequest(threadShell.id, linkKey(link), watching));
|
||||||
};
|
};
|
||||||
|
|
||||||
const linkDialog = () => {
|
const linkDialog = () => {
|
||||||
@@ -324,8 +344,15 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
const resolved = resolveLinkInput({ reference: text, project, projects: deps.projects });
|
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 (resolved === null) return deps.say("Use a pull request URL, 123, or #123.", true);
|
||||||
if ("error" in resolved) return deps.say(resolved.error, true);
|
if ("error" in resolved) return deps.say(resolved.error, true);
|
||||||
const mutation = planThreadPullRequestMutation({ capabilities, threadId: id, reference: resolved.link, linked: true });
|
const mutation = planThreadPullRequestMutation({
|
||||||
if (mutation === null || mutation.type !== "thread.pull-request.link") return deps.say("This environment does not support linking this pull request.", true);
|
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;
|
const { threadId: _threadId, source: _source, url, ...key } = mutation.input;
|
||||||
deps.run(`Linked #${key.number}`, () => session.linkPullRequest(id, key, url));
|
deps.run(`Linked #${key.number}`, () => session.linkPullRequest(id, key, url));
|
||||||
},
|
},
|
||||||
@@ -377,7 +404,9 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
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 watchingCurrent = loaded
|
||||||
|
? links.some((link) => isSameLink(link, loaded.link) && link.watch !== undefined)
|
||||||
|
: false;
|
||||||
|
|
||||||
const view: PullRequestViewState | null = loaded
|
const view: PullRequestViewState | null = loaded
|
||||||
? {
|
? {
|
||||||
@@ -442,7 +471,13 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
}
|
}
|
||||||
if (threadShell) {
|
if (threadShell) {
|
||||||
for (const link of links) {
|
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) });
|
const verb = link.source === "stack" ? "Dismiss" : "Unlink";
|
||||||
|
commands.push({
|
||||||
|
id: `unlink-pull-request:${link.number}`,
|
||||||
|
title: `${verb} pull request #${link.number} from thread`,
|
||||||
|
keywords: ["unlink", "pull request", "pr"],
|
||||||
|
run: () => unlink(link),
|
||||||
|
});
|
||||||
if (supportsWatch && (link.snapshot === null || link.snapshot.state === "open")) {
|
if (supportsWatch && (link.snapshot === null || link.snapshot.state === "open")) {
|
||||||
const watching = link.watch !== undefined;
|
const watching = link.watch !== undefined;
|
||||||
commands.push({
|
commands.push({
|
||||||
@@ -467,12 +502,19 @@ export function usePullRequests(deps: PullRequestDeps) {
|
|||||||
return { view, isOpen: loaded !== null, open, close, handleKey, commands };
|
return { view, isOpen: loaded !== null, open, close, handleKey, commands };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Two links name the same pull request when host, repository and number all match. */
|
||||||
|
function isSameLink(left: ThreadPullRequestLink, right: ThreadPullRequestLink): boolean {
|
||||||
|
return left.host === right.host && left.repository === right.repository && left.number === right.number;
|
||||||
|
}
|
||||||
|
|
||||||
/** The project's configured merge method, as the web pre-selects it. */
|
/** The project's configured merge method, as the web pre-selects it. */
|
||||||
function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) {
|
function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) {
|
||||||
return resolveProjectSettings(config.settings, projectId).settings.pullRequestMergeMethod ?? undefined;
|
return resolveProjectSettings(config.settings, projectId).settings.pullRequestMergeMethod ?? undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
function messageOf(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The composer's `#` search, debounced as the web's (180ms): the recent list (host-searched for
|
* The composer's `#` search, debounced as the web's (180ms): the recent list (host-searched for
|
||||||
@@ -498,16 +540,36 @@ export function useComposerPullRequests(input: {
|
|||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const list = await session.pullRequestsList({ state: "all", projectId, limit: COMPOSER_PULL_REQUEST_LIST_LIMIT, ...(textQuery === null ? {} : { query: textQuery }) });
|
const list = await session.pullRequestsList({
|
||||||
|
state: "all",
|
||||||
|
projectId,
|
||||||
|
limit: COMPOSER_PULL_REQUEST_LIST_LIMIT,
|
||||||
|
...(textQuery === null ? {} : { query: textQuery }),
|
||||||
|
});
|
||||||
const number = exactPullRequestNumber(query);
|
const number = exactPullRequestNumber(query);
|
||||||
const hasExact =
|
const hasExact =
|
||||||
number !== null &&
|
number !== null &&
|
||||||
list.entries.some((entry) => entry.projectId === projectId && entry.repository.trim().toLowerCase() === repository.trim().toLowerCase() && entry.number === number);
|
list.entries.some((entry) => {
|
||||||
const exact = number !== null && !hasExact ? await session.pullRequestDetail({ projectId, repository, number }).catch(() => null) : null;
|
const sameRepository = entry.repository.trim().toLowerCase() === repository.trim().toLowerCase();
|
||||||
|
return entry.projectId === projectId && sameRepository && entry.number === number;
|
||||||
|
});
|
||||||
|
// A typed number names one pull request exactly, so look it up when the list lacks it.
|
||||||
|
const exact =
|
||||||
|
number !== null && !hasExact
|
||||||
|
? await session.pullRequestDetail({ projectId, repository, number }).catch(() => null)
|
||||||
|
: null;
|
||||||
const exactDetail = exact?.number === number ? exact : null;
|
const exactDetail = exact?.number === number ? exact : null;
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const matches = rankComposerPullRequests({ result: list, exact: exactDetail, links: linksRef.current, projectId, repository, query });
|
const matches = rankComposerPullRequests({
|
||||||
setResult({ key, items: pullRequestItems(matches, repository), failed: list.errors.some((error) => error.projectId === projectId) });
|
result: list,
|
||||||
|
exact: exactDetail,
|
||||||
|
links: linksRef.current,
|
||||||
|
projectId,
|
||||||
|
repository,
|
||||||
|
query,
|
||||||
|
});
|
||||||
|
const failed = list.errors.some((error) => error.projectId === projectId);
|
||||||
|
setResult({ key, items: pullRequestItems(matches, repository), failed });
|
||||||
} catch {
|
} catch {
|
||||||
if (!cancelled) setResult({ key, items: [], failed: true });
|
if (!cancelled) setResult({ key, items: [], failed: true });
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-12
@@ -11,45 +11,81 @@ export function useThreadFind(session: T3Session, id: ThreadId | undefined, thre
|
|||||||
const [index, setIndex] = useState(0);
|
const [index, setIndex] = useState(0);
|
||||||
const [result, setResult] = useState<{ key: string; value: OrchestrationV2SearchThreadResult } | null>(null);
|
const [result, setResult] = useState<{ key: string; value: OrchestrationV2SearchThreadResult } | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const normalized = query.trim().slice(0, 200).trim();
|
const normalized = query.trim().slice(0, 200).trim();
|
||||||
const key = open && id && normalized ? JSON.stringify([id, normalized, index]) : null;
|
const key = open && id && normalized ? JSON.stringify([id, normalized, index]) : null;
|
||||||
|
// A new tail entry can hold a new match, so it re-runs the search below.
|
||||||
const latestText = thread?.projection?.visibleTurnItems.at(-1);
|
const latestText = thread?.projection?.visibleTurnItems.at(-1);
|
||||||
useEffect(() => { setQuery(""); setIndex(0); }, [id]);
|
|
||||||
|
useEffect(() => {
|
||||||
|
setQuery("");
|
||||||
|
setIndex(0);
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setError(null);
|
setError(null);
|
||||||
if (!key || !id) return;
|
if (!key || !id) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
session.searchThread({ threadId: id, query: normalized, index }).then(
|
session.searchThread({ threadId: id, query: normalized, index }).then(
|
||||||
(value) => { if (!cancelled) setResult({ key, value }); },
|
(value) => {
|
||||||
(error) => { if (!cancelled) setError(String(error)); },
|
if (!cancelled) setResult({ key, value });
|
||||||
|
},
|
||||||
|
(searchError) => {
|
||||||
|
if (!cancelled) setError(String(searchError));
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}, 100);
|
}, 100);
|
||||||
return () => { cancelled = true; clearTimeout(timer); };
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
}, [session, id, key, latestText]);
|
}, [session, id, key, latestText]);
|
||||||
|
|
||||||
const data = key && result?.key === key ? result.value : null;
|
const data = key && result?.key === key ? result.value : null;
|
||||||
const match = data?.match ?? null;
|
const match = data?.match ?? null;
|
||||||
|
|
||||||
|
// Page in older history until the selected match is on screen, once per cursor.
|
||||||
const requested = useRef<string | null>(null);
|
const requested = useRef<string | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id || !match || !timeline || timeline.rows.some((row) => row.id === match.entryId)) return;
|
if (!id || !match || !timeline) return;
|
||||||
|
if (timeline.rows.some((row) => row.id === match.entryId)) return;
|
||||||
const history = thread?.history;
|
const history = thread?.history;
|
||||||
if (!history?.hasMore || history.loading || history.error) return;
|
if (!history?.hasMore || history.loading || history.error) return;
|
||||||
const request = `${key}:${history.cursor}`;
|
const request = `${key}:${history.cursor}`;
|
||||||
if (requested.current === request) return;
|
if (requested.current === request) return;
|
||||||
requested.current = request;
|
requested.current = request;
|
||||||
session.loadEarlier(id).catch((error) => setError(String(error)));
|
session.loadEarlier(id).catch((loadError) => setError(String(loadError)));
|
||||||
}, [session, id, match, timeline, thread?.history, key]);
|
}, [session, id, match, timeline, thread?.history, key]);
|
||||||
|
|
||||||
const step = (delta: number) => {
|
const step = (delta: number) => {
|
||||||
if (data) setIndex(stepThreadFindIndex(data.activeIndex, data.totalMatches, delta));
|
if (data) setIndex(stepThreadFindIndex(data.activeIndex, data.totalMatches, delta));
|
||||||
};
|
};
|
||||||
const handleKey = (key: KeyEvent): boolean => {
|
|
||||||
|
const handleKey = (keyEvent: KeyEvent): boolean => {
|
||||||
if (!open) return false;
|
if (!open) return false;
|
||||||
if (key.name === "escape") return true;
|
if (keyEvent.name === "escape") return true;
|
||||||
else if (key.name === "return") step(key.shift ? -1 : 1);
|
if (keyEvent.name === "return") step(keyEvent.shift ? -1 : 1);
|
||||||
else if (key.ctrl && key.name === "n") step(1);
|
else if (keyEvent.ctrl && keyEvent.name === "n") step(1);
|
||||||
else if (key.ctrl && key.name === "p") step(-1);
|
else if (keyEvent.ctrl && keyEvent.name === "p") step(-1);
|
||||||
else return false;
|
else return false;
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
return { open, query, onQuery: (value: string) => { setQuery(value); setIndex(0); }, data, match, error, pending: key !== null && data === null && !error, step, handleKey };
|
|
||||||
|
const onQuery = (value: string) => {
|
||||||
|
setQuery(value);
|
||||||
|
setIndex(0);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
open,
|
||||||
|
query,
|
||||||
|
onQuery,
|
||||||
|
data,
|
||||||
|
match,
|
||||||
|
error,
|
||||||
|
pending: key !== null && data === null && !error,
|
||||||
|
step,
|
||||||
|
handleKey,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+141
-35
@@ -1,5 +1,11 @@
|
|||||||
import type { KeyEvent } from "@opentui/core";
|
import type { KeyEvent } from "@opentui/core";
|
||||||
import type { OrchestrationV2ArchivedShellSnapshot, OrchestrationV2OlderSettledCursor, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
|
import type {
|
||||||
|
OrchestrationV2ArchivedShellSnapshot,
|
||||||
|
OrchestrationV2OlderSettledCursor,
|
||||||
|
OrchestrationV2ShellSnapshot,
|
||||||
|
OrchestrationV2ThreadShell,
|
||||||
|
ThreadId,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
import { ThreadId as ThreadIdSchema } from "@t3tools/contracts";
|
import { ThreadId as ThreadIdSchema } from "@t3tools/contracts";
|
||||||
import * as DateTime from "effect/DateTime";
|
import * as DateTime from "effect/DateTime";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
@@ -10,6 +16,9 @@ import type { PaletteCommand } from "../model/palette.ts";
|
|||||||
|
|
||||||
type Command = PaletteCommand & { readonly run: () => void };
|
type Command = PaletteCommand & { readonly run: () => void };
|
||||||
|
|
||||||
|
/** How many settled threads one "show more" step reveals, as the web's shelf pages. */
|
||||||
|
const SETTLED_PAGE_SIZE = 30;
|
||||||
|
|
||||||
/** The sidebar's fetched shelves live separately from its live shell. */
|
/** The sidebar's fetched shelves live separately from its live shell. */
|
||||||
export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string) {
|
export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string) {
|
||||||
const [archived, setArchived] = useState(false);
|
const [archived, setArchived] = useState(false);
|
||||||
@@ -17,79 +26,176 @@ export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2Sh
|
|||||||
const [older, setOlder] = useState<readonly OrchestrationV2ThreadShell[]>([]);
|
const [older, setOlder] = useState<readonly OrchestrationV2ThreadShell[]>([]);
|
||||||
const [cursor, setCursor] = useState<OrchestrationV2OlderSettledCursor | null>(null);
|
const [cursor, setCursor] = useState<OrchestrationV2OlderSettledCursor | null>(null);
|
||||||
const [end, setEnd] = useState(false);
|
const [end, setEnd] = useState(false);
|
||||||
const [limit, setLimit] = useState(30);
|
const [limit, setLimit] = useState(SETTLED_PAGE_SIZE);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// A new live cut-off makes every fetched older page stale, so paging starts over.
|
||||||
const cut = snapshot?.olderSettled?.before;
|
const cut = snapshot?.olderSettled?.before;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setOlder([]);
|
setOlder([]);
|
||||||
setCursor(null);
|
setCursor(null);
|
||||||
setEnd(false);
|
setEnd(false);
|
||||||
setLimit(30);
|
setLimit(SETTLED_PAGE_SIZE);
|
||||||
}, [cut]);
|
}, [cut]);
|
||||||
|
|
||||||
const refreshArchive = () => session.archivedThreads().then(setArchive);
|
const refreshArchive = () => session.archivedThreads().then(setArchive);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!archived) { setLoading(false); return; }
|
if (!archived) {
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
session.archivedThreads().then(
|
session.archivedThreads().then(
|
||||||
(value) => { if (!cancelled) { setArchive(value); setLoading(false); } },
|
(value) => {
|
||||||
(error) => { if (!cancelled) { setError(String(error)); setLoading(false); } },
|
if (cancelled) return;
|
||||||
|
setArchive(value);
|
||||||
|
setLoading(false);
|
||||||
|
},
|
||||||
|
(archiveError) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setError(String(archiveError));
|
||||||
|
setLoading(false);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
return () => { cancelled = true; };
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
}, [session, archived]);
|
}, [session, archived]);
|
||||||
|
|
||||||
const merged = useMemo(() => mergeThreadShells(snapshot, older), [snapshot, older]);
|
const merged = useMemo(() => mergeThreadShells(snapshot, older), [snapshot, older]);
|
||||||
const listSnapshot = archived && snapshot ? { ...snapshot, projects: archive?.projects ?? snapshot.projects, threads: archive?.threads ?? [] } : merged;
|
|
||||||
const allRows = useMemo(() => threadRows(listSnapshot, { query, archived, settledLimit: limit }), [listSnapshot, query, archived, limit]);
|
// The archive keeps the live snapshot's shape so threadRows reads both the same way.
|
||||||
const totalSettled = useMemo(() => threadRows(merged, { query, settledLimit: Infinity }).filter((row) => row.section === "settled").length, [merged, query]);
|
const listSnapshot =
|
||||||
const hasOlder = !archived && (totalSettled > limit || (!end && (snapshot?.olderSettled?.counts.some((count) => count.count > 0) ?? false)));
|
archived && snapshot
|
||||||
|
? { ...snapshot, projects: archive?.projects ?? snapshot.projects, threads: archive?.threads ?? [] }
|
||||||
|
: merged;
|
||||||
|
|
||||||
|
const allRows = useMemo(
|
||||||
|
() => threadRows(listSnapshot, { query, archived, settledLimit: limit }),
|
||||||
|
[listSnapshot, query, archived, limit],
|
||||||
|
);
|
||||||
|
|
||||||
|
const totalSettled = useMemo(() => {
|
||||||
|
const settled = threadRows(merged, { query, settledLimit: Infinity });
|
||||||
|
return settled.filter((row) => row.section === "settled").length;
|
||||||
|
}, [merged, query]);
|
||||||
|
|
||||||
|
const serverHasOlder = snapshot?.olderSettled?.counts.some((count) => count.count > 0) ?? false;
|
||||||
|
const hasOlder = !archived && (totalSettled > limit || (!end && serverHasOlder));
|
||||||
|
|
||||||
const loadOlder = async () => {
|
const loadOlder = async () => {
|
||||||
if (loading) return;
|
if (loading) return;
|
||||||
setLimit((value) => value + 30);
|
setLimit((value) => value + SETTLED_PAGE_SIZE);
|
||||||
|
// Rows already fetched fill the wider limit without another request.
|
||||||
if (!cut || end || totalSettled > limit) return;
|
if (!cut || end || totalSettled > limit) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const page = await session.olderSettledThreads({ before: cursor ?? { settledAt: cut }, limit: 30 });
|
const page = await session.olderSettledThreads({ before: cursor ?? { settledAt: cut }, limit: SETTLED_PAGE_SIZE });
|
||||||
setOlder((previous) => [...previous, ...page.threads]);
|
setOlder((previous) => [...previous, ...page.threads]);
|
||||||
const last = page.threads.at(-1);
|
const last = page.threads.at(-1);
|
||||||
if (last?.settledAt) setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id });
|
if (last?.settledAt) {
|
||||||
setEnd(page.threads.length < 30);
|
setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id });
|
||||||
} catch (error) {
|
}
|
||||||
setError(String(error));
|
setEnd(page.threads.length < SETTLED_PAGE_SIZE);
|
||||||
|
} catch (loadError) {
|
||||||
|
setError(String(loadError));
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const toggle = () => { setError(null); setArchived((value) => !value); };
|
|
||||||
|
const toggle = () => {
|
||||||
|
setError(null);
|
||||||
|
setArchived((value) => !value);
|
||||||
|
};
|
||||||
|
|
||||||
const unarchive = async (id: ThreadId) => {
|
const unarchive = async (id: ThreadId) => {
|
||||||
await session.unarchiveThread(id);
|
await session.unarchiveThread(id);
|
||||||
await refreshArchive();
|
await refreshArchive();
|
||||||
};
|
};
|
||||||
|
|
||||||
const reorder = async (id: ThreadId, delta: 1 | -1) => {
|
const reorder = async (id: ThreadId, delta: 1 | -1) => {
|
||||||
const row = allRows.find((row) => row.thread.id === id);
|
const row = allRows.find((candidate) => candidate.thread.id === id);
|
||||||
// The web's Working shelf makes Active chronological, not manually reorderable.
|
// The web's Working shelf makes Active chronological, not manually reorderable.
|
||||||
if (row?.section === "active") { setError("Active threads are ordered by return time, as in T3 Code's Working shelf."); return; }
|
if (row?.section === "active") {
|
||||||
const plan = threadReorder(allRows, id, delta, threadRows(listSnapshot, { archived, settledLimit: limit }));
|
setError("Active threads are ordered by return time, as in T3 Code's Working shelf.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const unfilteredRows = threadRows(listSnapshot, { archived, settledLimit: limit });
|
||||||
|
const plan = threadReorder(allRows, id, delta, unfilteredRows);
|
||||||
if (!plan || archived) return;
|
if (!plan || archived) return;
|
||||||
try {
|
try {
|
||||||
for (const assignment of plan.assignments) await session.reorderThread(ThreadIdSchema.make(assignment.id), plan.section, assignment.orderKey);
|
for (const assignment of plan.assignments) {
|
||||||
} catch (error) { setError(String(error)); }
|
await session.reorderThread(ThreadIdSchema.make(assignment.id), plan.section, assignment.orderKey);
|
||||||
|
}
|
||||||
|
} catch (reorderError) {
|
||||||
|
setError(String(reorderError));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const commands = (id: ThreadId | undefined): Command[] => [
|
|
||||||
{ id: "archived", title: archived ? "Show active threads" : "Show archived threads", shortcut: "A", keywords: ["archive", "history", "restore"], run: toggle },
|
const commands = (id: ThreadId | undefined): Command[] => {
|
||||||
...(hasOlder ? [{ id: "older-settled", title: "Show more settled threads", keywords: ["older", "history", "load"], run: () => void loadOlder() }] : []),
|
const list: Command[] = [
|
||||||
...(id && archive?.threads.some((thread) => thread.id === id) ? [{ id: "unarchive", title: "Unarchive thread", keywords: ["restore", "archived"], run: () => void unarchive(id).catch((error) => setError(String(error))) }] : []),
|
{
|
||||||
...(id && allRows.some((row) => row.thread.id === id && row.section === "pinned") ? [
|
id: "archived",
|
||||||
{ id: "reorder-up", title: "Move pinned thread up", shortcut: "K", keywords: ["reorder", "sort"], run: () => void reorder(id, -1) },
|
title: archived ? "Show active threads" : "Show archived threads",
|
||||||
{ id: "reorder-down", title: "Move pinned thread down", shortcut: "J", keywords: ["reorder", "sort"], run: () => void reorder(id, 1) },
|
shortcut: "A",
|
||||||
] : []),
|
keywords: ["archive", "history", "restore"],
|
||||||
];
|
run: toggle,
|
||||||
const key = (key: KeyEvent, id: ThreadId | undefined): boolean => {
|
},
|
||||||
if (key.name === "a" && key.shift) return toggle(), true;
|
];
|
||||||
if (id && key.shift && (key.name === "j" || key.name === "k")) return void reorder(id, key.name === "j" ? 1 : -1), true;
|
if (hasOlder) {
|
||||||
|
list.push({
|
||||||
|
id: "older-settled",
|
||||||
|
title: "Show more settled threads",
|
||||||
|
keywords: ["older", "history", "load"],
|
||||||
|
run: () => void loadOlder(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (id && archive?.threads.some((thread) => thread.id === id)) {
|
||||||
|
list.push({
|
||||||
|
id: "unarchive",
|
||||||
|
title: "Unarchive thread",
|
||||||
|
keywords: ["restore", "archived"],
|
||||||
|
run: () => void unarchive(id).catch((unarchiveError) => setError(String(unarchiveError))),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (id && allRows.some((row) => row.thread.id === id && row.section === "pinned")) {
|
||||||
|
list.push(
|
||||||
|
{
|
||||||
|
id: "reorder-up",
|
||||||
|
title: "Move pinned thread up",
|
||||||
|
shortcut: "K",
|
||||||
|
keywords: ["reorder", "sort"],
|
||||||
|
run: () => void reorder(id, -1),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "reorder-down",
|
||||||
|
title: "Move pinned thread down",
|
||||||
|
shortcut: "J",
|
||||||
|
keywords: ["reorder", "sort"],
|
||||||
|
run: () => void reorder(id, 1),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
};
|
||||||
|
|
||||||
|
const key = (keyEvent: KeyEvent, id: ThreadId | undefined): boolean => {
|
||||||
|
if (keyEvent.name === "a" && keyEvent.shift) {
|
||||||
|
toggle();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (id && keyEvent.shift && (keyEvent.name === "j" || keyEvent.name === "k")) {
|
||||||
|
void reorder(id, keyEvent.name === "j" ? 1 : -1);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
return { archived, allRows, merged, archive, commands, key, hasOlder, loadOlder, loading, error };
|
return { archived, allRows, merged, archive, commands, key, hasOlder, loadOlder, loading, error };
|
||||||
}
|
}
|
||||||
+192
-68
@@ -38,7 +38,10 @@ export function useWorkspace(input: {
|
|||||||
const activeThread = useRef(thread?.id);
|
const activeThread = useRef(thread?.id);
|
||||||
activeThread.current = thread?.id;
|
activeThread.current = thread?.id;
|
||||||
const lastReady = useRef<string | null>(null);
|
const lastReady = useRef<string | null>(null);
|
||||||
useEffect(() => live ? session.watchTerminals(setTerminals) : undefined, [session, live]);
|
useEffect(() => {
|
||||||
|
if (!live) return undefined;
|
||||||
|
return session.watchTerminals(setTerminals);
|
||||||
|
}, [session, live]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setSetup(null);
|
setSetup(null);
|
||||||
setSetupError(null);
|
setSetupError(null);
|
||||||
@@ -48,26 +51,39 @@ export function useWorkspace(input: {
|
|||||||
setSetupError(state.status === "error" ? state.error ?? "Could not load worktree setup." : null);
|
setSetupError(state.status === "error" ? state.error ?? "Could not load worktree setup." : null);
|
||||||
});
|
});
|
||||||
}, [session, live, thread?.id]);
|
}, [session, live, thread?.id]);
|
||||||
useEffect(() => session.watchServerLifecycle((state) => {
|
// Server restarts and updates are worth a line, but the first "ready" is just startup.
|
||||||
const event: ServerLifecycleStreamEvent | null = state.event;
|
useEffect(() => {
|
||||||
if (event?.type === "ready" && event.payload.at !== lastReady.current) {
|
return session.watchServerLifecycle((state) => {
|
||||||
|
const event: ServerLifecycleStreamEvent | null = state.event;
|
||||||
|
if (event?.type === "legacyThreadMigration") {
|
||||||
|
sayRef.current(`Thread migration ${event.payload.status} · ${event.payload.totalThreadCount} threads`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event?.type !== "ready" || event.payload.at === lastReady.current) return;
|
||||||
const restarted = lastReady.current !== null;
|
const restarted = lastReady.current !== null;
|
||||||
lastReady.current = event.payload.at;
|
lastReady.current = event.payload.at;
|
||||||
const outcome = event.payload.updateOutcome;
|
const outcome = event.payload.updateOutcome;
|
||||||
sayRef.current(outcome
|
if (outcome) {
|
||||||
? `Server update ${outcome.targetVersion}: ${outcome.status}${outcome.reason ? ` · ${outcome.reason}` : ""}`
|
const reason = outcome.reason ? ` · ${outcome.reason}` : "";
|
||||||
: `Server ${restarted ? "restarted" : "ready"} · ${event.payload.environment.serverVersion}`, outcome !== undefined && outcome.status !== "committed");
|
sayRef.current(`Server update ${outcome.targetVersion}: ${outcome.status}${reason}`, outcome.status !== "committed");
|
||||||
} else if (event?.type === "legacyThreadMigration") {
|
return;
|
||||||
sayRef.current(`Thread migration ${event.payload.status} · ${event.payload.totalThreadCount} threads`);
|
}
|
||||||
}
|
const version = event.payload.environment.serverVersion;
|
||||||
}), [session]);
|
sayRef.current(`Server ${restarted ? "restarted" : "ready"} · ${version}`);
|
||||||
|
});
|
||||||
|
}, [session]);
|
||||||
|
|
||||||
const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
|
const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
|
||||||
const cwd = thread?.worktreePath ?? project?.workspaceRoot;
|
const cwd = thread?.worktreePath ?? project?.workspaceRoot;
|
||||||
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
|
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
|
||||||
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => {
|
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => {
|
||||||
if (!thread) return;
|
if (!thread) return;
|
||||||
attachTerminal(renderer, session, { threadId: thread.id, ...terminal, label: resolveTerminalSessionLabel(terminal.terminalId, terminal) }, (message) => {
|
const target = {
|
||||||
|
threadId: thread.id,
|
||||||
|
...terminal,
|
||||||
|
label: resolveTerminalSessionLabel(terminal.terminalId, terminal),
|
||||||
|
};
|
||||||
|
attachTerminal(renderer, session, target, (message) => {
|
||||||
if (message) say(message);
|
if (message) say(message);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -81,27 +97,53 @@ export function useWorkspace(input: {
|
|||||||
};
|
};
|
||||||
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
|
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
|
||||||
if (!thread) return;
|
if (!thread) return;
|
||||||
run(action === "close" ? "Terminal closed" : "Terminal cleared", () => action === "close" ? session.closeTerminal(thread.id, terminal.terminalId) : session.clearTerminal(thread.id, terminal.terminalId));
|
if (action === "close") {
|
||||||
|
run("Terminal closed", () => session.closeTerminal(thread.id, terminal.terminalId));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
run("Terminal cleared", () => session.clearTerminal(thread.id, terminal.terminalId));
|
||||||
};
|
};
|
||||||
const terminalItems = (action: "close" | "clear"): PickerItem[] => threadTerminals.map((terminal) => ({
|
|
||||||
id: `terminal:${action}:${terminal.terminalId}`, title: `${action === "close" ? "Close" : "Clear"} › ${label(terminal)}`,
|
const terminalItems = (action: "close" | "clear"): PickerItem[] => {
|
||||||
run: () => terminalMutation(terminal, action),
|
const verb = action === "close" ? "Close" : "Clear";
|
||||||
}));
|
return threadTerminals.map((terminal) => ({
|
||||||
|
id: `terminal:${action}:${terminal.terminalId}`,
|
||||||
|
title: `${verb} › ${label(terminal)}`,
|
||||||
|
run: () => terminalMutation(terminal, action),
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
// Close/clear appear as one sub-picker each, plus search-only rows so typing finds them.
|
||||||
|
const terminalActionItems = (): PickerItem[] => {
|
||||||
|
const items: PickerItem[] = [{ id: "terminal:new", title: "New terminal", run: newTerminal }];
|
||||||
|
for (const action of ["close", "clear"] as const) {
|
||||||
|
const targets = terminalItems(action);
|
||||||
|
if (targets.length === 0) continue;
|
||||||
|
const verb = action === "close" ? "Close" : "Clear";
|
||||||
|
items.push({
|
||||||
|
id: `terminal:${action}`,
|
||||||
|
title: `${verb} terminal…`,
|
||||||
|
run: () => openPicker({ placeholder: `${verb} terminal`, groups: [{ label: "Terminals", items: targets }] }),
|
||||||
|
});
|
||||||
|
for (const target of targets) items.push({ ...target, searchOnly: true });
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
};
|
||||||
|
|
||||||
const terminalPicker = () => {
|
const terminalPicker = () => {
|
||||||
if (!thread || input.draft) return say("Open a thread first.", true);
|
if (!thread || input.draft) return say("Open a thread first.", true);
|
||||||
openPicker({ placeholder: "Terminals · type close or clear for actions", groups: [
|
const openItems = threadTerminals.map((terminal) => ({
|
||||||
{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:${terminal.terminalId}`, title: label(terminal), hint: terminal.hasRunningSubprocess ? "busy" : terminal.status, run: () => enterTerminal(terminal) })) },
|
id: `terminal:${terminal.terminalId}`,
|
||||||
{ label: "Actions", items: [
|
title: label(terminal),
|
||||||
{ id: "terminal:new", title: "New terminal", run: newTerminal },
|
hint: terminal.hasRunningSubprocess ? "busy" : terminal.status,
|
||||||
...(["close", "clear"] as const).flatMap((action) => {
|
run: () => enterTerminal(terminal),
|
||||||
const items = terminalItems(action);
|
}));
|
||||||
return items.length ? [
|
openPicker({
|
||||||
{ id: `terminal:${action}`, title: `${action === "close" ? "Close" : "Clear"} terminal…`, run: () => openPicker({ placeholder: `${action === "close" ? "Close" : "Clear"} terminal`, groups: [{ label: "Terminals", items }] }) },
|
placeholder: "Terminals · type close or clear for actions",
|
||||||
...items.map((item) => ({ ...item, searchOnly: true })),
|
groups: [
|
||||||
] : [];
|
{ label: "Terminals", items: openItems },
|
||||||
}),
|
{ label: "Actions", items: terminalActionItems() },
|
||||||
] },
|
],
|
||||||
] });
|
});
|
||||||
};
|
};
|
||||||
const openTerminal = () => {
|
const openTerminal = () => {
|
||||||
if (!thread || input.draft) return say("Open a thread first.", true);
|
if (!thread || input.draft) return say("Open a thread first.", true);
|
||||||
@@ -113,48 +155,88 @@ export function useWorkspace(input: {
|
|||||||
const branchPicker = () => {
|
const branchPicker = () => {
|
||||||
if (!thread || !cwd || !project || input.draft) return say("Open a thread with a repository first.", true);
|
if (!thread || !cwd || !project || input.draft) return say("Open a thread with a repository first.", true);
|
||||||
say("Loading refs…");
|
say("Loading refs…");
|
||||||
session.listRefs(cwd).then((refs) => {
|
session.listRefs(cwd).then(
|
||||||
if (activeThread.current !== thread.id) return;
|
(refs) => {
|
||||||
const updateWorkspace = (branch: string | null, path: string | null) => session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath);
|
if (activeThread.current !== thread.id) return;
|
||||||
const promptBranch = (worktree: boolean) => confirm({
|
openRefPicker(refs);
|
||||||
|
},
|
||||||
|
(error) => say(`Could not list refs: ${messageOf(error)}`, true),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const openRefPicker = (refs: Awaited<ReturnType<T3Session["listRefs"]>>) => {
|
||||||
|
if (!thread || !cwd || !project) return;
|
||||||
|
const updateWorkspace = (branch: string | null, path: string | null) =>
|
||||||
|
session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath);
|
||||||
|
|
||||||
|
const promptBranch = (worktree: boolean) =>
|
||||||
|
confirm({
|
||||||
title: worktree ? "Create a new worktree?" : "Create and switch ref",
|
title: worktree ? "Create a new worktree?" : "Create and switch ref",
|
||||||
detail: worktree ? `Based on ${thread.branch ?? "HEAD"}. The thread will move to the new worktree.` : cwd,
|
detail: worktree ? `Based on ${thread.branch ?? "HEAD"}. The thread will move to the new worktree.` : cwd,
|
||||||
message: { placeholder: "New branch name" }, confirmLabel: "create",
|
message: { placeholder: "New branch name" },
|
||||||
|
confirmLabel: "create",
|
||||||
run: (raw) => {
|
run: (raw) => {
|
||||||
const name = sanitizeNewRefName(raw);
|
const name = sanitizeNewRefName(raw);
|
||||||
if (!name) return say("Enter a branch name.", true);
|
if (!name) return say("Enter a branch name.", true);
|
||||||
run(worktree ? "Worktree created" : "Branch created", async () => {
|
run(worktree ? "Worktree created" : "Branch created", async () => {
|
||||||
if (worktree) {
|
if (worktree) {
|
||||||
const result = await session.createWorktree(cwd, thread.branch ?? "HEAD", name);
|
const created = await session.createWorktree(cwd, thread.branch ?? "HEAD", name);
|
||||||
await updateWorkspace(result.worktree.refName, result.worktree.path);
|
await updateWorkspace(created.worktree.refName, created.worktree.path);
|
||||||
} else {
|
} else {
|
||||||
const result = await session.createRef(cwd, name);
|
const created = await session.createRef(cwd, name);
|
||||||
await updateWorkspace(result.refName, thread.worktreePath);
|
await updateWorkspace(created.refName, thread.worktreePath);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
openPicker({ placeholder: "Select ref", groups: [
|
|
||||||
{ label: "Refs", items: refs.map((ref) => ({
|
const selectRef = (ref: (typeof refs)[number]) => {
|
||||||
id: `ref:${ref.isRemote ? "remote:" : ""}${ref.name}`, title: ref.name,
|
run("Ref selected", async () => {
|
||||||
hint: ref.current ? "current" : ref.worktreePath ? "worktree" : ref.isRemote ? "remote" : ref.isDefault ? "default" : "local",
|
const target = resolveBranchSelectionTarget({
|
||||||
run: () => run("Ref selected", async () => {
|
activeProjectCwd: project.workspaceRoot,
|
||||||
const target = resolveBranchSelectionTarget({ activeProjectCwd: project.workspaceRoot, activeWorktreePath: thread.worktreePath, refName: ref });
|
activeWorktreePath: thread.worktreePath,
|
||||||
const result = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name);
|
refName: ref,
|
||||||
await updateWorkspace(ref.isRemote ? result?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name) : ref.name, target.nextWorktreePath);
|
});
|
||||||
|
const switched = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name);
|
||||||
|
const branch = ref.isRemote ? (switched?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name)) : ref.name;
|
||||||
|
await updateWorkspace(branch, target.nextWorktreePath);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const refItems = refs.map((ref) => ({
|
||||||
|
id: `ref:${ref.isRemote ? "remote:" : ""}${ref.name}`,
|
||||||
|
title: ref.name,
|
||||||
|
hint: refHint(ref),
|
||||||
|
run: () => selectRef(ref),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const actionItems: PickerItem[] = [
|
||||||
|
{ id: "branch:create", title: "Create and switch ref…", run: () => promptBranch(false) },
|
||||||
|
{ id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) },
|
||||||
|
{ id: "worktree:create", title: "Create worktree…", run: () => promptBranch(true) },
|
||||||
|
];
|
||||||
|
if (thread.worktreePath) {
|
||||||
|
const worktreePath = thread.worktreePath;
|
||||||
|
actionItems.push({
|
||||||
|
id: "worktree:remove",
|
||||||
|
title: "Remove worktree…",
|
||||||
|
run: () =>
|
||||||
|
confirm({
|
||||||
|
title: "Remove this worktree?",
|
||||||
|
detail: `${worktreePath} · Stops this thread's provider session. Refuses shared worktrees and uncommitted changes.`,
|
||||||
|
confirmLabel: "remove",
|
||||||
|
run: () => run("Worktree removed", () => session.removeThreadWorktree(thread.id, project.workspaceRoot, worktreePath)),
|
||||||
}),
|
}),
|
||||||
})) },
|
});
|
||||||
{ label: "Actions", items: [
|
}
|
||||||
{ id: "branch:create", title: "Create and switch ref…", run: () => promptBranch(false) },
|
|
||||||
{ id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) },
|
openPicker({
|
||||||
{ id: "worktree:create", title: "Create worktree…", run: () => promptBranch(true) },
|
placeholder: "Select ref",
|
||||||
...(thread.worktreePath ? [{ id: "worktree:remove", title: "Remove worktree…", run: () => confirm({
|
groups: [
|
||||||
title: "Remove this worktree?", detail: `${thread.worktreePath} · Stops this thread's provider session. Refuses shared worktrees and uncommitted changes.`, confirmLabel: "remove",
|
{ label: "Refs", items: refItems },
|
||||||
run: () => run("Worktree removed", () => session.removeThreadWorktree(thread.id, project.workspaceRoot, thread.worktreePath!)),
|
{ label: "Actions", items: actionItems },
|
||||||
}) }] : []),
|
],
|
||||||
] },
|
});
|
||||||
] });
|
|
||||||
}, (error) => say(`Could not list refs: ${messageOf(error)}`, true));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const openInEditor = () => {
|
const openInEditor = () => {
|
||||||
@@ -167,11 +249,22 @@ export function useWorkspace(input: {
|
|||||||
if (diff.path) return open(resolvePathLinkTarget(diff.path, diff.cwd));
|
if (diff.path) return open(resolvePathLinkTarget(diff.path, diff.cwd));
|
||||||
const files = splitPatch(diff.patch ?? "");
|
const files = splitPatch(diff.patch ?? "");
|
||||||
if (!files.length) return say("No file to open in this diff.", true);
|
if (!files.length) return say("No file to open in this diff.", true);
|
||||||
openPicker({ placeholder: "Open diff file in editor", groups: [{ label: "Files", items: files.map((file) => ({ id: `editor:${file.path}`, title: file.path, run: () => open(resolvePathLinkTarget(file.path, diff.cwd)) })) }] });
|
const fileItems = files.map((file) => ({
|
||||||
|
id: `editor:${file.path}`,
|
||||||
|
title: file.path,
|
||||||
|
run: () => open(resolvePathLinkTarget(file.path, diff.cwd)),
|
||||||
|
}));
|
||||||
|
openPicker({ placeholder: "Open diff file in editor", groups: [{ label: "Files", items: fileItems }] });
|
||||||
};
|
};
|
||||||
|
|
||||||
const cancelSetup = () => {
|
const cancelSetup = () => {
|
||||||
if (!setup || setup.threadId !== thread?.id || setup.phase !== "running") return;
|
if (!setup || setup.threadId !== thread?.id || setup.phase !== "running") return;
|
||||||
confirm({ title: "Cancel worktree setup?", detail: "Stops workspace preparation and its setup script.", confirmLabel: "cancel setup", run: () => run("Worktree setup cancellation requested", () => session.cancelWorktreeSetup(setup.threadId)) });
|
confirm({
|
||||||
|
title: "Cancel worktree setup?",
|
||||||
|
detail: "Stops workspace preparation and its setup script.",
|
||||||
|
confirmLabel: "cancel setup",
|
||||||
|
run: () => run("Worktree setup cancellation requested", () => session.cancelWorktreeSetup(setup.threadId)),
|
||||||
|
});
|
||||||
};
|
};
|
||||||
const commands: Command[] = thread && !input.draft ? [
|
const commands: Command[] = thread && !input.draft ? [
|
||||||
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
|
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
|
||||||
@@ -182,14 +275,45 @@ export function useWorkspace(input: {
|
|||||||
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
|
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
|
||||||
...(setup?.threadId === thread.id && setup.phase === "running" ? [{ id: "setup-cancel", title: "Cancel worktree setup…", keywords: ["preparation", "stop"], run: cancelSetup }] : []),
|
...(setup?.threadId === thread.id && setup.phase === "running" ? [{ id: "setup-cancel", title: "Cancel worktree setup…", keywords: ["preparation", "stop"], run: cancelSetup }] : []),
|
||||||
] : [];
|
] : [];
|
||||||
const key = (key: KeyEvent): boolean => {
|
const key = (keyEvent: KeyEvent): boolean => {
|
||||||
if (key.ctrl || key.meta) return false;
|
if (keyEvent.ctrl || keyEvent.meta) return false;
|
||||||
if (key.name === "t" && key.shift) return terminalPicker(), true;
|
if (keyEvent.name === "t" && keyEvent.shift) {
|
||||||
if (key.name === "b" && !key.shift) return branchPicker(), true;
|
terminalPicker();
|
||||||
if (key.name === "e" && key.shift) return openInEditor(), true;
|
return true;
|
||||||
|
}
|
||||||
|
if (keyEvent.name === "b" && !keyEvent.shift) {
|
||||||
|
branchPicker();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (keyEvent.name === "e" && keyEvent.shift) {
|
||||||
|
openInEditor();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
return { commands, key, openTerminal, note: input.draft ? null : setupError ?? worktreeSetupNote(setup?.threadId === thread?.id ? setup : null), setupFailed: setup?.phase === "failed" || setupError !== null };
|
|
||||||
|
// Setup belongs to one thread; another thread's snapshot is not this one's note.
|
||||||
|
const setupForThread = setup?.threadId === thread?.id ? setup : null;
|
||||||
|
const note = input.draft ? null : (setupError ?? worktreeSetupNote(setupForThread));
|
||||||
|
|
||||||
|
return {
|
||||||
|
commands,
|
||||||
|
key,
|
||||||
|
openTerminal,
|
||||||
|
note,
|
||||||
|
setupFailed: setup?.phase === "failed" || setupError !== null,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageOf = (error: unknown) => error instanceof Error ? error.message : String(error);
|
/** Why a ref matters at a glance, in the web branch picker's order of importance. */
|
||||||
|
function refHint(ref: { readonly current: boolean; readonly worktreePath: string | null; readonly isRemote?: boolean | undefined; readonly isDefault: boolean }): string {
|
||||||
|
if (ref.current) return "current";
|
||||||
|
if (ref.worktreePath) return "worktree";
|
||||||
|
if (ref.isRemote) return "remote";
|
||||||
|
if (ref.isDefault) return "default";
|
||||||
|
return "local";
|
||||||
|
}
|
||||||
|
|
||||||
|
function messageOf(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user