chore: effect rpc and layer based startup (#929)
Co-authored-by: codex <[email protected]> Co-authored-by: Cursor Agent <[email protected]>
This commit is contained in:
116 files changed
+6706
-6678
No files matched your search
@@ -4,16 +4,14 @@ import "../index.css";
|
||||
import {
|
||||
EventId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
type MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
OrchestrationSessionStatus,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
@@ -32,8 +30,10 @@ import {
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { __resetNativeApiForTests } from "../nativeApi";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
@@ -44,25 +44,16 @@ const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
const BASE_TIME_MS = Date.parse(NOW_ISO);
|
||||
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
|
||||
|
||||
interface WsRequestEnvelope {
|
||||
id: string;
|
||||
body: {
|
||||
_tag: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
welcome: ServerLifecycleWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
|
||||
let wsClient: { send: (message: string) => void } | null = null;
|
||||
let pushSequence = 1;
|
||||
const rpcHarness = new BrowserWsRpcHarness();
|
||||
const wsRequests = rpcHarness.requests;
|
||||
let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -388,32 +379,20 @@ function createThreadCreatedEvent(threadId: ThreadId, sequence: number): Orchest
|
||||
}
|
||||
|
||||
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
|
||||
if (!wsClient) {
|
||||
throw new Error("WebSocket client not connected");
|
||||
}
|
||||
wsClient.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
|
||||
data: event,
|
||||
}),
|
||||
);
|
||||
rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event);
|
||||
}
|
||||
|
||||
async function waitForWsClient(): Promise<{ send: (message: string) => void }> {
|
||||
let client: { send: (message: string) => void } | null = null;
|
||||
async function waitForWsClient(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
client = wsClient;
|
||||
expect(client).toBeTruthy();
|
||||
expect(
|
||||
wsRequests.some(
|
||||
(request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents,
|
||||
),
|
||||
).toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
if (!client) {
|
||||
throw new Error("WebSocket client not connected");
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
|
||||
@@ -637,7 +616,7 @@ function createSnapshotWithPlanFollowUpPrompt(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
|
||||
const customResult = customWsRpcResolver?.(body);
|
||||
if (customResult !== undefined) {
|
||||
return customResult;
|
||||
@@ -684,6 +663,9 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.shellOpenInEditor) {
|
||||
return null;
|
||||
}
|
||||
if (tag === WS_METHODS.terminalOpen) {
|
||||
return {
|
||||
threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
|
||||
@@ -702,34 +684,11 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
wsClient = client;
|
||||
pushSequence = 1;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
void rpcHarness.connect(client);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: WsRequestEnvelope;
|
||||
try {
|
||||
request = JSON.parse(rawData) as WsRequestEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
wsRequests.push(request.body);
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(request.body),
|
||||
}),
|
||||
);
|
||||
void rpcHarness.onMessage(rawData);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () =>
|
||||
@@ -903,7 +862,9 @@ async function waitForInteractionModeButton(
|
||||
async function waitForServerConfigToApply(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true);
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe(
|
||||
true,
|
||||
);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
@@ -1041,7 +1002,7 @@ async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
configureFixture?: (fixture: TestFixture) => void;
|
||||
resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined;
|
||||
resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
options.configureFixture?.(fixture);
|
||||
@@ -1129,10 +1090,37 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rpcHarness.disconnect();
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await rpcHarness.reset({
|
||||
resolveUnary: resolveWsRpc,
|
||||
getInitialStreamValues: (request) => {
|
||||
if (request._tag === WS_METHODS.subscribeServerLifecycle) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
type: "welcome",
|
||||
payload: fixture.welcome,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === WS_METHODS.subscribeServerConfig) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: fixture.serverConfig,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
__resetNativeApiForTests();
|
||||
await setViewport(DEFAULT_VIEWPORT);
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
@@ -1342,6 +1330,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
@@ -1349,6 +1338,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
@@ -1384,6 +1376,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
@@ -1391,6 +1384,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
@@ -1426,6 +1422,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const menuButton = await waitForElement(
|
||||
() => document.querySelector('button[aria-label="Copy options"]'),
|
||||
"Unable to find Open picker button.",
|
||||
@@ -1474,7 +1471,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
it("falls back to the first installed editor when the stored favorite is unavailable", async () => {
|
||||
localStorage.setItem("t3code:last-editor", "vscodium");
|
||||
localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium"));
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1489,6 +1486,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
@@ -1496,6 +1494,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
|
||||
@@ -11,11 +11,9 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ServerProvider,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
OrchestrationThreadActivity,
|
||||
ProviderInteractionMode,
|
||||
@@ -30,7 +28,6 @@ import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||
import { isElectron } from "../env";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import {
|
||||
@@ -195,15 +192,18 @@ import {
|
||||
waitForStartedServerThread,
|
||||
} from "./ChatView.logic";
|
||||
import { useLocalStorage } from "~/hooks/useLocalStorage";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerConfig,
|
||||
useServerKeybindings,
|
||||
} from "~/rpc/serverState";
|
||||
|
||||
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
|
||||
@@ -794,8 +794,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDERS;
|
||||
const serverConfig = useServerConfig();
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? "codex",
|
||||
@@ -1202,8 +1202,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
|
||||
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
|
||||
const keybindings = useServerKeybindings();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => ({
|
||||
codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [],
|
||||
@@ -1698,10 +1698,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
if (isElectron && keybindingRule) {
|
||||
await api.server.upsertKeybinding(keybindingRule);
|
||||
await queryClient.invalidateQueries({ queryKey: serverQueryKeys.all });
|
||||
}
|
||||
},
|
||||
[queryClient],
|
||||
[],
|
||||
);
|
||||
const saveProjectScript = useCallback(
|
||||
async (input: NewProjectScriptInput) => {
|
||||
|
||||
@@ -294,74 +294,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
})
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Don't clear timestamps here — the HTTP response handler (line 496)
|
||||
// sets activeGitActionProgressRef to null and shows the success toast.
|
||||
// Clearing timestamps early causes the "Running for Xs" description
|
||||
// to disappear before the success state renders, leaving a bare
|
||||
// "Pushing..." toast in the gap between the WS event and HTTP response.
|
||||
return;
|
||||
case "action_failed":
|
||||
// Same reasoning as action_finished — let the HTTP error handler
|
||||
// manage the final toast state to avoid a flash of bare title.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
return api.git.onActionProgress(applyProgressEvent);
|
||||
}, [gitCwd, updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = window.setInterval(() => {
|
||||
if (!activeGitActionProgressRef.current) {
|
||||
@@ -483,12 +415,69 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
}
|
||||
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Let the resolved mutation update the toast so we keep the
|
||||
// elapsed description visible until the final success state renders.
|
||||
return;
|
||||
case "action_failed":
|
||||
// Let the rejected mutation publish the error toast to avoid a
|
||||
// transient intermediate state before the final failure message.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
actionId,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
onProgress: applyProgressEvent,
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
@@ -6,9 +6,8 @@ import {
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
type ServerConfig,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
type ThreadId,
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
@@ -18,8 +17,10 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { __resetNativeApiForTests } from "../nativeApi";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
|
||||
|
||||
const THREAD_ID = "thread-kb-toast-test" as ThreadId;
|
||||
const PROJECT_ID = "project-1" as ProjectId;
|
||||
@@ -28,12 +29,11 @@ const NOW_ISO = "2026-03-04T12:00:00.000Z";
|
||||
interface TestFixture {
|
||||
snapshot: OrchestrationReadModel;
|
||||
serverConfig: ServerConfig;
|
||||
welcome: WsWelcomePayload;
|
||||
welcome: ServerLifecycleWelcomePayload;
|
||||
}
|
||||
|
||||
let fixture: TestFixture;
|
||||
let wsClient: { send: (data: string) => void } | null = null;
|
||||
let pushSequence = 1;
|
||||
const rpcHarness = new BrowserWsRpcHarness();
|
||||
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
@@ -179,52 +179,23 @@ function resolveWsRpc(tag: string): unknown {
|
||||
|
||||
const worker = setupWorker(
|
||||
wsLink.addEventListener("connection", ({ client }) => {
|
||||
wsClient = client;
|
||||
pushSequence = 1;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: fixture.welcome,
|
||||
}),
|
||||
);
|
||||
void rpcHarness.connect(client);
|
||||
client.addEventListener("message", (event) => {
|
||||
const rawData = event.data;
|
||||
if (typeof rawData !== "string") return;
|
||||
let request: { id: string; body: { _tag: string; [key: string]: unknown } };
|
||||
try {
|
||||
request = JSON.parse(rawData);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const method = request.body?._tag;
|
||||
if (typeof method !== "string") return;
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
}),
|
||||
);
|
||||
void rpcHarness.onMessage(rawData);
|
||||
});
|
||||
}),
|
||||
http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
|
||||
http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
|
||||
);
|
||||
|
||||
function sendServerConfigUpdatedPush(issues: Array<{ kind: string; message: string }>) {
|
||||
if (!wsClient) throw new Error("WebSocket client not connected");
|
||||
wsClient.send(
|
||||
JSON.stringify({
|
||||
type: "push",
|
||||
sequence: pushSequence++,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues,
|
||||
providers: fixture.serverConfig.providers,
|
||||
},
|
||||
}),
|
||||
);
|
||||
function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
|
||||
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
|
||||
version: 1,
|
||||
type: "keybindingsUpdated",
|
||||
payload: { issues },
|
||||
});
|
||||
}
|
||||
|
||||
function queryToastTitles(): string[] {
|
||||
@@ -308,13 +279,39 @@ describe("Keybindings update toast", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rpcHarness.disconnect();
|
||||
await worker.stop();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
await rpcHarness.reset({
|
||||
resolveUnary: (request) => resolveWsRpc(request._tag),
|
||||
getInitialStreamValues: (request) => {
|
||||
if (request._tag === WS_METHODS.subscribeServerLifecycle) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
sequence: 1,
|
||||
type: "welcome",
|
||||
payload: fixture.welcome,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (request._tag === WS_METHODS.subscribeServerConfig) {
|
||||
return [
|
||||
{
|
||||
version: 1,
|
||||
type: "snapshot",
|
||||
config: fixture.serverConfig,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
__resetNativeApiForTests();
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
pushSequence = 1;
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
|
||||
@@ -1,30 +1,15 @@
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
function getServerHttpOrigin(): string {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsUrl =
|
||||
bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
|
||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
||||
try {
|
||||
return new URL(httpUrl).origin;
|
||||
} catch {
|
||||
return httpUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const serverHttpOrigin = getServerHttpOrigin();
|
||||
import { resolveServerUrl } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Set<string>();
|
||||
|
||||
export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) {
|
||||
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
|
||||
const src = resolveServerUrl({
|
||||
protocol: "http",
|
||||
pathname: "/api/project-favicon",
|
||||
searchParams: { cwd },
|
||||
});
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
|
||||
);
|
||||
|
||||
@@ -43,9 +43,8 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import { useQueries } from "@tanstack/react-query";
|
||||
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
type SidebarProjectSortOrder,
|
||||
@@ -67,7 +66,6 @@ import {
|
||||
} from "../keybindings";
|
||||
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
||||
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
@@ -125,9 +123,8 @@ import {
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import type { Project, Thread } from "../types";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
@@ -469,10 +466,7 @@ export default function Sidebar() {
|
||||
strict: false,
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
});
|
||||
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
|
||||
...serverConfigQueryOptions(),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const keybindings = useServerKeybindings();
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
setDesktopUpdateStateQueryData,
|
||||
useDesktopUpdateState,
|
||||
} from "../../lib/desktopUpdateReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../../lib/serverReactQuery";
|
||||
import {
|
||||
MAX_CUSTOM_MODEL_LENGTH,
|
||||
getCustomModelOptionsByProvider,
|
||||
@@ -59,6 +58,11 @@ import { Switch } from "../ui/switch";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerKeybindingsConfigPath,
|
||||
useServerProviders,
|
||||
} from "../../rpc/serverState";
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{
|
||||
@@ -81,8 +85,6 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
|
||||
|
||||
type InstallProviderSettings = {
|
||||
provider: ProviderKind;
|
||||
title: string;
|
||||
@@ -516,7 +518,6 @@ export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({
|
||||
@@ -542,7 +543,6 @@ export function GeneralSettingsPanel() {
|
||||
>({});
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const refreshingRef = useRef(false);
|
||||
const queryClient = useQueryClient();
|
||||
const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
@@ -550,7 +550,6 @@ export function GeneralSettingsPanel() {
|
||||
setIsRefreshingProviders(true);
|
||||
void ensureNativeApi()
|
||||
.server.refreshProviders()
|
||||
.then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
@@ -558,11 +557,11 @@ export function GeneralSettingsPanel() {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, [queryClient]);
|
||||
}, []);
|
||||
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS;
|
||||
const keybindingsConfigPath = useServerKeybindingsConfigPath();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const serverProviders = useServerProviders();
|
||||
const codexHomePath = settings.providers.codex.homePath;
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
|
||||
Reference in new issue
Block a user