Skip to content
Merged
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
fix(desktop): keep new-session welcome and model labels stable
  • Loading branch information
SivanCola committed Nov 4, 2026
commit 1956aeaabc84b077fdb029791097129cb100af21
8 changes: 7 additions & 1 deletion desktop/blank_session_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ func (a *App) alignReusableBlankTabModel(tab *WorkspaceTab, model string) error
return fmt.Errorf("blank session changed while applying the default model; retry")
}
currentModel := strings.TrimSpace(tab.model)
workspaceRoot := tab.WorkspaceRoot
ctrl := tab.Ctrl
buildDone := tab.buildDone
a.mu.RUnlock()
Expand Down Expand Up @@ -62,6 +63,11 @@ func (a *App) alignReusableBlankTabModel(tab *WorkspaceTab, model string) error
// Fence the old build before publishing its replacement model. Legacy
// sources stay read-only; the replacement commits the selected model as a
// session/config event when it publishes its canonical identity.
cfg, err := config.LoadForRoot(workspaceRoot)
if err != nil {
return err
}
modelLabel := desktopModelLabel(cfg, model, "")
a.mu.Lock()
if tab.removed || a.tabs[tab.ID] != tab {
a.mu.Unlock()
Expand All @@ -74,7 +80,7 @@ func (a *App) alignReusableBlankTabModel(tab *WorkspaceTab, model string) error
a.supersedeTabBuildLocked(tab)
tab.effort = config.RebindSessionEffort(nil, tab.model, model, tab.effort)
tab.model = model
tab.Label = model
tab.Label = modelLabel
tab.Ready = false
clearTabStartupError(tab)
a.saveTabsLocked()
Expand Down
22 changes: 20 additions & 2 deletions desktop/frontend/bench/manual-creation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ await server.listen();
let browser;
try {
browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_EXECUTABLE });
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" });
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce", locale: "en-US" });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const address = server.httpServer.address();
Expand All @@ -32,7 +32,10 @@ try {
const operationFor = meta => [...operations.values()].find(op => op.ref.sessionId === (meta.session?.sessionId || meta.sessionId));
const startup = meta => {
const operation = operationFor(meta);
return operation?.phase === "starting" ? { ...meta, ready: false } : meta;
if (!operation) return meta;
// Older hosts can still send a qualified startup label. Catalog fallback
// must show the model ID even when no friendly model name is available.
return { ...meta, ready: operation.phase === "ready", label: operation.phase === "starting" ? "fixture-connection/org/custom-model" : "org/custom-model" };
};
installDesktopHostStub({ ...fallback,
BeginManualSessionCreation: async request => {
Expand All @@ -52,6 +55,9 @@ try {
ListManualSessionCreations: async () => [...operations.values()].filter(op => op.phase !== "ready"),
ListTabs: async () => (await fallback.ListTabs()).map(startup),
MetaForTab: async id => startup(await fallback.MetaForTab(id)),
ModelsForTab: async id => operationFor(await fallback.MetaForTab(id))
? [{ ref: "fixture-connection/org/custom-model", provider: "fixture-connection", model: "org/custom-model", current: true }]
: fallback.ModelsForTab(id),
});
window.manualCreationFixture = {
operations: () => [...operations.values()],
Expand All @@ -75,6 +81,10 @@ try {
assert.equal(await page.locator(".composer__btn--send").isDisabled(), true, "typing never sends before the new controller is ready");
const notice = page.getByTestId("creation-notice");
await notice.getByText(/You can type now/).waitFor();
const hero = page.locator(".chat-pane--creation-empty");
await hero.locator(".welcome-creation__headline").waitFor({ state: "visible" });
await hero.locator(".composer-workspace-bar").waitFor({ state: "visible" });
await page.waitForFunction(() => document.querySelector('.modelsw__label')?.textContent === 'org/custom-model');
assert.equal(await notice.locator("button").count(), 0, "preparation does not ask for any user choice");
const noticeBox = await notice.boundingBox();
const inputBox = await input.boundingBox();
Expand All @@ -92,6 +102,8 @@ try {
const second = await page.evaluate(() => window.manualCreationFixture.operations()[1]);
assert.notEqual(second.ref.sessionId, first.ref.sessionId, "each explicit new action allocates its own session");
await input.fill("Second new session input while starting");
await hero.locator(".composer-workspace-bar").waitFor({ state: "visible" });
const startingFrame = await page.locator(".composer-workspace-frame").boundingBox();
const firstReads = await page.evaluate(id => window.manualCreationFixture.reads(id), first.operationId);
await page.evaluate(id => window.manualCreationFixture.finish(id), first.operationId);
assert.equal(await page.evaluate(() => window.manualCreationFixture.active()), second.ref.sessionId);
Expand All @@ -100,6 +112,12 @@ try {
await page.waitForFunction(id => window.manualCreationFixture.observedReady(id), second.operationId);
await page.waitForFunction(() => !document.querySelector(".composer__btn--send")?.disabled);
await notice.waitFor({ state: "detached" });
await hero.locator(".welcome-creation__headline").waitFor({ state: "visible" });
await hero.locator(".composer-workspace-bar").waitFor({ state: "visible" });
assert.equal(await page.locator(".modelsw__label").textContent(), "org/custom-model", "runtime completion keeps the model name consistent");
const readyFrame = await page.locator(".composer-workspace-frame").boundingBox();
assert.ok(Math.abs(startingFrame.x - readyFrame.x) < 1 && Math.abs(startingFrame.width - readyFrame.width) < 1,
"startup completion retains the welcome composer width and position");
assert.equal(await input.inputValue(), "Second new session input while starting", "runtime completion preserves typed input");
assert.equal(await page.evaluate(() => window.manualCreationFixture.active()), second.ref.sessionId, "out-of-order startup never changes the user's selection");
assert.equal(await page.evaluate(id => window.manualCreationFixture.reads(id), first.operationId), firstReads, "leaving a starting session stops its request polling while the host continues");
Expand Down
35 changes: 35 additions & 0 deletions desktop/frontend/src/__tests__/model-switcher-refresh.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -587,5 +587,40 @@ for (const [index, fixture] of presetBrands.entries()) {
}
await Promise.all([...providerBrandIcons].map(id => access(new URL(`../../public/provider-icons/${id}.svg`, import.meta.url))));

// Catalogs belong to the selected surface. Neither a delayed response nor a
// failed pick in an old session may replace the new session's model name.
const delayedCatalog = deferred<ModelInfo[]>();
catalogLoader = () => delayedCatalog.promise;
await act(async () => root.render(renderSwitcher("org/new-model", "new-tab", false, "new-session")));
const modelText = () => document.querySelector(".modelsw__label")?.textContent;
if (modelText() !== "org/new-model") throw new Error("new tab displayed the outgoing session's catalog while loading");
await act(async () => {
delayedCatalog.resolve([{ ref: "connection/org/new-model", provider: "connection", model: "org/new-model", current: true }]);
await delayedCatalog.promise;
});
await act(async () => root.render(renderSwitcher("connection/org/new-model", "new-tab", false, "new-session")));
if (modelText() !== "org/new-model") throw new Error("a model without a friendly name exposed its connection ref");
await act(async () => root.render(renderSwitcher("org/new-model", "new-tab", true, "new-session")));
if (modelText() !== "org/new-model") throw new Error("runtime readiness changed the displayed model name");
await act(async () => root.render(renderSwitcher("org/new-model + planner custom", "new-tab", true, "new-session")));
if (modelText() !== "org/new-model + planner custom") throw new Error("catalog fallback hid the composite planner label");

const replacedCatalog = deferred<ModelInfo[]>();
catalogLoader = () => replacedCatalog.promise;
await act(async () => root.render(renderSwitcher("org/rebound-model", "new-tab", false, "rebound-session")));
if (modelText() !== "org/rebound-model") throw new Error("rebinding a tab displayed another session's catalog");
const latestCatalog = deferred<ModelInfo[]>();
catalogLoader = () => latestCatalog.promise;
await act(async () => root.render(renderSwitcher("org/latest-model", "new-tab", false, "latest-session")));
await act(async () => {
replacedCatalog.resolve([{ ref: "old/org/rebound-model", provider: "old", model: "org/rebound-model", current: true }]);
await replacedCatalog.promise;
});
if (modelText() !== "org/latest-model") throw new Error("late catalog replaced a rebound session's model label");
await act(async () => {
latestCatalog.resolve([{ ref: "latest/org/latest-model", provider: "latest", model: "org/latest-model", current: true }]);
await latestCatalog.promise;
});

await act(async () => root.unmount());
console.log(`model switcher refresh: PASS (${Object.keys(providerCatalog.catalogs).length} presets, ${presetBrands.length} brand cases in rail and list)`);
16 changes: 14 additions & 2 deletions desktop/frontend/src/__tests__/session-recovery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ const paintProjection = (input: TranscriptSurfaceProjectionInput) => act(async (
try {
await paintProjection(common);
assert.equal(projection.emptyHero, true, "successful empty history shows the welcome");
const startingAvailability = projectSessionAvailability({ local: { ...readyLocal, meta: { ...readyLocal.meta, ready: false } } });
assert.equal(startingAvailability.kind, "loading", "the runtime still fences submission while starting");
await paintProjection({ ...common, controllerReady: false, availability: startingAvailability });
assert.equal(projection.emptyHero, true, "readable empty sessions keep the welcome while the controller starts");
await paintProjection({ ...common, controllerReady: false, availability: { kind: "loading", source: "history" } });
assert.equal(projection.emptyHero, false, "unknown history is never presented as an empty session");
await paintProjection({ ...common, availability: startingAvailability, hydrating: true, hydrateHistoryLoaded: false });
assert.equal(projection.emptyHero, false, "history hydration keeps the main surface visible even during runtime startup");
await paintProjection({ ...common, availability: { kind: "error", source: "runtime" } });
assert.equal(projection.emptyHero, false, "startup failure retains recovery presentation");
const guidance = { key: "inbox-second", itemId: "inbox-second", text: "same guidance" };
await paintProjection({ ...common, items: [{ kind: "notice", id: "he:m:first", level: "info", text: "↪ same guidance" }] });
assert.equal(projection.latestGuidanceConsumed, null, "history rows never consume a matching pending draft");
Expand All @@ -49,8 +59,10 @@ try {
await paintProjection({ ...common, availability: projectSessionAvailability({ local: failedLocal }) });
assert.equal(projection.emptyHero, false, "failed history is not a successful empty session");
for (const partial of [{ sessionActivity: true }, { hydratePlaceholderActive: true, hydratePlaceholderItems: [] }, { sessionHasContent: true }]) {
await paintProjection({ ...common, ...partial });
assert.equal(projection.emptyHero, false, "decisions, running turns and content keep the main surface visible");
for (const availability of [common.availability, startingAvailability]) {
await paintProjection({ ...common, availability, ...partial });
assert.equal(projection.emptyHero, false, "decisions, running turns and content keep the main surface visible");
}
}

let retries = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,14 @@ export type TranscriptSurfaceProjectionInput = {
export function useTranscriptSurfaceProjection(input: TranscriptSurfaceProjectionInput) {
const { activeTabId, ports } = input;
const transcriptHydrating = input.hydrating && !input.hydrateHistoryLoaded;
// Show the hero only after history hydration settles on a truly empty session.
// Avoid flash while switching tabs: items may be empty while placeholders show.
// Exclude IM/Bot detail: hero CSS collapses .main, which also hosts that panel.
// Empty history owns the welcome layout; runtime readiness only gates sending.
// A new/restored blank session can be readable while its controller starts.
// History loading/errors and retained placeholders must still keep the main
// surface visible so switching to an existing session never flashes a hero.
const welcomeAvailable = input.availability.kind === "ready"
|| (input.availability.kind === "loading" && input.availability.source === "runtime");
const emptyHero =
input.availability.kind === "ready" &&
welcomeAvailable &&
!input.sessionActivity &&
!input.sessionHasContent &&
!transcriptHydrating &&
Expand Down
25 changes: 17 additions & 8 deletions desktop/frontend/src/components/ModelSwitcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { AnchoredPopover } from "./AnchoredPopover";
import { Tooltip } from "./Tooltip";
import { useModelApplicationStatus } from "../lib/useModelApplicationStatus";

const emptyModels: ModelInfo[] = [];

// ModelSwitcher opens an upward popover listing configured providers. Selecting
// one switches the active model while the current conversation continues.
export function ModelSwitcher({
Expand Down Expand Up @@ -42,7 +44,11 @@ export function ModelSwitcher({
const t = useT();
const application=useModelApplicationStatus(tabId);
const [open, setOpen] = useState(false);
const [models, setModels] = useState<ModelInfo[]>([]);
const catalogScope = JSON.stringify([tabId ?? "", sessionKey ?? ""]);
const [catalog, setCatalog] = useState<{ scope: string; models: ModelInfo[] }>({ scope: "", models: emptyModels });
// A new surface must not display the previous session's current model while
// its own catalog is loading (including rebinding within the same tab).
const models = catalog.scope === catalogScope ? catalog.models : emptyModels;
const [query, setQuery] = useState("");
const [activeFilter, setActiveFilter] = useState("all");
const [favorites, setFavorites] = useState<Set<string>>(() => readModelFavorites());
Expand All @@ -51,9 +57,11 @@ export function ModelSwitcher({
const inputRef = useRef<HTMLInputElement>(null);
const loadSeqRef = useRef(0);
const currentTabKeyRef = useRef(tabId ?? "");
const currentCatalogScopeRef = useRef(catalogScope);
const pendingPickCountByTabRef = useRef(new Map<string, number>());
const pickSeqByTabRef = useRef(new Map<string, number>());
currentTabKeyRef.current = tabId ?? "";
currentCatalogScopeRef.current = catalogScope;

useEffect(() => {
setOpen(false);
Expand All @@ -75,12 +83,12 @@ export function ModelSwitcher({
const seq = ++loadSeqRef.current;
return (targetTabId ? app.ModelsForTab(targetTabId) : app.Models())
.then((next) => {
if (seq === loadSeqRef.current && currentTabKeyRef.current === targetKey) {
setModels(asArray(next).map(normalizeModelInfo));
if (seq === loadSeqRef.current && currentTabKeyRef.current === targetKey && currentCatalogScopeRef.current === catalogScope) {
setCatalog({ scope: catalogScope, models: asArray(next).map(normalizeModelInfo) });
}
})
.catch(() => {});
}, []);
}, [catalogScope]);

const loadModels = useCallback(
() => loadModelsForTab(tabId),
Expand Down Expand Up @@ -155,7 +163,8 @@ export function ModelSwitcher({
const currentModel = useMemo(() => models.find((m) => m.current)
?? models.find((m) => m.model === label || m.ref === label), [label, models]);
const currentProvider = currentModel ? (currentModel.displayName?.trim() || providerLabel(currentModel.provider, t)) : null;
const displayLabel = currentModel?.modelDisplayName?.trim() || label;
const fallbackLabel = currentModel && (label === currentModel.ref || !label) ? currentModel.model : label;
const displayLabel = currentModel?.modelDisplayName?.trim() || fallbackLabel;
const triggerLabel = [displayLabel, currentModel && displayLabel !== currentModel.model ? currentModel.model : null, currentProvider, detailLabel].filter(Boolean).join(" · ");

const toggleFavorite = (ref: string) => {
Expand All @@ -182,7 +191,7 @@ export function ModelSwitcher({
// Catalog requests started before this click describe the outgoing model
// and must not overwrite the optimistic last-click choice.
loadSeqRef.current += 1;
setModels((prev) => prev.map((m) => ({ ...m, current: m.ref === model.ref })));
setCatalog({ scope: catalogScope, models: models.map((m) => ({ ...m, current: m.ref === model.ref })) });
pendingPickCountByTabRef.current.set(pendingKey, pendingPickCount + 1);
const settlePick = (switched: boolean) => {
const nextCount = Math.max(
Expand All @@ -196,11 +205,11 @@ export function ModelSwitcher({
if (
switched ||
pickSeqByTabRef.current.get(pendingKey) !== pickSeq ||
currentTabKeyRef.current !== pendingKey
currentTabKeyRef.current !== pendingKey || currentCatalogScopeRef.current !== catalogScope
) {
return;
}
setModels(previousModels);
setCatalog({ scope: catalogScope, models: previousModels });
void loadModelsForTab(tabId);
};
try {
Expand Down
7 changes: 7 additions & 0 deletions desktop/manual_creation_target_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,10 @@ func TestManualCreationOpensInputBeforeRuntimeReady(t *testing.T) {
if !preservedBuild {
t.Fatal("opening input built a competing runtime")
}
earlyLabel := a.metaForTab(early.ID).Label
if earlyLabel == "" {
t.Fatal("new session has no model label before runtime startup")
}
input, err := a.GetSessionComposerState(v.Ref)
if err != nil {
t.Fatal(err)
Expand All @@ -159,6 +163,9 @@ func TestManualCreationOpensInputBeforeRuntimeReady(t *testing.T) {
if !correct {
t.Fatal("initialization did not preserve the selected session")
}
if readyLabel := a.metaForTab(active.ID).Label; readyLabel != earlyLabel {
t.Fatalf("startup changed model label: %q -> %q", earlyLabel, readyLabel)
}
}

func TestManualCreationResolvesAbsorbedWorkspaceOnRecovery(t *testing.T) {
Expand Down
6 changes: 5 additions & 1 deletion desktop/manual_session_creation.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,13 @@ func (a *App) reserveManualSessionTab(ctx context.Context, view ManualSessionCre
}
}
settings := view.Settings
cfg, err := config.LoadForRoot(root)
if err != nil {
return nil, err
}
tab := &WorkspaceTab{Scope: view.Scope, WorkspaceRoot: desktopWorkspaceRoot(view.Scope, view.WorkspaceRoot),
SessionID: view.Ref.SessionID, TopicID: view.TopicID, TopicTitle: defaultTopicTitle, topicTitleSource: topicTitleSourceAuto,
PendingCreateOperationID: view.OperationID, model: settings.Model,
PendingCreateOperationID: view.OperationID, model: settings.Model, Label: desktopModelLabel(cfg, settings.Model, ""),
mode: tabModeForPlan(tabModeHasPlan(settings.Mode)),
toolApprovalMode: settings.ToolApprovalMode, disabledMCP: cloneServerViewMap(settings.DisabledMCP), mcpOrder: append([]string(nil), settings.MCPOrder...)}
tab.SessionWorkspace.ID = view.WorkspaceID
Expand Down
20 changes: 20 additions & 0 deletions desktop/model_catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,33 @@ package main

import (
"log/slog"
"strings"
"time"

"deepzora/internal/config"
"deepzora/internal/control"
"deepzora/internal/provider"
)

// Use the same configured name before and after boot, including while the
// renderer's catalog request is pending. Resolve the connection rather than
// splitting refs: routing model IDs can themselves contain slashes. Extension
// and composite controller labels remain owned by their runtime.
func desktopModelLabel(cfg *config.Config, ref, controllerLabel string) string {
entry, ok := cfg.ResolveModel(ref)
if !ok {
return controllerLabel
}
if controllerLabel != "" && controllerLabel != entry.Model {
return controllerLabel
}
info := configuredModelInfo(cfg, entry.Name, entry.Model, true)
if name := strings.TrimSpace(info.ModelDisplayName); name != "" {
return name
}
return entry.Model
}

func (a *App) recordModelSwitchTiming(tabID string, timing *modelSwitchTiming, started time.Time, result *error) {
timing.Total = time.Since(started)
if *result != nil {
Expand Down
Loading
Loading