Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/browser/contexts/AgentContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,10 @@ function AgentProviderWithState(props: {
return <AgentContext.Provider value={agentContextValue}>{props.children}</AgentContext.Provider>;
}

export function useOptionalAgent(): AgentContextValue | undefined {
return useContext(AgentContext);
}

export function useAgent(): AgentContextValue {
const ctx = useContext(AgentContext);
if (!ctx) {
Expand Down
4 changes: 4 additions & 0 deletions src/browser/contexts/WorkspaceContext.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { createTestApiClient, type TestApiOverrides } from "@/browser/testUtils"
import { readPersistedState, updatePersistedState } from "@/browser/hooks/usePersistedState";
import { getProjectRouteId } from "@/common/utils/projectRouteId";
import {
getWorkspaceAiMetadata,
markAiSelectionIntent,
resetAiSelectionIntentForTests,
} from "@/browser/utils/aiSelectionIntent";
Expand Down Expand Up @@ -538,6 +539,9 @@ describe("WorkspaceContext", () => {
});
await setup();
await waitFor(() => expect(processed).toBe(true));
expect(getWorkspaceAiMetadata(workspaceId)?.aiSettings?.model).toBe(
archived ? undefined : "openai:gpt-5.2"
);
expect(readPersistedState<string | null>(getModelKey(workspaceId), null)).toBe(
archived ? null : "openai:gpt-5.2"
);
Expand Down
14 changes: 10 additions & 4 deletions src/browser/contexts/WorkspaceContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { normalizeAgentId, resolvePersistedAgentId } from "@/common/utils/agentI
import { WORKSPACE_DEFAULTS } from "@/constants/workspaceDefaults";
import {
hasPendingAiSelectionIntent,
setWorkspaceAiMetadata,
type AiSelectionField,
} from "@/browser/utils/aiSelectionIntent";
import type { APIClient } from "@/browser/contexts/API";
Expand All @@ -73,20 +74,25 @@ import {
import { createDraftId } from "@/common/utils/drafts";

/**
* Seed per-workspace localStorage from backend workspace metadata.
*
* This keeps a workspace's model/thinking consistent across devices/browsers.
* Record backend workspace AI metadata for the AI selection resolver and seed
* per-workspace localStorage from it.
*/
/** The metadata fields the seeding reads; the VS Code webview only receives these (#4738). */
export type WorkspaceAiSeedSource = Pick<
FrontendWorkspaceMetadata,
"id" | "agentId" | "agentType" | "parentWorkspaceId" | "aiSettings" | "aiSettingsByAgent"
>;
> &
Partial<Pick<FrontendWorkspaceMetadata, "projectPath">>;

export function seedWorkspaceLocalStorageFromBackend(
metadata: WorkspaceAiSeedSource,
previous?: WorkspaceAiSeedSource
): void {
setWorkspaceAiMetadata(metadata.id, {
projectPath: metadata.projectPath,
aiSettings: metadata.aiSettings,
aiSettingsByAgent: metadata.aiSettingsByAgent,
});
// Snapshot all main-workspace choices on client load, not on navigation.
// Later metadata must not overwrite unsent choices; reload to restore backend settings.
if (metadata.parentWorkspaceId == null && previous != null) {
Expand Down
57 changes: 56 additions & 1 deletion src/browser/utils/aiSelectionIntent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* a re-pick made while an earlier send is outstanding survives that send's consume.
*/
import type { AiSelectionIntent } from "@/common/types/agentAiSettings";
import type { FrontendWorkspaceMetadata } from "@/common/types/workspace";
import { getAgentIdKey } from "@/common/constants/storage";
import { normalizeSelectedModel } from "@/common/utils/ai/models";
import assert from "@/common/utils/assert";
Expand All @@ -25,8 +26,42 @@ interface PendingSelection {
token: number;
}

export type WorkspaceAiMetadata = Pick<
FrontendWorkspaceMetadata,
"aiSettings" | "aiSettingsByAgent"
> &
Partial<Pick<FrontendWorkspaceMetadata, "projectPath">>;

const pendingByScope = new Map<string, Partial<Record<AiSelectionField, PendingSelection>>>();
const metadataByWorkspace = new Map<string, WorkspaceAiMetadata>();
const listeners = new Set<() => void>();
let nextToken = 1;
let version = 0;

function notify(): void {
version++;
for (const listener of listeners) listener();
}

export function subscribeAiSelection(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}

export function getAiSelectionVersion(): number {
return version;
}

export function setWorkspaceAiMetadata(workspaceId: string, metadata: WorkspaceAiMetadata): void {
const previous = metadataByWorkspace.get(workspaceId);
if (JSON.stringify(previous) === JSON.stringify(metadata)) return;
metadataByWorkspace.set(workspaceId, metadata);
Comment thread
ibetitsmike marked this conversation as resolved.
notify();
}

export function getWorkspaceAiMetadata(workspaceId: string): WorkspaceAiMetadata | undefined {
return metadataByWorkspace.get(workspaceId);
}

function normalizeAgent(agentId: string): string {
return agentId.trim().toLowerCase() || WORKSPACE_DEFAULTS.agentId;
Expand Down Expand Up @@ -62,6 +97,15 @@ export function markAiSelectionIntent(
assert(normalized != null, "markAiSelectionIntent: value must be non-empty");
const token = nextToken++;
pendingByScope.set(key, { ...pendingByScope.get(key), [field]: { value: normalized, token } });
notify();
}

export function getPendingAiSelection(
workspaceId: string,
agentId: string,
field: AiSelectionField
): string | undefined {
return pendingByScope.get(`${workspaceId}\u0000${normalizeAgent(agentId)}`)?.[field]?.value;
}

/**
Expand Down Expand Up @@ -145,6 +189,7 @@ export function consumeAiSelectionIntent(
} else {
pendingByScope.set(key, next);
}
notify();
}

/** Whether a local field value still reflects an unsent deliberate pick (reseed guard). */
Expand All @@ -158,7 +203,17 @@ export function hasPendingAiSelectionIntent(
return selection != null && comparable(field, localValue) === selection.value;
}

/** Test-only: forget all pending picks. */
/** A removed provider's pending model picks would otherwise outrank the repaired settings. */
export function dropPendingModelPicks(shouldDrop: (model: string) => boolean): void {
for (const pending of pendingByScope.values()) {
if (pending.model != null && shouldDrop(pending.model.value)) delete pending.model;
}
notify();
}

/** Test-only: forget all pending picks and metadata. */
export function resetAiSelectionIntentForTests(): void {
pendingByScope.clear();
metadataByWorkspace.clear();
notify();
}
178 changes: 178 additions & 0 deletions src/browser/utils/workspaceAiSettingsSync.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { act, cleanup, renderHook } from "@testing-library/react";
import { GlobalWindow } from "happy-dom";
import { restoreDomGlobals, saveDomGlobals } from "../../../tests/ui/domGlobals";

import { updatePersistedState } from "@/browser/hooks/usePersistedState";
import { getAppConfigStore } from "@/browser/stores/AppConfigStore";
import {
markAiSelectionIntent,
resetAiSelectionIntentForTests,
setWorkspaceAiMetadata,
} from "@/browser/utils/aiSelectionIntent";
import {
getWorkspaceAiSelection,
useWorkspaceAiSelection,
type WorkspaceAiSelection,
} from "@/browser/utils/workspaceAiSettingsSync";
import { getProjectScopeId, getReasoningModeKey } from "@/common/constants/storage";
import type { OpenAIReasoningMode, ThinkingLevel } from "@/common/types/thinking";

const WS = "resolver-ws";
const PROJECT = "/repo";

type Tier = "pick" | "saved" | "legacy" | "configured" | "project";

function seed(tiers: readonly Tier[]): void {
const has = (tier: Tier) => tiers.includes(tier);
getAppConfigStore().updateOptimistically({
defaultModel: "openai:global",
agentAiDefaults: has("configured")
? { exec: { modelString: "openai:configured", thinkingLevel: "high", reasoningMode: "pro" } }
: {},
userPreferences: {
ai: {
globalDefaults: { thinkingLevel: "low" },
projectDefaults: has("project")
? { [PROJECT]: { model: "openai:project", thinkingLevel: "medium" } }
: undefined,
},
},
});
setWorkspaceAiMetadata(WS, {
projectPath: PROJECT,
aiSettings: has("legacy") ? { model: "openai:legacy", thinkingLevel: "xhigh" } : undefined,
aiSettingsByAgent: has("saved")
? { exec: { model: "openai:saved", thinkingLevel: "xhigh" } }
: undefined,
});
if (has("pick")) {
markAiSelectionIntent(WS, "model", "openai:picked");
markAiSelectionIntent(WS, "thinkingLevel", "max");
markAiSelectionIntent(WS, "reasoningMode", "pro");
}
}

describe("getWorkspaceAiSelection", () => {
beforeEach(() => {
saveDomGlobals();
globalThis.window = new GlobalWindow() as unknown as Window & typeof globalThis;
globalThis.document = globalThis.window.document;
globalThis.localStorage = globalThis.window.localStorage;
resetAiSelectionIntentForTests();
});

afterEach(() => {
cleanup();
resetAiSelectionIntentForTests();
getAppConfigStore().updateOptimistically({
defaultModel: undefined,
agentAiDefaults: undefined,
userPreferences: undefined,
});
restoreDomGlobals();
});

test("each field falls through the unsent pick, saved settings, agent and project defaults", () => {
const cases: Array<{
tiers: Tier[];
model: string;
thinkingLevel: ThinkingLevel;
reasoning: OpenAIReasoningMode;
}> = [
{
tiers: ["pick", "saved", "legacy", "configured", "project"],
model: "openai:picked",
thinkingLevel: "max",
reasoning: "pro",
},
{
tiers: ["saved", "legacy", "configured", "project"],
model: "openai:saved",
thinkingLevel: "xhigh",
// A saved bucket owns reasoning: its absent mode means standard.
reasoning: "standard",
},
{
tiers: ["legacy", "configured", "project"],
model: "openai:legacy",
thinkingLevel: "xhigh",
reasoning: "standard",
},
{
tiers: ["configured", "project"],
model: "openai:configured",
thinkingLevel: "high",
reasoning: "pro",
},
{
tiers: ["project"],
model: "openai:project",
thinkingLevel: "medium",
reasoning: "standard",
},
{ tiers: [], model: "openai:global", thinkingLevel: "low", reasoning: "standard" },
];

for (const testCase of cases) {
resetAiSelectionIntentForTests();
seed(testCase.tiers);
expect({ tiers: testCase.tiers, ...getWorkspaceAiSelection(WS, "exec") }).toEqual({
tiers: testCase.tiers,
model: testCase.model,
thinkingLevel: testCase.thinkingLevel,
reasoningMode: testCase.reasoning,
});
}
});

test("the hook follows a default model that loads after it rendered", () => {
setWorkspaceAiMetadata(WS, {
projectPath: PROJECT,
aiSettings: undefined,
aiSettingsByAgent: undefined,
});
const { result } = renderHook(() => useWorkspaceAiSelection(WS, "exec"));

act(() => getAppConfigStore().updateOptimistically({ defaultModel: "openai:loaded-later" }));

expect(result.current.model).toBe("openai:loaded-later");
});

test("a legacy workspace id that starts with __ resolves its saved settings", () => {
const legacyId = "__proj-main";
setWorkspaceAiMetadata(legacyId, {
projectPath: PROJECT,
aiSettings: undefined,
aiSettingsByAgent: { exec: { model: "openai:saved", thinkingLevel: "high" } },
});

const { result } = renderHook(() => useWorkspaceAiSelection(legacyId, "exec"));
expect(result.current.model).toBe("openai:saved");
expect(getWorkspaceAiSelection(legacyId, "exec").model).toBe("openai:saved");
});

test("a creation scope resolves its own defaults in the hook and the plain reader", () => {
const scopeId = getProjectScopeId(PROJECT);
// Workspace resolution would apply the configured Exec model here instead.
getAppConfigStore().updateOptimistically({
defaultModel: "openai:global",
agentAiDefaults: { exec: { modelString: "openai:configured" } },
userPreferences: {
ai: {
projectDefaults: { [PROJECT]: { model: "openai:project", thinkingLevel: "medium" } },
},
},
});
updatePersistedState(getReasoningModeKey(scopeId), "pro");

const expected: WorkspaceAiSelection = {
model: "openai:project",
thinkingLevel: "medium",
reasoningMode: "pro",
};
const { result } = renderHook(() => useWorkspaceAiSelection(scopeId));
expect(result.current).toEqual(expected);
expect(getWorkspaceAiSelection(scopeId)).toEqual(expected);
});
});
Loading
Loading