Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): re-check daemon status after machine.registered (#315)

Gener72b232318e66
diff --git a/src/shared/src/db/queries/machine-token.ts b/src/shared/src/db/queries/machine-token.ts
index 8e104b57a..6c03b6525 100644
--- a/src/shared/src/db/queries/machine-token.ts
+++ b/src/shared/src/db/queries/machine-token.ts
@@ -99,6 +99,7 @@ export async function getLatestTokenForUser(db: Database, userId: string) {
const rows = await db
.select({
id: machineToken.id,
+ token: machineToken.token,
status: machineToken.status,
workspaceId: machineToken.workspaceId,
hostname: machineToken.hostname,
diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsx
index e8630c059..be938ae60 100644
--- a/src/web/src/app/(app)/studio/new/client.tsx
+++ b/src/web/src/app/(app)/studio/new/client.tsx
@@ -47,6 +47,7 @@ export function StudioOnboardingClient({
const [runtimes, setRuntimes] = useState<Runtime[]>([]);
const runtimesRef = useRef(runtimes);
useEffect(() => { runtimesRef.current = runtimes; }, [runtimes]);
+ const wsSendRef = useRef<(msg: object) => void>(() => {});
const [loadingRuntimes, setLoadingRuntimes] = useState(!!initialWorkspaceId);
const [scenarioId, setScenarioId] = useState<ScenarioId | null>(
initialTemplate ? initialTemplate.baseScenario : null,
@@ -59,6 +60,7 @@ export function StudioOnboardingClient({
const [checkingName, setCheckingName] = useState(false);
const [members, setMembers] = useState<TeamMember[]>([]);
const [creating, setCreating] = useState(false);
+ const creatingRef = useRef(false);
// Connect machine state
const [generatedToken, setGeneratedToken] = useState("");
@@ -136,10 +138,9 @@ export function StudioOnboardingClient({
updated_at: "",
})));
}
- } else if (data.status === "pending") {
+ } else if (data.status === "pending" && data.token) {
try {
- const { token } = await createMachineToken("cli");
- await doDesktopRegister(token);
+ await doDesktopRegister(data.token);
} catch {
toast.error("Failed to auto-register CLI — please check that Claude or Codex is installed");
}
@@ -182,6 +183,7 @@ export function StudioOnboardingClient({
// WebSocket for runtime registration events
const handleWsMessage = useCallback((msg: WsMessage) => {
+ if (creatingRef.current) return;
const currentWsId = workspaceIdRef.current;
if (msg.type === "machine.registered") {
setMachineRegistered(true);
@@ -205,10 +207,11 @@ export function StudioOnboardingClient({
if (data.daemon_online) setDaemonOnline(true);
}).catch(() => {});
}
+ wsSendRef.current({ type: "check_daemon_status" });
} else if (msg.type === "runtime.registered") {
setMachineRegistered(true);
const eventWsId = msg.workspaceId;
- if (eventWsId && !currentWsId) {
+ if (eventWsId && !currentWsId && !isNewWorkspace) {
setWorkspaceId(eventWsId);
listRuntimes(eventWsId).then(setRuntimes).catch(() => {});
} else if (currentWsId) {
@@ -216,38 +219,42 @@ export function StudioOnboardingClient({
}
} else if (msg.type === "runtime.status" && msg.status === "online") {
setDaemonOnline(true);
+ const wsId = workspaceIdRef.current;
if (runtimesRef.current.length === 0) {
- getMachineTokenStatus().then(data => {
- if (data.runtimes?.length) {
- setRuntimes(data.runtimes.map(rt => ({
- id: rt.id,
- workspace_id: "",
- daemon_id: data.hostname || null,
- runtime_mode: "local",
- provider: rt.type,
- status: "online" as const,
- device_info: data.hostname || "",
- metadata: { version: rt.version },
- last_seen_at: null,
- created_at: "",
- updated_at: "",
- })));
- }
- }).catch(() => {});
+ if (wsId) {
+ listRuntimes(wsId).then(setRuntimes).catch(() => {});
+ } else {
+ getMachineTokenStatus().then(data => {
+ if (data.runtimes?.length) {
+ setRuntimes(data.runtimes.map(rt => ({
+ id: rt.id,
+ workspace_id: "",
+ daemon_id: data.hostname || null,
+ runtime_mode: "local",
+ provider: rt.type,
+ status: "online" as const,
+ device_info: data.hostname || "",
+ metadata: { version: rt.version },
+ last_seen_at: null,
+ created_at: "",
+ updated_at: "",
+ })));
+ }
+ }).catch(() => {});
+ }
+ } else if (wsId) {
+ listRuntimes(wsId).then(setRuntimes).catch(() => {});
} else {
setRuntimes(prev => prev.map(r => ({ ...r, status: "online" })));
}
- const wsId = workspaceIdRef.current;
- if (wsId) {
- listRuntimes(wsId).then(setRuntimes).catch(() => {});
- }
} else if (msg.type === "runtime.status" && msg.status === "offline") {
setDaemonOnline(false);
setRuntimes(prev => prev.map(r => ({ ...r, status: "offline" })));
}
- }, []);
+ }, [isNewWorkspace]);
- useUserWs(handleWsMessage);
+ const { send: wsSend } = useUserWs(handleWsMessage);
+ useEffect(() => { wsSendRef.current = wsSend; }, [wsSend]);
// Auto-assign first available runtime when runtimes load/change
useEffect(() => {
@@ -392,6 +399,7 @@ export function StudioOnboardingClient({
const handleCreate = async () => {
setCreating(true);
+ creatingRef.current = true;
try {
let resolvedWorkspaceId = workspaceId;
@@ -430,6 +438,7 @@ export function StudioOnboardingClient({
if (!resolvedWorkspaceId) {
toast.error("Please connect a computer first");
+ creatingRef.current = false;
setCreating(false);
return;
}
@@ -460,6 +469,7 @@ export function StudioOnboardingClient({
}
if (resolvedMembers.some((m) => !m.runtimeId || m.runtimeId.startsWith("temp_"))) {
toast.error("Waiting for runtime — please ensure the daemon is running");
+ creatingRef.current = false;
setCreating(false);
return;
}
@@ -510,6 +520,7 @@ export function StudioOnboardingClient({
router.push(`/w/${data.workspace.slug}/agents/${data.leader_agent_id}`);
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to create company");
+ creatingRef.current = false;
setCreating(false);
}
};
@@ -524,7 +535,7 @@ export function StudioOnboardingClient({
members.length > 0 &&
(isTauriDesktop || isNewWorkspace || members.every((m) => m.runtimeId)) &&
nameValid &&
- (hasOnlineRuntime || (machineRegistered && daemonOnline && runtimes.length > 0) || isTauriDesktop);
+ (hasOnlineRuntime || (machineRegistered && daemonOnline && runtimes.length > 0) || (isTauriDesktop && runtimes.length > 0));
// Page 1: Scenario selection
if (!scenarioId) {
diff --git a/src/web/src/app/api/machine-tokens/status/route.test.ts b/src/web/src/app/api/machine-tokens/status/route.test.ts
index 3ac61f435..d33697e52 100644
--- a/src/web/src/app/api/machine-tokens/status/route.test.ts
+++ b/src/web/src/app/api/machine-tokens/status/route.test.ts
@@ -37,9 +37,9 @@ describe("GET /api/machine-tokens/status", () => {
expect(body.status).toBeNull();
});
- it("returns pending status", async () => {
+ it("returns pending status with token", async () => {
mockGetLatestTokenForUser.mockResolvedValue({
- id: "mt_1", status: "pending", workspaceId: null, hostname: null,
+ id: "mt_1", token: "al_pending123", status: "pending", workspaceId: null, hostname: null,
});
const req = new NextRequest("http://localhost/api/machine-tokens/status");
@@ -48,10 +48,25 @@ describe("GET /api/machine-tokens/status", () => {
expect(res.status).toBe(200);
expect(body.status).toBe("pending");
+ expect(body.token).toBe("al_pending123");
expect(body.workspace_id).toBeUndefined();
expect(body.hostname).toBeUndefined();
});
+ it("does NOT return token when status is not pending", async () => {
+ mockGetLatestTokenForUser.mockResolvedValue({
+ id: "mt_1", token: "al_secret", status: "registered", workspaceId: null, hostname: "MacBook.local",
+ });
+
+ const req = new NextRequest("http://localhost/api/machine-tokens/status");
+ const res = await GET(req);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.status).toBe("registered");
+ expect(body.token).toBeUndefined();
+ });
+
it("returns registered status with hostname", async () => {
mockGetLatestTokenForUser.mockResolvedValue({
id: "mt_1", status: "registered", workspaceId: null, hostname: "MacBook.local",
diff --git a/src/web/src/app/api/machine-tokens/status/route.ts b/src/web/src/app/api/machine-tokens/status/route.ts
index ffd6dc5f1..3a3d605e7 100644
--- a/src/web/src/app/api/machine-tokens/status/route.ts
+++ b/src/web/src/app/api/machine-tokens/status/route.ts
@@ -34,6 +34,7 @@ export const GET = withAuth(async (_req, ctx) => {
return writeJSON({
status: token.status,
+ token: token.status === "pending" ? token.token : undefined,
workspace_id: token.workspaceId || undefined,
hostname: token.hostname || undefined,
daemon_online: daemonOnline,
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 7c2d4d0fc..0351149e6 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -443,7 +443,7 @@ export const createMachineToken = (name?: string, workspaceId?: string) =>
);
export const getMachineTokenStatus = () =>
- apiFetch<{ status: "pending" | "registered" | "active" | null; workspace_id?: string; hostname?: string; daemon_online?: boolean; runtimes?: Array<{ id: string; type: string; version: string; status: string }> }>(
+ apiFetch<{ status: "pending" | "registered" | "active" | null; token?: string; workspace_id?: string; hostname?: string; daemon_online?: boolean; runtimes?: Array<{ id: string; type: string; version: string; status: string }> }>(
"/api/machine-tokens/status",
);
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index cd4e69579..4e7697393 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -231,6 +231,34 @@ describe("useUserWs", () => {
expect(mockFetch.mock.calls.length).toBe(callsAfterCleanup)
})
+ it("send() delivers message when WS is open", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ const mod = await import("./use-user-ws")
+ const { send } = mod.useUserWs(onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ send({ type: "check_daemon_status" })
+ expect(ws.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))
+ })
+
+ it("send() is a no-op when WS is not connected", async () => {
+ mockFetch.mockRejectedValue(new Error("network error"))
+
+ const onMsg = vi.fn()
+ const mod = await import("./use-user-ws")
+ const { send } = mod.useUserWs(onMsg)
+ await vi.advanceTimersByTimeAsync(100)
+
+ // No WS created, send should not throw
+ expect(() => send({ type: "test" })).not.toThrow()
+ expect(MockWebSocket.instances.length).toBe(0)
+ })
+
it("effect cleanup clears pending reconnect timer", async () => {
setupTokenFetch()
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 7786c1019..ee5eee432 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -8,7 +8,7 @@ const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000
-export function useUserWs(onMessage: (msg: WsMessage) => void, options?: { onReconnect?: () => void }) {
+export function useUserWs(onMessage: (msg: WsMessage) => void, options?: { onReconnect?: () => void }): { send: (msg: object) => void } {
const wsRef = useRef<WebSocket | null>(null)
const reconnectDelay = useRef(WS_RECONNECT_INIT)
const onMessageRef = useRef(onMessage)
@@ -134,4 +134,13 @@ export function useUserWs(onMessage: (msg: WsMessage) => void, options?: { onRec
ws?.close()
}
}, [connect])
+
+ const send = useCallback((msg: object) => {
+ const ws = wsRef.current
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify(msg))
+ }
+ }, [])
+
+ return { send }
}