fix(web): make the web console work end-to-end
- Pair through the public POST /api/v1/pair and persist the device scopes; keep the allow-listed next deep link. Rename the manual field to pairing code. - Authenticate the WebSocket with the raw device token (strip Bearer) and recover from a 401 by clearing the connection once. - Fix chat payloads: setModel/setThinking, attention/diff responses, subagent dispatch items, queue ids/mode, task output and WS resume since. - Render exactly one assistant message per turn: one-to-one snapshot/history merge plus a stale-delta guard after message_end (fixes PONGONG). - Fix dialogs (content above the overlay), unknown-session deep links (error + retry, no silent fallback), device list/revoke, status identity and live pairing code, reconnect banner and Playwright selectors.
This commit is contained in:
1 parent
5572ac0d84
commit
0ef019f58d
57 files changed
+3549
-684
No files matched your search
+131
-58
@@ -7,7 +7,7 @@ import type {
|
||||
ThinkingLevel,
|
||||
} from "@protocol/types";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useRouterState } from "@tanstack/react-router";
|
||||
import { Link, useNavigate, useParams, useRouterState } from "@tanstack/react-router";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -24,17 +24,18 @@ import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { AttentionDialog } from "@/features/chat/attention";
|
||||
import { Composer } from "@/features/chat/composer";
|
||||
import { chatCommands, runCommand, type ChatCommand, type PromptImage } from "@/features/chat/commands";
|
||||
import { chatCommands, runCommand, type AttentionResponse, type ChatCommand, type PromptImage, type PromptMode } from "@/features/chat/commands";
|
||||
import {
|
||||
useActiveSession,
|
||||
useChatModels,
|
||||
useChatSessions,
|
||||
useChatSocket,
|
||||
useChatWorkspaces,
|
||||
useSessionLookup,
|
||||
} from "@/features/chat/data";
|
||||
import { useSessionHistory } from "@/features/chat/history";
|
||||
import { ChatLayout } from "@/features/chat/layout";
|
||||
import { MessageStream } from "@/features/chat/message-stream";
|
||||
import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration";
|
||||
import { DispatchModal, RenameDialog, SubagentModal, TaskOutputModal, type DispatchInput } from "@/features/chat/modals";
|
||||
import { flattenSubagents, emptySessionState, sessionDot, sessionStatusKey } from "@/features/chat/session-state";
|
||||
import { SessionTree } from "@/features/chat/session-tree";
|
||||
@@ -91,10 +92,17 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
workspaces.find((workspace) => workspace.instance)?.workspaceId ??
|
||||
workspaces[0]?.workspaceId;
|
||||
|
||||
const sessions = useChatSessions(workspaceId, paired);
|
||||
const sessionsQuery = useChatSessions(workspaceId, paired);
|
||||
const sessions = sessionsQuery.sessions;
|
||||
const sessionIds = useMemo(() => sessions.map((session) => session.sessionId), [sessions]);
|
||||
useChatSocket(workspaceId, sessionIds, paired);
|
||||
const active = useActiveSession(sessionId, sessions);
|
||||
// An unknown deep link resolves to nothing (never to another session);
|
||||
// `missing` stays false until the list has loaded, so no error flash.
|
||||
const { session: active, missing: sessionMissing } = useSessionLookup(
|
||||
sessionId,
|
||||
sessions,
|
||||
sessionsQuery.loaded,
|
||||
);
|
||||
const history = useSessionHistory(active?.sessionId, active?.entries ?? NO_ENTRIES, paired);
|
||||
const models = useChatModels(workspaceId, paired);
|
||||
const workspace = workspaces.find((item) => item.workspaceId === workspaceId);
|
||||
@@ -133,9 +141,9 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const title = active?.name?.trim() || t("nav.chat");
|
||||
const title = active?.name?.trim() || (sessionMissing ? t("errors.sessionNotFound") : t("nav.chat"));
|
||||
document.title = `${title} — pi2.nvim`;
|
||||
}, [active?.name, t]);
|
||||
}, [active?.name, sessionMissing, t]);
|
||||
|
||||
// The optimistic "sending" chip disappears when the authoritative user
|
||||
// entry arrives (via entry_appended) or after a safety timeout.
|
||||
@@ -160,6 +168,24 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
return () => clearTimeout(timer);
|
||||
}, [sending, setSending]);
|
||||
|
||||
// A `tmp-N` → real-id migration re-keys the stores and the socket; the router
|
||||
// still addresses the old id, so swap the URL in place and refresh the tree.
|
||||
useEffect(
|
||||
() =>
|
||||
onSessionMigration((migration) => {
|
||||
if (replaceChatUrl(migration.from, migration.to, workspaceId)) {
|
||||
void navigate({
|
||||
to: "/chat/$sessionId",
|
||||
params: { sessionId: migration.to },
|
||||
search: workspaceId ? { workspace: workspaceId } : {},
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
void queryClient.invalidateQueries({ queryKey: ["chat-sessions", migration.workspaceId] });
|
||||
}),
|
||||
[navigate, queryClient, workspaceId],
|
||||
);
|
||||
|
||||
async function exec(
|
||||
command: ChatCommand,
|
||||
successKey?: string,
|
||||
@@ -167,7 +193,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const result = await runCommand(command);
|
||||
if (successKey) toast(t(successKey, params));
|
||||
if (successKey) toast.success(t(successKey, params));
|
||||
return result;
|
||||
} catch (error) {
|
||||
toast.error(t("chat.commandFailed", { error: errorText(error, t) }));
|
||||
@@ -189,17 +215,33 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
void navigate({ to: "/chat", search: { workspace: id } });
|
||||
}
|
||||
|
||||
async function handleSend(text: string, images: PromptImage[]) {
|
||||
async function handleSend(text: string, images: PromptImage[], mode?: PromptMode) {
|
||||
if (!active) return;
|
||||
setSending({ sessionId: active.sessionId, text });
|
||||
try {
|
||||
await runCommand(chatCommands.sendPrompt(active.sessionId, text, images));
|
||||
await runCommand(chatCommands.sendPrompt(active.sessionId, text, images, mode));
|
||||
} catch (error) {
|
||||
setSending(null);
|
||||
toast.error(t("chat.sendFailed", { error: errorText(error, t) }));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Steering is a session-wide mode (`queue.setSteer {mode}`), so the toast
|
||||
* names the mode instead of implying a per-message flag.
|
||||
*/
|
||||
async function setSteerMode(steer: boolean) {
|
||||
const sessionId = active?.sessionId;
|
||||
if (!sessionId) return;
|
||||
const mode = steer ? "all" : "one-at-a-time";
|
||||
try {
|
||||
await runCommand(chatCommands.setQueueSteer(sessionId, steer));
|
||||
toast.success(`${t("chat.steer")}: ${mode}`);
|
||||
} catch (error) {
|
||||
toast.error(t("chat.commandFailed", { error: errorText(error, t) }));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNewSession() {
|
||||
if (!workspaceId || creating) return;
|
||||
setCreating(true);
|
||||
@@ -212,7 +254,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
: typeof (result.session as Record<string, unknown> | undefined)?.sessionId === "string"
|
||||
? String((result.session as Record<string, unknown>).sessionId)
|
||||
: undefined;
|
||||
toast(t("chat.newSessionCreated"));
|
||||
toast.success(t("chat.newSessionCreated"));
|
||||
if (created) navigateSession(created);
|
||||
} catch (error) {
|
||||
toast.error(t("chat.newSessionFailed", { error: errorText(error, t) }));
|
||||
@@ -224,43 +266,49 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
async function dispatchSubagent(input: DispatchInput) {
|
||||
if (!active) return;
|
||||
const result = await exec(chatCommands.dispatchSubagent(active.sessionId, input));
|
||||
if (result !== undefined) toast(t("chat.dispatched", { name: input.name ?? "-" }));
|
||||
if (result !== undefined) toast.success(t("chat.dispatched", { name: input.name ?? "-" }));
|
||||
}
|
||||
|
||||
async function saveRename(value: string) {
|
||||
if (!renaming) return;
|
||||
if (renaming.kind === "session") {
|
||||
const target = renaming.session;
|
||||
const previous = useSessionsStore.getState().getSession(target.sessionId)?.name ?? target.name;
|
||||
try {
|
||||
await runCommand(chatCommands.renameSession(renaming.session.sessionId, value));
|
||||
useSessionsStore.getState().upsertSession({ ...renaming.session, name: value });
|
||||
toast(t("chat.renamed", { name: value }));
|
||||
// The plugin owns the name: apply it only after the ack.
|
||||
await runCommand(chatCommands.renameSession(target.sessionId, value));
|
||||
useSessionsStore.getState().upsertSession({ ...target, name: value });
|
||||
toast.success(t("chat.renamed", { name: value }));
|
||||
} catch (error) {
|
||||
// Roll back so the tree never keeps an unconfirmed name.
|
||||
useSessionsStore.getState().upsertSession({ ...target, name: previous });
|
||||
toast.error(t("chat.commandFailed", { error: errorText(error, t) }));
|
||||
throw error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!active) return;
|
||||
// Subagent names are local display only (the plugin has no rename command).
|
||||
useSessionsStore.getState().upsertSession({
|
||||
...active,
|
||||
subagents: renameInTree(active.subagents, renaming.subagent.id, value) ?? [],
|
||||
});
|
||||
toast(t("chat.renamed", { name: value }));
|
||||
toast.success(t("chat.renamed", { name: value }));
|
||||
}
|
||||
|
||||
async function closeSession(session: SessionState) {
|
||||
const result = await exec(chatCommands.closeSession(session.sessionId));
|
||||
if (result !== undefined) toast.error(t("chat.closedProcess", { name: session.name ?? session.sessionId }));
|
||||
await exec(chatCommands.closeSession(session.sessionId), "chat.closedProcess", {
|
||||
name: session.name ?? session.sessionId,
|
||||
});
|
||||
setClosing(null);
|
||||
}
|
||||
|
||||
async function stopTask(task: TaskItem) {
|
||||
const result = await exec(chatCommands.stopTask(active?.sessionId ?? "", task.id));
|
||||
if (result !== undefined) toast.error(t("chat.taskStopped", { id: task.id }));
|
||||
await exec(chatCommands.stopTask(active?.sessionId ?? "", task.id), "chat.taskStopped", { id: task.id });
|
||||
setStoppingTask(null);
|
||||
}
|
||||
|
||||
async function respondAttention(item: AttentionItem, response: unknown) {
|
||||
async function respondAttention(item: AttentionItem, response: AttentionResponse | string) {
|
||||
if (!active) return;
|
||||
await exec(chatCommands.respondAttention(active.sessionId, item.requestId, response));
|
||||
}
|
||||
@@ -364,7 +412,35 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
stream={
|
||||
<>
|
||||
{streamHead}
|
||||
{active ? (
|
||||
{sessionMissing ? (
|
||||
<div className="stream-body stream-blank">
|
||||
<div className="stream-status stream-status--err" data-testid="session-not-found">
|
||||
<Empty
|
||||
icon={<Icon name="alert" size={28} />}
|
||||
title={t("errors.sessionNotFound")}
|
||||
description={`${t("errors.notFound")}: ${sessionId ?? ""}`}
|
||||
action={
|
||||
<div className="row">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--sm btn--primary"
|
||||
data-testid="session-not-found-retry"
|
||||
onClick={sessionsQuery.refetch}
|
||||
disabled={sessionsQuery.fetching}
|
||||
>
|
||||
<Icon name="refresh" />
|
||||
{t("common.retry")}
|
||||
</button>
|
||||
<Link to="/workspaces" className="btn btn--sm">
|
||||
<Icon name="folder" />
|
||||
{t("connect.backToWorkspaces")}
|
||||
</Link>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : active ? (
|
||||
<MessageStream
|
||||
session={active}
|
||||
entries={history.entries}
|
||||
@@ -401,41 +477,38 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Composer
|
||||
session={active ?? null}
|
||||
models={models}
|
||||
connected={connected}
|
||||
paired={paired}
|
||||
sending={sending}
|
||||
onSend={(text, images) => void handleSend(text, images)}
|
||||
onAbort={() => {
|
||||
setSending(null);
|
||||
void exec(chatCommands.abort(active?.sessionId ?? ""));
|
||||
}}
|
||||
onRemoveQueue={(id) =>
|
||||
void exec(chatCommands.removeQueued(active?.sessionId ?? "", id), "chat.queueRemoved")
|
||||
}
|
||||
onSetSteer={(id, steer) =>
|
||||
void exec(
|
||||
chatCommands.setQueueSteer(active?.sessionId ?? "", id, steer),
|
||||
steer ? "chat.steerOn" : "chat.steerOff",
|
||||
)
|
||||
}
|
||||
onSetModel={(model: ModelRef) =>
|
||||
void exec(
|
||||
chatCommands.setModel(active?.sessionId ?? "", model),
|
||||
"chat.modelSwitched",
|
||||
{ model: model.id },
|
||||
)
|
||||
}
|
||||
onSetThinking={(level: ThinkingLevel) =>
|
||||
void exec(
|
||||
chatCommands.setThinking(active?.sessionId ?? "", level),
|
||||
"chat.thinkingSet",
|
||||
{ level },
|
||||
)
|
||||
}
|
||||
/>
|
||||
{sessionMissing ? null : (
|
||||
<Composer
|
||||
session={active ?? null}
|
||||
models={models}
|
||||
connected={connected}
|
||||
paired={paired}
|
||||
sending={sending}
|
||||
onSend={(text, images, mode) => void handleSend(text, images, mode)}
|
||||
onAbort={() => {
|
||||
setSending(null);
|
||||
void exec(chatCommands.abort(active?.sessionId ?? ""));
|
||||
}}
|
||||
onRemoveQueue={(id) =>
|
||||
void exec(chatCommands.removeQueued(active?.sessionId ?? "", id), "chat.queueRemoved")
|
||||
}
|
||||
onSetSteer={(steer) => void setSteerMode(steer)}
|
||||
onSetModel={(model: ModelRef) =>
|
||||
void exec(
|
||||
chatCommands.setModel(active?.sessionId ?? "", model),
|
||||
"chat.modelSwitched",
|
||||
{ model: model.id },
|
||||
)
|
||||
}
|
||||
onSetThinking={(level: ThinkingLevel) =>
|
||||
void exec(
|
||||
chatCommands.setThinking(active?.sessionId ?? "", level),
|
||||
"chat.thinkingSet",
|
||||
{ level },
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
panel={
|
||||
@@ -478,7 +551,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
onBack={() => {
|
||||
if (preview) {
|
||||
navigateSession(preview.session.sessionId);
|
||||
toast(t("chat.returnedParent", { name: preview.session.name ?? preview.session.sessionId }));
|
||||
toast.success(t("chat.returnedParent", { name: preview.session.name ?? preview.session.sessionId }));
|
||||
}
|
||||
setPreview(null);
|
||||
}}
|
||||
|
||||
+68
-30
@@ -10,10 +10,12 @@ import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { KV } from "@/components/ui/kv";
|
||||
import { toast } from "@/components/ui/toast";
|
||||
import { ManualConnectForm, type ManualConnectInput } from "@/features/connect/manual-form";
|
||||
import { ManualConnectForm, pairErrorMessage, type ManualConnectInput } from "@/features/connect/manual-form";
|
||||
import {
|
||||
clearPairMeta,
|
||||
isPairCode,
|
||||
maskSecret,
|
||||
normalizePairCode,
|
||||
readPairMeta,
|
||||
redeemPairing,
|
||||
safePairNext,
|
||||
@@ -23,9 +25,9 @@ import {
|
||||
type PairTarget,
|
||||
} from "@/features/connect/pairing";
|
||||
import { ScanDialog } from "@/features/connect/scan-dialog";
|
||||
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
|
||||
import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server";
|
||||
import { useInfoQuery } from "@/features/status/queries";
|
||||
import { ApiError, errorI18nKey } from "@/lib/api";
|
||||
import { setDeviceToken } from "@/lib/api";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
import "@/styles/pages/connect.css";
|
||||
@@ -37,19 +39,16 @@ function scopeTone(scope: string): "default" | "info" | "ok" {
|
||||
return "default";
|
||||
}
|
||||
|
||||
function messageFor(error: unknown, t: (key: string) => string): string {
|
||||
if (error instanceof ApiError) return t(errorI18nKey(error.code));
|
||||
return t("connect.pairFailed");
|
||||
}
|
||||
|
||||
export function ConnectPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const searchStr = useRouterState({ select: (state) => state.location.searchStr });
|
||||
const next = useMemo(
|
||||
() => safePairNext(new URLSearchParams(searchStr).get("next")),
|
||||
[searchStr],
|
||||
);
|
||||
const search = useMemo(() => new URLSearchParams(searchStr), [searchStr]);
|
||||
const next = useMemo(() => safePairNext(search.get("next")), [search]);
|
||||
const codeParam = useMemo(() => {
|
||||
const raw = normalizePairCode(search.get("code"));
|
||||
return isPairCode(raw) ? raw : "";
|
||||
}, [search]);
|
||||
|
||||
const refreshFromStorage = useConnectionStore((state) => state.refreshFromStorage);
|
||||
const paired = useConnectionStore((state) => state.paired);
|
||||
@@ -60,6 +59,7 @@ export function ConnectPage() {
|
||||
const connectedAt = useConnectionStore((state) => state.connectedAt);
|
||||
const wsState = useConnectionStore((state) => state.wsState);
|
||||
const storedServer = useConnectionStore((state) => state.server);
|
||||
const storedScopes = useConnectionStore((state) => state.scopes);
|
||||
|
||||
const [meta, setMeta] = useState<PairMeta | null>(() => readPairMeta());
|
||||
const [scanOpen, setScanOpen] = useState(false);
|
||||
@@ -86,9 +86,17 @@ export function ConnectPage() {
|
||||
fetchedAt: info.dataUpdatedAt || null,
|
||||
nameFallback: storedServer?.name || meta?.server?.name,
|
||||
});
|
||||
const scopes = scopesForIdentity(meta, info.data);
|
||||
const scopes = scopesForIdentity(meta, info.data, storedScopes);
|
||||
const defaultDeviceName = t("connect.defaultDeviceName");
|
||||
const osLabel = info.data?.os || info.data?.platform || server.os || "—";
|
||||
const uptimeSeconds =
|
||||
typeof info.data?.uptimeMs === "number" ? info.data.uptimeMs / 1000 : server.uptimeSec;
|
||||
|
||||
/**
|
||||
* One pairing path for the scan/confirm dialog and the manual form:
|
||||
* redeem against the public endpoint, persist token + scopes, then follow
|
||||
* the allow-listed `next`.
|
||||
*/
|
||||
const finishPairing = useCallback(
|
||||
async (target: PairTarget, deviceName: string) => {
|
||||
const result = await redeemPairing({
|
||||
@@ -96,10 +104,12 @@ export function ConnectPage() {
|
||||
code: target.code,
|
||||
deviceName,
|
||||
});
|
||||
connect({ endpoint: target.endpoint, deviceName, token: result.token });
|
||||
setDeviceToken(result.token);
|
||||
connect({ endpoint: target.endpoint, deviceName, token: result.token, scopes: result.scopes });
|
||||
const nextMeta: PairMeta = {
|
||||
scopes: result.scopes,
|
||||
deviceName,
|
||||
kind: result.kind,
|
||||
server: result.server,
|
||||
pairedAt: Date.now(),
|
||||
};
|
||||
@@ -112,15 +122,17 @@ export function ConnectPage() {
|
||||
);
|
||||
|
||||
async function handleManual(input: ManualConnectInput) {
|
||||
const url = new URL(input.endpoint);
|
||||
let hostname = "";
|
||||
let port = 4321;
|
||||
try {
|
||||
const url = new URL(input.endpoint);
|
||||
hostname = url.hostname;
|
||||
port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
|
||||
} catch {
|
||||
/* validate host/port above guarantees a parseable endpoint */
|
||||
}
|
||||
await finishPairing(
|
||||
{
|
||||
endpoint: input.endpoint,
|
||||
code: input.code,
|
||||
name: url.hostname,
|
||||
hostname: url.hostname,
|
||||
port: url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80,
|
||||
},
|
||||
{ endpoint: input.endpoint, code: input.code, name: hostname, hostname, port },
|
||||
input.deviceName,
|
||||
);
|
||||
}
|
||||
@@ -138,7 +150,7 @@ export function ConnectPage() {
|
||||
await finishPairing(pending, defaultDeviceName);
|
||||
setPending(null);
|
||||
} catch (error) {
|
||||
const message = messageFor(error, t);
|
||||
const message = t(pairErrorMessage(error));
|
||||
setPairError(message);
|
||||
toast.error(message);
|
||||
} finally {
|
||||
@@ -187,24 +199,30 @@ export function ConnectPage() {
|
||||
<div className="cn-kvs">
|
||||
<KV label={t("connect.server")}>{server.name || "—"}</KV>
|
||||
<KV label={t("connect.hostname")} mono>
|
||||
{server.hostname || "—"}
|
||||
{info.data?.hostname || server.hostname || "—"}
|
||||
</KV>
|
||||
<KV label={t("connect.endpoint")} mono>
|
||||
{storedEndpoint || server.endpoint || "—"}
|
||||
</KV>
|
||||
<KV label={t("connect.os")}>{osLabel}</KV>
|
||||
<KV label={t("connect.version")}>
|
||||
{info.data?.version || meta?.server?.version || "—"}
|
||||
</KV>
|
||||
<KV label={t("connect.pluginVersion")}>
|
||||
{info.data?.pluginVersion || meta?.server?.pluginVersion || "—"}
|
||||
</KV>
|
||||
<KV label={t("connect.uptime")}>{formatUptime(uptimeSeconds)}</KV>
|
||||
<KV label={t("connect.device")}>{storedDeviceName || meta?.deviceName || "—"}</KV>
|
||||
<KV label={t("connect.scopes")} className="cn-kv--badges">
|
||||
{scopes.length ? (
|
||||
<span className="cn-scopes">
|
||||
{scopes.map((scope) => (
|
||||
<Badge key={scope} tone={scopeTone(scope)}>
|
||||
{scope}
|
||||
<Badge
|
||||
key={scope}
|
||||
tone={scopeTone(scope)}
|
||||
title={t("connect.scopeHint", { scope })}
|
||||
>
|
||||
{t(`connect.scope.${scope}`, { defaultValue: scope })}
|
||||
</Badge>
|
||||
))}
|
||||
</span>
|
||||
@@ -235,13 +253,19 @@ export function ConnectPage() {
|
||||
) : (
|
||||
<>
|
||||
<div className="cn-actions">
|
||||
<Button variant="primary" className="cn-action" onClick={() => setScanOpen(true)}>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="cn-action"
|
||||
data-testid="connect-scan"
|
||||
onClick={() => setScanOpen(true)}
|
||||
>
|
||||
<Icon name="scan" />
|
||||
{t("connect.scan")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="cn-action"
|
||||
data-testid="connect-manual"
|
||||
onClick={() => hostInputRef.current?.focus()}
|
||||
>
|
||||
<Icon name="server" />
|
||||
@@ -252,6 +276,7 @@ export function ConnectPage() {
|
||||
onConnect={handleManual}
|
||||
hostInputRef={hostInputRef}
|
||||
defaultDeviceName={defaultDeviceName}
|
||||
initialCode={codeParam}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
@@ -271,10 +296,23 @@ export function ConnectPage() {
|
||||
title={t("connect.confirmTitle")}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={() => setPending(null)} disabled={redeeming}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
data-testid="connect-confirm-cancel"
|
||||
onClick={() => {
|
||||
setPairError(null);
|
||||
setPending(null);
|
||||
}}
|
||||
disabled={redeeming}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => void confirmPending()} disabled={redeeming}>
|
||||
<Button
|
||||
variant="primary"
|
||||
data-testid="connect-confirm-connect"
|
||||
onClick={() => void confirmPending()}
|
||||
disabled={redeeming}
|
||||
>
|
||||
{redeeming ? t("connect.connecting") : t("connect.connect")}
|
||||
</Button>
|
||||
</>
|
||||
@@ -288,7 +326,7 @@ export function ConnectPage() {
|
||||
<KV label={t("connect.endpoint")} mono>
|
||||
{pending.hostname}:{pending.port}
|
||||
</KV>
|
||||
<KV label={t("connect.token")} mono>
|
||||
<KV label={t("connect.pairCode")} mono>
|
||||
{maskSecret(pending.code)}
|
||||
</KV>
|
||||
</div>
|
||||
|
||||
@@ -16,19 +16,24 @@ import { deviceKey, DevicesCard } from "@/features/status/devices-card";
|
||||
import { HealthCard } from "@/features/status/health-card";
|
||||
import { ModelsCard } from "@/features/status/models-card";
|
||||
import {
|
||||
mergeTasks,
|
||||
sessionTasks,
|
||||
useDevicesQuery,
|
||||
useHealthQuery,
|
||||
useInfoQuery,
|
||||
useModelsQuery,
|
||||
usePairCodeQuery,
|
||||
useResourcesQuery,
|
||||
useWorkspaceSessionsQueries,
|
||||
useWorkspacesQuery,
|
||||
type DeviceEntry,
|
||||
type DevicesResponse,
|
||||
type StatusTask,
|
||||
} from "@/features/status/queries";
|
||||
import { ResourcesCard } from "@/features/status/resources-card";
|
||||
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
|
||||
import { ServerInfoCard } from "@/features/status/server-info-card";
|
||||
import { TasksCard, type StatusTask } from "@/features/status/tasks-card";
|
||||
import { TasksCard } from "@/features/status/tasks-card";
|
||||
import { ApiError, api, errorI18nKey } from "@/lib/api";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
@@ -50,6 +55,7 @@ export function StatusPage() {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const paired = useConnectionStore((state) => state.paired);
|
||||
const endpoint = useConnectionStore((state) => state.endpoint);
|
||||
const wsState = useConnectionStore((state) => state.wsState);
|
||||
const storedServer = useConnectionStore((state) => state.server);
|
||||
@@ -62,6 +68,8 @@ export function StatusPage() {
|
||||
const resources = useResourcesQuery();
|
||||
const workspacesQuery = useWorkspacesQuery();
|
||||
const devices = useDevicesQuery();
|
||||
// The card shows the daemon's live code, not a cached one: mint on mount.
|
||||
const pairCode = usePairCodeQuery(paired);
|
||||
|
||||
const workspaces = workspacesQuery.data ?? [];
|
||||
const visibleWorkspaces = workspaces.filter((workspace) => !workspace.hidden);
|
||||
@@ -83,8 +91,12 @@ export function StatusPage() {
|
||||
status: info.isError ? "offline" : healthOk === false ? "degraded" : undefined,
|
||||
});
|
||||
|
||||
// Background tasks: the live store covers open sessions, the REST session
|
||||
// lists cover everything else (a hard reload empties the store). Only
|
||||
// workspaces with a live instance are asked: `/sessions` relays through
|
||||
// `instances.ensure()`, which would spawn a Neovim for every idle workspace.
|
||||
const byWorkspace = useSessionsStore((state) => state.byWorkspace);
|
||||
const tasks = useMemo<StatusTask[]>(
|
||||
const liveTasks = useMemo<StatusTask[]>(
|
||||
() =>
|
||||
Object.values(byWorkspace).flatMap((sessions) =>
|
||||
sessions.flatMap((session) =>
|
||||
@@ -94,10 +106,25 @@ export function StatusPage() {
|
||||
[byWorkspace],
|
||||
);
|
||||
|
||||
const workspaceIds = visibleWorkspaces
|
||||
.filter((workspace) => workspace.instance != null)
|
||||
.map((workspace) => workspace.workspaceId);
|
||||
const sessionQueries = useWorkspaceSessionsQueries(workspaceIds);
|
||||
const fetchedTasks = sessionQueries.flatMap((query) => (query.data ? sessionTasks(query.data) : []));
|
||||
const tasks = mergeTasks(liveTasks, fetchedTasks);
|
||||
const tasksLoading = tasks.length === 0 && sessionQueries.some((query) => query.isPending);
|
||||
const tasksFailed = sessionQueries.find((query) => query.isError);
|
||||
const tasksError = tasksFailed ? translatedError(tasksFailed.error, "status.tasksError", t) : null;
|
||||
|
||||
function retryTasks() {
|
||||
for (const query of sessionQueries) void query.refetch();
|
||||
}
|
||||
|
||||
async function revokeDevice(device: DeviceEntry) {
|
||||
const key = deviceKey(device);
|
||||
try {
|
||||
await api.command({ method: "device.revoke", params: { deviceId: key } });
|
||||
// DELETE /api/v1/devices/:id — the daemon marks the token revoked.
|
||||
await api.revokeDevice(key);
|
||||
queryClient.setQueryData<DevicesResponse>(["devices"], (previous) =>
|
||||
previous
|
||||
? { ...previous, devices: previous.devices.filter((item) => deviceKey(item) !== key) }
|
||||
@@ -137,6 +164,7 @@ export function StatusPage() {
|
||||
<div className="status-grid">
|
||||
<ServerInfoCard
|
||||
server={server}
|
||||
resources={resources.data}
|
||||
loading={info.isPending}
|
||||
error={info.isError ? translatedError(info.error, "status.infoError", t) : null}
|
||||
onRetry={() => void info.refetch()}
|
||||
@@ -167,7 +195,12 @@ export function StatusPage() {
|
||||
onRetry={() => void models.refetch()}
|
||||
/>
|
||||
|
||||
<TasksCard tasks={tasks} />
|
||||
<TasksCard
|
||||
tasks={tasks}
|
||||
loading={tasksLoading}
|
||||
error={tasks.length === 0 ? tasksError : null}
|
||||
onRetry={retryTasks}
|
||||
/>
|
||||
|
||||
<DevicesCard
|
||||
devices={devices.data?.devices ?? []}
|
||||
@@ -186,6 +219,10 @@ export function StatusPage() {
|
||||
error={info.isError ? translatedError(info.error, "status.infoError", t) : null}
|
||||
onRetry={() => void info.refetch()}
|
||||
onDisconnect={handleDisconnect}
|
||||
pairCode={pairCode.data}
|
||||
pairLoading={pairCode.isPending}
|
||||
pairError={pairCode.isError ? translatedError(pairCode.error, "connect.pairFailed", t) : null}
|
||||
onRetryPair={() => void pairCode.refetch()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user