Skip to content

Commit 4777669

Browse files
Merge remote-tracking branch 'origin/main' into fix/issue-24895
2 parents a843632 + daa720a commit 4777669

35 files changed

Lines changed: 934 additions & 653 deletions

‎apps/mobile/src/features/pull-requests/pullRequestList.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import {
99
appendPullRequestListPage,
1010
DEFAULT_PR_LIST_CONTROLS,
11+
EMPTY_PULL_REQUEST_STATS_CACHE,
1112
filterPullRequestList,
1213
mergePullRequestListEntries,
1314
mergeEnvironmentPullRequestPages,
@@ -21,6 +22,8 @@ import {
2122
scopedPullRequestListKey,
2223
shownPullRequestListPages,
2324
pullRequestListRowsAreEqual,
25+
withAnsweredPullRequestStats,
26+
withListedPullRequests,
2427
withShownPullRequestStats,
2528
withoutScratchProjectScope,
2629
} from "./pullRequestList";
@@ -435,3 +438,37 @@ describe("shown PR diff stats", () => {
435438
expect(filled[1]).toBe(rows[1]);
436439
});
437440
});
441+
442+
describe("cached PR diff stats", () => {
443+
const stat = (number: number, additions: number) => ({
444+
projectId: "project" as PullRequestListEntry["projectId"],
445+
repository: "org/repo",
446+
number,
447+
additions,
448+
deletions: 0,
449+
});
450+
451+
it("drops a row's stat and refreshes its stats query when its updatedAt moves", () => {
452+
const query = {
453+
refs: [1, 2].map((number) => ({
454+
projectId: stat(number, 0).projectId,
455+
repository: "org/repo",
456+
number,
457+
})),
458+
};
459+
const listed = withListedPullRequests(EMPTY_PULL_REQUEST_STATS_CACHE, [entry(1), entry(2)]);
460+
expect(listed.refresh).toEqual([]);
461+
const answered = withAnsweredPullRequestStats(listed.cache, query, [stat(1, 5), stat(2, 7)]);
462+
expect(withListedPullRequests(answered, [entry(1), entry(2)])).toEqual({
463+
cache: answered,
464+
refresh: [],
465+
});
466+
467+
const pushed = withListedPullRequests(answered, [
468+
entry(1, { updatedAt: "2026-10-20T00:00:00Z" }),
469+
entry(2),
470+
]);
471+
expect([...pushed.cache.stats.values()]).toEqual([stat(2, 7)]);
472+
expect(pushed.refresh).toEqual([query]);
473+
});
474+
});

‎apps/mobile/src/features/pull-requests/pullRequestList.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
type PullRequestListEntry,
88
type PullRequestListInput,
99
type PullRequestListResult,
10+
type PullRequestListStatsInput,
1011
} from "@t3tools/contracts";
1112
import type { PullRequestListControls } from "../../persistence/mobile-preferences";
1213

@@ -50,6 +51,71 @@ export const pullRequestStatKey = (
5051
row: Pick<PullRequestDiffStat, "projectId" | "repository" | "number">,
5152
) => `${row.projectId}:${row.repository}:${row.number}`;
5253

