Skip to content

Commit 750edea

Browse files
t3dotggclaude
andcommitted
fix(shell): older settled lookups match every pull request field and environment
- Older settled search matches the branch and linked pull requests, as the palette does. - Prompt links ask every environment with the repository for an older pull request thread, and web waits for a fresh answer instead of trusting a cached one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0e5f22b commit 750edea

6 files changed

Lines changed: 229 additions & 61 deletions

File tree

‎apps/mobile/src/features/prompt-links/usePromptLinkResolver.ts‎

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as Dialog from "../../components/ui/Dialog";
22
import { StackActions, useNavigation } from "@react-navigation/native";
33
import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
44
import {
5-
findPromptLinkProject,
5+
findPromptLinkProjects,
66
findPromptLinkPullRequestThread,
77
resolvePromptLinkModelSelection,
88
} from "@t3tools/client-runtime/prompt-links";
@@ -111,26 +111,40 @@ export function usePromptLinkResolver(params: Readonly<Record<string, unknown>>
111111
}
112112
};
113113

114+
// A pull request's thread can be an older settled thread no shell holds, so ask every
115+
// connected environment with the repository. A lookup on another one would wait forever.
116+
const findServerPullRequestThread = async (
117+
projects: ReadonlyArray<EnvironmentProject>,
118+
pullRequest: PromptLinkPullRequest,
119+
) => {
120+
const connected = new Set(
121+
connectedEnvironments
122+
.filter((environment) => environment.connectionState === "connected")
123+
.map((environment) => environment.environmentId),
124+
);
125+
const found = await Promise.all(
126+
projects
127+
.filter((project) => connected.has(project.environmentId))
128+
.map(async (project) => {
129+
const linked = await loadLinkedThreads({
130+
environmentId: project.environmentId,
131+
input: {
132+
projectId: project.id,
133+
repository: promptLinkRepositoryName(pullRequest),
134+
number: pullRequest.number,
135+
},
136+
});
137+
const thread =
138+
linked._tag === "Success"
139+
? linked.value.threads.find((candidate) => candidate.archivedAt === null)
140+
: undefined;
141+
return thread && { environmentId: project.environmentId, id: thread.id };
142+
}),
143+
);
144+
return found.find((thread) => thread !== undefined);
145+
};
146+
114147
const openProjectDraft = async (project: EnvironmentProject, request: LinkedDraftRequest) => {
115-
if (request.pullRequest) {
116-
// The pull request's thread can be an older settled thread the shell left out.
117-
const linked = await loadLinkedThreads({
118-
environmentId: project.environmentId,
119-
input: {
120-
projectId: project.id,
121-
repository: promptLinkRepositoryName(request.pullRequest),
122-
number: request.pullRequest.number,
123-
},
124-
});
125-
const thread =
126-
linked._tag === "Success"
127-
? linked.value.threads.find((candidate) => candidate.archivedAt === null)
128-
: undefined;
129-
if (thread) {
130-
openThread({ environmentId: project.environmentId, id: thread.id }, request.prompt);
131-
return;
132-
}
133-
}
134148
try {
135149
await waitForComposerDraftsLoaded();
136150
} catch {
@@ -292,14 +306,20 @@ export function usePromptLinkResolver(params: Readonly<Record<string, unknown>>
292306
}
293307
const activityOf = (project: EnvironmentProject) =>
294308
lastActivity.get(`${project.environmentId}:${project.id}`) ?? "";
295-
const project = findPromptLinkProject(
309+
const projects = findPromptLinkProjects(
296310
flow.projectScopes
297311
.flatMap((scope) => scope.projects)
298312
.sort((left, right) => activityOf(right).localeCompare(activityOf(left))),
299313
repository,
300314
);
315+
const project = projects[0];
301316
if (project) {
302-
void openProjectDraft(project, request);
317+
const { pullRequest } = request;
318+
void (async () => {
319+
const thread = pullRequest && (await findServerPullRequestThread(projects, pullRequest));
320+
if (thread) openThread(thread, request.prompt);
321+
else await openProjectDraft(project, request);
322+
})();
303323
return;
304324
}
305325
Dialog.alert(`You don't have ${promptLinkRepositoryName(repository)}`, undefined, [

‎apps/server/src/orchestration-v2/ThreadSearch.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
ProviderInstanceId,
77
ThreadId,
88
type OrchestrationV2DomainEvent,
9+
type ThreadLinkedPullRequest,
910
} from "@t3tools/contracts";
1011
import * as NodeServices from "@effect/platform-node/NodeServices";
1112
import * as DateTime from "effect/DateTime";
@@ -66,6 +67,8 @@ const thread = (
6667
readonly subagentOf?: ThreadId;
6768
readonly title?: string;
6869
readonly settledAt?: DateTime.Utc;
70+
readonly linkedPullRequest?: ThreadLinkedPullRequest;
71+
readonly branchPullRequest?: ThreadLinkedPullRequest;
6972
} = {},
7073
): OrchestrationV2DomainEvent => ({
7174
id: EventId.make(`created:${threadId}`),
@@ -85,6 +88,8 @@ const thread = (
8588
interactionMode: "default",
8689
branch: null,
8790
worktreePath: null,
91+
linkedPullRequest: overrides.linkedPullRequest ?? null,
92+
branchPullRequest: overrides.branchPullRequest ?? null,
8893
activeProviderThreadId: null,
8994
lineage: overrides.subagentOf
9095
? {
@@ -715,6 +720,47 @@ it.layer(layerTest)("ThreadSearch.searchOlderSettled", (it) => {
715720
);
716721
}),
717722
);
723+
724+
it.effect("matches the branch and linked pull requests, like the palette", () =>
725+
Effect.gen(function* () {
726+
const projections = yield* ProjectionStore.ProjectionStoreV2;
727+
const search = yield* ThreadSearch.ThreadSearch;
728+
const project = ProjectId.make("project:heron");
729+
yield* createProject(project);
730+
const pullRequest = (number: number): ThreadLinkedPullRequest => ({
731+
projectId: project,
732+
repository: "acme/heron",
733+
number,
734+
url: `https://github.com/acme/heron/pull/${number}`,
735+
});
736+
const branch = ThreadId.make("thread:heron-branch");
737+
const linked = ThreadId.make("thread:heron-linked");
738+
yield* Effect.forEach(
739+
[
740+
thread(branch, project, {
741+
title: "Heron",
742+
settledAt: at(10),
743+
branchPullRequest: pullRequest(4101),
744+
}),
745+
thread(linked, project, {
746+
title: "Heron",
747+
settledAt: at(10),
748+
linkedPullRequest: pullRequest(4202),
749+
}),
750+
],
751+
projections.apply,
752+
{ discard: true },
753+
);
754+
const find = (query: string) =>
755+
search.searchOlderSettled({
756+
query,
757+
before: DateTime.formatIso(at(30)),
758+
messageThreadIds: [],
759+
});
760+
assert.deepEqual(yield* find("#4101"), [branch]);
761+
assert.deepEqual(yield* find("acme/heron#4202"), [linked]);
762+
}),
763+
);
718764
});
719765

720766
it.layer(layerTest)("ThreadSearch.searchThreadsWithOlderSettledRows", (it) => {

‎apps/server/src/orchestration-v2/ThreadSearch.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
OrchestrationThreadSearchSource,
55
OrchestrationV2AppThreadJson,
66
OrchestrationV2ThreadOpens,
7+
ThreadLinkedPullRequest,
78
ThreadPullRequestLink,
89
type OrchestrationSearchThreadsInput,
910
type OrchestrationSearchThreadsResult,
@@ -283,6 +284,8 @@ const OlderSettledTitleRow = Schema.Struct({
283284
title: Schema.String,
284285
branch: Schema.NullOr(Schema.String),
285286
pullRequests: Schema.NullOr(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink))),
287+
linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
288+
branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
286289
opens: Schema.NullOr(Schema.String),
287290
createdAt: IsoDateTime,
288291
projectTitle: Schema.String,
@@ -344,6 +347,8 @@ export const make = Effect.gen(function* () {
344347
json_extract(threads.payload_json, '$.title') AS title,
345348
json_extract(threads.payload_json, '$.branch') AS branch,
346349
json_extract(threads.payload_json, '$.pullRequests') AS "pullRequests",
350+
json_extract(threads.payload_json, '$.linkedPullRequest') AS "linkedPullRequest",
351+
json_extract(threads.payload_json, '$.branchPullRequest') AS "branchPullRequest",
347352
json_extract(threads.payload_json, '$.opens') AS opens,
348353
json_extract(threads.payload_json, '$.createdAt') AS "createdAt",
349354
projects.title AS "projectTitle",
@@ -579,7 +584,11 @@ export const make = Effect.gen(function* () {
579584
branch: row.branch,
580585
projectTitle: row.projectTitle,
581586
environmentLabel: environmentLabel ?? null,
582-
pullRequests: threadSearchPullRequests({ pullRequests: row.pullRequests ?? undefined }),
587+
pullRequests: threadSearchPullRequests({
588+
pullRequests: row.pullRequests ?? undefined,
589+
linkedPullRequest: row.linkedPullRequest,
590+
branchPullRequest: row.branchPullRequest,
591+
}),
583592
// Like the clients: what the user last wrote, else when the thread began.
584593
activityAt: Date.parse(row.latestUserMessageAt ?? row.createdAt),
585594
opens: Option.getOrNull(decodeThreadOpens(row.opens)),

‎apps/web/src/components/promptLinks/NewThreadLinkView.tsx‎

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
11
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
22
import { getCloneDestinationPath } from "@t3tools/client-runtime/operations/projects";
33
import {
4-
findPromptLinkProject,
4+
findPromptLinkProjects,
55
findPromptLinkPullRequestThread,
6+
pickPromptLinkPullRequestThread,
67
resolvePromptLinkModelSelection,
78
} from "@t3tools/client-runtime/prompt-links";
89
import {
910
isAtomCommandInterrupted,
1011
squashAtomCommandFailure,
1112
} from "@t3tools/client-runtime/state/runtime";
1213
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
14+
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
1315
import {
1416
type NewThreadLink,
1517
type PromptLinkRepository,
1618
promptLinkPullRequestUrl,
1719
} from "@t3tools/shared/promptLinks";
1820
import { useAtomValue } from "@effect/atom-react";
1921
import { useLocation, useNavigate } from "@tanstack/react-router";
22+
import { Atom } from "effect/reactivity";
2023
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
2124

2225
import { useComposerDraftStore } from "~/composerDraftStore";
@@ -28,10 +31,9 @@ import { useProjects, useThreadShells, waitForProject } from "~/state/entities";
2831
import { appAtomRegistry } from "~/rpc/atomRegistry";
2932
import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
3033
import { environmentPresentations } from "~/state/presentation";
31-
import { allReachableShellsLiveAtom } from "~/state/shell";
34+
import { allReachableShellsLiveAtom, environmentShell } from "~/state/shell";
3235
import { sourceControlEnvironment } from "~/state/sourceControl";
3336
import { pullRequestEnvironment } from "~/state/pullRequests";
34-
import { useEnvironmentQuery } from "~/state/query";
3537
import { useAtomCommand } from "~/state/use-atom-command";
3638

3739
import { usePullRequestHandoffs } from "../pullRequest/usePullRequestActions";
@@ -64,6 +66,36 @@ type LinkLaunch =
6466

6567
const openedLinkKeys = new Set<string>();
6668

69+
type PullRequestThreadLookup = {
70+
readonly targets: ReadonlyArray<readonly [environmentId: EnvironmentId, projectId: ProjectId]>;
71+
readonly repository: string;
72+
readonly number: number;
73+
};
74+
75+
// A pull request's thread can be an older settled thread no shell holds, so ask every
76+
// environment with the repository.
77+
const pullRequestThreadLookupAtom = Atom.family((key: string) => {
78+
const { targets, repository, number } = JSON.parse(key) as PullRequestThreadLookup;
79+
return Atom.make((get) =>
80+
pickPromptLinkPullRequestThread(
81+
targets
82+
// A shell that is not live cannot answer, and its lookup would wait forever.
83+
.filter(([environmentId]) => get(environmentShell.statusAtom(environmentId)) === "live")
84+
.map(([environmentId, projectId]) => ({
85+
environmentId,
86+
result: get(
87+
pullRequestEnvironment.linkedThreads({
88+
environmentId,
89+
input: { projectId, repository, number },
90+
}),
91+
),
92+
})),
93+
),
94+
).pipe(Atom.withLabel(`web-prompt-link-pull-request-thread:${key}`));
95+
});
96+
97+
const NO_PULL_REQUEST_THREAD_LOOKUP = Atom.make(null);
98+
6799
export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
68100
const locationKey = useLocation({ select: (location) => location.state.__TSR_key ?? "" });
69101
const navigate = useNavigate();
@@ -223,41 +255,32 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
223255
await openDraft(project);
224256
};
225257

226-
// A pull request's thread can be an older settled thread the shell left out; the server knows.
227258
const localPullRequestThread =
228259
ready && link.kind === "pull-request"
229260
? findPromptLinkPullRequestThread(threads, link.pullRequest)
230261
: undefined;
231-
const pullRequestProject =
262+
const lookupProjects =
232263
ready && link.kind === "pull-request" && localPullRequestThread === undefined
233-
? findPromptLinkProject(recentProjects(), link.pullRequest)
234-
: undefined;
235-
const linkedThreads = useEnvironmentQuery(
236-
pullRequestProject === undefined || link.kind !== "pull-request"
237-
? null
238-
: pullRequestEnvironment.linkedThreads({
239-
environmentId: pullRequestProject.environmentId,
240-
input: {
241-
projectId: pullRequestProject.id,
264+
? findPromptLinkProjects(recentProjects(), link.pullRequest)
265+
: [];
266+
const serverPullRequestThread = useAtomValue(
267+
link.kind === "pull-request" && lookupProjects.length > 0
268+
? pullRequestThreadLookupAtom(
269+
JSON.stringify({
270+
targets: lookupProjects.map((project) => [project.environmentId, project.id]),
242271
repository: `${link.pullRequest.owner}/${link.pullRequest.name}`,
243272
number: link.pullRequest.number,
244-
},
245-
}),
273+
} satisfies PullRequestThreadLookup),
274+
)
275+
: NO_PULL_REQUEST_THREAD_LOOKUP,
246276
);
247-
const linkedThread = linkedThreads.data?.threads.find((thread) => thread.archivedAt === null);
248-
const linkedThreadsDone =
249-
pullRequestProject === undefined || linkedThreads.data !== null || linkedThreads.error !== null;
250277

251-
if (ready && linkedThreadsDone && state.status === "opening" && !started) {
278+
if (ready && serverPullRequestThread !== undefined && state.status === "opening" && !started) {
252279
setStarted(true);
253-
const pullRequestThread =
254-
localPullRequestThread ??
255-
(linkedThread === undefined || pullRequestProject === undefined
256-
? undefined
257-
: { environmentId: pullRequestProject.environmentId, id: linkedThread.id });
280+
const pullRequestThread = localPullRequestThread ?? serverPullRequestThread ?? undefined;
258281
const repository = link.kind === "new" ? link.repository : link.pullRequest;
259282
const project =
260-
repository === null ? undefined : findPromptLinkProject(recentProjects(), repository);
283+
repository === null ? undefined : findPromptLinkProjects(recentProjects(), repository)[0];
261284
if (pullRequestThread !== undefined) {
262285
setState({ status: "opened" });
263286
setLaunch({ kind: "thread", thread: pullRequestThread });

0 commit comments

Comments
 (0)