Skip to content

Commit 8cfe053

Browse files
authored
Merge branch 'main' into feat/text-generation-fallback-model
2 parents 26ddda2 + 807319c commit 8cfe053

18 files changed

Lines changed: 894 additions & 69 deletions

File tree

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { useLayoutEffect, useState } from "react";
2+
import { StyleSheet, View } from "react-native";
3+
import { GestureDetector, usePanGesture } from "react-native-gesture-handler";
4+
import Animated, {
5+
cancelAnimation,
6+
Easing,
7+
FadeOut,
8+
ReduceMotion,
9+
runOnJS,
10+
useAnimatedStyle,
11+
useSharedValue,
12+
withTiming,
13+
type EntryAnimationsValues,
14+
} from "react-native-reanimated";
15+
import { useSafeAreaInsets } from "react-native-safe-area-context";
16+
import { Toast } from "../../components/ui/Toast";
17+
import { MOBILE_MOTION } from "../../lib/designTokens";
18+
import {
19+
dismissThreadUndoNotice,
20+
readThreadUndoNotice,
21+
useThreadUndoNotice,
22+
} from "./thread-undo-notice";
23+
24+
const SWIPE_TIMING = { duration: 160, reduceMotion: ReduceMotion.System };
25+
const ENTER_TIMING = {
26+
duration: MOBILE_MOTION.enter,
27+
easing: Easing.out(Easing.cubic),
28+
reduceMotion: ReduceMotion.System,
29+
};
30+
const NOTICE_EXITING = FadeOut.duration(MOBILE_MOTION.exit).reduceMotion(ReduceMotion.System);
31+
const noticeEntering = (values: EntryAnimationsValues) => {
32+
"worklet";
33+
return {
34+
initialValues: { originY: values.targetOriginY + values.targetHeight + 12 },
35+
animations: { originY: withTiming(values.targetOriginY, ENTER_TIMING) },
36+
};
37+
};
38+
39+
export function ThreadUndoNotice(props: { readonly visible: boolean }) {
40+
const notice = useThreadUndoNotice();
41+
// Replacing a notice must also cancel the native gesture tracking the old one.
42+
const [instance, setInstance] = useState({ notice, key: 0 });
43+
if (instance.notice !== notice) setInstance({ notice, key: instance.key + 1 });
44+
if (!props.visible || notice === null) return null;
45+
return <SwipeableUndoNotice key={instance.key} notice={notice} />;
46+
}
47+
48+
function SwipeableUndoNotice(props: {
49+
readonly notice: NonNullable<ReturnType<typeof useThreadUndoNotice>>;
50+
}) {
51+
const { notice } = props;
52+
const insets = useSafeAreaInsets();
53+
const translation = useSharedValue(0);
54+
const width = useSharedValue(0);
55+
56+
useLayoutEffect(
57+
() => () => {
58+
cancelAnimation(translation);
59+
},
60+
[translation],
61+
);
62+
63+
const dismiss = () => {
64+
// A newer action can replace the notice while the swipe is animating out.
65+
if (readThreadUndoNotice() === notice) dismissThreadUndoNotice();
66+
};
67+
const gesture = usePanGesture({
68+
activeOffsetX: [-10, 10],
69+
failOffsetY: [-12, 12],
70+
onUpdate: (event) => {
71+
translation.set(event.translationX);
72+
},
73+
onDeactivate: (event) => {
74+
if (
75+
!event.canceled &&
76+
(Math.abs(event.translationX) > width.value * 0.25 ||
77+
(Math.abs(event.velocityX) > 800 && event.translationX * event.velocityX > 0))
78+
) {
79+
const direction = Math.sign(event.translationX || event.velocityX);
80+
translation.set(
81+
withTiming(direction * (width.value + 24), SWIPE_TIMING, (finished) => {
82+
if (finished) runOnJS(dismiss)();
83+
}),
84+
);
85+
} else {
86+
translation.set(withTiming(0, SWIPE_TIMING));
87+
}
88+
},
89+
});
90+
const animatedStyle = useAnimatedStyle(() => ({
91+
transform: [{ translateX: translation.value }],
92+
}));
93+
94+
// Clip the entrance above navigation; the notice intentionally covers the anchored FAB.
95+
return (
96+
<Animated.View
97+
className="absolute inset-x-3 z-[100] overflow-hidden"
98+
style={{ bottom: insets.bottom + 12 }}
99+
pointerEvents="box-none"
100+
exiting={NOTICE_EXITING}
101+
onLayout={(event) => {
102+
width.set(event.nativeEvent.layout.width);
103+
}}
104+
>
105+
<GestureDetector gesture={gesture}>
106+
<Animated.View collapsable={false} entering={noticeEntering} style={animatedStyle}>
107+
{/* Keep the dismiss target separate so TalkBack can also focus Undo. */}
108+
<View
109+
accessible
110+
accessibilityRole="alert"
111+
accessibilityLiveRegion="assertive"
112+
accessibilityLabel={`${notice.action} thread`}
113+
accessibilityActions={[{ name: "dismiss", label: "Dismiss message" }]}
114+
onAccessibilityAction={({ nativeEvent }) => {
115+
if (nativeEvent.actionName === "dismiss") dismiss();
116+
}}
117+
pointerEvents="none"
118+
style={StyleSheet.absoluteFill}
119+
/>
120+
<Toast
121+
message={`${notice.action} thread`}
122+
action={{ label: "Undo", onPress: () => void notice.undo() }}
123+
/>
124+
</Animated.View>
125+
</GestureDetector>
126+
</Animated.View>
127+
);
128+
}

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

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
import * as NodeStream from "node:stream";
33