54+
/**
55+
* Diff stats an environment has answered, the stats query that answered each, and each row's
56+
* `updatedAt` as its list last answered it.
57+
*/
58+
export interface PullRequestStatsCache {
59+
readonly stats: ReadonlyMap<string, PullRequestDiffStat>;
60+
readonly answeredBy: ReadonlyMap<string, PullRequestListStatsInput>;
61+
readonly updatedAt: ReadonlyMap<string, string>;
62+
}
63+
64+
export const EMPTY_PULL_REQUEST_STATS_CACHE: PullRequestStatsCache = {
65+
stats: new Map(),
66+
answeredBy: new Map(),
67+
updatedAt: new Map(),
68+
};
69+
70+
/**
71+
* Records the rows a list answered. Stats carry no head, so a row whose `updatedAt` moved (a push,
72+
* among other changes) drops its cached stat, and the stats queries that answered it are returned
73+
* to refresh: one can still be fresh and would otherwise answer the row's next read with the old
74+
* counts.
75+
*/
76+
export function withListedPullRequests(
77+
cache: PullRequestStatsCache,
78+
entries: readonly Pick<
79+
PullRequestListEntry,
80+
"projectId" | "repository" | "number" | "updatedAt"
81+
>[],
82+
): {
83+
readonly cache: PullRequestStatsCache;
84+
readonly refresh: readonly PullRequestListStatsInput[];
85+
} {
86+
const moved = entries.filter(
87+
(entry) => cache.updatedAt.get(pullRequestStatKey(entry)) !== entry.updatedAt,
88+
);
89+
if (!moved.length) return { cache, refresh: [] };
90+
const stats = new Map(cache.stats);
91+
const answeredBy = new Map(cache.answeredBy);
92+
const updatedAt = new Map(cache.updatedAt);
93+
const refresh = new Set<PullRequestListStatsInput>();
94+
for (const entry of moved) {
95+
const key = pullRequestStatKey(entry);
96+
const query = answeredBy.get(key);
97+
if (query) refresh.add(query);
98+
stats.delete(key);
99+
answeredBy.delete(key);
100+
updatedAt.set(key, entry.updatedAt);
101+
}
102+
return { cache: { stats, answeredBy, updatedAt }, refresh: [...refresh] };
103+
}
104+
105+
export function withAnsweredPullRequestStats(
106+
cache: PullRequestStatsCache,
107+
input: PullRequestListStatsInput,
108+
answered: readonly PullRequestDiffStat[],
109+
): PullRequestStatsCache {
110+
const stats = new Map(cache.stats);
111+
const answeredBy = new Map(cache.answeredBy);
112+
for (const row of answered) {
113+
stats.set(pullRequestStatKey(row), row);
114+
answeredBy.set(pullRequestStatKey(row), input);
115+
}
116+
return { ...cache, stats, answeredBy };
117+
}
118+
53119
/**
54120
* Fills rows that have no diff stat yet from the stats answers on screen. Returns `entries`
55121
* itself when no row changes, so the list keeps its identity across renders.

‎apps/mobile/src/features/pull-requests/usePullRequestList.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
185185
pages: {
186186
...pages,
187187
entries: pages.entries.map((entry) => {
188-
const stat = stats.get(statKey(entry));
188+
const stat = stats.stats.get(statKey(entry));
189189
return stat
190190
? { ...entry, additions: stat.additions, deletions: stat.deletions }
191191
: entry;

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,10 @@ function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentat
643643
if (item.type !== "dynamic_tool") {
644644
return null;
645645
}
646-
return resolveT3McpToolPresentation(item.toolName) ?? resolveT3McpToolPresentation(item.title);
646+
return (
647+
resolveT3McpToolPresentation(item.toolName, item.input) ??
648+
resolveT3McpToolPresentation(item.title, item.input)
649+
);
647650
}
648651

649652
function itemSummary(

‎apps/mobile/src/state/pull-requests.ts‎

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@ import {
22
createPullRequestEnvironmentAtoms,
33
createPullRequestStackAtomFamily,
44
} from "@t3tools/client-runtime/state/pull-requests";
5-
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
5+
import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
66
import * as Effect from "effect/Effect";
77
import * as Option from "effect/Option";
88
import { AsyncResult, Atom } from "effect/reactivity";
99
import { connectionAtomRuntime } from "../connection/runtime";
1010
import {
11+
EMPTY_PULL_REQUEST_STATS_CACHE,
1112
pullRequestListHead,
12-
pullRequestStatKey,
13+
withAnsweredPullRequestStats,
14+
withListedPullRequests,
1315
type PullRequestListPages,
16+
type PullRequestStatsCache,
1417
} from "../features/pull-requests/pullRequestList";
1518

1619
export const pullRequestListPagesKey = (target: {
@@ -25,7 +28,9 @@ export const pullRequestListPagesFamily = Atom.family((_key: string) =>
2528

2629
/** Diff stats each environment has answered so far, so rows keep them when they scroll away. */
2730
export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =>
28-
Atom.make<ReadonlyMap<string, PullRequestDiffStat>>(new Map()).pipe(Atom.setIdleTTL(5 * 60_000)),
31+
Atom.make<PullRequestStatsCache>(EMPTY_PULL_REQUEST_STATS_CACHE).pipe(
32+
Atom.setIdleTTL(5 * 60_000),
33+
),
2934
);
3035

