From 0e57cac72db33ade583bf7988767bf680ef73d31 Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:45:16 +0900 Subject: [PATCH 1/6] feat(tui): add /sidebar and remember the side panel and todo fold Add /sidebar, a footer hint showing the hide key, and remember the side panel and Todo fold across restarts. --- .../src/feature-plugins/sidebar/footer.tsx | 8 + .../tui/src/feature-plugins/sidebar/todo.tsx | 12 +- packages/tui/src/i18n/en.ts | 1 + packages/tui/src/i18n/ko.ts | 1 + packages/tui/src/routes/session/index.tsx | 19 +-- packages/tui/src/routes/session/panel.ts | 16 ++ .../tui/test/feature-plugins/sidebar.test.tsx | 149 ++++++++++++++++++ 7 files changed, 192 insertions(+), 14 deletions(-) create mode 100644 packages/tui/src/routes/session/panel.ts create mode 100644 packages/tui/test/feature-plugins/sidebar.test.tsx diff --git a/packages/tui/src/feature-plugins/sidebar/footer.tsx b/packages/tui/src/feature-plugins/sidebar/footer.tsx index 2d17c9f49a..875af95344 100644 --- a/packages/tui/src/feature-plugins/sidebar/footer.tsx +++ b/packages/tui/src/feature-plugins/sidebar/footer.tsx @@ -22,6 +22,13 @@ function View(props: { api: TuiPluginApi; sessionID: string }) { const version = createMemo(() => props.api.app.version === "local" ? language.t("app.version.local") : props.api.app.version, ) + // The user's own key for hiding this panel, or the slash command when it is unbound. + const hide = createMemo(() => { + const key = props.api.tuiConfig.keybinds.get("session.sidebar.toggle")[0]?.key + if (!key) return "/sidebar" + const keymap = props.api.keymap + return keymap ? props.api.keys.formatSequence(Array.from(keymap.parseKeySequence(key))) : String(key) + }) const path = createMemo(() => { const session = props.api.state.session.get(props.sessionID) const dir = session?.directory || props.api.state.path.directory || paths.cwd @@ -68,6 +75,7 @@ function View(props: { api: TuiPluginApi; sessionID: string }) { + {language.t("sidebar.hide_hint", { shortcut: hide() })} {path().parent}/ {path().name} diff --git a/packages/tui/src/feature-plugins/sidebar/todo.tsx b/packages/tui/src/feature-plugins/sidebar/todo.tsx index c7e969807b..5cd683b2ce 100644 --- a/packages/tui/src/feature-plugins/sidebar/todo.tsx +++ b/packages/tui/src/feature-plugins/sidebar/todo.tsx @@ -1,14 +1,16 @@ import type { TuiPlugin, TuiPluginApi } from "@redrob-code/plugin/tui" import type { BuiltinTuiPlugin } from "../builtins" -import { createMemo, For, Show, createSignal } from "solid-js" +import { createMemo, For, Show } from "solid-js" import { TodoItem } from "../../component/todo-item" import { useLanguage } from "../../context/language" const id = "internal:sidebar-todo" +// Remembered in kv.json so a folded list stays folded across sessions and restarts. +export const TODO_OPEN = "sidebar_todo_open" function View(props: { api: TuiPluginApi; session_id: string }) { const language = useLanguage() - const [open, setOpen] = createSignal(true) + const open = () => props.api.kv.get(TODO_OPEN, true) const theme = () => props.api.theme.current const list = createMemo(() => props.api.state.session.todo(props.session_id)) const show = createMemo(() => list().length > 0 && list().some((item) => item.status !== "completed")) @@ -16,7 +18,11 @@ function View(props: { api: TuiPluginApi; session_id: string }) { return ( - list().length > 2 && setOpen((x) => !x)}> + list().length > 2 && props.api.kv.set(TODO_OPEN, !open())} + > 2}> {open() ? "▼" : "▶"} diff --git a/packages/tui/src/i18n/en.ts b/packages/tui/src/i18n/en.ts index 676fa89082..e8e44d62b4 100644 --- a/packages/tui/src/i18n/en.ts +++ b/packages/tui/src/i18n/en.ts @@ -312,6 +312,7 @@ export const dict = { "sidebar.context.spent": "{{cost}} spent", "sidebar.modified_files": "Modified Files", "sidebar.todo": "Todo", + "sidebar.hide_hint": "{{shortcut}} hide panel", // Help "help.title": "Help", diff --git a/packages/tui/src/i18n/ko.ts b/packages/tui/src/i18n/ko.ts index dda9a4591f..3d2af722cf 100644 --- a/packages/tui/src/i18n/ko.ts +++ b/packages/tui/src/i18n/ko.ts @@ -297,6 +297,7 @@ export const dict: Record = { "sidebar.context.spent": "{{cost}} 씀", "sidebar.modified_files": "바뀐 파일", "sidebar.todo": "할 일", + "sidebar.hide_hint": "{{shortcut}} 옆 패널 숨기기", "help.title": "도움말", "help.body": "어디서든 {{shortcut}} 키를 누르면 할 수 있는 동작과 명령을 모두 볼 수 있어요.", diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index 8733918068..6fe985f51d 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -1,5 +1,4 @@ import { - batch, createContext, createEffect, createMemo, @@ -55,6 +54,7 @@ import { DialogTimeline } from "./dialog-timeline" import { DialogForkFromTimeline } from "./dialog-fork-from-timeline" import { DialogSessionRename } from "../../component/dialog-session-rename" import { Sidebar } from "./sidebar" +import { panelNext, panelVisible, type PanelMode } from "./panel" import { SubagentFooter } from "./subagent-footer.tsx" import { filetype } from "../../util/filetype" import parsers from "../../parsers-config" @@ -279,8 +279,7 @@ export function Session() { } const dimensions = useTerminalDimensions() - const [sidebar, setSidebar] = kv.signal<"auto" | "hide">("sidebar", "auto") - const [sidebarOpen, setSidebarOpen] = createSignal(false) + const [sidebar, setSidebar] = kv.signal("sidebar", "auto") const [conceal, setConceal] = createSignal(true) const thinking = useThinkingMode() const thinkingMode = thinking.mode @@ -296,9 +295,7 @@ export function Session() { const wide = createMemo(() => dimensions().width > 120) const sidebarVisible = createMemo(() => { if (session()?.parentID) return false - if (sidebarOpen()) return true - if (sidebar() === "auto" && wide()) return true - return false + return panelVisible(sidebar(), wide()) }) const showTimestamps = createMemo(() => timestamps() === "show") const contentWidth = createMemo(() => dimensions().width - (sidebarVisible() ? 42 : 0) - 4) @@ -712,12 +709,12 @@ export function Session() { value: "session.sidebar.toggle", description: language.t("command.desc.session.sidebar.toggle"), category: "Session", + slash: { + name: "sidebar", + }, run: () => { - batch(() => { - const isVisible = sidebarVisible() - setSidebar(() => (isVisible ? "hide" : "auto")) - setSidebarOpen(!isVisible) - }) + const next = panelNext(sidebarVisible(), wide()) + setSidebar(() => next) dialog.clear() }, }, diff --git a/packages/tui/src/routes/session/panel.ts b/packages/tui/src/routes/session/panel.ts new file mode 100644 index 0000000000..a53d16d887 --- /dev/null +++ b/packages/tui/src/routes/session/panel.ts @@ -0,0 +1,16 @@ +// The session side panel's remembered mode, stored in kv.json under `sidebar`. +// `auto` shows it on wide terminals only (upstream's default), `hide` keeps it closed, +// and `show` keeps it open on a narrow terminal too, so a choice made there survives a restart. +export type PanelMode = "auto" | "hide" | "show" + +export function panelVisible(mode: PanelMode, wide: boolean) { + if (mode === "show") return true + if (mode === "hide") return false + return wide +} + +// The mode to store after the toggle, given what is on screen now. +export function panelNext(visible: boolean, wide: boolean): PanelMode { + if (visible) return "hide" + return wide ? "auto" : "show" +} diff --git a/packages/tui/test/feature-plugins/sidebar.test.tsx b/packages/tui/test/feature-plugins/sidebar.test.tsx new file mode 100644 index 0000000000..1d33e71f22 --- /dev/null +++ b/packages/tui/test/feature-plugins/sidebar.test.tsx @@ -0,0 +1,149 @@ +/** @jsxImportSource @opentui/solid */ +import { describe, expect, test } from "bun:test" +import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" +import { testRender, useRenderer } from "@opentui/solid" +import { createStore } from "solid-js/store" +import type { JSX } from "solid-js" +import type { TuiPlugin, TuiPluginApi } from "@redrob-code/plugin/tui" +import { tmpdir } from "../fixture/fixture" +import { LocaleHarness, localeState } from "../fixture/tui-locale" +import { createTuiPluginApi } from "../fixture/tui-plugin" +import { createTuiResolvedConfig } from "../fixture/tui-runtime" +import { registerRedrobKeymap } from "../../src/keymap" +import { panelNext, panelVisible } from "../../src/routes/session/panel" +import todoPlugin, { TODO_OPEN } from "../../src/feature-plugins/sidebar/todo" +import footerPlugin from "../../src/feature-plugins/sidebar/footer" + +describe("side panel mode", () => { + test("auto shows on wide terminals only", () => { + expect(panelVisible("auto", true)).toBe(true) + expect(panelVisible("auto", false)).toBe(false) + expect(panelVisible("hide", true)).toBe(false) + expect(panelVisible("show", false)).toBe(true) + }) + + test("the stored mode reproduces the toggled state after a restart", () => { + for (const wide of [true, false]) { + // Hide it, restart: still hidden. Show it again, restart: still shown. + const hidden = panelNext(true, wide) + expect(panelVisible(hidden, wide)).toBe(false) + const shown = panelNext(panelVisible(hidden, wide), wide) + expect(panelVisible(shown, wide)).toBe(true) + } + // Opening it on a narrow terminal is remembered, which a plain `auto` would forget. + expect(panelNext(false, false)).toBe("show") + expect(panelNext(false, true)).toBe("auto") + }) +}) + +const todos = [ + { id: "1", content: "first step", status: "in_progress", priority: "high" }, + { id: "2", content: "second step", status: "pending", priority: "high" }, + { id: "3", content: "third step", status: "pending", priority: "high" }, +] + +// A reactive KV, like the real kv.json store behind `api.kv`. +function kvStore(seed: Record) { + const [store, setStore] = createStore>({ ...seed }) + return { + store, + kv: { + get: (key: string, fallback?: unknown) => store[key] ?? fallback, + set: (key: string, value: unknown) => setStore(key, value), + ready: true, + }, + } +} + +async function render( + locale: "en" | "ko", + plugin: { tui: TuiPlugin }, + slot: string, + seed: Record, + drive?: (app: Awaited>) => Promise, +) { + await using tmp = await tmpdir() + const state = await localeState(tmp.path, locale) + const config = createTuiResolvedConfig() + const store = { current: undefined as ReturnType | undefined } + + function Harness() { + const renderer = useRenderer() + const keymap = createDefaultOpenTuiKeymap(renderer) + registerRedrobKeymap(keymap, renderer, config) + const kv = kvStore(seed) + store.current = kv + const base = createTuiPluginApi({ keymap, state: { session: { todo: () => todos as never } } }) + const slots: Record JSX.Element> = {} + const api = { + ...base, + kv: kv.kv, + app: { version: "local" }, + state: { + ...base.state, + provider: [], + path: { state: state, config: "", worktree: tmp.path, directory: tmp.path }, + vcs: undefined, + }, + slots: { + register(input: { slots: typeof slots }) { + Object.assign(slots, input.slots) + return () => {} + }, + }, + } as unknown as TuiPluginApi + void plugin.tui(api, undefined, {} as never) + return ( + + {slots[slot]?.({}, { session_id: "ses" })} + + ) + } + + const app = await testRender(() => , { width: 42, height: 20 }) + try { + for (let attempt = 0; attempt < 40; attempt++) { + await app.renderOnce() + if (app.captureCharFrame().trim()) break + await Bun.sleep(10) + } + if (drive) { + await drive(app) + await app.renderOnce() + await Bun.sleep(20) + await app.renderOnce() + } + return { frame: app.captureCharFrame(), kv: store.current!.store } + } finally { + app.renderer.destroy() + } +} + +describe("todo section fold", () => { + test("clicking the header folds the list and stores it", async () => { + const result = await render("en", todoPlugin, "sidebar_content", {}, (app) => app.mockMouse.click(1, 0)) + expect(result.kv[TODO_OPEN]).toBe(false) + expect(result.frame).toContain("▶") + expect(result.frame).not.toContain("second step") + }) + + test("a stored fold is restored on the next start", async () => { + const folded = await render("en", todoPlugin, "sidebar_content", { [TODO_OPEN]: false }) + expect(folded.frame).toContain("▶") + expect(folded.frame).not.toContain("first step") + + const open = await render("en", todoPlugin, "sidebar_content", {}) + expect(open.frame).toContain("▼") + expect(open.frame).toContain("third step") + }) +}) + +describe("panel footer hint", () => { + test("names the user's real key for hiding the panel", async () => { + const korean = await render("ko", footerPlugin, "sidebar_footer", {}) + expect(korean.frame).toContain("ctrl+x b 옆 패널 숨기기") + + const english = await render("en", footerPlugin, "sidebar_footer", {}) + expect(english.frame).toContain("ctrl+x b hide panel") + }) +}) From 8d7d3e8a27539e3561031d1c5c15ce3e46b94900 Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:45:37 +0900 Subject: [PATCH 2/6] feat(desk): run PC schedules from Redrob Chat on this machine The engine claims Redrob Chat schedule runs targeted at this machine (target hive), runs each prompt in a new session, and reports done or failed with the final text. A run is recorded before claim so a restart finishes it as failed instead of running it twice. --- packages/redrob/src/desk/auth.ts | 66 ++++++- packages/redrob/src/desk/hive.ts | 259 +++++++++++++++++++++++++ packages/redrob/src/desk/relay.ts | 6 + packages/redrob/test/desk/hive.test.ts | 215 ++++++++++++++++++++ 4 files changed, 537 insertions(+), 9 deletions(-) create mode 100644 packages/redrob/src/desk/hive.ts create mode 100644 packages/redrob/test/desk/hive.test.ts diff --git a/packages/redrob/src/desk/auth.ts b/packages/redrob/src/desk/auth.ts index 84d5620576..5e5c1fe8df 100644 --- a/packages/redrob/src/desk/auth.ts +++ b/packages/redrob/src/desk/auth.ts @@ -106,11 +106,13 @@ export async function startDeviceLogin(issuer: string): Promise 0 ? b.interval : 5) * 1000, } @@ -256,6 +258,31 @@ export type RelayTicket = { readonly room: string } +/** A schedule firing for this machine (redrob-chat `HiveRunJson`). `prompt` already ends with the new-chat guide. */ +export type HiveRun = { + readonly id: string + readonly scheduleId: string + readonly chatId: string + readonly name: string + readonly prompt: string + readonly dueAt: string + readonly status: string +} + +/** redrob-chat `FinishHiveRunDto`. */ +export type HiveFinish = { + readonly machineId: string + readonly status: "done" | "failed" + readonly error?: string + readonly text?: string +} + +function isHiveRun(value: unknown): value is HiveRun { + if (typeof value !== "object" || value === null) return false + const run = value as Record + return typeof run.id === "string" && typeof run.prompt === "string" && typeof run.scheduleId === "string" +} + export class ChatError extends Error { constructor( readonly status: number, @@ -265,25 +292,25 @@ export class ChatError extends Error { } } -/** The chat API calls the daemon makes, with the redrob-auth bearer. */ +/** The chat API calls the daemon makes, with the redrob-auth bearer (the `/schedules` hive routes take it too). */ export class ChatApi { constructor( private readonly base: string, private readonly tokens: AccessTokens, ) {} - private async post(path: string, body: unknown): Promise { + private async call(path: string, body?: unknown, method: "GET" | "POST" = "POST"): Promise { let token = "" const send = async () => { token = await this.tokens.get() return fetch(`${this.base}${path}`, { - method: "POST", + method, headers: { Authorization: `Bearer ${token}`, - "Content-Type": "application/json", Accept: "application/json", + ...(body !== undefined ? { "Content-Type": "application/json" } : {}), }, - body: JSON.stringify(body), + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(20_000), }) } @@ -297,11 +324,32 @@ export class ChatApi { } async relayTicket(): Promise { - return (await (await this.post("/mobile/relay-ticket", { as: "desk" })).json()) as RelayTicket + return (await (await this.call("/mobile/relay-ticket", { as: "desk" })).json()) as RelayTicket + } + + /** Schedule firings due on this machine, oldest first (`GET /schedules/hive/due`, hive.ts). */ + async hiveDue(machineId: string): Promise { + const response = await this.call(`/schedules/hive/due?machineId=${encodeURIComponent(machineId)}`, undefined, "GET") + const body = (await response.json()) as { items?: unknown } + return Array.isArray(body.items) ? body.items.filter(isHiveRun) : [] + } + + /** Take one firing; a `ChatError` 409 when another claim won or it is no longer due. */ + async hiveClaim(runId: string, machineId: string): Promise { + const body = (await ( + await this.call(`/schedules/runs/${encodeURIComponent(runId)}/claim`, { machineId }) + ).json()) as unknown + if (!isHiveRun(body)) throw new ChatError(502, "claim: malformed answer") + return body + } + + /** Report how a claimed firing ended; `text` becomes the answer in the schedule's chat. */ + async hiveFinish(runId: string, finish: HiveFinish): Promise { + await this.call(`/schedules/runs/${encodeURIComponent(runId)}/finish`, finish) } async notify(kind: "done" | "approval", sessionId: string, title?: string, machineId?: string): Promise { - await this.post("/mobile/notify", { + await this.call("/mobile/notify", { kind, sessionId, ...(title ? { title: title.slice(0, 120) } : {}), diff --git a/packages/redrob/src/desk/hive.ts b/packages/redrob/src/desk/hive.ts new file mode 100644 index 0000000000..13bc062755 --- /dev/null +++ b/packages/redrob/src/desk/hive.ts @@ -0,0 +1,259 @@ +/** + * PC schedules (redrob-chat `SchedulesService`, target `hive`). A schedule set to run on one of the + * person's computers stays `due` on the chat server until that computer takes it; unclaimed for an + * hour it is missed. The server has no path to the machine, so this machine pulls: + * + * every minute while the desk relay runs (signed in, desk on): `GET /schedules/hive/due?machineId=`, + * claim one (`POST /schedules/runs/:id/claim`; a 409 means it was taken or is no longer due), run + * its prompt as a new session on this engine (the PC's default model and tools, approval as the web + * gets it: Auto all on a trusted machine with the launcher's switch on, else edits), wait for the + * turn to end, and report `POST /schedules/runs/:id/finish` with done or failed and the final text. + * The server saves that text in the schedule's chat and opens a chat per `` block. + * + * A claimed run is written to `~/.redrob/desk/hive.json` before the claim and removed once the + * server has its finish. What is left there when the engine starts again (it stopped mid-run) is + * finished as failed, never run a second time; a finish the server did not get is sent again. + */ +import { mkdir, readFile, rename, writeFile } from "node:fs/promises" +import path from "node:path" +import { MobileProfile } from "@redrob-code/core/permission/mobile" +import { ChatError, type ChatApi, type HiveFinish, type HiveRun } from "./auth" +import type { DaemonApi } from "./daemon" +import type { Logger } from "./relay" +import { allowAutoAll, deskHome, machine, type Machine } from "./settings" + +/** How often due firings are asked for. */ +export const EVERY_MS = 60_000 +/** The first ask after the relay starts. */ +const FIRST_MS = 5_000 +/** redrob-chat `FinishHiveRunDto` limits. */ +const TEXT_MAX = 400_000 +const ERROR_MAX = 2_000 +/** How often a running session is looked at. */ +const POLL_MS = 2_000 +/** Inactive this many looks in a row with no finished answer (the turn never started): failed. */ +const SETTLE_TRIES = 30 + +export const INTERRUPTED = + "Redrob stopped on this computer before the run finished (the app or the computer restarted)." +export const READ_ONLY = "This computer is set to read only for Redrob Chat, so it runs no schedules." +export const NO_ANSWER = "The run ended without an answer." + +export type HiveChat = Pick +export type HiveDaemon = Pick + +/** One claimed run as kept on disk. `finish` is set once the run ended and the server has not taken it yet. */ +type Entry = { readonly at: number; readonly sessionId?: string; readonly finish?: HiveFinish } + +/** + * Runs this process is working on. Module state, not the runner's: the relay (and its runner) is + * made again when the sign-in changes, and its new runner must not take these for leftovers. + */ +const active = new Set() + +export function hivePath(): string { + return path.join(deskHome(), ".redrob", "desk", "hive.json") +} + +async function readEntries(): Promise> { + try { + const value = JSON.parse(await readFile(hivePath(), "utf8")) as { runs?: unknown } + return typeof value.runs === "object" && value.runs !== null ? (value.runs as Record) : {} + } catch { + return {} + } +} + +let writing: Promise = Promise.resolve() + +/** Serialized read-change-replace of the whole file. */ +function updateEntries(change: (runs: Record) => void): Promise { + const run = writing.then(async () => { + const runs = await readEntries() + change(runs) + const file = hivePath() + await mkdir(path.dirname(file), { recursive: true }) + const temp = `${file}.${process.pid}.tmp` + await writeFile(temp, JSON.stringify({ runs }, null, 2) + "\n", "utf8") + await rename(temp, file) + }) + writing = run.catch(() => undefined) + return run +} + +const setEntry = (id: string, entry: Entry) => updateEntries((runs) => void (runs[id] = entry)) +const dropEntry = (id: string) => updateEntries((runs) => void delete runs[id]) + +/** The server will never take this finish (the run is gone, or no longer running). */ +const settled = (error: unknown) => error instanceof ChatError && (error.status === 404 || error.status === 409) + +const message = (error: unknown) => (error instanceof Error ? error.message : String(error)) + +type Outcome = { readonly status: "done" | "failed"; readonly text?: string; readonly error?: string } + +/** + * PURE. How a run's session ended, from its context messages (`GET /api/session/:id/context`): + * the last assistant message's text, failed when it carries an error or no text. Undefined while + * no assistant message has finished yet. + */ +export function outcome(messages: unknown): Outcome | undefined { + if (!Array.isArray(messages)) return undefined + const last = messages + .filter((m): m is Record => typeof m === "object" && m !== null && m.type === "assistant") + .at(-1) + if (!last) return undefined + const error = (last.error as { message?: unknown } | undefined)?.message + const completed = (last.time as { completed?: unknown } | undefined)?.completed + if (completed === undefined && error === undefined) return undefined + const text = (Array.isArray(last.content) ? last.content : []) + .filter((c): c is { type: "text"; text: string } => c?.type === "text" && typeof c.text === "string") + .map((c) => c.text) + .join("\n\n") + .trim() + if (error !== undefined) return { status: "failed", error: String(error), ...(text ? { text } : {}) } + return text ? { status: "done", text } : { status: "failed", error: NO_ANSWER } +} + +function finishBody(machineId: string, out: Outcome): HiveFinish { + return { + machineId, + status: out.status, + ...(out.error ? { error: out.error.slice(0, ERROR_MAX) } : {}), + ...(out.text ? { text: out.text.slice(0, TEXT_MAX) } : {}), + } +} + +export class HiveRunner { + private timers: ReturnType[] = [] + private ticking = false + /** Runs started by this runner, for tests and shutdown. */ + readonly running = new Set>() + + constructor( + private readonly chat: HiveChat, + private readonly daemon: HiveDaemon, + private readonly log: Logger, + private readonly pollMs = POLL_MS, + ) {} + + start(): void { + if (this.timers.length) return + this.timers.push( + setTimeout(() => void this.tick(), FIRST_MS), + setInterval(() => void this.tick(), EVERY_MS), + ) + for (const timer of this.timers) timer.unref?.() + } + + /** No new runs. A run already going finishes and reports. */ + stop(): void { + for (const timer of this.timers) clearTimeout(timer) + this.timers = [] + } + + /** One pass: report leftovers, then take at most one due firing. */ + async tick(): Promise { + if (this.ticking) return + this.ticking = true + try { + const self = await machine() + const left = await this.settle(self.id) + const due = await this.chat.hiveDue(self.id) + const next = due.find((run) => !active.has(run.id) && !left.has(run.id)) + if (next) await this.take(next, self) + } catch (error) { + this.log.warn(`schedules: ${message(error)}`) + } finally { + this.ticking = false + } + } + + /** Sends what is left on disk and not running here. Returns the ids still kept after that. */ + private async settle(machineId: string): Promise> { + const left = new Set() + for (const [id, entry] of Object.entries(await readEntries())) { + if (active.has(id)) continue + const finish = entry.finish ?? finishBody(machineId, { status: "failed", error: INTERRUPTED }) + if (!(await this.report(id, finish))) left.add(id) + } + return left + } + + /** Sends a finish; kept on disk until the server has it. True when nothing is left to send. */ + private async report(id: string, finish: HiveFinish): Promise { + try { + await this.chat.hiveFinish(id, finish) + } catch (error) { + if (!settled(error)) { + await setEntry(id, { at: Date.now(), finish }) + this.log.warn(`schedules: finishing run ${id} failed, will retry: ${message(error)}`) + return false + } + } + await dropEntry(id) + return true + } + + /** Claims a firing and starts it. Written to disk first, so a stop between the claim and the run is reported. */ + private async take(run: HiveRun, self: Machine): Promise { + await setEntry(run.id, { at: Date.now() }) + active.add(run.id) + let claimed: HiveRun + try { + claimed = await this.chat.hiveClaim(run.id, self.id) + } catch (error) { + active.delete(run.id) + // Not ours (taken or no longer due): forget it. Anything else: the claim may have landed, + // so the entry stays and the next pass finishes it as failed (a 409 there drops it). + if (settled(error)) await dropEntry(run.id) + throw error + } + this.log.info(`schedules: running ${run.id}`) + const going = this.run(claimed, self).finally(() => { + active.delete(run.id) + this.running.delete(going) + }) + this.running.add(going) + } + + private async run(run: HiveRun, self: Machine): Promise { + let out: Outcome + try { + out = self.access === "read_only" ? { status: "failed", error: READ_ONLY } : await this.execute(run, self) + } catch (error) { + out = { status: "failed", error: message(error) } + } + await this.report(run.id, finishBody(self.id, out)) + this.log.info(`schedules: run ${run.id} ${out.status}`) + } + + /** A new session with the run's prompt, followed to the end of its turn. */ + private async execute(run: HiveRun, self: Machine): Promise { + const created = await this.daemon.raw("POST", "/api/session", {}) + const sessionId = (created.body as { data?: { id?: unknown } } | undefined)?.data?.id + if (created.status >= 300 || typeof sessionId !== "string") + throw new Error(`could not start a session on this computer (${created.status})`) + await setEntry(run.id, { at: Date.now(), sessionId }) + // Nobody is at the screen: the web's approval rules, as for a chat sent from the web. + MobileProfile.mark(sessionId, self.access === "trusted" && (await allowAutoAll()) ? "all" : "edits") + const sent = await this.daemon.raw("POST", `/api/session/${sessionId}/prompt`, { prompt: { text: run.prompt } }) + if (sent.status >= 300) throw new Error(`could not send the prompt (${sent.status})`) + // `POST /api/session/:id/wait` answers 503 on V2 sessions (forward.ts watchTurn), so the turn is + // followed by polling: over once the session is no longer active and its last answer is complete. + let idle = 0 + while (idle < SETTLE_TRIES) { + await Bun.sleep(this.pollMs) + const active = await this.daemon.raw("GET", "/api/session/active") + const running = (active.body as { data?: Record } | undefined)?.data?.[sessionId] !== undefined + if (running) { + idle = 0 + continue + } + const context = await this.daemon.raw("GET", `/api/session/${sessionId}/context`) + const out = outcome((context.body as { data?: unknown } | undefined)?.data) + if (out) return out + idle += 1 + } + return { status: "failed", error: NO_ANSWER } + } +} diff --git a/packages/redrob/src/desk/relay.ts b/packages/redrob/src/desk/relay.ts index 5d3859dd90..d8822cd15f 100644 --- a/packages/redrob/src/desk/relay.ts +++ b/packages/redrob/src/desk/relay.ts @@ -16,6 +16,7 @@ import { AccessTokens, ChatApi, endpoints, type AppToken, type RelayTicket } fro import * as DeskCrypto from "./crypto" import { DaemonApi } from "./daemon" import { Forwarder, type Link } from "./forward" +import { HiveRunner } from "./hive" import { MACHINE_NAMESPACE, decodeAction, @@ -67,6 +68,8 @@ export class DeskRelay { private readonly chat: ChatApi private readonly forwarder: Forwarder private readonly tools: ToolCatalog + /** PC schedules: pulls this machine's due firings and runs them (hive.ts). */ + private readonly hive: HiveRunner private readonly peers = new Map() private socket?: WebSocket private ticket?: RelayTicket @@ -101,6 +104,7 @@ export class DeskRelay { () => this.machineChanged(), ) this.tools = new ToolCatalog(this.api, InstallationVersion) + this.hive = new HiveRunner(this.chat, this.api, this.log) } get connected(): boolean { @@ -111,6 +115,7 @@ export class DeskRelay { if (!this.stopped) return this.stopped = false this.forwarder.start() + this.hive.start() const refreshTools = () => void this.tools.refresh().catch(() => undefined) refreshTools() this.timers.push( @@ -134,6 +139,7 @@ export class DeskRelay { if (this.machineSent) this.sendRaw(MACHINE_NAMESPACE, encodeMachine({ ...this.machineSent, online: false })) this.machineSent = undefined this.forwarder.stop() + this.hive.stop() this.dropAll() this.socket?.close(1000, "stop") this.socket = undefined diff --git a/packages/redrob/test/desk/hive.test.ts b/packages/redrob/test/desk/hive.test.ts new file mode 100644 index 0000000000..9582a87446 --- /dev/null +++ b/packages/redrob/test/desk/hive.test.ts @@ -0,0 +1,215 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { readFile, rm, writeFile, mkdir } from "node:fs/promises" +import path from "node:path" +import { MobileProfile } from "@redrob-code/core/permission/mobile" +import { ChatError, type HiveFinish, type HiveRun } from "../../src/desk/auth" +import { HiveRunner, INTERRUPTED, NO_ANSWER, READ_ONLY, hivePath, outcome, type HiveDaemon } from "../../src/desk/hive" +import { machine, settingsPath, updateMachine } from "../../src/desk/settings" + +const quiet = { info: () => undefined, warn: () => undefined } + +const run = (id: string): HiveRun => ({ + id, + scheduleId: "sch_1", + chatId: "chat_1", + name: "Morning notes", + prompt: "Summarise my notes", + dueAt: new Date().toISOString(), + status: "due", +}) + +const answer = (text: string, extra: Record = {}) => ({ + type: "assistant", + content: [ + { type: "reasoning", id: "r", text: "thinking" }, + { type: "text", id: "t", text }, + ], + time: { created: 1, completed: 2 }, + ...extra, +}) + +/** A chat server holding due runs; claim moves due to running once. */ +function fakeChat(due: HiveRun[]) { + const state = new Map(due.map((r) => [r.id, "due"])) + const claims: string[] = [] + const finishes: { id: string; body: HiveFinish }[] = [] + let finishFails = 0 + return { + claims, + finishes, + failNextFinishes(n: number) { + finishFails = n + }, + setRunning(id: string) { + state.set(id, "running") + }, + chat: { + hiveDue: async () => due.filter((r) => state.get(r.id) === "due"), + hiveClaim: async (id: string) => { + claims.push(id) + if (state.get(id) !== "due") throw new ChatError(409, "no longer due") + state.set(id, "running") + return { ...due.find((r) => r.id === id)!, status: "running" } + }, + hiveFinish: async (id: string, body: HiveFinish) => { + if (finishFails > 0) { + finishFails -= 1 + throw new Error("offline") + } + if (state.get(id) !== "running") throw new ChatError(409, "not running") + state.set(id, body.status) + finishes.push({ id, body }) + }, + }, + } +} + +/** An engine whose new session stays active for `busy` looks, then holds `messages`. */ +function fakeDaemon(messages: unknown[], busy = 1) { + const calls: string[] = [] + const daemon: HiveDaemon = { + raw: (async (method: string, p: string, body?: unknown) => { + calls.push(`${method} ${p}`) + if (method === "POST" && p === "/api/session") return { status: 200, body: { data: { id: "ses_hive" } } } + if (p.endsWith("/prompt")) { + expect(body).toEqual({ prompt: { text: "Summarise my notes" } }) + return { status: 200, body: { data: {} } } + } + if (p === "/api/session/active") + return { status: 200, body: { data: busy-- > 0 ? { ses_hive: { type: "running" } } : {} } } + if (p.endsWith("/context")) return { status: 200, body: { data: messages } } + return { status: 404 } + }) as HiveDaemon["raw"], + } + return { daemon, calls } +} + +async function settle(runner: HiveRunner) { + await runner.tick() + await Promise.all([...runner.running]) +} + +afterEach(async () => { + await rm(hivePath(), { force: true }) + await rm(settingsPath(), { force: true }) +}) + +describe("desk hive outcome", () => { + test("the last assistant message's text is the answer", () => { + expect(outcome([{ type: "user" }, answer("first"), answer("final")])).toEqual({ status: "done", text: "final" }) + }) + test("an unfinished turn is not an outcome yet", () => { + expect(outcome([{ type: "user" }])).toBeUndefined() + expect(outcome([answer("x", { time: { created: 1 } })])).toBeUndefined() + }) + test("an error fails the run and keeps any text", () => { + expect(outcome([answer("half", { error: { type: "unknown", message: "No model" } })])).toEqual({ + status: "failed", + error: "No model", + text: "half", + }) + }) + test("a turn that never answers fails after a while, it does not hang", async () => { + const server = fakeChat([run("run_a")]) + const { daemon } = fakeDaemon([{ type: "user" }], 0) + await settle(new HiveRunner(server.chat, daemon, quiet, 1)) + expect(server.finishes.map((f) => [f.body.status, f.body.error])).toEqual([["failed", NO_ANSWER]]) + }) + test("no text fails the run", () => { + expect(outcome([{ ...answer(""), content: [] }])).toEqual({ status: "failed", error: NO_ANSWER }) + }) +}) + +describe("desk hive runner", () => { + test("claims one due run, runs it as a session and finishes it with the answer", async () => { + const self = await machine() + const server = fakeChat([run("run_a"), run("run_b")]) + const { daemon, calls } = fakeDaemon([{ type: "user" }, answer("Three new notes.")]) + const runner = new HiveRunner(server.chat, daemon, quiet, 1) + + await settle(runner) + + expect(server.claims).toEqual(["run_a"]) + expect(server.finishes).toEqual([ + { id: "run_a", body: { machineId: self.id, status: "done", text: "Three new notes." } }, + ]) + expect(calls).toEqual([ + "POST /api/session", + "POST /api/session/ses_hive/prompt", + "GET /api/session/active", + "GET /api/session/active", + "GET /api/session/ses_hive/context", + ]) + // A trusted machine with the launcher's switch on: nobody is at the screen, nothing asks. + expect(MobileProfile.mode("ses_hive")).toBe("all") + expect(JSON.parse(await readFile(hivePath(), "utf8"))).toEqual({ runs: {} }) + + // The next pass takes the next one; run_a is never run again. + await settle(runner) + expect(server.claims).toEqual(["run_a", "run_b"]) + }) + + test("a run another claim took is skipped", async () => { + const server = fakeChat([run("run_a")]) + const chat = { ...server.chat, hiveDue: async () => [run("run_a")] } + server.setRunning("run_a") + const { daemon, calls } = fakeDaemon([answer("x")]) + await settle(new HiveRunner(chat, daemon, quiet, 1)) + expect(server.claims).toEqual(["run_a"]) + expect(calls).toEqual([]) + expect(JSON.parse(await readFile(hivePath(), "utf8"))).toEqual({ runs: {} }) + }) + + test("a run left over from a restart is finished as failed, not run again", async () => { + const self = await machine() + const server = fakeChat([run("run_left")]) + server.setRunning("run_left") + await mkdir(path.dirname(hivePath()), { recursive: true }) + await writeFile(hivePath(), JSON.stringify({ runs: { run_left: { at: 1, sessionId: "ses_old" } } })) + const { daemon, calls } = fakeDaemon([answer("x")]) + await settle(new HiveRunner(server.chat, daemon, quiet, 1)) + expect(server.finishes).toEqual([ + { id: "run_left", body: { machineId: self.id, status: "failed", error: INTERRUPTED } }, + ]) + expect(server.claims).toEqual([]) + expect(calls).toEqual([]) + }) + + test("a finish the server did not get is kept and sent on the next pass", async () => { + const server = fakeChat([run("run_a")]) + server.failNextFinishes(1) + const { daemon } = fakeDaemon([answer("Done.")]) + const runner = new HiveRunner(server.chat, daemon, quiet, 1) + await settle(runner) + expect(server.finishes).toEqual([]) + const kept = JSON.parse(await readFile(hivePath(), "utf8")) as { runs: Record } + expect(kept.runs.run_a?.finish?.text).toBe("Done.") + await settle(runner) + expect(server.finishes.map((f) => [f.id, f.body.status, f.body.text])).toEqual([["run_a", "done", "Done."]]) + expect(server.claims).toEqual(["run_a"]) + }) + + test("a read-only machine fails the run without starting a session", async () => { + await updateMachine({ access: "read_only" }) + const server = fakeChat([run("run_a")]) + const { daemon, calls } = fakeDaemon([answer("x")]) + await settle(new HiveRunner(server.chat, daemon, quiet, 1)) + expect(server.finishes.map((f) => [f.body.status, f.body.error])).toEqual([["failed", READ_ONLY]]) + expect(calls).toEqual([]) + }) + + test("signed out (the chat API refuses): nothing runs", async () => { + const chat = { + hiveDue: async () => { + throw new Error("signed_out") + }, + hiveClaim: async () => { + throw new Error("unreachable") + }, + hiveFinish: async () => undefined, + } + const { daemon, calls } = fakeDaemon([]) + await settle(new HiveRunner(chat, daemon, quiet, 1)) + expect(calls).toEqual([]) + }) +}) From 7aabeebc0943a381e7a49811bbe1f84f95edf8a6 Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:52:25 +0900 Subject: [PATCH 3/6] feat(tui): show usage in /status /status now has a Usage section: this session's tokens in/out/cache and cost (the footer's figure), and today, this month and all time summed over every session on this machine, plus a link to the Console balance page. The machine-wide totals come from a new GET /experimental/usage engine route (Session.usage). It sums the same step-finish parts that make up Session.cost, so nothing is re-priced. All time reads the session columns; today and this month sum part rows by time_created, with the day and month starts passed by the caller in its own time zone. Console exposes no balance or spend route a workspace API key can read: /v1/billing, /v1/billing/summary and /v1/usage are JWT-only, and every ApiKeyGuard route is inference. So the Console figure is a link for now. --- .../instance/httpapi/groups/experimental.ts | 19 +++++ .../instance/httpapi/handlers/experimental.ts | 13 +++- .../server/routes/instance/httpapi/public.ts | 2 + packages/redrob/src/session/session.ts | 75 +++++++++++++++++++ .../test/server/httpapi-exercise/index.ts | 12 +++ packages/redrob/test/session/session.test.ts | 55 ++++++++++++++ packages/sdk/js/src/v2/gen/sdk.gen.ts | 47 ++++++++++++ packages/sdk/js/src/v2/gen/types.gen.ts | 49 ++++++++++++ packages/tui/src/component/dialog-status.tsx | 73 +++++++++++++++++- packages/tui/src/i18n/en.ts | 10 +++ packages/tui/src/i18n/ko.ts | 10 +++ packages/tui/src/util/usage.ts | 42 +++++++++++ packages/tui/test/util/usage.test.ts | 30 ++++++++ 13 files changed, 435 insertions(+), 2 deletions(-) create mode 100644 packages/tui/src/util/usage.ts create mode 100644 packages/tui/test/util/usage.test.ts diff --git a/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts b/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts index aaf5431fbd..7d16f2a1eb 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts @@ -109,6 +109,13 @@ export const SessionListQuery = Schema.Struct({ archived: Schema.optional(QueryBoolean), }) +/** Where "today" and "this month" start, as epoch ms in the caller's time zone. */ +export const UsageQuery = Schema.Struct({ + ...WorkspaceRoutingQueryFields, + day: Schema.NumberFromString, + month: Schema.NumberFromString, +}) + export const ExperimentalPaths = { capabilities: "/experimental/capabilities", console: "/experimental/console", @@ -120,6 +127,7 @@ export const ExperimentalPaths = { worktreeReset: "/experimental/worktree/reset", session: "/experimental/session", sessionBackground: "/experimental/session/:sessionID/background", + usage: "/experimental/usage", resource: "/experimental/resource", } as const @@ -267,6 +275,17 @@ export const ExperimentalApi = HttpApi.make("experimental") "Detach any synchronous subagents currently blocking the session and continue them in the background.", }), ), + HttpApiEndpoint.get("usage", ExperimentalPaths.usage, { + query: UsageQuery, + success: described(Session.UsageSummary, "Usage on this machine"), + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.usage.get", + summary: "Get usage", + description: + "Cost and tokens across every session on this machine: today, this month and all time. Archived and subagent sessions are included.", + }), + ), HttpApiEndpoint.get("resource", ExperimentalPaths.resource, { query: WorkspaceRoutingQuery, success: described(Schema.Record(Schema.String, MCP.Resource), "MCP resources"), diff --git a/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts b/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts index 1661838f69..635abad9cc 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts @@ -15,7 +15,13 @@ import { Effect, Option } from "effect" import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" -import { ConsoleSwitchPayload, SessionListQuery, ToolListQuery, WorktreeApiError } from "../groups/experimental" +import { + ConsoleSwitchPayload, + SessionListQuery, + ToolListQuery, + UsageQuery, + WorktreeApiError, +} from "../groups/experimental" function mapWorktreeError(self: Effect.Effect) { return self.pipe( @@ -181,6 +187,10 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper return promoted.some((job) => job !== undefined) }) + const usage = Effect.fn("ExperimentalHttpApi.usage")(function* (ctx: { query: typeof UsageQuery.Type }) { + return yield* sessions.usage({ day: ctx.query.day, month: ctx.query.month }) + }) + const resource = Effect.fn("ExperimentalHttpApi.resource")(function* () { return yield* mcp.resources() }) @@ -198,6 +208,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper .handle("worktreeReset", worktreeReset) .handle("session", session) .handle("sessionBackground", sessionBackground) + .handle("usage", usage) .handle("resource", resource) }), ) diff --git a/packages/redrob/src/server/routes/instance/httpapi/public.ts b/packages/redrob/src/server/routes/instance/httpapi/public.ts index 9c64dd3729..744d8e5730 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/public.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/public.ts @@ -62,6 +62,8 @@ const QueryParameterSchemas: Record = { "GET /find/file limit": { type: "integer", minimum: 1, maximum: 200 }, "GET /experimental/session cursor": { type: "number" }, "GET /experimental/session limit": { type: "number" }, + "GET /experimental/usage day": { type: "number" }, + "GET /experimental/usage month": { type: "number" }, "GET /session start": { type: "number" }, "GET /session roots": QueryBooleanOpenApi, "GET /session limit": { type: "number" }, diff --git a/packages/redrob/src/session/session.ts b/packages/redrob/src/session/session.ts index ec3a4693cb..193eb9ceb7 100644 --- a/packages/redrob/src/session/session.ts +++ b/packages/redrob/src/session/session.ts @@ -310,6 +310,26 @@ export type ListInput = { limit?: number } +/** What one period cost on this machine: the same step-finish figures that add up to `Session.cost`. */ +export const UsageTotal = Schema.Struct({ + cost: Schema.Finite, + tokens: Tokens, +}).annotate({ identifier: "UsageTotal" }) +export type UsageTotal = Types.DeepMutable> + +export const UsageSummary = Schema.Struct({ + day: UsageTotal, + month: UsageTotal, + total: UsageTotal, +}).annotate({ identifier: "UsageSummary" }) +export type UsageSummary = Types.DeepMutable> + +/** Epoch milliseconds where "today" and "this month" start, in the caller's own time zone. */ +export type UsageInput = { + day: number + month: number +} + export type GlobalListInput = { directory?: string roots?: boolean @@ -451,6 +471,8 @@ export type NotFound = NotFoundError export interface Interface { readonly list: (input?: ListInput) => Effect.Effect readonly listGlobal: (input?: GlobalListInput) => Effect.Effect + /** Spend across every session on this machine, archived and subagent sessions included. */ + readonly usage: (input: UsageInput) => Effect.Effect readonly create: (input?: { parentID?: SessionID title?: string @@ -631,6 +653,58 @@ const layer: Layer.Layer< return rows.map((row) => ({ ...fromRow(row), project: projects.get(row.project_id) ?? null })) }) + const usage = Effect.fn("Session.usage")(function* (input: UsageInput) { + // `Session.cost` and its token columns are the sum of the session's step-finish parts (see + // applyUsage in core's session projector), so the all-time figure reads those columns and the + // dated figures sum the same parts by when they were written. Nothing is re-priced here. + const total = yield* db + .select({ + cost: sql`coalesce(sum(${SessionTable.cost}), 0)`, + input: sql`coalesce(sum(${SessionTable.tokens_input}), 0)`, + output: sql`coalesce(sum(${SessionTable.tokens_output}), 0)`, + reasoning: sql`coalesce(sum(${SessionTable.tokens_reasoning}), 0)`, + read: sql`coalesce(sum(${SessionTable.tokens_cache_read}), 0)`, + write: sql`coalesce(sum(${SessionTable.tokens_cache_write}), 0)`, + }) + .from(SessionTable) + .get() + .pipe(Effect.orDie) + const since = Math.min(input.day, input.month) + const field = (path: string, from: number) => + sql`coalesce(sum(case when ${PartTable.time_created} >= ${from} then json_extract(${PartTable.data}, ${path}) else 0 end), 0)` + const period = (from: number) => ({ + cost: field("$.cost", from), + input: field("$.tokens.input", from), + output: field("$.tokens.output", from), + reasoning: field("$.tokens.reasoning", from), + read: field("$.tokens.cache.read", from), + write: field("$.tokens.cache.write", from), + }) + const dated = yield* db + .select({ day: period(input.day), month: period(input.month) }) + .from(PartTable) + .where(and(gte(PartTable.time_created, since), sql`json_extract(${PartTable.data}, '$.type') = 'step-finish'`)) + .get() + .pipe(Effect.orDie) + const shape = (row?: { + cost: number + input: number + output: number + reasoning: number + read: number + write: number + }) => ({ + cost: Number(row?.cost ?? 0), + tokens: { + input: Number(row?.input ?? 0), + output: Number(row?.output ?? 0), + reasoning: Number(row?.reasoning ?? 0), + cache: { read: Number(row?.read ?? 0), write: Number(row?.write ?? 0) }, + }, + }) + return { day: shape(dated?.day), month: shape(dated?.month), total: shape(total) } + }) + const children = Effect.fn("Session.children")(function* (parentID: SessionID) { const rows = yield* db .select() @@ -944,6 +1018,7 @@ const layer: Layer.Layer< return Service.of({ list, listGlobal, + usage, create, fork, touch, diff --git a/packages/redrob/test/server/httpapi-exercise/index.ts b/packages/redrob/test/server/httpapi-exercise/index.ts index f23959abaa..02c330ca89 100644 --- a/packages/redrob/test/server/httpapi-exercise/index.ts +++ b/packages/redrob/test/server/httpapi-exercise/index.ts @@ -619,6 +619,18 @@ const scenarios: Scenario[] = [ check(body === false, "background route should be a no-op without running subagents") }), http.protected.get("/experimental/resource", "experimental.resource.list").json(), + http.protected + .get("/experimental/usage", "experimental.usage.get") + .at((ctx) => ({ + path: `/experimental/usage?${new URLSearchParams({ day: "0", month: "0" })}`, + headers: ctx.headers(), + })) + .json(200, (body) => { + const value = body as { day?: { cost?: unknown }; month?: { cost?: unknown }; total?: { cost?: unknown } } + check(typeof value.day?.cost === "number", "usage should report today's cost") + check(typeof value.month?.cost === "number", "usage should report this month's cost") + check(typeof value.total?.cost === "number", "usage should report the all-time cost") + }), http.protected .post("/sync/history", "sync.history.list") .at((ctx) => ({ path: "/sync/history", headers: ctx.headers(), body: {} })) diff --git a/packages/redrob/test/session/session.test.ts b/packages/redrob/test/session/session.test.ts index 858eb8ac5a..7b41505b59 100644 --- a/packages/redrob/test/session/session.test.ts +++ b/packages/redrob/test/session/session.test.ts @@ -205,6 +205,61 @@ describe("step-finish token propagation via event", () => { ) }) +describe("Session.usage", () => { + it.instance( + "sums step-finish cost and tokens by when they were written", + () => + Effect.gen(function* () { + const session = yield* SessionNs.Service + const before = yield* session.usage({ day: 0, month: 0 }) + const info = yield* session.create({}) + const messageID = MessageID.ascending() + yield* session.updateMessage({ + id: messageID, + sessionID: info.id, + role: "user", + time: { created: Date.now() }, + agent: "user", + model: { providerID: "test", modelID: "test" }, + tools: {}, + mode: "", + } as unknown as SessionV1.Info) + const finish = (cost: number, input: number) => + session.updatePart({ + id: PartID.ascending(), + messageID, + sessionID: info.id, + type: "step-finish" as const, + reason: "stop", + cost, + tokens: { total: input + 10, input, output: 10, reasoning: 0, cache: { read: 3, write: 1 } }, + }) + yield* finish(0.25, 100) + yield* finish(0.5, 200) + + const after = yield* session.usage({ day: 0, month: 0 }) + expect(after.day.cost - before.day.cost).toBeCloseTo(0.75) + expect(after.month.tokens.input - before.month.tokens.input).toBe(300) + expect(after.total.cost - before.total.cost).toBeCloseTo(0.75) + expect(after.total.tokens.output - before.total.tokens.output).toBe(20) + expect(after.total.tokens.cache.read - before.total.tokens.cache.read).toBe(6) + expect(after.total.tokens.cache.write - before.total.tokens.cache.write).toBe(2) + + // A day that starts after the parts were written leaves them in the month and out of today. + const later = Date.now() + 60_000 + const split = yield* session.usage({ day: later, month: 0 }) + expect(split.day.cost).toBe(0) + expect(split.day.tokens.input).toBe(0) + expect(split.month.cost).toBeCloseTo(after.month.cost) + + yield* session.remove(info.id) + const removed = yield* session.usage({ day: 0, month: 0 }) + expect(removed.total.cost).toBeCloseTo(before.total.cost) + }), + { timeout: 30000 }, + ) +}) + describe("Session", () => { it.live("remove works without an instance", () => Effect.gen(function* () { diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index b0bf21f54a..5a88a0f4e3 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -54,6 +54,8 @@ import type { ExperimentalSessionBackgroundResponses, ExperimentalSessionListErrors, ExperimentalSessionListResponses, + ExperimentalUsageGetErrors, + ExperimentalUsageGetResponses, ExperimentalWorkspaceAdapterListErrors, ExperimentalWorkspaceAdapterListResponses, ExperimentalWorkspaceCreateErrors, @@ -1067,6 +1069,46 @@ export class Session extends HeyApiClient { } } +export class Usage extends HeyApiClient { + /** + * Get usage + * + * Cost and tokens across every session on this machine: today, this month and all time. Archived and subagent sessions are included. + */ + public get( + parameters: { + directory?: string + workspace?: string + day: number + month: number + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "query", key: "directory" }, + { in: "query", key: "workspace" }, + { in: "query", key: "day" }, + { in: "query", key: "month" }, + ], + }, + ], + ) + return (options?.client ?? this.client).get< + ExperimentalUsageGetResponses, + ExperimentalUsageGetErrors, + ThrowOnError + >({ + url: "/experimental/usage", + ...options, + ...params, + }) + } +} + export class Resource extends HeyApiClient { /** * Get MCP resources @@ -1491,6 +1533,11 @@ export class Experimental extends HeyApiClient { return (this._session ??= new Session({ client: this.client })) } + private _usage?: Usage + get usage(): Usage { + return (this._usage ??= new Usage({ client: this.client })) + } + private _resource?: Resource get resource(): Resource { return (this._resource ??= new Resource({ client: this.client })) diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 61f7b8d26d..d2ad6e2f33 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -2428,6 +2428,25 @@ export type GlobalSession = { project: ProjectSummary | null } +export type UsageTotal = { + cost: number + tokens: { + input: number + output: number + reasoning: number + cache: { + read: number + write: number + } + } +} + +export type UsageSummary = { + day: UsageTotal + month: UsageTotal + total: UsageTotal +} + export type McpResource = { name: string uri: string @@ -8750,6 +8769,36 @@ export type ExperimentalSessionBackgroundResponses = { export type ExperimentalSessionBackgroundResponse = ExperimentalSessionBackgroundResponses[keyof ExperimentalSessionBackgroundResponses] +export type ExperimentalUsageGetData = { + body?: never + path?: never + query: { + directory?: string + workspace?: string + day: number + month: number + } + url: "/experimental/usage" +} + +export type ExperimentalUsageGetErrors = { + /** + * Bad request + */ + 400: BadRequestError +} + +export type ExperimentalUsageGetError = ExperimentalUsageGetErrors[keyof ExperimentalUsageGetErrors] + +export type ExperimentalUsageGetResponses = { + /** + * Usage on this machine + */ + 200: UsageSummary +} + +export type ExperimentalUsageGetResponse = ExperimentalUsageGetResponses[keyof ExperimentalUsageGetResponses] + export type ExperimentalResourceListData = { body?: never path?: never diff --git a/packages/tui/src/component/dialog-status.tsx b/packages/tui/src/component/dialog-status.tsx index 19b29c7481..0e4e383346 100644 --- a/packages/tui/src/component/dialog-status.tsx +++ b/packages/tui/src/component/dialog-status.tsx @@ -3,8 +3,14 @@ import { fileURLToPath } from "bun" import { useTheme } from "../context/theme" import { useDialog } from "../ui/dialog" import { useSync } from "../context/sync" -import { For, Match, Switch, Show, createMemo } from "solid-js" +import { For, Match, Switch, Show, createMemo, createResource } from "solid-js" import { useLanguage } from "../context/language" +import { useRoute } from "../context/route" +import { useSDK } from "../context/sdk" +import { Usage } from "../util/usage" +import { CONSOLE_HOME_URL } from "@redrob-code/core/links" + +const EMPTY: Usage.Total = { cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } } export type DialogStatusProps = {} @@ -13,6 +19,38 @@ export function DialogStatus() { const { theme } = useTheme() const dialog = useDialog() const language = useLanguage() + const route = useRoute() + const sdk = useSDK() + + // The current session's running total is the footer's figure; the machine-wide periods come from + // the engine, which sums every session's step-finish parts. Console exposes no balance or spend + // route an API key may read, so the Console figure is a link rather than a number. + const session = createMemo((): Usage.Total | undefined => { + if (route.data.type !== "session") return + const info = sync.session.get(route.data.sessionID) + if (!info) return + return { cost: info.cost ?? 0, tokens: info.tokens ?? EMPTY.tokens } + }) + const [machine] = createResource(async () => { + const result = await sdk.client.experimental.usage.get(Usage.bounds()) + if (result.error || !result.data) throw new Error("usage unavailable") + return result.data + }) + const rows = createMemo(() => { + const data = machine.error ? undefined : machine() + return [ + ...(session() ? [{ label: language.t("status.usage.session"), total: session()! }] : []), + ...(data + ? [ + { label: language.t("status.usage.day"), total: data.day }, + { label: language.t("status.usage.month"), total: data.month }, + { label: language.t("status.usage.total"), total: data.total }, + ] + : []), + ] + }) + const width = createMemo(() => Math.max(...rows().map((row) => Bun.stringWidth(row.label)), 0)) + const redrob = createMemo(() => sync.data.provider.some((item) => item.id === "redrob")) const enabledFormatters = createMemo(() => sync.data.formatter.filter((f) => f.enabled)) @@ -52,6 +90,39 @@ export function DialogStatus() { {language.t("dialog.esc")} + + {language.t("status.usage")} + + {(row) => ( + + + {row.label} + + + {language.t("status.usage.line", Usage.format(row.total))} + + + )} + + + + {language.t("status.usage.loading")} + + + {language.t("status.usage.failed")} + + + + {language.t("status.usage.note")} + + + + + + {language.t("status.usage.console", { url: `${CONSOLE_HOME_URL}/billing` })} + + + 0} fallback={{language.t("status.mcp.empty")}} diff --git a/packages/tui/src/i18n/en.ts b/packages/tui/src/i18n/en.ts index e8e44d62b4..10657407c7 100644 --- a/packages/tui/src/i18n/en.ts +++ b/packages/tui/src/i18n/en.ts @@ -282,6 +282,16 @@ export const dict = { // Status "status.title": "Status", + "status.usage": "Usage", + "status.usage.session": "This session", + "status.usage.day": "Today", + "status.usage.month": "This month", + "status.usage.total": "All time", + "status.usage.line": "in {{input}} · out {{output}} · cache {{cache}} · {{cost}}", + "status.usage.loading": "Loading usage…", + "status.usage.failed": "Could not load usage on this machine", + "status.usage.note": "Today, this month and all time add up every session on this machine.", + "status.usage.console": "Console balance: {{url}}", "status.mcp.empty": "No MCP Servers", "status.mcp.count.one": "{{count}} MCP Server", "status.mcp.count.other": "{{count}} MCP Servers", diff --git a/packages/tui/src/i18n/ko.ts b/packages/tui/src/i18n/ko.ts index 3d2af722cf..c37bc3bdaa 100644 --- a/packages/tui/src/i18n/ko.ts +++ b/packages/tui/src/i18n/ko.ts @@ -268,6 +268,16 @@ export const dict: Record = { "footer.subagent.next": "다음", "status.title": "상태", + "status.usage": "사용량", + "status.usage.session": "이 세션", + "status.usage.day": "오늘", + "status.usage.month": "이번 달", + "status.usage.total": "전체", + "status.usage.line": "입력 {{input}} · 출력 {{output}} · 캐시 {{cache}} · {{cost}}", + "status.usage.loading": "사용량을 불러오는 중…", + "status.usage.failed": "이 컴퓨터의 사용량을 불러오지 못했어요", + "status.usage.note": "오늘, 이번 달, 전체는 이 컴퓨터의 모든 세션을 더한 값이에요.", + "status.usage.console": "콘솔 잔액: {{url}}", "status.mcp.empty": "MCP 서버 없음", "status.mcp.count.one": "MCP 서버 {{count}}개", "status.mcp.count.other": "MCP 서버 {{count}}개", diff --git a/packages/tui/src/util/usage.ts b/packages/tui/src/util/usage.ts new file mode 100644 index 0000000000..b859119364 --- /dev/null +++ b/packages/tui/src/util/usage.ts @@ -0,0 +1,42 @@ +import { Locale } from "./locale" + +/** + * What `/status` shows under Usage. The figures are the engine's own step-finish cost and tokens -- + * the same numbers the prompt footer's `$7.92` comes from -- so nothing here re-prices anything. + */ +export type Tokens = { + input: number + output: number + reasoning: number + cache: { read: number; write: number } +} + +export type Total = { + cost: number + tokens: Tokens +} + +const money = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", +}) + +/** Epoch ms where today and this month start, in the user's local time zone. */ +export function bounds(now = new Date()) { + return { + day: new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(), + month: new Date(now.getFullYear(), now.getMonth(), 1).getTime(), + } +} + +/** Reasoning is billed as output, and cache reads and writes are one cache figure. */ +export function format(total: Total) { + return { + input: Locale.number(total.tokens.input), + output: Locale.number(total.tokens.output + total.tokens.reasoning), + cache: Locale.number(total.tokens.cache.read + total.tokens.cache.write), + cost: money.format(total.cost), + } +} + +export * as Usage from "./usage" diff --git a/packages/tui/test/util/usage.test.ts b/packages/tui/test/util/usage.test.ts new file mode 100644 index 0000000000..4b39c99097 --- /dev/null +++ b/packages/tui/test/util/usage.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from "bun:test" +import { Usage } from "../../src/util/usage" +import { createTranslator } from "../../src/i18n" + +describe("Usage", () => { + test("bounds start today and this month at local midnight", () => { + const now = new Date(2026, 10, 13, 14, 28, 5) + expect(Usage.bounds(now)).toEqual({ + day: new Date(2026, 10, 13).getTime(), + month: new Date(2026, 10, 1).getTime(), + }) + }) + + test("format folds reasoning into output and cache reads into writes, like the footer", () => { + const value = Usage.format({ + cost: 7.92, + tokens: { input: 96_400, output: 1_200, reasoning: 300, cache: { read: 1_000_000, write: 500_000 } }, + }) + expect(value).toEqual({ input: "96.4K", output: "1.5K", cache: "1.5M", cost: "$7.92" }) + }) + + test("the usage line reads in both languages", () => { + const value = Usage.format({ + cost: 0, + tokens: { input: 12, output: 3, reasoning: 0, cache: { read: 0, write: 0 } }, + }) + expect(createTranslator("en").t("status.usage.line", value)).toBe("in 12 · out 3 · cache 0 · $0.00") + expect(createTranslator("ko").t("status.usage.line", value)).toBe("입력 12 · 출력 3 · 캐시 0 · $0.00") + }) +}) From eb241ad2fa0ee827bbdca913c590aacee24c4ac2 Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:58:36 +0900 Subject: [PATCH 4/6] feat(install): one-line PowerShell install (install.ps1) irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex installs redrob.exe into %USERPROFILE%\.redrob\bin (where Redrob Desktop and redrob upgrade look), verified against the release SHA256SUMS.txt, and adds it to the user PATH. Works in Windows PowerShell 5.1 and PowerShell 7, through iex or the scriptblock form with -Version. redrob upgrade on a Windows curl install now runs install.ps1 with PowerShell instead of piping install.sh into bash. --- README.ko.md | 22 ++ README.md | 23 ++ install.ps1 | 286 ++++++++++++++++++ packages/redrob/src/installation/index.ts | 55 +++- .../test/installation/install-ps1.test.ts | 83 +++++ .../test/installation/installation.test.ts | 44 +++ 6 files changed, 507 insertions(+), 6 deletions(-) create mode 100644 install.ps1 create mode 100644 packages/redrob/test/installation/install-ps1.test.ts diff --git a/README.ko.md b/README.ko.md index 5d71b6e421..e8399b3fde 100644 --- a/README.ko.md +++ b/README.ko.md @@ -44,6 +44,28 @@ XDG_BIN_DIR=$HOME/.local/bin curl -fsSL https://raw.githubusercontent.com/redrob redrob ``` +#### Windows + +PowerShell(Windows PowerShell 5.1 또는 PowerShell 7)에서 실행합니다. 관리자 권한은 필요 없습니다. + +```powershell +irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex +``` + +[`install.ps1`](./install.ps1) 은 CPU에 맞는 x64, x64-baseline, arm64 빌드를 골라 릴리스의 +`SHA256SUMS.txt` 로 검증한 뒤 `redrob.exe` 를 `%USERPROFILE%\.redrob\bin` 에 설치하고(Redrob +Desktop 이 찾는 위치이고, `redrob upgrade` 로 업데이트됩니다) 그 폴더를 사용자 PATH 에 추가합니다. +버전이나 설치 폴더를 지정하려면: + +```powershell +& ([scriptblock]::Create((irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1))) -Version 0.18.16 +$env:REDROB_INSTALL_DIR = "D:\tools\redrob"; irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex +``` + +`REDROB_VERSION`, `REDROB_NO_MODIFY_PATH=1`, `REDROB_CONNECT=rc_...` 는 각각 `-Version`, +`-NoModifyPath`, `-Connect` 와 같습니다. [릴리스 페이지](https://github.com/redrob-labs/redrob-code/releases) +의 서명된 `.msi` 와 `setup.exe` 는 `%LOCALAPPDATA%\Redrob\bin` 에 설치합니다. + ### 인증 레드롭 코드는 의 레드롭 콘솔과 통신하며 워크스페이스 API 키로 diff --git a/README.md b/README.md index 8810e37124..170acee97a 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,29 @@ Then start it in any project: redrob ``` +#### Windows + +In PowerShell (Windows PowerShell 5.1 or PowerShell 7), no administrator rights needed: + +```powershell +irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex +``` + +[`install.ps1`](./install.ps1) picks the x64, x64-baseline or arm64 build for your CPU, checks it +against the release's `SHA256SUMS.txt`, installs `redrob.exe` into `%USERPROFILE%\.redrob\bin` +(where Redrob Desktop looks, and where `redrob upgrade` can replace it) and adds that folder to +your user PATH. A specific version, or a different folder: + +```powershell +& ([scriptblock]::Create((irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1))) -Version 0.18.16 +$env:REDROB_INSTALL_DIR = "D:\tools\redrob"; irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex +``` + +`REDROB_VERSION`, `REDROB_NO_MODIFY_PATH=1` and `REDROB_CONNECT=rc_...` do the same as +`-Version`, `-NoModifyPath` and `-Connect`. The signed `.msi` and `setup.exe` on the +[releases page](https://github.com/redrob-labs/redrob-code/releases) install into +`%LOCALAPPDATA%\Redrob\bin` instead. + ### Authentication Redrob Code talks to the Redrob console at and authenticates diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 0000000000..b998b3837e --- /dev/null +++ b/install.ps1 @@ -0,0 +1,286 @@ +# Redrob Code installer for Windows (Windows PowerShell 5.1 and PowerShell 7). +# +# irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex +# & ([scriptblock]::Create((irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1))) -Version 0.18.16 +# +# The Windows counterpart of `install`: it picks the build for this CPU from the GitHub release, +# checks it against the release's SHA256SUMS.txt, and puts redrob.exe (and a redrob-code.exe copy) +# in %USERPROFILE%\.redrob\bin. That is where Redrob Desktop and the engine client look for the +# engine, and where `redrob upgrade` recognises an install it can replace. The folder goes on your +# own PATH. Nothing here needs administrator rights. +# +# There is deliberately no param() block: `irm ... | iex` cannot pass one. Options come from the +# arguments of the scriptblock form above, or from environment variables: +# +# -Version REDROB_VERSION, REDROB_CODE_VERSION Which release. Default: latest +# -InstallDir REDROB_INSTALL_DIR, REDROB_CODE_INSTALL_DIR +# Default: %USERPROFILE%\.redrob\bin +# -Binary REDROB_CODE_BIN Install a redrob.exe you already have +# -NoModifyPath REDROB_NO_MODIFY_PATH=1, REDROB_CODE_NO_PATH=1 +# Leave your PATH alone +# -Connect REDROB_CONNECT Connect this PC to Redrob Chat after +# installing (the code from its connect card) +# REDROB_CODE_DOWNLOAD_BASE Where the releases are (for tests) +# +# Everything runs inside one scriptblock so `iex` leaves no variables behind in your session, and a +# failure throws instead of calling `exit`, which would close the window `iex` was typed into. + +& { + $ErrorActionPreference = 'Stop' + Set-StrictMode -Version 2.0 + # Invoke-WebRequest's progress bar makes a 150 MB download in Windows PowerShell 5.1 many times slower. + $ProgressPreference = 'SilentlyContinue' + + $Repo = 'redrob-labs/redrob-code' + $ReadmeUrl = "https://github.com/$Repo#readme" + + function Get-Setting([string[]] $Names) { + foreach ($name in $Names) { + $value = [Environment]::GetEnvironmentVariable($name) + if ($value) { return $value.Trim() } + } + return '' + } + + $requestedVersion = Get-Setting @('REDROB_VERSION', 'REDROB_CODE_VERSION') + $installDir = Get-Setting @('REDROB_INSTALL_DIR', 'REDROB_CODE_INSTALL_DIR') + $binaryPath = Get-Setting @('REDROB_CODE_BIN') + $connectCode = Get-Setting @('REDROB_CONNECT') + $noModifyPath = (Get-Setting @('REDROB_NO_MODIFY_PATH', 'REDROB_CODE_NO_PATH')) -eq '1' + $downloadBase = Get-Setting @('REDROB_CODE_DOWNLOAD_BASE') + if (-not $downloadBase) { $downloadBase = "https://github.com/$Repo/releases" } + $downloadBase = $downloadBase.TrimEnd('/') + + $rest = @($args) + for ($i = 0; $i -lt $rest.Count; $i++) { + $arg = [string] $rest[$i] + $next = if ($i + 1 -lt $rest.Count) { [string] $rest[$i + 1] } else { '' } + switch -Regex ($arg) { + '^-{1,2}(h|help|\?)$' { + Write-Host 'Redrob Code installer for Windows' + Write-Host '' + Write-Host ' irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1 | iex' + Write-Host ' & ([scriptblock]::Create((irm https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1))) -Version 0.18.16' + Write-Host '' + Write-Host 'Options: -Version -InstallDir -Binary -NoModifyPath -Connect ' + Write-Host 'Env: REDROB_VERSION REDROB_INSTALL_DIR REDROB_CODE_BIN REDROB_NO_MODIFY_PATH=1 REDROB_CONNECT' + return + } + '^-{1,2}(v|version)$' { + if (-not $next) { throw '-Version needs a version, for example -Version 0.18.16' } + $requestedVersion = $next; $i++; continue + } + '^-{1,2}(installdir|install-dir)$' { + if (-not $next) { throw '-InstallDir needs a folder' } + $installDir = $next; $i++; continue + } + '^-{1,2}(b|binary)$' { + if (-not $next) { throw '-Binary needs the path of a redrob.exe' } + $binaryPath = $next; $i++; continue + } + '^-{1,2}(nomodifypath|no-modify-path)$' { $noModifyPath = $true; continue } + '^-{1,2}connect$' { + if (-not $next) { throw "-Connect needs the rc_... code from Redrob Chat's connect card" } + $connectCode = $next; $i++; continue + } + default { Write-Warning "Unknown option '$arg'" } + } + } + + if ($connectCode -and $connectCode -notmatch '^rc_[A-Za-z0-9_-]{8,128}$') { + throw "-Connect needs the rc_... code from Redrob Chat's connect card" + } + if (-not $installDir) { $installDir = Join-Path $env:USERPROFILE '.redrob\bin' } + $installDir = [IO.Path]::GetFullPath($installDir) + $target = Join-Path $installDir 'redrob.exe' + + # Windows PowerShell 5.1 still defaults to TLS 1.0, which github.com refuses. + try { + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + } catch {} + + function Get-Text([string] $Url) { + $response = Invoke-WebRequest -Uri $Url -UseBasicParsing + $content = $response.Content + if ($content -is [byte[]]) { $content = [Text.Encoding]::UTF8.GetString($content) } + return [string] $content + } + + function Get-Arch { + $arch = '' + try { $arch = [string] [Runtime.InteropServices.RuntimeInformation]::OSArchitecture } catch {} + if (-not $arch) { + # A 32-bit PowerShell on 64-bit Windows reports the real CPU in PROCESSOR_ARCHITEW6432. + $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } + } + switch -Regex ($arch) { + '^(X64|AMD64)$' { return 'x64' } + '^(Arm64|ARM64)$' { return 'arm64' } + default { throw "Redrob Code has no Windows build for $arch. x64 and arm64 are the builds there are." } + } + } + + function Test-Avx2 { + # PF_AVX2_INSTRUCTIONS_AVAILABLE (40). Without AVX2 the regular x64 build crashes on start, + # so such a CPU gets the baseline build, as `install` does. + try { + if (-not ('RedrobInstall.Kernel32' -as [type])) { + Add-Type -Namespace RedrobInstall -Name Kernel32 -MemberDefinition '[DllImport("kernel32.dll")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' + } + return [RedrobInstall.Kernel32]::IsProcessorFeaturePresent(40) + } catch { + return $false + } + } + + function Install-Binary([string] $From) { + New-Item -ItemType Directory -Force -Path $installDir | Out-Null + foreach ($name in @('redrob.exe', 'redrob-code.exe')) { + $to = Join-Path $installDir $name + $old = "$to.old" + # A running .exe cannot be overwritten or deleted, but it can be renamed, so the one in use + # (`redrob upgrade`, a daemon Redrob Desktop started) moves aside and the .old goes next time. + Remove-Item -LiteralPath $old -Force -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath $to) { Move-Item -LiteralPath $to -Destination $old -Force } + Copy-Item -LiteralPath $From -Destination $to -Force + Remove-Item -LiteralPath $old -Force -ErrorAction SilentlyContinue + } + } + + function Add-UserPath([string] $Dir) { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true) + try { + # Read it unexpanded and write it back as REG_EXPAND_SZ, so entries like %USERPROFILE%\bin survive. + $current = [string] $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $want = $Dir.TrimEnd('\') + $present = $current -split ';' | Where-Object { $_ -and [Environment]::ExpandEnvironmentVariables($_).TrimEnd('\') -ieq $want } + if ($present) { return $false } + # First, as `install` does, so this copy wins over an older one (an .msi install appends). + $value = if ($current) { $Dir + ';' + $current.TrimStart(';') } else { $Dir } + $key.SetValue('Path', $value, [Microsoft.Win32.RegistryValueKind]::ExpandString) + } finally { + $key.Close() + } + # Tell Explorer the environment changed, so terminals opened from it see the new PATH. + try { + if (-not ('RedrobInstall.User32' -as [type])) { + Add-Type -Namespace RedrobInstall -Name User32 -MemberDefinition '[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint Msg, System.UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out System.UIntPtr lpdwResult);' + } + $result = [UIntPtr]::Zero + [RedrobInstall.User32]::SendMessageTimeout([IntPtr] 0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref] $result) | Out-Null + } catch {} + return $true + } + + if ($binaryPath) { + if (-not (Test-Path -LiteralPath $binaryPath -PathType Leaf)) { throw "Binary not found at $binaryPath" } + Write-Host "Installing redrob from $binaryPath" + Install-Binary ([IO.Path]::GetFullPath($binaryPath)) + } else { + $arch = Get-Arch + $asset = "redrob-windows-$arch" + if ($arch -eq 'x64' -and -not (Test-Avx2)) { $asset = "$asset-baseline" } + $asset = "$asset.zip" + + if ($requestedVersion) { + $version = $requestedVersion -replace '^v', '' + } else { + # The marker the release workflow publishes beside the newest release: a redirect, not the + # GitHub API, so it has no anonymous rate limit. `redrob upgrade` reads the same file. + try { + $version = (Get-Text "$downloadBase/latest/download/VERSION").Trim() -replace '^v', '' + } catch { + throw "Could not read $downloadBase/latest/download/VERSION, so the newest version is unknown. Releases: https://github.com/$Repo/releases" + } + } + if ($version -notmatch '^\d+\.\d+\.\d+([-.][0-9A-Za-z.-]+)?$') { throw "'$version' is not a version" } + + $installed = '' + if (Test-Path -LiteralPath $target) { + try { $installed = ((& $target --version) | Out-String).Trim() } catch {} + if ($installed -eq $version -and -not $connectCode) { + Write-Host "Version $version already installed in $installDir" + return + } + if ($installed) { Write-Host "Installed version: $installed" } + } + + $work = Join-Path ([IO.Path]::GetTempPath()) ("redrob-install-" + [Guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Force -Path $work | Out-Null + try { + if (-not ($installed -eq $version)) { + Write-Host '' + Write-Host "Installing redrob version: $version ($asset)" + $releaseUrl = "$downloadBase/download/v$version" + $zip = Join-Path $work $asset + try { + Invoke-WebRequest -Uri "$releaseUrl/$asset" -OutFile $zip -UseBasicParsing + } catch { + throw "Could not download $releaseUrl/$asset. Is v$version a release? https://github.com/$Repo/releases" + } + + # One checksum file per release covers every asset; the line for this asset is picked by + # name. Releases up to v0.6.4 published it as SHA256SUMS. + $sums = $null + foreach ($name in @('SHA256SUMS.txt', 'SHA256SUMS')) { + try { $sums = Get-Text "$releaseUrl/$name"; break } catch {} + } + if (-not $sums) { throw "v$version publishes no SHA256SUMS.txt, so $asset cannot be verified. Nothing was installed." } + $expected = '' + foreach ($line in ($sums -split "`n")) { + $parts = $line.Trim() -split '\s+' + if ($parts.Count -ge 2 -and ($parts[1] -eq $asset -or $parts[1] -eq "*$asset")) { $expected = $parts[0].ToLowerInvariant(); break } + } + if (-not $expected) { throw "SHA256SUMS.txt in v$version has no line for $asset. Nothing was installed." } + $actual = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $expected) { throw "Checksum mismatch for $asset (expected $expected, got $actual). Nothing was installed." } + + $unpacked = Join-Path $work 'x' + Expand-Archive -LiteralPath $zip -DestinationPath $unpacked -Force + $exe = Get-ChildItem -LiteralPath $unpacked -Recurse -Filter 'redrob.exe' | Select-Object -First 1 + if (-not $exe) { throw "$asset holds no redrob.exe" } + Install-Binary $exe.FullName + } + } finally { + Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue + } + } + + $onPath = @($env:Path -split ';' | Where-Object { $_ -and $_.TrimEnd('\') -ieq $installDir.TrimEnd('\') }).Count -gt 0 + if (-not $onPath) { + if ($noModifyPath) { + Write-Host '' + Write-Host "$installDir is not on your PATH, and your PATH was left alone. Add it yourself to run redrob by name." + } else { + if (Add-UserPath $installDir) { Write-Host "Added $installDir to your user PATH" } + # This session too, so `redrob` works right away after `irm ... | iex`. + $env:Path = "$installDir;$env:Path" + } + } + + if ($env:GITHUB_ACTIONS -eq 'true' -and $env:GITHUB_PATH) { + Add-Content -LiteralPath $env:GITHUB_PATH -Value $installDir + Write-Host "Added $installDir to `$GITHUB_PATH" + } + + Write-Host '' + Write-Host 'Redrob Code' + Write-Host '' + Write-Host 'To start, open your project and run redrob, then type /connect to sign in:' + # The same line in Korean, kept as UTF-8 bytes so this file stays ASCII: Windows PowerShell 5.1 + # reads a script without a BOM in the ANSI code page, and `irm` text is not always UTF-8 either. + Write-Host ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('7Iuc7J6R7ZWY66Ck66m0IO2UhOuhnOygne2KuCDtj7TrjZTsl5DshJwgcmVkcm9i7J2EIOyLpO2Wie2VnCDrkqQgL2Nvbm5lY3Trpbwg7J6F66Cl7ZW0IOuhnOq3uOyduO2VmOyEuOyalDo='))) + Write-Host '' + Write-Host ' cd ' + Write-Host ' redrob' + Write-Host ' /connect' + Write-Host '' + Write-Host "More: $ReadmeUrl" + Write-Host '' + + if ($connectCode) { + Write-Host 'Connecting this PC to Redrob Chat' + & $target desk connect $connectCode + if ($LASTEXITCODE -ne 0) { throw "redrob desk connect failed with code $LASTEXITCODE" } + } +} @args diff --git a/packages/redrob/src/installation/index.ts b/packages/redrob/src/installation/index.ts index 12a6800ada..8ed83b627c 100644 --- a/packages/redrob/src/installation/index.ts +++ b/packages/redrob/src/installation/index.ts @@ -90,6 +90,27 @@ export class UpgradeFailedError extends Schema.TaggedErrorClass fs.writeFile(file, "\uFEFF" + body, "utf8")) + const result = yield* appProcess + .run( + ChildProcess.make( + "powershell.exe", + ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file], + { env, extendEnv: true }, + ), + ) + .pipe(Effect.ensuring(Effect.promise(() => fs.rm(file, { force: true })))) + return { + code: result.exitCode, + stdout: result.stdout.toString("utf8"), + stderr: result.stderr.toString("utf8"), + } + } const bodyBytes = new TextEncoder().encode(body) const shell = yield* upgradeScriptShell() const result = yield* appProcess.run( ChildProcess.make(shell, [], { stdin: Stream.make(bodyBytes), - // The directory rather than the default, so the binary that is running is the one - // replaced when it was installed somewhere other than `$HOME/.redrob/bin`. Anything else - // the user set, `REDROB_CODE_DOWNLOAD_BASE` included, arrives through the inherited env. - env: { REDROB_CODE_VERSION: target, REDROB_CODE_INSTALL_DIR: path.dirname(process.execPath) }, + env, extendEnv: true, }), ) @@ -292,7 +335,7 @@ const layer: Layer.Layer !line.trimStart().startsWith("#")) + .join("\n") + +describe("install.ps1", () => { + test("runs through iex: no param block, no exit", () => { + // `irm ... | iex` cannot bind a param() block, so options come from $args and the environment. + expect(code).not.toMatch(/^\s*param\s*\(/im) + // `exit` inside `iex` closes the PowerShell window the person typed the command into. + expect(code).not.toMatch(/\bexit\b/i) + // One scriptblock, so `iex` leaves no variables in the person's session. + expect(code.trimStart().startsWith("& {")).toBe(true) + expect(code.trimEnd().endsWith("} @args")).toBe(true) + }) + + test("is ASCII, which Windows PowerShell 5.1 reads the same in every code page", () => { + expect([...script].every((ch) => ch.charCodeAt(0) < 128)).toBe(true) + }) + + test("installs where Redrob Desktop and `redrob upgrade` look", () => { + // redrob-desktop's enginesetup.rs: `~/.redrob/bin/redrob.exe`; isCurlInstall: a `.redrob\bin` dir. + expect(code).toContain("Join-Path $env:USERPROFILE '.redrob\\bin'") + expect(code).toContain("'redrob.exe', 'redrob-code.exe'") + }) + + test("reads its options from the environment, under the names both installers use", () => { + for (const name of [ + "REDROB_VERSION", + "REDROB_CODE_VERSION", + "REDROB_INSTALL_DIR", + "REDROB_CODE_INSTALL_DIR", + "REDROB_CODE_DOWNLOAD_BASE", + "REDROB_NO_MODIFY_PATH", + "REDROB_CONNECT", + ]) { + expect(code).toContain(`'${name}'`) + } + }) + + test("downloads assets the release publishes and verifies them", () => { + // The release workflow zips `dist/redrob-windows-*` (x64, x64-baseline, arm64) and publishes + // SHA256SUMS.txt covering every asset. + expect(code).toContain('"redrob-windows-$arch"') + expect(code).toContain('"$asset-baseline"') + expect(code).toContain("'SHA256SUMS.txt'") + expect(code).toContain("Get-FileHash") + expect(code).toContain("/latest/download/VERSION") + }) + + test("changes only the user's PATH", () => { + expect(code).toContain("[Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)") + expect(code).not.toContain("LocalMachine") + expect(code).not.toMatch(/HKLM/i) + }) + + const pwsh = Bun.which("pwsh") + test.skipIf(!pwsh)("parses in PowerShell", () => { + const result = Bun.spawnSync([ + pwsh!, + "-NoProfile", + "-NonInteractive", + "-Command", + `$e = $null; [void][System.Management.Automation.Language.Parser]::ParseFile('${file.replace(/'/g, "''")}', [ref]$null, [ref]$e); if ($e) { $e | ForEach-Object { $_.ToString() }; exit 1 }`, + ]) + expect(result.stdout.toString() + result.stderr.toString()).toBe("") + expect(result.exitCode).toBe(0) + }) +}) diff --git a/packages/redrob/test/installation/installation.test.ts b/packages/redrob/test/installation/installation.test.ts index bd0246c06f..6a016bda3a 100644 --- a/packages/redrob/test/installation/installation.test.ts +++ b/packages/redrob/test/installation/installation.test.ts @@ -9,6 +9,7 @@ import { Installation } from "../../src/installation" import { CrossSpawnSpawner } from "@redrob-code/core/cross-spawn-spawner" import { testEffect } from "../lib/effect" import path from "path" +import fs from "fs" const encoder = new TextEncoder() @@ -212,6 +213,49 @@ describe("installation", () => { yield* Installation.use.upgrade("curl", "9.9.9") }), ) + + test("picks the installer for the platform", () => { + expect(Installation.upgradeScriptUrl("linux")).toBe(Installation.CONSOLE_INSTALL_SCRIPT_URL) + expect(Installation.upgradeScriptUrl("darwin")).toBe(Installation.CONSOLE_INSTALL_SCRIPT_URL) + expect(Installation.upgradeScriptUrl("win32")).toBe( + "https://raw.githubusercontent.com/redrob-labs/redrob-code/main/install.ps1", + ) + expect(Installation.reinstallCommand("win32")).toBe(`irm ${Installation.INSTALL_PS1_URL} | iex`) + expect(Installation.reinstallCommand("linux")).toBe(`curl -fsSL ${Installation.CONSOLE_INSTALL_SCRIPT_URL} | sh`) + }) + + const winCalls: string[] = [] + const winRuns: Array<{ cmd: string; args: readonly string[]; env: Record }> = [] + testEffect( + testLayer( + (request) => { + winCalls.push(request.url) + return new Response("Write-Host install", { status: 200 }) + }, + (cmd, args, env) => { + winRuns.push({ cmd, args, env }) + return "installed" + }, + ), + ).effect("upgrades a Windows curl install through install.ps1, not sh", () => + Effect.gen(function* () { + const platform = process.platform + Object.defineProperty(process, "platform", { value: "win32" }) + yield* Installation.use + .upgrade("curl", "9.9.9") + .pipe(Effect.ensuring(Effect.sync(() => Object.defineProperty(process, "platform", { value: platform })))) + expect(winCalls).toEqual([Installation.INSTALL_PS1_URL]) + // Windows has no bash or sh to pipe install.sh into, and install.sh refuses Windows anyway. + expect(winRuns.some((run) => run.cmd === "bash" || run.cmd === "sh")).toBe(false) + const run = winRuns.find((r) => r.cmd === "powershell.exe") + expect(run?.args.slice(0, 5)).toEqual(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File"]) + expect(run?.args[5]).toEndWith(".ps1") + expect(run?.env["REDROB_CODE_VERSION"]).toBe("9.9.9") + expect(run?.env["REDROB_CODE_INSTALL_DIR"]).toBe(path.dirname(process.execPath)) + // The script file is removed once it has run. + expect(fs.existsSync(run!.args[5]!)).toBe(false) + }), + ) }) describe("method", () => { From a5b0311c290c457153f543ab9662fa9fbf933b3c Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:09:48 +0900 Subject: [PATCH 5/6] fix: decode Windows shell output in the console code page Ask PowerShell, cmd and Python for UTF-8 output on Windows, and decode output that is still not UTF-8 with the system ANSI code page instead of U+FFFD. --- packages/core/src/shell.ts | 84 ++++++++++++++++++++++++++- packages/core/test/shell.test.ts | 51 ++++++++++++++++ packages/redrob/src/session/prompt.ts | 6 +- packages/redrob/src/tool/shell.ts | 7 ++- 4 files changed, 141 insertions(+), 7 deletions(-) diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index abc18a2fac..b56d5ff92a 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -1,7 +1,7 @@ export * as Shell from "./shell" import path from "path" -import { spawn, type ChildProcess } from "child_process" +import { execFileSync, spawn, type ChildProcess } from "child_process" import { readFile } from "fs/promises" import { statSync } from "fs" import { setTimeout as sleep } from "node:timers/promises" @@ -224,3 +224,85 @@ export async function list(): Promise { const shells = process.platform === "win32" ? win() : await unix() return shells.filter((s) => resolve(s)).map(info) } + +// Windows console programs write in the console or ANSI code page (949 on Korean Windows), and we +// decode their output as UTF-8. Ask the shell and Python for UTF-8 up front, and decode whatever +// still arrives as non-UTF-8 with the system code page instead of turning it into U+FFFD. + +/** Child env defaults that make Python write UTF-8 to a pipe. The caller's own values win. */ +export function env(platform = process.platform): Record { + if (platform !== "win32") return {} + return { PYTHONUTF8: "1", PYTHONIOENCODING: "utf-8" } +} + +/** Prefix a Windows command so PowerShell and cmd write UTF-8. */ +export function utf8(file: string, command: string, platform = process.platform) { + if (platform !== "win32") return command + if (ps(file)) return `[Console]::OutputEncoding=$OutputEncoding=[Text.UTF8Encoding]::new($false);${command}` + if (name(file) === "cmd") return `chcp 65001>nul&${command}` + return command +} + +let acp: number | undefined | null = null + +/** The system ANSI code page, read once from the registry. */ +function codepage() { + if (acp !== null) return acp + acp = undefined + try { + const text = execFileSync("reg", ["query", "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage", "/v", "ACP"], { + encoding: "utf8", + windowsHide: true, + timeout: 2000, + }) + const match = /ACP\s+REG_SZ\s+(\d+)/.exec(text) + if (match) acp = Number(match[1]) + } catch {} + return acp +} + +const LABELS: Record = { 866: "ibm866", 932: "shift_jis", 936: "gbk", 949: "euc-kr", 950: "big5" } + +function legacy(page: number | undefined) { + if (page && page !== 65001) { + try { + return new TextDecoder((LABELS[page] ?? `windows-${page}`) as ConstructorParameters[0]) + } catch {} + } + return new TextDecoder("utf-8") +} + +// Trailing bytes that open a UTF-8 sequence the chunk does not finish; the decoder holds them back. +function pending(bytes: Uint8Array) { + for (let i = 1; i <= Math.min(3, bytes.length); i++) { + const byte = bytes[bytes.length - i] + if ((byte & 0xc0) === 0x80) continue + const need = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1 + return need > i ? bytes.slice(bytes.length - i) : new Uint8Array() + } + return new Uint8Array() +} + +/** + * A streaming decoder for shell output. UTF-8 everywhere; on Windows, once the output turns out not + * to be UTF-8, the rest of the stream is decoded with the system code page. + */ +export function decoder(platform = process.platform, page: () => number | undefined = codepage) { + const text = new TextDecoder("utf-8", { fatal: platform === "win32" }) + let fallback: TextDecoder | undefined + let tail = new Uint8Array() + return (bytes: Uint8Array) => { + if (fallback) return fallback.decode(bytes, { stream: true }) + try { + const out = text.decode(bytes, { stream: true }) + tail = pending(bytes) + return out + } catch { + fallback = legacy(page()) + const all = new Uint8Array(tail.length + bytes.length) + all.set(tail) + all.set(bytes, tail.length) + return fallback.decode(all, { stream: true }) + } + } +} diff --git a/packages/core/test/shell.test.ts b/packages/core/test/shell.test.ts index d4225224b0..9b29fae255 100644 --- a/packages/core/test/shell.test.ts +++ b/packages/core/test/shell.test.ts @@ -106,3 +106,54 @@ describe("shell", () => { }) } }) + +describe("shell output encoding", () => { + // "한글" in UTF-8 and in code page 949 + const utf8 = new TextEncoder().encode("한글 ok") + const cp949 = new Uint8Array([0xc7, 0xd1, 0xb1, 0xdb, 0x20, 0x6f, 0x6b]) + + test("env asks Python for UTF-8 on Windows only", () => { + expect(Shell.env("win32")).toEqual({ PYTHONUTF8: "1", PYTHONIOENCODING: "utf-8" }) + expect(Shell.env("linux")).toEqual({}) + expect(Shell.env("darwin")).toEqual({}) + }) + + test("utf8 prefixes PowerShell and cmd on Windows only", () => { + expect(Shell.utf8("pwsh", "Write-Output hi", "win32")).toBe( + "[Console]::OutputEncoding=$OutputEncoding=[Text.UTF8Encoding]::new($false);Write-Output hi", + ) + expect(Shell.utf8("powershell", "dir", "win32")).toStartWith("[Console]::OutputEncoding=") + expect(Shell.utf8("cmd", "echo hi", "win32")).toBe("chcp 65001>nul&echo hi") + expect(Shell.utf8("bash", "echo hi", "win32")).toBe("echo hi") + expect(Shell.utf8("pwsh", "echo hi", "linux")).toBe("echo hi") + expect(Shell.utf8("/bin/bash", "echo hi", "darwin")).toBe("echo hi") + }) + + test("decoder keeps UTF-8 output as is", () => { + const decode = Shell.decoder("win32", () => 949) + expect(decode(utf8.subarray(0, 2)) + decode(utf8.subarray(2))).toBe("한글 ok") + }) + + test("decoder falls back to the system code page on Windows", () => { + const decode = Shell.decoder("win32", () => 949) + expect(decode(cp949)).toBe("한글 ok") + expect(decode(cp949)).toBe("한글 ok") + }) + + test("decoder keeps a code page lead byte split across chunks", () => { + // 0xc7 alone looks like the start of a UTF-8 sequence; the next chunk proves it is not + const decode = Shell.decoder("win32", () => 949) + expect(decode(new Uint8Array([0x61, 0xc7])) + decode(cp949.subarray(1))).toBe("a한글 ok") + }) + + test("decoder without a known code page replaces invalid bytes", () => { + expect(Shell.decoder("win32", () => undefined)(cp949)).toBe(new TextDecoder().decode(cp949)) + expect(Shell.decoder("win32", () => 65001)(cp949)).toBe(new TextDecoder().decode(cp949)) + }) + + test("decoder never switches code page off Windows", () => { + const decode = Shell.decoder("linux", () => 949) + expect(decode(cp949)).toBe(new TextDecoder().decode(cp949)) + expect(decode(utf8)).toBe("한글 ok") + }) +}) diff --git a/packages/redrob/src/session/prompt.ts b/packages/redrob/src/session/prompt.ts index d0f7ed5374..8eee2dce2e 100644 --- a/packages/redrob/src/session/prompt.ts +++ b/packages/redrob/src/session/prompt.ts @@ -574,7 +574,7 @@ const layer = Layer.effect( const cfg = yield* config.get() const sh = Shell.preferred(cfg.shell) - const args = Shell.args(sh, input.command, cwd) + const args = Shell.args(sh, Shell.utf8(sh, input.command), cwd) let output = "" let aborted = false @@ -612,12 +612,12 @@ const layer = Layer.effect( const cmd = ChildProcess.make(sh, args, { cwd, extendEnv: true, - env: { ...shellEnv.env, TERM: "dumb" }, + env: { ...Shell.env(), ...process.env, ...shellEnv.env, TERM: "dumb" }, stdin: "ignore", forceKillAfter: "3 seconds", }) const handle = yield* spawner.spawn(cmd) - yield* Stream.runForEach(Stream.decodeText(handle.all), (chunk) => + yield* Stream.runForEach(Stream.map(handle.all, Shell.decoder()), (chunk) => Effect.gen(function* () { output += chunk if (part.state.status === "running") { diff --git a/packages/redrob/src/tool/shell.ts b/packages/redrob/src/tool/shell.ts index a93f020a4e..e2908c5821 100644 --- a/packages/redrob/src/tool/shell.ts +++ b/packages/redrob/src/tool/shell.ts @@ -327,7 +327,7 @@ const ask = Effect.fn("ShellTool.ask")(function* (ctx: Tool.Context, scan: Scan, function cmd(shell: string, command: string, cwd: string, env: NodeJS.ProcessEnv) { if (process.platform === "win32" && Shell.ps(shell)) { - return ChildProcess.make(shell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command], { + return ChildProcess.make(shell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", Shell.utf8(shell, command)], { cwd, env, stdin: "ignore", @@ -335,7 +335,7 @@ function cmd(shell: string, command: string, cwd: string, env: NodeJS.ProcessEnv }) } - return ChildProcess.make(command, [], { + return ChildProcess.make(Shell.utf8(shell, command), [], { shell, cwd, env, @@ -455,6 +455,7 @@ export const ShellTool = Tool.define( { env: {} }, ) return { + ...Shell.env(), ...process.env, ...extra.env, } @@ -519,7 +520,7 @@ export const ShellTool = Tool.define( const handle = yield* spawner.spawn(cmd(input.shell, input.command, input.cwd, input.env)) yield* Effect.forkScoped( - Stream.runForEach(Stream.decodeText(handle.all), (chunk) => { + Stream.runForEach(Stream.map(handle.all, Shell.decoder()), (chunk) => { const size = Buffer.byteLength(chunk, "utf-8") list.push({ text: chunk, size }) used += size From 53921043bf0148beb4a410c50e18ae394fee72e9 Mon Sep 17 00:00:00 2001 From: Janghoon Lee <44862514+its-janghoon@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:58:16 +0900 Subject: [PATCH 6/6] feat(tui): show Console balance and spend in /status /status gets a Console block: the workspace balance, today's spend and this month's spend across every device, with request counts and the billing link. A complimentary workspace says so instead of showing a balance, and a balance under $1 is shown as a warning. The engine reads it through a new GET /experimental/console/usage?tz= route. It calls the Console's GET /usage/summary with the key and base URL the Redrob provider already uses for inference (options.apiKey, else the merged credential; options.baseURL, else CONSOLE_URL, so REDROB_CONSOLE_URL still selects dev). The key never reaches the TUI and is never logged. The TUI fetches once when /status opens, not on a timer. The engine waits at most 5 seconds. No key, 401, 400, 429, 404 (a Console without the route), a timeout or a body that does not parse all return null, and the dialog shows the plain billing link as before. --- packages/core/src/balance.ts | 64 ++++++++++++++ packages/core/test/balance.test.ts | 87 +++++++++++++++++++ .../instance/httpapi/groups/experimental.ts | 18 ++++ .../instance/httpapi/handlers/experimental.ts | 20 +++++ .../test/server/httpapi-exercise/index.ts | 10 +++ packages/sdk/js/src/v2/gen/sdk.gen.ts | 38 ++++++++ packages/sdk/js/src/v2/gen/types.gen.ts | 46 ++++++++++ packages/tui/src/component/dialog-status.tsx | 69 ++++++++++++++- packages/tui/src/i18n/en.ts | 9 ++ packages/tui/src/i18n/ko.ts | 9 ++ packages/tui/src/util/usage.ts | 31 +++++++ packages/tui/test/util/usage.test.ts | 33 +++++++ 12 files changed, 430 insertions(+), 4 deletions(-) create mode 100644 packages/core/src/balance.ts create mode 100644 packages/core/test/balance.test.ts diff --git a/packages/core/src/balance.ts b/packages/core/src/balance.ts new file mode 100644 index 0000000000..ec799f65c4 --- /dev/null +++ b/packages/core/src/balance.ts @@ -0,0 +1,64 @@ +export * as Balance from "./balance" + +import { Effect, Schema } from "effect" +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" + +/** + * The workspace's balance and spend, read from the console for `/status`. + * + * `GET /usage/summary?tz=` with the same workspace API key the Redrob provider + * already sends for inference. The figures are the workspace's, across every device and app, which is + * what the local session totals cannot say. + * + * Every failure is quiet: no key, a refused key (401), a bad zone (400), the rate limit (429), a console + * that does not have the route yet (404), a timeout or a body that does not parse all return + * `undefined`, and the caller shows the billing link it showed before. Nothing here logs, and the key + * never leaves the request header. + */ + +/** `/status` waits for this, so it stays short: a slow console must not hold the dialog. */ +const TIMEOUT = "5 seconds" + +const Period = Schema.Struct({ + since: Schema.String, + spend: Schema.Finite, + requestCount: Schema.Finite, +}).annotate({ identifier: "ConsoleUsagePeriod" }) + +export const Summary = Schema.Struct({ + currency: Schema.String, + balance: Schema.Finite, + complimentary: Schema.Boolean, + plan: Schema.optional(Schema.String), + tz: Schema.String, + today: Period, + month: Period, +}).annotate({ identifier: "ConsoleUsageSummary" }) +export type Summary = Schema.Schema.Type + +export type Input = { + /** The console API base, `CONSOLE_URL` or the provider's configured `baseURL`. */ + url: string + key: string + tz: string +} + +const decode = Schema.decodeUnknownOption(Schema.fromJsonString(Summary)) + +const read = Effect.fn("Balance.read")(function* (input: Input) { + const http = yield* HttpClient.HttpClient + const url = `${input.url.replace(/\/+$/, "")}/usage/summary?${new URLSearchParams({ tz: input.tz })}` + const response = yield* http.execute( + HttpClientRequest.get(url).pipe(HttpClientRequest.acceptJson, HttpClientRequest.bearerToken(input.key)), + ) + if (response.status !== 200) return undefined + const parsed = decode(yield* response.text) + return parsed._tag === "Some" ? parsed.value : undefined +}) + +export const summary = (input: Input): Effect.Effect => + read(input).pipe( + Effect.timeout(TIMEOUT), + Effect.provide(FetchHttpClient.layer), + Effect.catchCause(() => Effect.succeed(undefined)), + ) diff --git a/packages/core/test/balance.test.ts b/packages/core/test/balance.test.ts new file mode 100644 index 0000000000..7f92b8d4f2 --- /dev/null +++ b/packages/core/test/balance.test.ts @@ -0,0 +1,87 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test" +import { Effect } from "effect" +import { Balance } from "@redrob-code/core/balance" + +/** + * A stand-in console on loopback. Each test picks the reply by the key it sends, so the request the + * module builds (path, query, bearer header) is checked on every call. + */ +const body = { + currency: "USD", + balance: 20.368355, + complimentary: false, + plan: "free", + tz: "Asia/Seoul", + today: { since: "2026-11-12T15:00:00.000Z", spend: 0, requestCount: 0 }, + month: { since: "2026-10-31T15:00:00.000Z", spend: 147.07, requestCount: 16764 }, +} + +const seen: { path: string; tz: string | null; auth: string | null }[] = [] +let server: ReturnType +let url: string + +beforeAll(() => { + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const parsed = new URL(request.url) + const auth = request.headers.get("authorization") + seen.push({ path: parsed.pathname, tz: parsed.searchParams.get("tz"), auth }) + if (parsed.pathname !== "/api/backend/v1/usage/summary") return new Response("not found", { status: 404 }) + switch (auth) { + case "Bearer ok": + return Response.json(body) + case "Bearer slow": + await Bun.sleep(7_000) + return Response.json(body) + case "Bearer garbled": + return new Response("{not json", { status: 200 }) + case "Bearer partial": + return Response.json({ currency: "USD", balance: 1 }) + case "Bearer limited": + return Response.json({ message: "slow down" }, { status: 429, headers: { "retry-after": "30" } }) + default: + return Response.json({ message: "invalid api key" }, { status: 401 }) + } + }, + }) + url = `http://127.0.0.1:${server.port}/api/backend/v1` +}) + +afterAll(() => server.stop(true)) + +const run = (key: string, base = url) => Effect.runPromise(Balance.summary({ url: base, key, tz: "Asia/Seoul" })) + +describe("Balance.summary", () => { + test("reads the console's summary with the key as a bearer token and the zone as a query", async () => { + seen.length = 0 + expect(await run("ok")).toEqual(body) + expect(seen).toEqual([{ path: "/api/backend/v1/usage/summary", tz: "Asia/Seoul", auth: "Bearer ok" }]) + }) + + test("tolerates a trailing slash on the base URL", async () => { + expect(await run("ok", `${url}/`)).toEqual(body) + }) + + test("a refused key, the rate limit and a missing route fall back quietly", async () => { + expect(await run("wrong")).toBeUndefined() + expect(await run("limited")).toBeUndefined() + expect(await run("ok", `http://127.0.0.1:${server.port}/old`)).toBeUndefined() + }) + + test("a body that does not parse or misses fields falls back", async () => { + expect(await run("garbled")).toBeUndefined() + expect(await run("partial")).toBeUndefined() + }) + + test("an unreachable console falls back", async () => { + expect(await run("ok", "http://127.0.0.1:1/api/backend/v1")).toBeUndefined() + }) + + test("a console slower than the timeout falls back", async () => { + const start = Date.now() + expect(await run("slow")).toBeUndefined() + expect(Date.now() - start).toBeLessThan(6_500) + }, 10_000) +}) diff --git a/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts b/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts index 7d16f2a1eb..1e9d7d53a7 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/groups/experimental.ts @@ -18,6 +18,7 @@ import { described } from "./metadata" import { QueryBoolean } from "./query" import { ProviderV2 } from "@redrob-code/core/provider" import { ModelV2 } from "@redrob-code/core/model" +import { Balance } from "@redrob-code/core/balance" const ConsoleStateResponse = Schema.Struct({ consoleManagedProviders: Schema.mutable(Schema.Array(Schema.String)), @@ -99,6 +100,11 @@ export class WorktreeApiError extends Schema.ErrorClass("Workt }, { httpApiStatus: 400 }, ) {} +/** The caller's IANA zone, so "today" and "this month" are the user's own. */ +export const ConsoleUsageQuery = Schema.Struct({ + ...WorkspaceRoutingQueryFields, + tz: Schema.String, +}) export const SessionListQuery = Schema.Struct({ ...WorkspaceRoutingQueryFields, roots: Schema.optional(QueryBoolean), @@ -121,6 +127,7 @@ export const ExperimentalPaths = { console: "/experimental/console", consoleOrgs: "/experimental/console/orgs", consoleSwitch: "/experimental/console/switch", + consoleUsage: "/experimental/console/usage", tool: "/experimental/tool", toolIDs: "/experimental/tool/ids", worktree: "/experimental/worktree", @@ -167,6 +174,17 @@ export const ExperimentalApi = HttpApi.make("experimental") description: "Get the available Console orgs across logged-in accounts, including the current active org.", }), ), + HttpApiEndpoint.get("consoleUsage", ExperimentalPaths.consoleUsage, { + query: ConsoleUsageQuery, + success: described(Schema.NullOr(Balance.Summary), "Console balance and spend, or null"), + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.console.usage", + summary: "Get Console balance and spend", + description: + "The Redrob workspace's balance and today's and this month's spend across every device, read from the Console with the Redrob provider's key. Null when there is no key or the Console does not answer.", + }), + ), HttpApiEndpoint.post("consoleSwitch", ExperimentalPaths.consoleSwitch, { query: WorkspaceRoutingQuery, payload: ConsoleSwitchPayload, diff --git a/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts b/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts index 635abad9cc..4226629678 100644 --- a/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts +++ b/packages/redrob/src/server/routes/instance/httpapi/handlers/experimental.ts @@ -11,12 +11,17 @@ import type { SessionID } from "@/session/schema" import { ToolJsonSchema } from "@/tool/json-schema" import { ToolRegistry } from "@/tool/registry" import { Worktree } from "@/worktree" +import { Provider } from "@/provider/provider" +import { Balance } from "@redrob-code/core/balance" +import { CONSOLE_URL } from "@redrob-code/core/plugin/provider/redrob-constants" +import { ProviderV2 } from "@redrob-code/core/provider" import { Effect, Option } from "effect" import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" import { ConsoleSwitchPayload, + ConsoleUsageQuery, SessionListQuery, ToolListQuery, UsageQuery, @@ -41,6 +46,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper const sessions = yield* Session.Service const background = yield* BackgroundJob.Service const flags = yield* RuntimeFlags.Service + const providers = yield* Provider.Service const capabilities = Effect.fn("ExperimentalHttpApi.capabilities")(function* () { return { @@ -191,6 +197,19 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper return yield* sessions.usage({ day: ctx.query.day, month: ctx.query.month }) }) + const consoleUsage = Effect.fn("ExperimentalHttpApi.consoleUsage")(function* (ctx: { + query: typeof ConsoleUsageQuery.Type + }) { + // The key and base URL the Redrob provider sends inference with, resolved the way the SDK gets + // them (`options.apiKey`, else the merged credential). "public" is the keyless placeholder. + const info = (yield* providers.list())[ProviderV2.ID.redrob] + const options = (info?.options ?? {}) as { apiKey?: unknown; baseURL?: unknown } + const key = typeof options.apiKey === "string" ? options.apiKey : info?.key + if (!key || key === "public") return null + const url = typeof options.baseURL === "string" && options.baseURL ? options.baseURL : CONSOLE_URL + return (yield* Balance.summary({ url, key, tz: ctx.query.tz })) ?? null + }) + const resource = Effect.fn("ExperimentalHttpApi.resource")(function* () { return yield* mcp.resources() }) @@ -200,6 +219,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper .handle("console", getConsole) .handle("consoleOrgs", listConsoleOrgs) .handle("consoleSwitch", switchConsole) + .handle("consoleUsage", consoleUsage) .handle("tool", tool) .handle("toolIDs", toolIDs) .handle("worktree", worktree) diff --git a/packages/redrob/test/server/httpapi-exercise/index.ts b/packages/redrob/test/server/httpapi-exercise/index.ts index 02c330ca89..aa6a1e25b4 100644 --- a/packages/redrob/test/server/httpapi-exercise/index.ts +++ b/packages/redrob/test/server/httpapi-exercise/index.ts @@ -619,6 +619,16 @@ const scenarios: Scenario[] = [ check(body === false, "background route should be a no-op without running subagents") }), http.protected.get("/experimental/resource", "experimental.resource.list").json(), + http.protected + .get("/experimental/console/usage", "experimental.console.usage") + .at((ctx) => ({ + path: `/experimental/console/usage?${new URLSearchParams({ tz: "Asia/Seoul" })}`, + headers: ctx.headers(), + })) + .json(200, (body) => { + // The exerciser has no Redrob key, so the route answers null rather than reaching the console. + check(body === null, "console usage should be null without a Redrob key") + }), http.protected .get("/experimental/usage", "experimental.usage.get") .at((ctx) => ({ diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index 5a88a0f4e3..51e105eefe 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -42,6 +42,8 @@ import type { ExperimentalConsoleListOrgsErrors, ExperimentalConsoleListOrgsResponses, ExperimentalConsoleSwitchOrgResponses, + ExperimentalConsoleUsageErrors, + ExperimentalConsoleUsageResponses, ExperimentalControlPlaneMoveSessionErrors, ExperimentalControlPlaneMoveSessionResponses, ExperimentalExtensionsCallErrors, @@ -945,6 +947,42 @@ export class Console extends HeyApiClient { }) } + /** + * Get Console balance and spend + * + * The Redrob workspace's balance and today's and this month's spend across every device, read from the Console with the Redrob provider's key. Null when there is no key or the Console does not answer. + */ + public usage( + parameters: { + directory?: string + workspace?: string + tz: string + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "query", key: "directory" }, + { in: "query", key: "workspace" }, + { in: "query", key: "tz" }, + ], + }, + ], + ) + return (options?.client ?? this.client).get< + ExperimentalConsoleUsageResponses, + ExperimentalConsoleUsageErrors, + ThrowOnError + >({ + url: "/experimental/console/usage", + ...options, + ...params, + }) + } + /** * Switch active Console org * diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index d2ad6e2f33..8ddf3e865d 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -2322,6 +2322,22 @@ export type EffectHttpApiErrorInternalServerError = { _tag: "InternalServerError" } +export type ConsoleUsagePeriod = { + since: string + spend: number + requestCount: number +} + +export type ConsoleUsageSummary = { + currency: string + balance: number + complimentary: boolean + plan?: string + tz: string + today: ConsoleUsagePeriod + month: ConsoleUsagePeriod +} + export type ToolListItem = { id: string description: string @@ -8510,6 +8526,36 @@ export type ExperimentalConsoleListOrgsResponses = { export type ExperimentalConsoleListOrgsResponse = ExperimentalConsoleListOrgsResponses[keyof ExperimentalConsoleListOrgsResponses] +export type ExperimentalConsoleUsageData = { + body?: never + path?: never + query: { + directory?: string + workspace?: string + tz: string + } + url: "/experimental/console/usage" +} + +export type ExperimentalConsoleUsageErrors = { + /** + * Bad request + */ + 400: BadRequestError +} + +export type ExperimentalConsoleUsageError = ExperimentalConsoleUsageErrors[keyof ExperimentalConsoleUsageErrors] + +export type ExperimentalConsoleUsageResponses = { + /** + * Console balance and spend, or null + */ + 200: ConsoleUsageSummary +} + +export type ExperimentalConsoleUsageResponse = + ExperimentalConsoleUsageResponses[keyof ExperimentalConsoleUsageResponses] + export type ExperimentalConsoleSwitchOrgData = { body?: { accountID: string diff --git a/packages/tui/src/component/dialog-status.tsx b/packages/tui/src/component/dialog-status.tsx index 0e4e383346..580a14c254 100644 --- a/packages/tui/src/component/dialog-status.tsx +++ b/packages/tui/src/component/dialog-status.tsx @@ -23,8 +23,9 @@ export function DialogStatus() { const sdk = useSDK() // The current session's running total is the footer's figure; the machine-wide periods come from - // the engine, which sums every session's step-finish parts. Console exposes no balance or spend - // route an API key may read, so the Console figure is a link rather than a number. + // the engine, which sums every session's step-finish parts. The Console block is the workspace's + // balance and spend across every device, which the engine reads from the Console with the Redrob + // provider's key (the key never reaches the TUI). Any failure leaves the plain billing link. const session = createMemo((): Usage.Total | undefined => { if (route.data.type !== "session") return const info = sync.session.get(route.data.sessionID) @@ -51,6 +52,21 @@ export function DialogStatus() { }) const width = createMemo(() => Math.max(...rows().map((row) => Bun.stringWidth(row.label)), 0)) const redrob = createMemo(() => sync.data.provider.some((item) => item.id === "redrob")) + // Read once when the dialog opens, never on a timer: the Console rate-limits this per workspace. + const [remote] = createResource(redrob, async () => { + const result = await sdk.client.experimental.console + .usage({ tz: Intl.DateTimeFormat().resolvedOptions().timeZone }) + .catch(() => undefined) + return result?.data ? Usage.workspace(result.data) : null + }) + const workspace = createMemo(() => (remote.error ? null : remote())) + const billing = `${CONSOLE_HOME_URL}/billing` + const labels = createMemo(() => [ + language.t("status.console.balance"), + language.t("status.console.today"), + language.t("status.console.month"), + ]) + const consoleWidth = createMemo(() => Math.max(...labels().map((label) => Bun.stringWidth(label)))) const enabledFormatters = createMemo(() => sync.data.formatter.filter((f) => f.enabled)) @@ -117,12 +133,57 @@ export function DialogStatus() { - + - {language.t("status.usage.console", { url: `${CONSOLE_HOME_URL}/billing` })} + {language.t("status.usage.console", { url: billing })} + + {(value) => ( + + {language.t("status.console")} + + + {labels()[0]} + + + + + {language.t("status.console.complimentary")} + + + + + {language.t("status.console.low", { balance: value().balance })} + + + + {value().balance} + + + + + + {labels()[1]} + + {language.t("status.console.spend", value().today)} + + + + {labels()[2]} + + {language.t("status.console.spend", value().month)} + + + {language.t("status.console.note")} + + + {language.t("status.console.billing", { url: billing })} + + + )} + 0} fallback={{language.t("status.mcp.empty")}} diff --git a/packages/tui/src/i18n/en.ts b/packages/tui/src/i18n/en.ts index 10657407c7..72a7dbed33 100644 --- a/packages/tui/src/i18n/en.ts +++ b/packages/tui/src/i18n/en.ts @@ -292,6 +292,15 @@ export const dict = { "status.usage.failed": "Could not load usage on this machine", "status.usage.note": "Today, this month and all time add up every session on this machine.", "status.usage.console": "Console balance: {{url}}", + "status.console": "Console", + "status.console.balance": "Balance", + "status.console.today": "Today", + "status.console.month": "This month", + "status.console.spend": "{{spend}} · {{count}} requests", + "status.console.complimentary": "Complimentary, nothing is charged", + "status.console.low": "{{balance}} · running low, top up below", + "status.console.note": "Workspace totals across every device.", + "status.console.billing": "Billing: {{url}}", "status.mcp.empty": "No MCP Servers", "status.mcp.count.one": "{{count}} MCP Server", "status.mcp.count.other": "{{count}} MCP Servers", diff --git a/packages/tui/src/i18n/ko.ts b/packages/tui/src/i18n/ko.ts index c37bc3bdaa..190a5f7078 100644 --- a/packages/tui/src/i18n/ko.ts +++ b/packages/tui/src/i18n/ko.ts @@ -278,6 +278,15 @@ export const dict: Record = { "status.usage.failed": "이 컴퓨터의 사용량을 불러오지 못했어요", "status.usage.note": "오늘, 이번 달, 전체는 이 컴퓨터의 모든 세션을 더한 값이에요.", "status.usage.console": "콘솔 잔액: {{url}}", + "status.console": "콘솔", + "status.console.balance": "잔액", + "status.console.today": "오늘", + "status.console.month": "이번 달", + "status.console.spend": "{{spend}} · 요청 {{count}}건", + "status.console.complimentary": "무료 제공 중이라 차감되지 않아요", + "status.console.low": "{{balance}} · 얼마 남지 않았어요, 아래에서 충전하세요", + "status.console.note": "모든 기기를 합친 워크스페이스 기준이에요.", + "status.console.billing": "결제: {{url}}", "status.mcp.empty": "MCP 서버 없음", "status.mcp.count.one": "MCP 서버 {{count}}개", "status.mcp.count.other": "MCP 서버 {{count}}개", diff --git a/packages/tui/src/util/usage.ts b/packages/tui/src/util/usage.ts index b859119364..80a4cb1ce9 100644 --- a/packages/tui/src/util/usage.ts +++ b/packages/tui/src/util/usage.ts @@ -39,4 +39,35 @@ export function format(total: Total) { } } +/** The console's `/usage/summary` reply, as the engine passes it through. */ +export type Console = { + currency: string + balance: number + complimentary: boolean + today: { spend: number; requestCount: number } + month: { spend: number; requestCount: number } +} + +/** Below this the balance is shown as a warning. */ +export const LOW_BALANCE = 1 + +/** The Console block's figures, formatted in the workspace's own currency. */ +export function workspace(value: Console) { + const currency = (() => { + try { + return new Intl.NumberFormat("en-US", { style: "currency", currency: value.currency }) + } catch { + return money + } + })() + const count = new Intl.NumberFormat("en-US") + return { + balance: currency.format(value.balance), + low: !value.complimentary && value.balance < LOW_BALANCE, + complimentary: value.complimentary, + today: { spend: currency.format(value.today.spend), count: count.format(value.today.requestCount) }, + month: { spend: currency.format(value.month.spend), count: count.format(value.month.requestCount) }, + } +} + export * as Usage from "./usage" diff --git a/packages/tui/test/util/usage.test.ts b/packages/tui/test/util/usage.test.ts index 4b39c99097..77c53420fe 100644 --- a/packages/tui/test/util/usage.test.ts +++ b/packages/tui/test/util/usage.test.ts @@ -27,4 +27,37 @@ describe("Usage", () => { expect(createTranslator("en").t("status.usage.line", value)).toBe("in 12 · out 3 · cache 0 · $0.00") expect(createTranslator("ko").t("status.usage.line", value)).toBe("입력 12 · 출력 3 · 캐시 0 · $0.00") }) + + const reply = { + currency: "USD", + balance: 20.368355, + complimentary: false, + today: { spend: 0, requestCount: 0 }, + month: { spend: 147.07, requestCount: 16764 }, + } + + test("workspace formats the Console balance and spend in the workspace's currency", () => { + expect(Usage.workspace(reply)).toEqual({ + balance: "$20.37", + low: false, + complimentary: false, + today: { spend: "$0.00", count: "0" }, + month: { spend: "$147.07", count: "16,764" }, + }) + expect(createTranslator("en").t("status.console.spend", Usage.workspace(reply).month)).toBe( + "$147.07 · 16,764 requests", + ) + expect(createTranslator("ko").t("status.console.spend", Usage.workspace(reply).month)).toBe( + "$147.07 · 요청 16,764건", + ) + }) + + test("a low balance warns, unless the workspace is complimentary", () => { + expect(Usage.workspace({ ...reply, balance: 0.4 }).low).toBe(true) + expect(Usage.workspace({ ...reply, balance: 0, complimentary: true }).low).toBe(false) + }) + + test("an unknown currency code still formats", () => { + expect(Usage.workspace({ ...reply, currency: "not-a-code" }).balance).toBe("$20.37") + }) })