diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a6fb21ded..cd71b7ec91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — desktop Studio endpoint model and key + +- Default Studio's model to the one the local endpoint serves, so the copied example request targets a served model and Apply serving mode does not switch models unless you choose another. Clear revealed API keys and ignore stale key-read results when the endpoint stops, changes or disconnects, requiring a fresh Reveal after it returns. Report clipboard or key-read failures instead of showing "Copied". Copying the base URL now confirms on its own button instead of on Copy example. + ## Unreleased — desktop hardware load - Serve real whole-machine load to the desktop app over the authenticated loopback control API: per-core CPU load with the chip's tier and cluster layout (including M5 Super cores), GPU utilization and memory, ANE activity, memory use and pressure, thermal state, and Darkbloom's share of GPU time. Sampling runs in the desktop API process only while the app is looking, without root, and never reaches heartbeats, logs or the coordinator. diff --git a/desktop-app/src/renderer/features/Studio.tsx b/desktop-app/src/renderer/features/Studio.tsx index 51dda3cd80..220ee25875 100644 --- a/desktop-app/src/renderer/features/Studio.tsx +++ b/desktop-app/src/renderer/features/Studio.tsx @@ -1,8 +1,8 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Check, Copy, Play, Terminal } from 'lucide-react'; import type { BackendState } from '../useBackend'; import { api } from '../useBackend'; -import { Button, Header, Status } from '../components/UI'; +import { Button, Header, Notice, Status } from '../components/UI'; export function Studio({ backend, @@ -13,18 +13,63 @@ export function Studio({ }) { const state = backend.state!; const [mode, setMode] = useState('combined'); - const [key, setKey] = useState(); - const [copied, setCopied] = useState(false); + const [revealed, setKey] = useState<{ identity: string; key: string }>(); + const keySession = useRef<{ identity: string; alive: boolean; request: number } | null>(null); + // Which value was just copied, so only that button confirms it. + const [copied, setCopied] = useState<'url' | 'example' | null>(null); + const [problem, setProblem] = useState(''); const models = state.models.filter((model) => model.downloaded && model.eligible); - const [selected, setSelected] = useState(''); - const model = selected || models[0]?.id || ''; const endpoint = state.endpoint; - const copy = async (value: string) => { - await api?.copy(value); - setCopied(true); - setTimeout(() => setCopied(false), 1600); + // Local credentials are independent of account sign-in. Ordinary snapshots and model + // changes preserve a reveal; endpoint/runtime changes require another explicit Reveal. + const keyIdentity = + endpoint?.authenticated && backend.status.state === 'ready' + ? JSON.stringify([state.installation_id, state.activity.started_at, endpoint.base_url]) + : undefined; + useEffect(() => { + setKey(undefined); + if (!keyIdentity) return; + const current = { identity: keyIdentity, alive: true, request: 0 }; + keySession.current = current; + return () => { + current.alive = false; + if (keySession.current === current) keySession.current = null; + }; + }, [keyIdentity]); + // Default to what the endpoint serves now, so the example works as copied and applying the + // serving mode does not switch models unless the user chooses another. + const served = endpoint?.models.filter((id) => models.some((model) => model.id === id)) ?? []; + const [selected, setSelected] = useState(''); + const model = selected || served[0] || models[0]?.id || ''; + const example = served.length && !served.includes(model) ? served[0] : model; + // Also mask during the render that precedes effect cleanup for a changed endpoint. + const key = revealed?.identity === keyIdentity ? revealed?.key : undefined; + const toggleKey = async () => { + const current = keySession.current; + if (!keyIdentity || !current?.alive || current.identity !== keyIdentity) return; + const request = ++current.request; + if (key) return setKey(undefined); + try { + setProblem(''); + const value = await api?.read<{ key: string }>('endpoint-key'); + if (current.alive && current.request === request) + setKey(value?.key ? { identity: current.identity, key: value.key } : undefined); + } catch { + if (current.alive && current.request === request) + setProblem('Couldn’t read the API key. Try again.'); + } + }; + const copy = async (value: string, what: 'url' | 'example') => { + try { + setProblem(''); + await api?.copy(value); + setCopied(what); + setTimeout(() => setCopied((current) => (current === what ? null : current)), 1600); + } catch { + setProblem('Couldn’t copy to the clipboard.'); + } }; - const curl = `curl ${endpoint?.base_url || 'http://127.0.0.1:8000/v1'}/chat/completions \\\n -H 'Authorization: Bearer ' \\\n -H 'Content-Type: application/json' \\\n -d '${JSON.stringify({ model, messages: [{ role: 'user', content: 'Hello' }] })}'`; + const curl = `curl ${endpoint?.base_url || 'http://127.0.0.1:8000/v1'}/chat/completions \\\n -H 'Authorization: Bearer ' \\\n -H 'Content-Type: application/json' \\\n -d '${JSON.stringify({ model: example, messages: [{ role: 'user', content: 'Hello' }] })}'`; return ( <>
void copy(endpoint.base_url)} + aria-label={copied === 'url' ? 'Base URL copied' : 'Copy base URL'} + onClick={() => void copy(endpoint.base_url, 'url')} > - + {copied === 'url' ? : } )}
API key {key || '••••••••••••••••'} -
- Requires an API key. Accessible only on this Mac. + + {endpoint?.authenticated === false ? 'No API key required.' : 'Requires an API key.'}{' '} + Accessible only on this Mac. + + {problem && {problem}}