3136
export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
@@ -38,20 +43,24 @@ export const composerPullRequests = createPullRequestEnvironmentAtoms(connection
3843
registry.refresh(composerPullRequests.filesViewed(target));
3944
}),
4045
list: (target, value, registry) =>
41-
target.input.cursors === undefined
42-
? Effect.sync(() =>
43-
registry.update(pullRequestListPagesFamily(pullRequestListPagesKey(target)), (previous) =>
44-
pullRequestListHead(previous, value),
45-
),
46-
)
47-
: Effect.void,
46+
Effect.sync(() => {
47+
const statsAtom = pullRequestListStatsFamily(target.environmentId);
48+
const { cache, refresh } = withListedPullRequests(registry.get(statsAtom), value.entries);
49+
registry.set(statsAtom, cache);
50+
for (const input of refresh)
51+
registry.refresh(
52+
composerPullRequests.listStats({ environmentId: target.environmentId, input }),
53+
);
54+
if (target.input.cursors === undefined)
55+
registry.update(pullRequestListPagesFamily(pullRequestListPagesKey(target)), (previous) =>
56+
pullRequestListHead(previous, value),
57+
);
58+
}),
4859
listStats: (target, value, registry) =>
4960
Effect.sync(() =>
50-
registry.update(pullRequestListStatsFamily(target.environmentId), (previous) => {
51-
const next = new Map(previous);
52-
for (const row of value.stats) next.set(pullRequestStatKey(row), row);
53-
return next;
54-
}),
61+
registry.update(pullRequestListStatsFamily(target.environmentId), (previous) =>
62+
withAnsweredPullRequestStats(previous, target.input, value.stats),
63+
),
5564
),
5665
});
5766
export const pullRequestStackAtom = createPullRequestStackAtomFamily(

‎apps/server/src/mcp/McpHttpServer.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ it.effect("refuses preview tools to a client outside a thread before they run",
344344
client: { sessionId: "session-1", label: "Claude Code", access: "read-only" as const },
345345
};
346346
const click = yield* server
347-
.callTool({ name: "preview_click", arguments: { locator: "text=Send" } })
347+
.callTool({ name: "preview_act", arguments: { action: "click", locator: "text=Send" } })
348348
.pipe(
349349
Effect.provideService(McpInvocationContext.McpInvocationContext, readOnly),
350350
Effect.provideService(McpSchema.McpServerClient, client),
@@ -356,6 +356,29 @@ it.effect("refuses preview tools to a client outside a thread before they run",
356356
}).pipe(Effect.provide(layerTest)),
357357
);
358358