44
import { describe, expect, it } from "@effect/vitest";
5+
import * as Deferred from "effect/Deferred";
56
import * as Effect from "effect/Effect";
67
import * as Fiber from "effect/Fiber";
78

8-
import { runAcpMcpStdioBridge } from "./AcpMcpStdioBridge.ts";
9+
import { mcpToolSession, runAcpMcpStdioBridge } from "./AcpMcpStdioBridge.ts";
910

1011
function makeHarness(responder: (request: Request) => Promise<Response> | Response) {
1112
const input = new NodeStream.PassThrough();
@@ -29,6 +30,13 @@ function makeHarness(responder: (request: Request) => Promise<Response> | Respon
2930
return { input, written, requests, bridge };
3031
}
3132

33+
function pendingFetch(started: Deferred.Deferred<AbortSignal | undefined>) {
34+
return (_url: string, init?: RequestInit): Promise<Response> => {
35+
Deferred.doneUnsafe(started, Effect.succeed(init?.signal ?? undefined));
36+
return new Promise(() => {});
37+
};
38+
}
39+
3240
describe("AcpMcpStdioBridge", () => {
3341
it.effect("forwards requests and replays the session id and protocol version", () =>
3442
Effect.gen(function* () {
@@ -282,4 +290,43 @@ describe("AcpMcpStdioBridge", () => {
282290
expect(JSON.parse(written[0]!)).toMatchObject({ id: 7, result: {} });
283291
}),
284292
);
293+
294+
it.effect("aborts the pending fetch when a tool call is interrupted", () =>
295+
Effect.gen(function* () {
296+
const started = yield* Deferred.make<AbortSignal | undefined>();
297+
const fiber = yield* mcpToolSession({
298+
endpoint: "http://127.0.0.1:1/mcp",
299+
authorization: "Bearer bridge-test",
300+
clientName: "t3-code-acp-cli",
301+
fetchImplementation: pendingFetch(started),
302+
}).pipe(
303+
Effect.flatMap((session) => session.call("orchestrator_capabilities", {})),
304+
Effect.scoped,
305+
Effect.forkChild,
306+
);
307+
308+
const signal = yield* Deferred.await(started);
309+
yield* Fiber.interrupt(fiber);
310+
expect(signal?.aborted).toBe(true);
311+
}),
312+
);
313+
314+
it.effect("aborts the pending fetch when the stdio bridge is interrupted", () =>
315+
Effect.gen(function* () {
316+
const started = yield* Deferred.make<AbortSignal | undefined>();
317+
const input = new NodeStream.PassThrough();
318+
const fiber = yield* runAcpMcpStdioBridge({
319+
endpoint: "http://127.0.0.1:1/mcp",
320+
authorization: "Bearer bridge-test",
321+
input,
322+
output: { write: () => undefined },
323+
fetchImplementation: pendingFetch(started),
324+
}).pipe(Effect.forkChild);
325+
326+
input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })}\n`);
327+
const signal = yield* Deferred.await(started);
328+
yield* Fiber.interrupt(fiber);
329+
expect(signal?.aborted).toBe(true);
330+
}),
331+
);
285332
});

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,12 @@ export const mcpToolSession = (
9292
message: unknown,
9393
): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
9494
const response = yield* Effect.tryPromise({
95-
try: () =>
95+
try: (signal) =>
9696
fetchImplementation(options.endpoint, {
9797
method: "POST",
9898
headers: { "content-type": "application/json", ...headers() },
9999
body: JSON.stringify(message),
100+
signal,
100101
}),
101102
catch: bridgeError,
102103
});
@@ -212,7 +213,7 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
212213
)(
213214
function* (line: string, envelope: JsonRpcEnvelope) {
214215
const response = yield* Effect.tryPromise({
215-
try: () =>
216+
try: (signal) =>
216217
fetchImplementation(options.endpoint, {
217218
method: "POST",
218219
headers: {
@@ -223,6 +224,7 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
223224
...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
224225
},
225226
body: line,
227+
signal,
226228
}),
227229
catch: bridgeError,
228230
});

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,79 @@ const makeFailedHandle = (stderr: string) =>
8787
stderr: Stream.encodeText(Stream.make(stderr)),
8888
});
8989

90+
describe("Git output collection", () => {
91+
// Git writes in arbitrary chunk sizes; one byte per chunk splits every
92+
// multibyte character across reads.
93+
const byteChunks = (text: string) =>
94+
Stream.fromIterable(Array.from(new TextEncoder().encode(text), (byte) => Uint8Array.of(byte)));
95+
const makeDriver = (output: { stdout?: string; stderr?: string }) =>
96+
makeGitVcsDriverCore().pipe(
97+
Effect.provideService(
98+
ChildProcessSpawner.ChildProcessSpawner,
99+
ChildProcessSpawner.make(() =>
100+
Effect.succeed(
101+
ChildProcessSpawner.makeHandle({
102+
...makeSuccessfulHandle(""),
103+
stdout: byteChunks(output.stdout ?? ""),
104+
stderr: byteChunks(output.stderr ?? ""),
105+
}),
106+
),
107+
),
108+
),
109+
);
110+
111+
it.effect("returns the same split UTF-8 and NUL output with and without line callbacks", () =>
112+
Effect.gen(function* () {
113+
const stdout = "a\\b\0雪\nlast ";
114+
const stderr = "Receiving é\r\nUpdating 雪\rdone";
115+
const driver = yield* makeDriver({ stdout, stderr });
116+
const input = { operation: "test.chunkedGitOutput", cwd: "/repo", args: ["status"] };
117+
const expected = {
118+
exitCode: 0,
119+
stdout,
120+
stderr,
121+
stdoutTruncated: false,
122+
stderrTruncated: false,
123+
};
124+
125+
assert.deepEqual(yield* driver.execute(input), expected);
126+
127+
const stdoutLines: string[] = [];
128+
const stderrLines: string[] = [];
129+
const withCallbacks = yield* driver.execute({
130+
...input,
131+
progress: {
132+
onStdoutLine: (line) => Effect.sync(() => void stdoutLines.push(line)),
133+
onStderrLine: (line) => Effect.sync(() => void stderrLines.push(line)),
134+
},
135+
});
136+
assert.deepEqual(withCallbacks, expected);
137+
assert.deepEqual(stdoutLines, ["a\\b\0雪", "last "]);
138+
assert.deepEqual(stderrLines, ["Receiving é", "Updating 雪", "done"]);
139+
}).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
140+
);
141+
142+
it.effect("caps output without line callbacks", () =>
143+
Effect.gen(function* () {
144+
const driver = yield* makeDriver({ stderr: "é雪\rdone" });
145+
const input = {
146+
operation: "test.cappedGitOutput",
147+
cwd: "/repo",
148+
args: ["status"],
149+
maxOutputBytes: 3,
150+
};
151+
152+
const truncated = yield* driver.execute({ ...input, appendTruncationMarker: true });
153+
assert.equal(truncated.stderr, "é\uFFFD");
154+
assert.isTrue(truncated.stderrTruncated);
155+
156+
const error = yield* driver.execute(input).pipe(Effect.flip);
157+
assert.equal(error.outputLength, 4);
158+
assert.include(error.detail, "exceeded 3 bytes");
159+
}).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
160+
);
161+
});
162+
90163
const makeTmpDir = (
91164
prefix = "git-vcs-driver-test-",
92165
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -900,8 +900,10 @@ const collectOutput = Effect.fnUntraced(function* (
900900

901901
const decoded = decoder.decode(chunkToDecode, { stream: !truncated });
902902
text += decoded;
903-
lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded;
904-
yield* emitCompleteLines(false);
903+
if (onLine) {
904+
lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded;
905+
yield* emitCompleteLines(false);
906+
}
905907
});
906908

907909
yield* Stream.runForEach(stream, processChunk).pipe(
@@ -917,9 +919,11 @@ const collectOutput = Effect.fnUntraced(function* (
917919

918920
const remainder = truncated ? "" : decoder.decode();
919921
text += remainder;
920-
lineBuffer += remainder;
921-
if (lineDecoder) lineBuffer += lineDecoder.decode();
922-
yield* emitCompleteLines(true);
922+
if (onLine) {
923+
lineBuffer += remainder;
924+
if (lineDecoder) lineBuffer += lineDecoder.decode();
925+
yield* emitCompleteLines(true);
926+
}
923927
return {
924928
text,
925929
truncated,

0 commit comments

Comments
 (0)