Make a request

-
{curl}
diff --git a/desktop-app/tests/studio.test.tsx b/desktop-app/tests/studio.test.tsx new file mode 100644 index 0000000000..471c2154d2 --- /dev/null +++ b/desktop-app/tests/studio.test.tsx @@ -0,0 +1,363 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import '@testing-library/jest-dom/vitest'; +import type { Snapshot } from '../src/shared/contracts'; +import { Studio } from '../src/renderer/features/Studio'; +import { backendWith } from './onboardingFixtures'; +import { poolSnapshot } from './modelsFixtures'; + +const api = vi.hoisted(() => ({ read: vi.fn(), copy: vi.fn(), onNavigate: () => () => {} })); +vi.mock('../src/renderer/useBackend', () => ({ isPreview: false, api, useBackend: vi.fn() })); +afterEach(() => { + cleanup(); + vi.resetAllMocks(); +}); + +// The endpoint serves Gemma although GPT-OSS is the first downloaded model. +const serving = () => + poolSnapshot( + {}, + { + activity: { started_at: 1_790_000_000, samples: [] }, + endpoint: { + base_url: 'http://127.0.0.1:8000/v1', + authenticated: true, + models: ['gemma-4-26b'], + }, + }, + ); + +it('defaults to the model the endpoint serves, so the example works as copied', () => { + render(); + expect(screen.getByRole('combobox')).toHaveValue('gemma-4-26b'); + expect(document.querySelector('pre')).toHaveTextContent('"model":"gemma-4-26b"'); +}); + +it('reads keys only on Reveal and supports Hide followed by a fresh Reveal', async () => { + api.read.mockResolvedValue({ key: 'sk-local-test' }); + render(); + expect(api.read).not.toHaveBeenCalled(); + expect(api.copy).not.toHaveBeenCalled(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('sk-local-test')).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: 'Hide' })); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); + expect(api.read).toHaveBeenCalledExactlyOnceWith('endpoint-key'); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('sk-local-test')).toBeVisible(); + expect(api.read).toHaveBeenCalledTimes(2); + expect(api.copy).not.toHaveBeenCalled(); +}); + +it.each(['sk-local-test', 'sk-replacement-test'])( + 'requires a fresh Reveal after stop and reappearance, even when the next key is %s', + async (nextKey) => { + const initial = serving(); + api.read + .mockResolvedValueOnce({ key: 'sk-local-test' }) + .mockResolvedValueOnce({ key: nextKey }); + const view = render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('sk-local-test')).toBeVisible(); + view.rerender(); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Reveal' })).toBeDisabled(); + view.rerender(); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); + expect(api.read).toHaveBeenCalledTimes(1); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText(nextKey)).toBeVisible(); + expect(api.read).toHaveBeenCalledTimes(2); + }, +); + +const replacements: [string, (state: Snapshot) => Snapshot][] = [ + [ + 'base URL', + (state) => ({ + ...state, + endpoint: { ...state.endpoint!, base_url: 'http://127.0.0.1:8100/v1' }, + }), + ], + ['runtime instance', (state) => ({ ...state, installation_id: 'replacement-runtime' })], + [ + 'provider session', + (state) => ({ ...state, activity: { ...state.activity, started_at: 1_790_000_100 } }), + ], +]; + +it.each(replacements)('clears a revealed key when the %s changes', async (_, replace) => { + const initial = serving(); + api.read + .mockResolvedValueOnce({ key: 'sk-local-test' }) + .mockResolvedValueOnce({ key: 'sk-replacement-test' }); + const view = render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + view.rerender(); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); + expect(api.read).toHaveBeenCalledTimes(1); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('sk-replacement-test')).toBeVisible(); +}); + +it('does not reveal a key for an unauthenticated endpoint or restore one when auth returns', async () => { + const initial = serving(); + api.read.mockResolvedValue({ key: 'sk-local-test' }); + const view = render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + view.rerender( + , + ); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); + const reveal = screen.getByRole('button', { name: 'Reveal' }); + expect(reveal).toBeDisabled(); + expect(screen.getByText('No API key required. Accessible only on this Mac.')).toBeVisible(); + fireEvent.click(reveal); + expect(api.read).toHaveBeenCalledTimes(1); + view.rerender(); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); +}); + +it('clears the reveal when the runtime disconnects even if its last endpoint snapshot remains', async () => { + const initial = serving(); + api.read.mockResolvedValue({ key: 'sk-local-test' }); + const view = render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + view.rerender(); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Reveal' })).toBeDisabled(); + view.rerender(); + expect(screen.queryByText('sk-local-test')).not.toBeInTheDocument(); +}); + +it('preserves a reveal, selection and focus across ordinary snapshots and account sign-out', async () => { + const initial = { + ...serving(), + account_revision: 'signed-in', + account: { signed_in: true, email: 'test@example.test' }, + }; + api.read.mockResolvedValue({ key: 'sk-local-test' }); + const view = render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + const select = screen.getByRole('combobox'); + fireEvent.change(select, { target: { value: 'gpt-oss-20b' } }); + const localMode = screen.getByRole('radio', { name: /Local only/ }); + fireEvent.click(localMode); + select.focus(); + view.rerender( + , + ); + expect(screen.getByText('sk-local-test')).toBeVisible(); + expect(screen.getByRole('combobox')).toBe(select); + expect(select).toHaveFocus(); + expect(select).toHaveValue('gpt-oss-20b'); + expect(localMode).toBeChecked(); + expect(api.read).toHaveBeenCalledTimes(1); +}); + +it('preserves a pending local-only Reveal across routine snapshots in Strict Mode', async () => { + // Local-only endpoints have no provider session timestamp. Account sign-out does not + // unlink the provider or rotate the local credential. + const initial = { ...serving(), activity: { samples: [] }, account_revision: 'signed-in' }; + let resolve!: (value: { key: string }) => void; + api.read.mockReturnValueOnce(new Promise((done) => (resolve = done))); + const view = render(, { reactStrictMode: true }); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + view.rerender( + , + ); + await act(async () => resolve({ key: 'sk-local-test' })); + expect(screen.getByText('sk-local-test')).toBeVisible(); + expect(api.read).toHaveBeenCalledExactlyOnceWith('endpoint-key'); +}); + +it.each(['stopped', 'restarted'])( + 'ignores a pending key read that resolves while the endpoint is %s', + async (phase) => { + const initial = serving(); + let resolve!: (value: { key: string }) => void; + api.read.mockReturnValueOnce(new Promise((done) => (resolve = done))); + const view = render(); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + view.rerender(); + if (phase === 'restarted') view.rerender(); + await act(async () => resolve({ key: 'sk-obsolete-test' })); + view.rerender(); + expect(screen.queryByText('sk-obsolete-test')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Reveal' })).toBeEnabled(); + expect(api.read).toHaveBeenCalledTimes(1); + }, +); + +it.each(replacements)('ignores a pending read from an obsolete %s', async (_, replace) => { + const initial = serving(); + let resolve!: (value: { key: string }) => void; + api.read + .mockReturnValueOnce(new Promise((done) => (resolve = done))) + .mockResolvedValueOnce({ key: 'sk-current-test' }); + const view = render(); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + view.rerender(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('sk-current-test')).toBeVisible(); + await act(async () => resolve({ key: 'sk-obsolete-test' })); + expect(screen.getByText('sk-current-test')).toBeVisible(); + expect(screen.queryByText('sk-obsolete-test')).not.toBeInTheDocument(); +}); + +it('ignores a pending key read when the endpoint no longer requires authentication', async () => { + const initial = serving(); + let resolve!: (value: { key: string }) => void; + api.read.mockReturnValueOnce(new Promise((done) => (resolve = done))); + const view = render(); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + view.rerender( + , + ); + await act(async () => resolve({ key: 'sk-obsolete-test' })); + expect(screen.queryByText('sk-obsolete-test')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Reveal' })).toBeDisabled(); + view.rerender(); + expect(screen.queryByText('sk-obsolete-test')).not.toBeInTheDocument(); +}); + +it('ignores a pending key read across a runtime disconnect and reconnect', async () => { + const initial = serving(); + let resolve!: (value: { key: string }) => void; + api.read.mockReturnValueOnce(new Promise((done) => (resolve = done))); + const view = render(); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + view.rerender(); + view.rerender(); + await act(async () => resolve({ key: 'sk-obsolete-test' })); + expect(screen.queryByText('sk-obsolete-test')).not.toBeInTheDocument(); +}); + +it.each(['resolves', 'rejects'])( + 'keeps a later explicit Reveal when an older read %s', + async (outcome) => { + let resolve!: (value: { key: string }) => void; + let reject!: (error: Error) => void; + api.read + .mockReturnValueOnce( + new Promise((done, fail) => { + resolve = done; + reject = fail; + }), + ) + .mockResolvedValueOnce({ key: 'sk-current-test' }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + await act(async () => { + if (outcome === 'resolves') resolve({ key: 'sk-obsolete-test' }); + else reject(new Error('unavailable')); + }); + expect(screen.getByText('sk-current-test')).toBeVisible(); + expect(screen.queryByText('sk-obsolete-test')).not.toBeInTheDocument(); + expect(screen.queryByText('Couldn’t read the API key. Try again.')).not.toBeInTheDocument(); + }, +); + +it('reports a failed key read and allows an explicit retry', async () => { + api.read + .mockRejectedValueOnce(new Error('unavailable')) + .mockResolvedValueOnce({ key: 'sk-local-test' }); + render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('Couldn’t read the API key. Try again.')).toBeVisible(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + expect(screen.getByText('sk-local-test')).toBeVisible(); + expect(screen.queryByText('Couldn’t read the API key. Try again.')).not.toBeInTheDocument(); +}); + +it('ignores an obsolete key-read failure after stop and reappearance', async () => { + const initial = serving(); + let reject!: (error: Error) => void; + api.read.mockReturnValueOnce(new Promise((_, fail) => (reject = fail))); + const view = render(); + fireEvent.click(screen.getByRole('button', { name: 'Reveal' })); + view.rerender(); + view.rerender(); + await act(async () => reject(new Error('unavailable'))); + expect(screen.queryByText('Couldn’t read the API key. Try again.')).not.toBeInTheDocument(); +}); + +it('keeps the selected model for Apply but uses a served model in the copied example', async () => { + api.copy.mockResolvedValue(undefined); + const backend = backendWith(serving()); + render(); + fireEvent.change(screen.getByRole('combobox'), { target: { value: 'qwen-3.5-9b' } }); + await act(async () => fireEvent.click(screen.getByRole('button', { name: /Copy example/ }))); + expect(api.copy).toHaveBeenCalledWith(expect.stringContaining('"model":"gemma-4-26b"')); + await act(async () => + fireEvent.click(screen.getByRole('button', { name: /Apply serving mode/ })), + ); + expect(backend.act).toHaveBeenCalledWith({ + action: 'start', + models: ['qwen-3.5-9b'], + local: false, + endpoint: true, + }); +}); + +it('reports a failed copy instead of claiming it was copied', async () => { + api.copy.mockRejectedValue(new Error('denied')); + render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: /Copy example/ }))); + expect(screen.queryByText('Copied')).not.toBeInTheDocument(); + expect(screen.getByText('Couldn’t copy to the clipboard.')).toBeVisible(); +}); + +it('confirms only the value that was copied', async () => { + api.copy.mockResolvedValue(undefined); + render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Copy base URL' }))); + expect(screen.getByRole('button', { name: 'Base URL copied' })).toBeVisible(); + expect(screen.getByRole('button', { name: /Copy example/ })).toBeVisible(); + expect(screen.queryByText('Copied')).not.toBeInTheDocument(); + expect(api.read).not.toHaveBeenCalled(); +}); + +it('copies a placeholder rather than a revealed key and confirms only the example', async () => { + api.read.mockResolvedValue({ key: 'sk-local-test' }); + api.copy.mockResolvedValue(undefined); + render(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Reveal' }))); + await act(async () => fireEvent.click(screen.getByRole('button', { name: /Copy example/ }))); + expect(api.copy).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining('Authorization: Bearer '), + ); + expect(api.copy.mock.calls[0][0]).not.toContain('sk-local-test'); + expect(screen.getByRole('button', { name: 'Copy base URL' })).toBeVisible(); + expect(screen.getByRole('button', { name: 'Copied' })).toBeVisible(); +});