Harden remote connect and subscription handling

- Scope cleartext mobile config to development
- Fix stale loads, ordering, and terminal reuse
- Clean up terminal metadata subscriptions on failure
This commit is contained in:
Julius Marminge committed 2026-05-20 11:05:37 +02:00
1 parent 4ac2618403
commit 7f03f4d19a
15 files changed
+276 -47

No files matched your search

+9 -4
View File
@@ -49,6 +49,7 @@ function resolveAppVariant(value: string | undefined): AppVariant {
}
const variant = VARIANT_CONFIG[APP_VARIANT];
const allowsCleartextTraffic = APP_VARIANT === "development";
const config: ExpoConfig = {
name: variant.appName,
@@ -77,9 +78,13 @@ const config: ExpoConfig = {
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
infoPlist: {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
},
...(allowsCleartextTraffic
? {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
},
}
: {}),
ITSAppUsesNonExemptEncryption: false,
},
},
@@ -128,7 +133,7 @@ const config: ExpoConfig = {
],
"expo-secure-store",
"expo-router",
"./plugins/withAndroidCleartextTraffic.cjs",
...(allowsCleartextTraffic ? ["./plugins/withAndroidCleartextTraffic.cjs"] : []),
],
extra: {
appVariant: APP_VARIANT,
@@ -768,6 +768,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
didSet {
tokenColorsByHex.removeAll()
tokenAttributedStringsByRowId.removeAll()
setNeedsDisplayForVisibleBounds()
}
}
private(set) var contentHeight: CGFloat = 0
@@ -1007,6 +1008,10 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
}
let point = gesture.location(in: self)
if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) {
return
}
guard let rowIndex = rowIndex(at: verticalOffset + point.y),
rows.indices.contains(rowIndex) else {
return
@@ -1420,6 +1425,10 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
lastDecelerationTimestamp = 0
}
deinit {
stopHorizontalDeceleration()
}
override func draw(_ rect: CGRect) {
let drawStartedAt = CACurrentMediaTime()
guard let context = UIGraphicsGetCurrentContext() else {
@@ -1914,7 +1923,6 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
let change = row.change ?? "context"
rowBackground(for: change).setFill()
context.fill(rect)
drawSelectionOverlay(row, rect: rect, context: context)
if change == "add" {
theme.addBar.setFill()
@@ -1926,6 +1934,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
)
}
drawSelectionOverlay(row, rect: rect, context: context)
let lineNumber = row.newLineNumber ?? row.oldLineNumber
if let lineNumber {
drawRightAlignedText(
@@ -59,4 +59,35 @@ describe("applyDiffRangesToTokens", () => {
},
]);
});
it("skips exhausted ranges when later tokens start after the last range", () => {
const tokens = [
{
content: "a",
color: "#fff",
fontStyle: null,
},
{
content: "b",
color: "#fff",
fontStyle: null,
},
];
const nextTokens = applyDiffRangesToTokens(tokens, [{ start: 0, end: 1 }]);
expect(nextTokens).toEqual([
{
content: "a",
color: "#fff",
fontStyle: null,
diffHighlight: true,
},
{
content: "b",
color: "#fff",
fontStyle: null,
},
]);
});
});
@@ -208,7 +208,7 @@ export function applyDiffRangesToTokens(
return;
}
while ((ranges[rangeIndex]?.end ?? 0) <= tokenStart) {
while (rangeIndex < ranges.length && ranges[rangeIndex]!.end <= tokenStart) {
rangeIndex += 1;
}
@@ -1,6 +1,6 @@
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useState } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
@@ -41,6 +41,8 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
});
const lastGridSizeRef = useRef(lastGridSize);
lastGridSizeRef.current = lastGridSize;
const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
const isRunning = terminal.status === "running" || terminal.status === "starting";
@@ -73,13 +75,11 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
terminalId,
cwd: props.cwd,
worktreePath: props.worktreePath,
cols: lastGridSize.cols,
rows: lastGridSize.rows,
cols: lastGridSizeRef.current.cols,
rows: lastGridSizeRef.current.rows,
},
});
}, [
lastGridSize.cols,
lastGridSize.rows,
props.cwd,
props.environmentId,
props.threadId,
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type {
EnvironmentId,
@@ -152,6 +152,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
const branchLoadVersionRef = useRef(0);
const [prompt, setPrompt] = useState("");
const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
const [submitting, setSubmitting] = useState(false);
@@ -329,11 +330,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}, [availableBranches, branchQuery]);
const setProject = useCallback((project: EnvironmentScopedProjectShell) => {
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
setSelectedProjectKey(nextProjectKey);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
setSelectedBranchName(null);
@@ -355,12 +361,17 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
try {
const result = await vcsRefManager.load({
environmentId: selectedProject.environmentId,
cwd: selectedProject.workspaceRoot,
query: null,
});
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
return;
}
setPendingConnectionError(null);
const branches = pipe(
result?.refs ?? [],
@@ -377,9 +388,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}
}
} catch {
if (loadVersion !== branchLoadVersionRef.current) {
return;
}
setPendingConnectionError("Failed to load branches.");
}
}, [selectedBranchName, selectedProject, workspaceMode]);
}, [selectedBranchName, selectedProject, selectedProjectKey, workspaceMode]);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
+68 -4
View File
@@ -108,10 +108,74 @@ describe("groupProjectsByRepository", () => {
threadCount: 2,
});
expect(
groups[0]?.projects
.map((entry) => entry.project.environmentId)
.toSorted((left, right) => left.localeCompare(right)),
).toEqual(["env-local", "env-staging"]);
groups[0]?.projects.map((entry) => ({
environmentId: entry.project.environmentId,
latestActivityAt: entry.latestActivityAt,
threads: entry.threads.map((thread) => thread.id),
})),
).toEqual([
{
environmentId: "env-local",
latestActivityAt: "2026-04-03T12:00:00.000Z",
threads: ["thread-1"],
},
{
environmentId: "env-staging",
latestActivityAt: "2026-04-02T12:00:00.000Z",
threads: ["thread-2"],
},
]);
expect(groups[0]?.latestActivityAt).toBe("2026-04-03T12:00:00.000Z");
});
it("orders threads, projects, and repository groups by latest activity", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("older-project"),
title: "Older",
}),
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("newer-project"),
title: "Newer",
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("older-thread"),
projectId: ProjectId.make("older-project"),
title: "Older thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newer-thread"),
projectId: ProjectId.make("older-project"),
title: "Newer thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-04T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newest-thread"),
projectId: ProjectId.make("newer-project"),
title: "Newest thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-05T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups.map((group) => group.title)).toEqual(["Newer", "Older"]);
expect(groups[1]?.projects[0]?.threads.map((thread) => thread.id)).toEqual([
"newer-thread",
"older-thread",
]);
});
it("falls back to a scoped project key when repository identity is unavailable", () => {
+5 -3
View File
@@ -8,6 +8,8 @@ import {
EnvironmentScopedThreadShell,
} from "@t3tools/client-runtime";
const DateDescending = Order.flip(Order.Date);
export interface MobileRepositoryProjectGroup {
readonly key: string;
readonly project: EnvironmentScopedProjectShell;
@@ -83,7 +85,7 @@ export function groupProjectsByRepository(input: {
const threads = Arr.sortWith(
threadsByProjectKey.get(projectKey) ?? [],
(s) => new Date(s.updatedAt ?? s.createdAt),
Order.Date,
DateDescending,
);
const latestActivityAt = deriveProjectLatestActivity(project, threads);
@@ -123,10 +125,10 @@ export function groupProjectsByRepository(input: {
projects: Arr.sortWith(
[...existing.projects, projectGroup],
(s) => new Date(s.latestActivityAt),
Order.Date,
DateDescending,
),
});
}
return Arr.sortWith([...grouped.values()], (s) => new Date(s.latestActivityAt), Order.Date);
return Arr.sortWith(grouped.values(), (s) => new Date(s.latestActivityAt), DateDescending);
}
@@ -1351,6 +1351,27 @@ it.layer(
}),
);
it.effect("removes terminal metadata subscriptions when initial delivery fails", () =>
Effect.gen(function* () {
const { manager } = yield* createManager();
yield* manager.open(openInput({ threadId: "existing-thread" }));
const leakedLiveEvents = yield* Ref.make(0);
const exit = yield* Effect.exit(
manager.subscribeMetadata((event) =>
event.type === "snapshot"
? Effect.die("snapshot listener failed")
: Ref.update(leakedLiveEvents, (count) => count + 1),
),
);
expect(Exit.isFailure(exit)).toBe(true);
yield* manager.open(openInput({ threadId: "new-thread" }));
expect(yield* Ref.get(leakedLiveEvents)).toBe(0);
}),
);
it.effect(
"streams attach snapshots followed by live events without duplicate start snapshots",
() =>
+11 -1
View File
@@ -2223,7 +2223,17 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
unsubscribe?.();
unsubscribe = null;
};
});
}).pipe(
Effect.catchCause((cause) =>
Effect.flatMap(
Effect.sync(() => {
unsubscribe?.();
unsubscribe = null;
}),
() => Effect.failCause(cause),
),
),
);
};
const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) {
+13 -17
View File
@@ -989,6 +989,10 @@ export default function ChatView(props: ChatViewProps) {
() => activeThreadKnownSessions.map((session) => session.target.terminalId),
[activeThreadKnownSessions],
);
const activeKnownTerminalIds = useMemo(
() => [...new Set([...activeServerOrderedTerminalIds, ...terminalUiState.terminalIds])],
[activeServerOrderedTerminalIds, terminalUiState.terminalIds],
);
const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds);
const activeThreadRef = useMemo(
() => (activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null),
@@ -2011,7 +2015,7 @@ export default function ChatView(props: ChatViewProps) {
if (!api) {
return;
}
const terminalId = nextTerminalId(activeServerOrderedTerminalIds);
const terminalId = nextTerminalId(activeKnownTerminalIds);
storeSplitTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
void (async () => {
@@ -2032,7 +2036,7 @@ export default function ChatView(props: ChatViewProps) {
})();
}, [
activeProject,
activeServerOrderedTerminalIds,
activeKnownTerminalIds,
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
@@ -2053,7 +2057,7 @@ export default function ChatView(props: ChatViewProps) {
if (!api) {
return;
}
const terminalId = nextTerminalId(activeServerOrderedTerminalIds);
const terminalId = nextTerminalId(activeKnownTerminalIds);
storeNewTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
void (async () => {
@@ -2074,7 +2078,7 @@ export default function ChatView(props: ChatViewProps) {
})();
}, [
activeProject,
activeServerOrderedTerminalIds,
activeKnownTerminalIds,
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
@@ -2086,7 +2090,7 @@ export default function ChatView(props: ChatViewProps) {
(terminalId: string) => {
const api = readEnvironmentApi(environmentId);
if (!activeThreadId || !api || !activeThreadRef) return;
const isFinalTerminal = activeServerOrderedTerminalIds.length <= 1;
const isFinalTerminal = activeKnownTerminalIds.length <= 1;
const fallbackExitWrite = () =>
api.terminal
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
@@ -2110,13 +2114,7 @@ export default function ChatView(props: ChatViewProps) {
storeCloseTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[
activeThreadId,
activeThreadRef,
activeServerOrderedTerminalIds,
environmentId,
storeCloseTerminal,
],
[activeThreadId, activeThreadRef, activeKnownTerminalIds, environmentId, storeCloseTerminal],
);
const runProjectScript = useCallback(
async (
@@ -2139,9 +2137,7 @@ export default function ChatView(props: ChatViewProps) {
}
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
const baseTerminalId =
terminalUiState.activeTerminalId ||
activeServerOrderedTerminalIds[0] ||
DEFAULT_THREAD_TERMINAL_ID;
terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal = wantsNewTerminal;
@@ -2166,7 +2162,7 @@ export default function ChatView(props: ChatViewProps) {
...(options?.env ? { extraEnv: options.env } : {}),
});
const targetTerminalId = shouldCreateNewTerminal
? nextTerminalId(activeServerOrderedTerminalIds)
? nextTerminalId(activeKnownTerminalIds)
: baseTerminalId;
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
? {
@@ -2218,7 +2214,7 @@ export default function ChatView(props: ChatViewProps) {
storeSetActiveTerminal,
setLastInvokedScriptByProjectId,
environmentId,
activeServerOrderedTerminalIds,
activeKnownTerminalIds,
runningTerminalIds,
terminalUiState.activeTerminalId,
],
@@ -252,6 +252,31 @@ describe("createVcsRefManager", () => {
expect(manager.getSnapshot(queriedTarget)).toEqual(EMPTY_VCS_REF_STATE);
});
it("invalidates target in-flight loads before they can write stale data", async () => {
const firstLoad = deferred<VcsListRefsResult>();
let callCount = 0;
const listRefs = vi.fn((async () => {
callCount += 1;
return callCount === 1 ? firstLoad.promise : SECOND_PAGE;
}) satisfies VcsRefClient["listRefs"]);
const client = { listRefs } satisfies VcsRefClient;
const manager = createVcsRefManager({
getRegistry: () => atomRegistry,
getClient: () => client,
});
const staleLoad = manager.load(TARGET, client);
manager.invalidate(TARGET);
const freshLoad = manager.load(TARGET, client);
expect(listRefs).toHaveBeenCalledTimes(2);
firstLoad.resolve(FIRST_PAGE);
await expect(staleLoad).resolves.toEqual(FIRST_PAGE);
await expect(freshLoad).resolves.toEqual(SECOND_PAGE);
expect(manager.getSnapshot(TARGET).data).toEqual(SECOND_PAGE);
});
it("watches refs with a ref-counted client-change subscription", async () => {
const mock = createMockClient();
let listener: () => void = noop;
@@ -389,14 +389,22 @@ export function createVcsRefManager(config: VcsRefManagerConfig) {
if (target) {
const targetKey = getVcsRefTargetKey(target);
if (targetKey !== null) {
bumpLoadVersion(targetKey);
setState(targetKey, EMPTY_VCS_REF_STATE);
for (const key of inFlight.keys()) {
if (key.startsWith(`${targetKey}:`)) {
inFlight.delete(key);
}
}
}
return;
}
for (const key of knownVcsRefKeys) {
bumpLoadVersion(key);
setState(key, EMPTY_VCS_REF_STATE);
}
inFlight.clear();
}
function invalidateScope(scope: VcsRefScope): void {
@@ -3,6 +3,7 @@ import type {
VcsStatusRemoteResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { ORCHESTRATION_WS_METHODS, ThreadId, WS_METHODS } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vitest";
vi.mock("./wsTransport.ts", () => ({
@@ -127,4 +128,36 @@ describe("createWsRpcClient", () => {
],
]);
});
it("tags stream subscriptions for targeted resubscribe handling", () => {
const subscribe = vi.fn(() => () => undefined);
const transport = {
dispose: vi.fn(async () => undefined),
reconnect: vi.fn(async () => undefined),
request: vi.fn(),
requestStream: vi.fn(),
subscribe,
} satisfies Pick<
WsTransport,
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
>;
const client = createWsRpcClient(transport as unknown as WsTransport);
const listener = vi.fn();
client.terminal.onMetadata(listener);
client.vcs.onStatus({ cwd: "/repo" }, listener);
client.server.subscribeConfig(listener);
client.orchestration.subscribeThread({ threadId: ThreadId.make("thread-1") }, listener);
const subscribeCalls = subscribe.mock.calls as unknown as Array<
readonly [unknown, unknown, { readonly tag?: string }?]
>;
expect(subscribeCalls.map((call) => call[2]?.tag)).toEqual([
WS_METHODS.subscribeTerminalMetadata,
WS_METHODS.subscribeVcsStatus,
WS_METHODS.subscribeServerConfig,
ORCHESTRATION_WS_METHODS.subscribeThread,
]);
});
});
+18 -8
View File
@@ -23,6 +23,16 @@ interface StreamSubscriptionOptions {
readonly onResubscribe?: () => void;
}
function subscriptionOptions(
options: StreamSubscriptionOptions | undefined,
tag: string,
): StreamSubscriptionOptions & { readonly tag: string } {
return {
...options,
tag,
};
}
type RpcUnaryMethod<TTag extends RpcTag> =
RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer TSuccess, any, any>
? (input: RpcInput<TTag>) => Promise<TSuccess>
@@ -145,7 +155,7 @@ export function createWsRpcClient(
transport.subscribe(
(client) => client[WS_METHODS.terminalAttach](input),
listener,
options,
subscriptionOptions(options, WS_METHODS.terminalAttach),
),
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
resize: (input) => transport.request((client) => client[WS_METHODS.terminalResize](input)),
@@ -156,7 +166,7 @@ export function createWsRpcClient(
transport.subscribe(
(client) => client[WS_METHODS.subscribeTerminalMetadata]({}),
listener,
options,
subscriptionOptions(options, WS_METHODS.subscribeTerminalMetadata),
),
},
projects: {
@@ -184,7 +194,7 @@ export function createWsRpcClient(
current = applyGitStatusStreamEvent(current, event);
listener(current);
},
options,
subscriptionOptions(options, WS_METHODS.subscribeVcsStatus),
);
},
runStackedAction: async (input, options) => {
@@ -238,19 +248,19 @@ export function createWsRpcClient(
transport.subscribe(
(client) => client[WS_METHODS.subscribeServerConfig]({}),
listener,
options,
subscriptionOptions(options, WS_METHODS.subscribeServerConfig),
),
subscribeLifecycle: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
listener,
options,
subscriptionOptions(options, WS_METHODS.subscribeServerLifecycle),
),
subscribeAuthAccess: (listener, options) =>
transport.subscribe(
(client) => client[WS_METHODS.subscribeAuthAccess]({}),
listener,
options,
subscriptionOptions(options, WS_METHODS.subscribeAuthAccess),
),
},
orchestration: {
@@ -264,13 +274,13 @@ export function createWsRpcClient(
transport.subscribe(
(client) => client[ORCHESTRATION_WS_METHODS.subscribeShell]({}),
listener,
options,
subscriptionOptions(options, ORCHESTRATION_WS_METHODS.subscribeShell),
),
subscribeThread: (input, listener, options) =>
transport.subscribe(
(client) => client[ORCHESTRATION_WS_METHODS.subscribeThread](input),
listener,
options,
subscriptionOptions(options, ORCHESTRATION_WS_METHODS.subscribeThread),
),
},
};