Skip to content

Commit 98d6134

Browse files
Merge branch 'main' into feat/acp-usage-limits
2 parents ebd0ad7 + 725573f commit 98d6134

13 files changed

Lines changed: 637 additions & 177 deletions

‎apps/server/src/auth/McpOAuth.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,7 @@ export const layerMcpClientAuthenticator = Layer.effect(
573573
label: client.label,
574574
access: client.access,
575575
linked: client.peerLink,
576+
...(client.peerLink ? {} : { webOrigin: requestUrls(request).issuer }),
576577
},
577578
capabilities: new Set<McpInvocationContext.McpCapability>([
578579
"orchestration",

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
2+
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
13
import { SourceControlProviderKind } from "@t3tools/contracts";
24
// @effect-diagnostics nodeBuiltinImport:off
35
import * as NodeFS from "node:fs";
@@ -69,6 +71,10 @@ type FakeChangeRequest = Omit<ChangeRequest, "provider" | "state" | "updatedAt">
6971
};
7072

7173
interface FakeProviderScenario {
74+
prListGate?: {
75+
readonly started: Deferred.Deferred<void>;
76+
readonly release: Deferred.Deferred<void>;
77+
};
7278
/** The kind the fake host reports itself as. */
7379
kind?: string;
7480
/** Answers to successive change request listings, whatever their head selector. */
@@ -452,6 +458,13 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): {
452458
[]
453459
).map(toChangeRequest),
454460
),
461+
Effect.tap(() =>
462+
scenario.prListGate
463+
? Deferred.succeed(scenario.prListGate.started, undefined).pipe(
464+
Effect.andThen(Deferred.await(scenario.prListGate.release)),
465+
)
466+
: Effect.void,
467+
),
455468
),
456469
createChangeRequest: (input) =>
457470
record(input.cwd, {
@@ -723,6 +736,108 @@ const layerGitManagerTest = GitVcsDriver.layer.pipe(
723736
);
724737

725738
it.layer(layerGitManagerTest)("GitManager", (it) => {
739+
it.effect(
740+
"publishes local Git changes during a held PR lookup without caching its old branch",
741+
() =>
742+
Effect.gen(function* () {
743+
const repoDir = yield* makeTempDir("t3code-refresh-status-gh-gate-");
744+
yield* initRepo(repoDir);
745+
yield* runGit(repoDir, ["checkout", "-b", "release"]);
746+
const remoteDir = yield* createBareRemote();
747+
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
748+
yield* runGit(repoDir, ["push", "-u", "origin", "release"]);
749+
yield* runGit(repoDir, ["tag", "release"]);
750+
const oldPr = {
751+
number: 613,
752+
title: "Release PR",
753+
url: "https://github.com/pingdotgg/codething-mvp/pull/613",
754+
baseRefName: "main",
755+
headRefName: "release",
756+
};
757+
const newPr = { ...oldPr, number: 614, headRefName: "heads/release" };
758+
const providerScenario: FakeProviderScenario = {
759+
prListSequence: [oldPr, oldPr, newPr].map((pr) => [pr]),
760+
};
761+
const { manager } = yield* makeManager({ providerScenario });
762+
const context = yield* Layer.build(
763+
VcsStatusBroadcaster.layer.pipe(
764+
Layer.provide(
765+
GitWorkflowService.layer.pipe(
766+
Layer.provide(Layer.succeed(GitManager.GitManager, manager)),
767+
Layer.provide(
768+
VcsDriverRegistry.layer.pipe(
769+
Layer.provide(VcsProjectConfig.layer),
770+
Layer.provide(VcsProcess.layer),
771+
),
772+
),
773+
),
774+
),
775+
Layer.provide(
776+
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
777+
shouldRunScopeWork: () => Effect.succeed(true),
778+
}),
779+
),
780+
),
781+
);
782+
const broadcaster = Context.get(context, VcsStatusBroadcaster.VcsStatusBroadcaster);
783+
const initial = yield* broadcaster.getStatus({ cwd: repoDir });
784+
expect(initial.refName).toBe("release");
785+
expect(initial.pr?.number).toBe(613);
786+
787+
const subscribed = yield* Deferred.make<void>();
788+
const published = yield* Deferred.make<void>();
789+
yield* broadcaster.streamStatus({ cwd: repoDir, includeRemote: false }).pipe(
790+
Stream.runForEach((event) => {
791+
if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
792+
if (event._tag === "localUpdated" && event.local.hasWorkingTreeChanges) {
793+
return Deferred.succeed(published, undefined);
794+
}
795+
return Effect.void;
796+
}),
797+
Effect.forkScoped,
798+
);
799+
yield* Deferred.await(subscribed);
800+
const gate = {
801+
started: yield* Deferred.make<void>(),
802+
release: yield* Deferred.make<void>(),
803+
};
804+
providerScenario.prListGate = gate;
805+
const fs = yield* FileSystem.FileSystem;
806+
yield* fs.writeFileString(NodePath.join(repoDir, "README.md"), "changed before refresh\n");
807+
const completed = yield* Deferred.make<void>();
808+
const refresh = yield* broadcaster
809+
.refreshStatus(repoDir)
810+
.pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);
811+
yield* Deferred.await(gate.started);
812+
const pending = Option.getOrThrow(
813+
yield* Stream.runHead(broadcaster.streamStatus({ cwd: repoDir, includeRemote: false })),
814+
);
815+
expect(pending._tag).toBe("snapshot");
816+
if (pending._tag === "snapshot") expect(pending.local.hasWorkingTreeChanges).toBe(true);
817+
yield* Deferred.await(published);
818+
expect(yield* Deferred.isDone(completed)).toBe(false);
819+
820+
yield* runGit(repoDir, ["checkout", "-b", "heads/release"]);
821+
yield* runGit(repoDir, ["push", "-u", "origin", "refs/heads/heads/release"]);
822+
yield* Deferred.succeed(gate.release, undefined);
823+
const refreshed = yield* Fiber.join(refresh);
824+
expect(refreshed.refName).toBe("heads/release");
825+
expect(refreshed.hasWorkingTreeChanges).toBe(true);
826+
expect(refreshed.pr).toBeNull();
827+
const snapshot = Option.getOrThrow(
828+
yield* Stream.runHead(broadcaster.streamStatus({ cwd: repoDir, includeRemote: false })),
829+
);
830+
expect(snapshot._tag).toBe("snapshot");
831+
if (snapshot._tag === "snapshot") expect(snapshot.remote).toBeNull();
832+
833+
delete providerScenario.prListGate;
834+
const recovered = yield* broadcaster.getStatus({ cwd: repoDir });
835+
expect(recovered.refName).toBe("heads/release");
836+
expect(recovered.pr?.number).toBe(614);
837+
expect((yield* broadcaster.getStatus({ cwd: repoDir })).pr?.number).toBe(614);
838+
}),
839+
);
840+
726841
it.effect("status reports the listed PR whose head is the branch", () =>
727842
Effect.gen(function* () {
728843
const repoDir = yield* makeTempDir("t3code-git-manager-");

‎apps/server/src/git/GitWorkflowService.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ export class GitWorkflowService extends Context.Service<
5252
readonly localStatus: (
5353
input: VcsStatusInput,
5454
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
55+
readonly currentBranch: (cwd: string) => Effect.Effect<string | null, GitManagerServiceError>;
5556
readonly remoteStatus: (
5657
input: VcsStatusInput,
5758
options?: GitManager.GitRemoteStatusOptions,
@@ -332,6 +333,32 @@ export const make = Effect.gen(function* () {
332333
),
333334
);
334335
}),
336+
currentBranch: Effect.fn("GitWorkflowService.currentBranch")(function* (cwd) {
337+
if (!(yield* detectGitRepositoryForStatus("GitWorkflowService.currentBranch", cwd))) {
338+
return null;
339+
}
340+
const result = yield* git.execute({
341+
operation: "GitWorkflowService.currentBranch",
342+
cwd,
343+
args: ["symbolic-ref", "--quiet", "HEAD"],
344+
allowNonZeroExit: true,
345+
timeoutMs: 5_000,
346+
});
347+
if (result.exitCode === 0) {
348+
return result.stdout.trim().replace(/^refs\/heads\//, "") || null;
349+
}
350+
if (result.exitCode === 1) return null;
351+
return yield* new GitCommandError({
352+
operation: "GitWorkflowService.currentBranch",
353+
command: "git symbolic-ref",
354+
cwd,
355+
argumentCount: 3,
356+
...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
357+
stdoutLength: result.stdout.length,
358+
stderrLength: result.stderr.length,
359+
detail: "Failed to read the checked-out branch.",
360+
});
361+
}),
335362
remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {
336363
return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
337364
Effect.flatMap((isGitRepository) =>

‎apps/server/src/mcp/McpInvocationContext.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
import * as Context from "effect/Context";
1313
import * as Effect from "effect/Effect";
1414
import * as Fiber from "effect/Fiber";
15+
import { formatThreadLink } from "@t3tools/shared/threadLinks";
1516

1617
const ALL_MCP_CAPABILITIES = [
1718
"preview",
@@ -44,6 +45,8 @@ export interface McpClientCaller {
4445
* another environment passing on the limits of the agent it calls for.
4546
*/
4647
readonly narrowedTo?: ClientModes | undefined;
48+
/** The origin an outside client reached; its thread links open the web app there. */
49+
readonly webOrigin?: string | undefined;
4750
}
4851

4952
/**
@@ -105,6 +108,20 @@ export interface McpInvocationScope {
105108
readonly linkedEnvironments?: boolean;
106109
}
107110

111+
/**
112+
* T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
113+
* they get a web URL on the origin they reached instead.
114+
*/
115+
export const threadLinkFor = (
116+
scope: Pick<McpInvocationScope, "environmentId" | "client">,
117+
threadId: ThreadId,
118+
): string => {
119+
const origin = scope.client?.webOrigin;
120+
return origin === undefined
121+
? formatThreadLink({ environmentId: scope.environmentId, threadId })
122+
: `${origin}/${encodeURIComponent(scope.environmentId)}/${encodeURIComponent(threadId)}`;
123+
};
124+
108125
export class McpInvocationContext extends Context.Service<
109126
McpInvocationContext,
110127
McpInvocationScope

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {
22
CommandId,
3-
type EnvironmentId,
43
type RunId,
54
isProviderAvailable,
65
MessageId,
@@ -108,6 +107,7 @@ import {
108107
type McpInvocationScope,
109108
type McpThreadInvocationScope,
110109
requireThreadScope,
110+
threadLinkFor,
111111
} from "./McpInvocationContext.ts";
112112
import * as Metrics from "../observability/Metrics.ts";
113113
import {
@@ -752,15 +752,15 @@ function threadPullRequests(
752752
}
753753

754754
function listItemFromShell(
755-
environmentId: EnvironmentId,
755+
scope: McpInvocationScope,
756756
shell: OrchestrationV2ThreadShell,
757757
nowMs: number,
758758
): OrchestratorMcpThreadListItem {
759759
return {
760760
threadId: shell.id,
761761
projectId: shell.projectId,
762762
title: shell.title,
763-
link: formatThreadLink({ environmentId, threadId: shell.id }),
763+
link: threadLinkFor(scope, shell.id),
764764
createdBy: shell.createdBy,
765765
creationSource: shell.creationSource,
766766
status: shell.activityRunStatus ?? shell.status,
@@ -782,7 +782,7 @@ function listItemFromShell(
782782
}
783783

784784
function threadDetail(
785-
environmentId: EnvironmentId,
785+
scope: McpInvocationScope,
786786
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "runtimeRequests">,
787787
itemCount: number,
788788
shell: OrchestrationV2ThreadShell,
@@ -794,7 +794,7 @@ function threadDetail(
794794
threadId: projection.thread.id,
795795
projectId: projection.thread.projectId,
796796
title: projection.thread.title,
797-
link: formatThreadLink({ environmentId, threadId: projection.thread.id }),
797+
link: threadLinkFor(scope, projection.thread.id),
798798
createdBy: projection.thread.createdBy,
799799
creationSource: projection.thread.creationSource,
800800
status: active?.status ?? latest?.status ?? "idle",
@@ -2806,7 +2806,7 @@ const make = Effect.gen(function* () {
28062806
return {
28072807
projectId,
28082808
currentThreadId: parent?.thread.id ?? null,
2809-
threads: page.map((shell) => listItemFromShell(scope.environmentId, shell, nowMs)),
2809+
threads: page.map((shell) => listItemFromShell(scope, shell, nowMs)),
28102810
nextCursor,
28112811
total: filtered.length,
28122812
} satisfies OrchestratorMcpThreadListResult;
@@ -2887,7 +2887,7 @@ const make = Effect.gen(function* () {
28872887
}
28882888
return {
28892889
thread: threadDetail(
2890-
scope.environmentId,
2890+
scope,
28912891
target,
28922892
timeline.totalItems,
28932893
shell,
@@ -2951,7 +2951,7 @@ const make = Effect.gen(function* () {
29512951
);
29522952
return {
29532953
threadId: input.threadId,
2954-
link: formatThreadLink({ environmentId: scope.environmentId, threadId: input.threadId }),
2954+
link: threadLinkFor(scope, input.threadId),
29552955
messageId,
29562956
runId: result.run.id,
29572957
...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }),

‎apps/server/src/mcp/toolkits/project/handlers.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const clientLaunchHarness = (input: {
4242
readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
4343
readonly workspaceRoot?: string;
4444
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
45+
readonly webOrigin?: string;
4546
}) => {
4647
const projectId = ProjectId.make("project:client-target");
4748
const modelSelection = {
@@ -75,6 +76,7 @@ const clientLaunchHarness = (input: {
7576
sessionId: "session-1",
7677
label: "Claude Code",
7778
access: input.runtimeModeCeiling,
79+
webOrigin: input.webOrigin,
7880
},
7981
issuedAt: 0,
8082
capabilities: new Set(["orchestration" as const]),
@@ -155,15 +157,17 @@ it.effect(
155157
readonly runtimeMode?: RuntimeMode;
156158
readonly targeted?: false;
157159
readonly overrideModel?: ModelSelection;
160+
readonly webOrigin?: string;
158161
},
159162
) {
160-
const { targeted, overrideModel, ...input } = params;
163+
const { targeted, overrideModel, webOrigin, ...input } = params;
161164
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
162165
const { projectId, modelSelection, dependencies } = clientLaunchHarness({
163166
runtimeModeCeiling,
164167
defaultRuntimeMode,
165168
launched,
166169
...(overrideModel === undefined ? {} : { overrideModel }),
170+
...(webOrigin === undefined ? {} : { webOrigin }),
167171
});
168172
const toolkit = yield* ProjectToolkit.pipe(
169173
Effect.provide(
@@ -190,8 +194,14 @@ it.effect(
190194
expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");
191195
expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
192196

193-
const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", { title: "Fix" });
197+
const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", {
198+
title: "Fix",
199+
webOrigin: "https://box.example.ts.net",
200+
});
194201
expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits");
202+
expect(aboveCeiling.result).toMatchObject({
203+
link: `https://box.example.ts.net/environment/${encodeURIComponent(aboveCeiling.launched[0]?.threadId ?? "")}`,
204+
});
195205

196206
const requested = yield* launchWith("full-access", "approval-required", {
197207
title: "Fix",

‎apps/server/src/mcp/toolkits/project/handlers.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import * as Repositories from "../../../sourceControl/SourceControlRepositorySer
1919
import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
2020
import * as ServerSettings from "../../../serverSettings.ts";
2121
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
22-
import { formatThreadLink } from "@t3tools/shared/threadLinks";
2322
import { resolveRuntimeMode } from "../../delegatedTaskModes.ts";
2423
import * as McpInvocationContext from "../../McpInvocationContext.ts";
2524
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -240,7 +239,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
240239
const run = result.projection.runs.find((run) => run.userMessageId === messageId);
241240
return {
242241
threadId: thread.id,
243-
link: formatThreadLink({ environmentId: scope.environmentId, threadId: thread.id }),
242+
link: McpInvocationContext.threadLinkFor(scope, thread.id),
244243
projectId: thread.projectId,
245244
modelSelection: thread.modelSelection,
246245
runId: run?.id ?? null,

0 commit comments

Comments
 (0)