359+
it.effect("checks each preview_act action against that action's own input", () =>
360+
Effect.scoped(
361+
Effect.gen(function* () {
362+
const inputs = yield* serveSnapshots("mcp-act-client", {});
363+
364+
const missingKey = yield* callTool("preview_act", { action: "press" });
365+
expect(missingKey.isError).toBe(true);
366+
expect(inputs).toEqual([]);
367+
368+
const click = yield* callTool("preview_act", {
369+
action: "click",
370+
locator: "text=Send",
371+
key: "Enter",
372+
});
373+
expect(click.isError).toBe(false);
374+
expect(inputs[0]).toEqual({ locator: "text=Send" });
375+
376+
yield* callTool("preview_act", { action: "type", selector: "#name", text: "Ada" });
377+
expect(inputs.at(-2)).toEqual({ selector: "#name", text: "Ada" });
378+
}),
379+
).pipe(Effect.provide(layerTest)),
380+
);
381+
359382
it.effect("decodes null optional arguments the way it decodes omitted ones", () => {
360383
const calls: Array<unknown> = [];
361384
return Effect.gen(function* () {

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

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
MAX_REPORTED_DEPTH,
3636
toolOutcome,
3737
} from "../telemetry/ProviderDimensions.ts";
38+
import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
3839
import * as McpInvocationContext from "./McpInvocationContext.ts";
3940
import * as McpToolAccess from "./McpToolAccess.ts";
4041
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
@@ -450,7 +451,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
450451
tool: new McpSchema.Tool({
451452
name: tool.name,
452453
description: Tool.getDescription(tool),
453-
inputSchema: Tool.getJsonSchema(tool),
454+
inputSchema: advertisedJsonSchema(tool),
454455
annotations: {
455456
...Context.getOption(tool.annotations, Tool.Title).pipe(
456457
Option.map((title) => ({ title })),
@@ -634,7 +635,7 @@ const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function*
634635
tool: new McpSchema.Tool({
635636
name: tool.name,
636637
description: Tool.getDescription(tool),
637-
inputSchema: Tool.getJsonSchema(tool),
638+
inputSchema: advertisedJsonSchema(tool),
638639
annotations: {
639640
...Context.getOption(tool.annotations, Tool.Title).pipe(
640641
Option.map((title) => ({ title })),
@@ -751,21 +752,31 @@ const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
751752
"t3_thread_launch",
752753
"t3_thread_send",
753754
"t3_thread_send_attachments",
754-
"t3_thread_fork",
755-
"t3_thread_merge_back",
756-
"t3_queue_edit",
757-
"t3_queue_promote_to_steer",
758-
"t3_pending_request_respond",
759755
"schedule_task",
760756
"run_scheduled_task_now",
761757
]);
762758

763-
/** Handoff tools whose result is only `{ sequence }`; their input names the receiving thread. */
764-
const INPUT_TARGET_TOOLS: ReadonlySet<string> = new Set([
765-
"t3_queue_edit",
766-
"t3_queue_promote_to_steer",
767-
"t3_pending_request_respond",
768-
]);
759+
/** Tool actions that hand work over with only a `{ sequence }` result; the input names the thread. */
760+
const INPUT_TARGET_ACTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
761+
t3_queue: new Set(["edit", "promote_to_steer"]),
762+
t3_pending_request: new Set(["respond"]),
763+
};
764+
765+
/** Tool actions that hand work over and name the receiving thread in their result. */
766+
const RESULT_TARGET_ACTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
767+
t3_thread_transfer: new Set(["fork", "merge_back"]),
768+
};
769+
770+
const hasAction = (
771+
actions: Readonly<Record<string, ReadonlySet<string>>>,
772+
tool: string,
773+
args: unknown,
774+
) =>
775+
actions[tool]?.has(String((args as { readonly action?: unknown } | null | undefined)?.action)) ===
776+
true;
777+
778+
const isInputTargetHandoff = (tool: string, args: unknown) =>
779+
hasAction(INPUT_TARGET_ACTIONS, tool, args);
769780

770781
const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
771782

@@ -787,7 +798,7 @@ const handoffTargetIds = (
787798
args: unknown,
788799
result: McpSchema.CallToolResult | undefined,
789800
): ReadonlyArray<string> => {
790-
if (!INPUT_TARGET_TOOLS.has(tool)) return resultThreadIds(result?.structuredContent);
801+
if (!isInputTargetHandoff(tool, args)) return resultThreadIds(result?.structuredContent);
791802
if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
792803
const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
793804
return typeof threadId === "string" ? [threadId] : [];
@@ -853,7 +864,10 @@ const withToolAnalytics =
853864
result: McpSchema.CallToolResult | undefined,
854865
durationMs: number,
855866
) {
856-
const handoff = HANDOFF_TOOLS.has(tool);
867+
const handoff =
868+
HANDOFF_TOOLS.has(tool) ||
869+
isInputTargetHandoff(tool, args) ||
870+
hasAction(RESULT_TARGET_ACTIONS, tool, args);
857871
const outcome = toolOutcome(result);
858872
// Agents call status, read, and preview tools in tight loops, so an
859873
// event per successful call floods analytics. Only failures count there.

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,16 @@ export const startsThreads = <P, A, E, R>(
181181
}),
182182
);
183183

184+
/** One tool with two access rules, picked per call, such as create versus update. */
185+
export const either = <P, A, E, R, A2, E2, R2>(
186+
useFirst: (params: P) => boolean,
187+
first: Declaration<(params: P) => Effect.Effect<A, E, R>>,
188+
second: Declaration<(params: P) => Effect.Effect<A2, E2, R2>>,
189+
) =>
190+
declare((params: P): Effect.Effect<A | A2, E | E2, R | R2> =>
191+
useFirst(params) ? checkedHandler(first)(params) : checkedHandler(second)(params),
192+
);
193+
184194
const fullAccessRequired =
185195
"Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
186196

0 commit comments

Comments
 (0)