Skip to content

Commit 02fb555

Browse files
committed
fix(server): preserve focus routing and host PR access boundaries
1 parent 65c59e9 commit 02fb555

7 files changed

Lines changed: 76 additions & 17 deletions

File tree

‎apps/server/src/clientIntents.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ const make = Effect.gen(function* () {
6464
return yield* subscriptionLock.withPermit(
6565
Effect.gen(function* () {
6666
const targetClientId = Array.from(windows.values())
67-
.filter((window) => window.environmentId === input.environmentId)
67+
.filter(
68+
(window) => window.environmentId === input.environmentId && window.focusedOrder > 0,
69+
)
6870
.sort(
6971
(left, right) =>
7072
right.focusedOrder - left.focusedOrder ||

‎apps/server/src/mcp/toolkits/core.test.ts‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ import { McpSchema, McpServer, Tool } from "effect/ai";
1919
import { FetchHttpClient } from "effect/http";
2020

2121
import * as ServerConfig from "../../config.ts";
22-
import { OrchestratorProjectionError } from "../../orchestration-v2/Orchestrator.ts";
22+
import {
23+
OrchestratorProjectionError,
24+
OrchestratorV2,
25+
} from "../../orchestration-v2/Orchestrator.ts";
2326
import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts";
2427
import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts";
2528
import * as PreviewBrowser from "../../preview/PreviewBrowser.ts";
@@ -305,6 +308,52 @@ const clientScope = (
305308
capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
306309
});
307310

311+
it.effect("gates host pull request reads before accessing another project's thread", () =>
312+
Effect.gen(function* () {
313+
let targetReads = 0;
314+
const server = yield* McpServer.McpServer;
315+
for (const runtimeModeCeiling of ["approval-required", "auto", "full-access"] as const) {
316+
const result = yield* server
317+
.callTool({
318+
name: "t3_pull_request_read",
319+
arguments: {
320+
threadId: "other-project-thread",
321+
url: "https://github.com/private/repo/pull/1",
322+
},
323+
})
324+
.pipe(
325+
Effect.provideService(
326+
McpInvocationContext.McpInvocationContext,
327+
clientScope(runtimeModeCeiling),
328+
),
329+
Effect.provideService(McpSchema.McpServerClient, client),
330+
Effect.provide(
331+
Layer.mock(ThreadManagement.ThreadManagementService)({
332+
getThreadShell: () =>
333+
Effect.sync(() => {
334+
targetReads += 1;
335+
return null;
336+
}),
337+
}),
338+
),
339+
);
340+
expect(declaredFailure(result)).toMatchObject({
341+
code: runtimeModeCeiling === "full-access" ? "thread_not_found" : "capability_denied",
342+
});
343+
expect(targetReads).toBe(runtimeModeCeiling === "full-access" ? 1 : 0);
344+
}
345+
}).pipe(
346+
Effect.provide(
347+
McpHttpServer.layerPullRequestsToolkit.pipe(
348+
Layer.provideMerge(McpServer.McpServer.layer),
349+
Layer.provide(NodeCrypto.layer),
350+
Layer.provide(Layer.mock(OrchestratorV2)({})),
351+
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
352+
),
353+
),
354+
),
355+
);
356+
308357
it.effect("a client caller targets any thread within its ceiling and cannot act as a thread", () =>
309358
Effect.gen(function* () {
310359
const server = yield* McpServer.McpServer;

‎apps/server/src/mcp/toolkits/environment/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ const EnvironmentReadTool = Tool.make("t3_environment_read", {
7272
const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update", {
7373
...shared,
7474
description:
75-
"Update environment-wide settings through normal settings persistence and notifications. Requires a live full-access/default calling thread or a full-access client. Omitted fields are preserved; empty customInstructions clears them. settings takes a patch of only the keys you change, shaped like t3_environment_read include=['settings'] (durations in milliseconds, nested objects merge; echoing the whole read back is rejected because some fields are read-only); credential fields (bitbucket, usageLimitSources, cursorKeychainUsageEnabled, providers.antigravity.apiKey, providers.opencode.serverPassword) and providerInstances/deviceHosts are rejected and stay in the Settings UI. providerInstance enables/disables one provider instance or replaces its custom models. keybinding upserts (optionally replacing an existing rule) or removes one rule matched by exact key/command/when text, in its own call; removing a command's last custom rule restores its default.",
75+
"Update environment-wide settings through normal settings persistence and notifications. Requires a live full-access/default calling thread or a full-access client. Omitted fields are preserved; empty customInstructions clears them. settings takes a patch of only the keys you change, shaped like t3_environment_read include=['settings'] (durations in milliseconds, nested objects merge; echoing the whole read back is rejected because some fields are read-only); credential fields (bitbucket, usageLimitSources, cursorKeychainUsageEnabled, providers.antigravity.apiKey, providers.opencode.serverPassword) and providerInstances/deviceHosts are rejected and stay in the Settings UI. providerInstance enables/disables one provider instance or replaces its custom models. keybinding upserts (optionally replacing an existing rule) or removes one rule matched by command and semantically equivalent key/when, in its own call; removing a command's last custom rule restores its default.",
7676
parameters: Schema.Struct({
7777
defaultThreadEnvMode: ServerSettingsPatch.fields.defaultThreadEnvMode,
7878
newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin,

‎apps/server/src/mcp/toolkits/provider/tools.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import {
66
UsageSummaryInput,
77
} from "@t3tools/contracts";
88
import * as Schema from "effect/Schema";
9-
import { Tool, Toolkit } from "effect/ai";
9+
import * as Tool from "effect/ai/Tool";
10+
import * as Toolkit from "effect/ai/Toolkit";
1011
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
1112
import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
1213
import * as UsageLimitSources from "../../../usage/UsageLimitSources.ts";

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

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -350,12 +350,12 @@ const make = Effect.gen(function* () {
350350

351351
/**
352352
* The host pull request a host-facing tool addresses. The thread only picks the project whose
353-
* checkout and credentials the host CLI runs with, so writes are gated on full access rather
353+
* checkout and credentials the host CLI runs with, so host calls are gated on full access rather
354354
* than on the thread.
355355
*/
356356
const resolveHostRef = Effect.fn("PullRequestsToolkit.resolveHostRef")(function* (
357357
input: PullRequestTargetInput,
358-
writable: boolean,
358+
fullAccess: boolean,
359359
) {
360360
yield* McpInvocationContext.requireMcpCapability("pull-requests").pipe(
361361
Effect.mapError(
@@ -366,9 +366,9 @@ const make = Effect.gen(function* () {
366366
}),
367367
),
368368
);
369-
if (writable)
369+
if (fullAccess)
370370
yield* readFullAccessCaller(
371-
"Pull request writes require a live full-access/default thread or a full-access client.",
371+
"Host pull request calls require a live full-access/default thread or a full-access client.",
372372
);
373373
const {
374374
projection: { thread },
@@ -460,7 +460,7 @@ const make = Effect.gen(function* () {
460460
unwatch_pull_request: (input) => setWatching(input, false),
461461
t3_pull_request_read: (input) =>
462462
Effect.gen(function* () {
463-
const { target, ref, service } = yield* resolveHostRef(input, false);
463+
const { target, ref, service } = yield* resolveHostRef(input, true);
464464
const budget = textBudget(input.maxCharacters ?? DEFAULT_PULL_REQUEST_CHARACTERS);
465465
const empty = { overview: null, checks: null, conversation: null, reviewThread: null };
466466
const login = (actor: { readonly login: string } | null | undefined) =>
@@ -486,8 +486,8 @@ const make = Effect.gen(function* () {
486486
state: detail.state,
487487
isDraft: detail.isDraft,
488488
author: login(detail.author),
489-
headBranch: budget.take(detail.headBranch),
490-
baseBranch: budget.take(detail.baseBranch),
489+
headBranch: detail.headBranch,
490+
baseBranch: detail.baseBranch,
491491
mergeability: detail.mergeability,
492492
baseComparison: detail.baseComparison ?? null,
493493
autoMergeEnabled: detail.autoMergeEnabled ?? null,
@@ -511,7 +511,7 @@ const make = Effect.gen(function* () {
511511
const activity = yield* service.activity(ref).pipe(Effect.mapError(hostFailure));
512512
const reviewThreadOf = (thread: PullRequestReviewThread) => ({
513513
id: thread.id,
514-
path: budget.take(thread.path),
514+
path: thread.path,
515515
line: thread.line,
516516
side: thread.side,
517517
isResolved: thread.isResolved,
@@ -530,7 +530,7 @@ const make = Effect.gen(function* () {
530530
.map((comment) => ({
531531
...threadComment(comment),
532532
kind: comment.kind,
533-
path: comment.path === null ? null : budget.take(comment.path),
533+
path: comment.path,
534534
reviewState: comment.reviewState,
535535
}))
536536
.toReversed();

‎apps/server/src/mcp/toolkits/pullRequests/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ const ThreadComment = Schema.Struct({
353353

354354
const ReadPullRequestTool = Tool.make("t3_pull_request_read", {
355355
description:
356-
"Read a pull request from its host (pass url, or repository plus number; threadId picks the project whose credentials are used, default this thread). section: overview (default: title, body, state, branches, mergeability, reviewers, labels, checks), checks (current check runs), conversation (comments and line review threads with resolution state; spend the text budget on unresolved threads and the newest comments first), or review_thread (more comments of one review thread: pass reviewThreadId and the cursor from its nextCommentsCursor). Display text is cut to maxCharacters in total (default 20,000, max 100,000) with truncated set when cut; identifiers, URLs, timestamps, cursors, and enum values stay intact. Check logs are not available; follow a check's url.",
356+
"Read a pull request from its host. Requires a live full-access/default calling thread or a full-access client (pass url, or repository plus number; threadId picks the project whose credentials are used, default this thread). section: overview (default: title, body, state, branches, mergeability, reviewers, labels, checks), checks (current check runs), conversation (comments and line review threads with resolution state; spend the text budget on unresolved threads and the newest comments first), or review_thread (more comments of one review thread: pass reviewThreadId and the cursor from its nextCommentsCursor). Display text is cut to maxCharacters in total (default 20,000, max 100,000) with truncated set when cut; identifiers, URLs, timestamps, cursors, and enum values stay intact. Check logs are not available; follow a check's url.",
357357
parameters: Schema.Struct({
358358
...PullRequestTargetInput.fields,
359359
section: Schema.optional(

‎apps/web/src/lib/backgroundActivityReporter.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,12 @@ export const layer = Layer.effectDiscard(
183183
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
184184
const clock = yield* Clock.Clock;
185185
const reportRequests = yield* Queue.sliding<void>(1);
186-
const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
186+
const focusReportRequests = yield* Queue.sliding<void>(1);
187+
const requestReport = (event?: Event) =>
188+
Queue.offerUnsafe(
189+
event?.type === "focus" || event?.type === "blur" ? focusReportRequests : reportRequests,
190+
undefined,
191+
);
187192
let lastInteractionAtMs = clock.currentTimeMillisUnsafe();
188193
const recordInteraction = () => {
189194
const observedAtMs = clock.currentTimeMillisUnsafe();
@@ -244,8 +249,10 @@ export const layer = Layer.effectDiscard(
244249
Stream.runForEach(() => Effect.sync(requestReport)),
245250
Effect.forkScoped,
246251
);
247-
yield* Stream.fromQueue(reportRequests).pipe(
248-
Stream.debounce("250 millis"),
252+
yield* Stream.merge(
253+
Stream.fromQueue(focusReportRequests),
254+
Stream.fromQueue(reportRequests).pipe(Stream.debounce("250 millis")),
255+
).pipe(
249256
Stream.runForEach(() => report),
250257
Effect.forkScoped,
251258
);

0 commit comments

Comments
 (0)