diff --git a/packages/app/component-tests/agent-progress-chip.spec.ts b/packages/app/component-tests/agent-progress-chip.spec.ts new file mode 100644 index 00000000000..19d490e1215 --- /dev/null +++ b/packages/app/component-tests/agent-progress-chip.spec.ts @@ -0,0 +1,50 @@ +import { expect, story } from "../../storybook/playwright/story" + +story("opens the batch's rows from the chip and closes with Escape", async ({ mount, page }) => { + await mount("session-agent-progress-chip--nineteen") + const chip = page.locator('[data-slot="agent-progress-chip"]') + const panel = page.getByRole("group", { name: "Subagents" }) + + await expect(chip).toHaveAccessibleName("14 of 19 done · 1 failed · 1 needs you") + await expect(chip).toHaveAttribute("aria-expanded", "false") + + await chip.click() + await expect(chip).toHaveAttribute("aria-expanded", "true") + await expect(panel.getByRole("button", { name: "Review", exact: true })).toBeVisible() + await expect(panel.getByText("Provider rate limit")).toBeVisible() + await expect(panel.getByRole("button", { name: "Interrupt subagent" })).toHaveCount(3) + + const done = panel.getByRole("button", { name: "14 done", exact: true }) + await expect(done).toHaveAttribute("aria-expanded", "false") + await done.click() + await expect(done).toHaveAttribute("aria-expanded", "true") + await expect(panel.locator('[data-slot="agent-progress-row"][data-state="done"]')).toHaveCount(14) + + await page.keyboard.press("Escape") + await expect(chip).toHaveAttribute("aria-expanded", "false") + await expect(chip).toBeFocused() +}) + +story("counts follow the batch as subagents finish, fail and need input", async ({ mount, page }) => { + await mount("session-agent-progress-chip--live") + const chip = page.locator('[data-slot="agent-progress-chip"]') + + const run = (action: string, value?: number) => + page.evaluate((detail) => document.dispatchEvent(new CustomEvent("agent-chip-story", { detail })), { + action, + value, + }) + + await run("add", 3) + await expect(chip).toHaveAccessibleName("3 running") + await run("finish") + await expect(chip).toHaveAccessibleName("1 of 3 done") + await run("fail") + await expect(chip).toHaveAccessibleName("1 of 3 done · 1 failed") + await run("needs") + await expect(chip).toHaveAccessibleName("1 of 3 done · 1 failed · 1 needs you") + await run("finishAll") + await expect(chip).toHaveAccessibleName("2 of 3 done · 1 failed") + await run("clear") + await expect(chip).toHaveCount(0) +}) diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index cf19246710c..c85a733b916 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -222,7 +222,6 @@ export const dict = { "provider.connect.toast.connected.title": "{{provider}} connected", "provider.connect.toast.connected.description": "{{provider}} models are now available to use.", - "provider.disconnect.toast.disconnected.title": "{{provider}} disconnected", "provider.disconnect.toast.disconnected.description": "{{provider}} models are no longer available.", "provider.disconnect.toast.noCredentials.description": "No removable credentials found for {{provider}}", @@ -557,8 +556,20 @@ export const dict = { "session.activity.shells.one": "{{count}} shell", "session.activity.shells.other": "{{count}} shells", "session.activity.summary": "{{subagents}} · {{shells}}", - "session.activity.section.subagents": "Subagents", - "session.activity.section.shells": "Shells", + "session.agents.running": "{{count}} running", + "session.agents.progress": "{{done}} of {{total}} done", + "session.agents.allDone": "All {{count}} done", + "session.agents.done": "{{count}} done", + "session.agents.failed": "{{count}} failed", + "session.agents.needsYou.one": "{{count}} needs you", + "session.agents.needsYou.other": "{{count}} need you", + "session.agents.state.done": "Done", + "session.agents.state.failed": "Failed", + "session.agents.state.stopped": "Stopped", + "session.agents.state.starting": "Starting", + "session.agents.review": "Review", + "session.agents.stopAll": "Stop all", + "session.agents.panel": "Subagents", "session.question.progress": "{{current}} of {{total}} questions", "session.question.title": "Question", diff --git a/packages/app/src/session/agent-glyph/agent-glyph.css b/packages/app/src/session/agent-glyph/agent-glyph.css new file mode 100644 index 00000000000..9a72f88552a --- /dev/null +++ b/packages/app/src/session/agent-glyph/agent-glyph.css @@ -0,0 +1,20 @@ +[data-component="agent-glyph"] { + --agent-glyph-base: var(--v2-icon-icon-muted); + --agent-glyph-core: var(--v2-text-text-base); + --agent-glyph-orange: var(--v2-state-fg-warning); + --agent-glyph-red: var(--v2-state-fg-danger); + --agent-glyph-green: var(--v2-state-fg-success); + --agent-glyph-blue: var(--v2-state-fg-info); + + position: relative; + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + pointer-events: none; + + > canvas { + display: block; + flex: none; + } +} diff --git a/packages/app/src/session/agent-glyph/agent-glyph.tsx b/packages/app/src/session/agent-glyph/agent-glyph.tsx new file mode 100644 index 00000000000..b83e9364d7f --- /dev/null +++ b/packages/app/src/session/agent-glyph/agent-glyph.tsx @@ -0,0 +1,150 @@ +import { frameLoop, observeReducedMotion, prefersReducedMotion } from "@opencode/ui/motion" +import { createEffect, on, onCleanup, onMount } from "solid-js" +import { ActivityGyro, type AgentActivity } from "./gyro" +import { drawOrb, orbMargin, readPalette, type OrbPalette } from "./orb" +import "./agent-glyph.css" + +export type { AgentActivity } from "./gyro" + +// Live-tunable: how fast the glyphs' own time runs (the story and the motion panel set it). +export const agentGlyphTuning = { speed: 1 } + +let seeds = 0 + +// Theme changes repaint resting glyphs, which otherwise draw nothing new. +const repaints = new Set<() => void>() + +let themeObserver: MutationObserver | undefined + +function watchTheme(repaint: () => void) { + repaints.add(repaint) + themeObserver ??= new MutationObserver(() => repaints.forEach((item) => item())) + + if (repaints.size === 1) { + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ["class", "style", "data-theme"], + }) + } + + return () => { + repaints.delete(repaint) + + if (repaints.size === 0) themeObserver?.disconnect() + } +} + +// The agent activity glyph, ported from the iOS app's `AgentActivityGlyph`: a small LED orb whose dots draw one of +// Kit's designs per state, morphing with momentum from one to the next. It draws only while something moves or +// cools; Done and Failed flash, settle and stop; reduced motion shows each state's still pose. +export function AgentGlyph(props: { + activity: AgentActivity + // Where a new glyph starts before moving to `activity`, so a glyph mounted for a fresh change still shows it. + from?: AgentActivity + // The layout box; the glow spills past it. + size?: number + // Hidden behind something: hold the pose and draw nothing new. + paused?: boolean + class?: string +}) { + let canvas: HTMLCanvasElement | undefined + const size = () => props.size ?? 16 + const seed = (seeds++ % 97) / 13 + let gyro = new ActivityGyro(props.from ?? props.activity, prefersReducedMotion(), seed) + let palette: OrbPalette | undefined + let scale = 1 + let remove: (() => void) | undefined + + const paint = (dt: number) => { + if (!canvas) return + const ctx = canvas.getContext("2d") + + if (!ctx) return + palette ??= readPalette(canvas) + drawOrb(ctx, gyro.render(dt), size(), scale, palette) + } + + const job = (frame: number) => { + // Steps never longer than 1/30 s, so a dropped frame slows the orb rather than jumping it. + const dt = Math.min(1 / 30, frame) * agentGlyphTuning.speed + + for (let remaining = dt; remaining > 1e-6; remaining -= 1 / 30) gyro.step(Math.min(1 / 30, remaining)) + paint(dt) + + if (!gyro.isResting && !props.paused && canvas?.isConnected) return true + remove = undefined + + return false + } + + const wake = () => { + if (!remove && !props.paused) remove = frameLoop.add(job) + } + + const resize = () => { + if (!canvas) return + // CSS zoom enlarges the canvas too, so its backing store follows. + scale = (window.devicePixelRatio || 1) * canvas.currentCSSZoom + const side = size() + 2 * orbMargin(size()) + canvas.width = Math.round(side * scale) + canvas.height = Math.round(side * scale) + canvas.style.width = `${side}px` + canvas.style.height = `${side}px` + canvas.style.margin = `${-orbMargin(size())}px` + } + + onMount(() => { + if (gyro.op !== props.activity) gyro.set(props.activity) + resize() + paint(0) + wake() + onCleanup( + watchTheme(() => { + palette = undefined + paint(0) + }), + ) + onCleanup( + observeReducedMotion(() => { + gyro = new ActivityGyro(gyro.op, prefersReducedMotion(), seed) + paint(0) + wake() + }), + ) + }) + + createEffect( + on( + () => props.activity, + (activity) => { + if (gyro.op === activity) return + gyro.set(activity) + wake() + }, + { defer: true }, + ), + ) + createEffect( + on( + () => props.paused, + (paused) => { + if (!paused) wake() + }, + { defer: true }, + ), + ) + createEffect(on(size, resize, { defer: true })) + onCleanup(() => remove?.()) + + return ( + + ) +} diff --git a/packages/app/src/session/agent-glyph/gyro.test.ts b/packages/app/src/session/agent-glyph/gyro.test.ts new file mode 100644 index 00000000000..6adb16e0d79 --- /dev/null +++ b/packages/app/src/session/agent-glyph/gyro.test.ts @@ -0,0 +1,41 @@ +import { expect, test } from "bun:test" +import { ActivityGyro, CELLS, type AgentActivity } from "./gyro" + +const run = (gyro: ActivityGyro, seconds: number) => { + for (let t = 0; t < seconds; t += 1 / 60) { + gyro.step(1 / 60) + gyro.render(1 / 60) + + if (gyro.isResting) return t + } + + return Infinity +} + +test("the orb is a 7 × 7 grid masked to a disc", () => { + expect(CELLS.length).toBe(37) +}) + +test("running keeps moving; done and failed flash, settle and rest", () => { + const gyro = new ActivityGyro("thinking", false, 1) + expect(run(gyro, 3)).toBe(Infinity) + + for (const final of ["done", "failed"] satisfies AgentActivity[]) { + gyro.set("thinking") + run(gyro, 1) + gyro.set(final) + const field = gyro.render(0) + expect(field.dots.length).toBe(CELLS.length) + expect(run(gyro, 8)).toBeLessThan(8) + } +}) + +test("reduced motion holds a still pose for every state", () => { + const states: AgentActivity[] = ["idle", "startup", "thinking", "longWork", "tool", "streaming", "waiting", "handoff"] + + for (const state of states) { + const gyro = new ActivityGyro("thinking", true) + gyro.set(state) + expect(run(gyro, 4)).toBeLessThan(4) + } +}) diff --git a/packages/app/src/session/agent-glyph/gyro.ts b/packages/app/src/session/agent-glyph/gyro.ts new file mode 100644 index 00000000000..16dab40e91b --- /dev/null +++ b/packages/app/src/session/agent-glyph/gyro.ts @@ -0,0 +1,1257 @@ +// The agent activity glyph's engine, ported from the iOS app's `ActivityGyro.swift` (itself a port of +// `prototypes/activity-glyph/gyro.js`, Kit's set). Keep it in step with the Swift: the per-state designs live in +// one table, `designs`, written as close to the Swift as TypeScript allows so tweaks copy straight over. +// +// A glyph is up to four strokes on an LED dot sphere. A stroke is the set of dots where dot(p, n) ≈ s: a great +// circle (s = 0), a smaller circle, or, seen edge-on, a straight line. Windows along it make dashes; a pitch term +// tilts it into a spiral stripe. Every design is a pose of these same numbers, so a change of state morphs the dots +// rather than cross-fading them. + +export type AgentActivity = + | "idle" + | "startup" + | "thinking" + | "longWork" + | "tool" + | "streaming" + | "waiting" + | "handoff" + | "done" + | "failed" + +export type ActivityAccent = "orange" | "red" | "green" | "blue" + +export const ACCENTS: readonly ActivityAccent[] = ["orange", "red", "green", "blue"] + +export const isFinal = (activity: AgentActivity) => activity === "done" || activity === "failed" + +const TAU = Math.PI * 2 + +const HALF = Math.PI / 2 + +class GyroSpring { + constructor( + readonly response: number, + readonly damping: number, + ) {} + + static smooth(duration: number) { + return new GyroSpring(duration, 1) + } + + // Advances a damped oscillator by `t` from displacement `x0` and velocity `v0`, into `out`. + solve(x0: number, v0: number, t: number, out: [number, number]) { + const w = TAU / Math.max(1e-4, this.response) + const z = this.damping + + if (z < 1) { + const wd = w * Math.sqrt(1 - z * z) + const e = Math.exp(-z * w * t) + const c = Math.cos(wd * t) + const s = Math.sin(wd * t) + const b = (v0 + z * w * x0) / wd + out[0] = e * (x0 * c + b * s) + out[1] = e * (-z * w * (x0 * c + b * s) + (-x0 * wd * s + b * wd * c)) + + return out + } + + if (z === 1) { + const e = Math.exp(-w * t) + const b = v0 + w * x0 + out[0] = e * (x0 + b * t) + out[1] = e * (b - w * (x0 + b * t)) + + return out + } + + const r = Math.sqrt(z * z - 1) + const r1 = -w * (z - r) + const r2 = -w * (z + r) + const c1 = (v0 - r2 * x0) / (r1 - r2) + const c2 = x0 - c1 + const e1 = Math.exp(r1 * t) + const e2 = Math.exp(r2 * t) + out[0] = c1 * e1 + c2 * e2 + out[1] = c1 * r1 * e1 + c2 * r2 * e2 + + return out + } +} + +const scratch: [number, number] = [0, 0] + +const MOVE = GyroSpring.smooth(0.6) + +const SLOW = GyroSpring.smooth(1.2) + +const FAST = GyroSpring.smooth(0.3) + +const FADE = GyroSpring.smooth(0.45) + +const RM = GyroSpring.smooth(0.35) + +const W_MOVE = TAU / 0.6 + +const W_MIN = TAU / 1.6 + +const W_MAX = TAU / 0.22 + +// Below this angular speed (rad/s) a pose change may take the nearest equivalent, either way. +const MOVING = 0.6 + +const clamp = (x: number, a: number, b: number) => (x < a ? a : x > b ? b : x) + +const sstep = (a: number, b: number, x: number) => { + const t = clamp((x - a) / (b - a), 0, 1) + + return t * t * (3 - 2 * t) +} + +const wrap = (a: number) => a - TAU * Math.floor((a + Math.PI) / TAU) + +const gauss = (x: number, s: number) => Math.exp(-(x * x) / (2 * s * s)) + +const sign = (x: number) => (x > 0 ? 1 : x < 0 ? -1 : 0) + +// Latitude as an angle: S(φ) falls from 1.1 to −1.1 over each turn, so a stroke rolling past one pole comes back +// from the other. +const S = (phi: number) => 1.1 - 2.2 * (phi / TAU - Math.floor(phi / TAU)) + +const Sinv = (s: number) => (TAU * (1.1 - s)) / 2.2 + +// Strokes fade out towards the wrap at |s| = 1.1 over their own width and pitch. +const visS = (s: number, w: number, pitch: number) => + sstep(1.1, 1.1 - Math.min(0.6, 0.06 + 2.2 * w + 0.5 * pitch), Math.abs(s)) + +const ringS = (rho: number) => Math.sqrt(1 - rho * rho) + +// The equivalent of x (mod period) nearest the angle's current value. +const near = (ang: GyroAngle, x: number, period = TAU) => x + period * Math.round((ang.value - x) / period) + +type Vec = [number, number, number] + +const dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + +// n, u, v for angles (θ, e, a, r): n = Rz(r)·Rx(a)·(cos e cos θ, sin e, cos e sin θ); u, v span its circle. +function frame(th: number, e: number, a: number, r: number) { + const ce = Math.cos(e) + const se = Math.sin(e) + const ct = Math.cos(th) + const st = Math.sin(th) + const ca = Math.cos(a) + const sa = Math.sin(a) + const cr = Math.cos(r) + const sr = Math.sin(r) + + const rot = (x: number, y: number, z: number): Vec => { + const y1 = y * ca - z * sa + const z1 = y * sa + z * ca + + return [x * cr - y1 * sr, x * sr + y1 * cr, z1] + } + + return { n: rot(ce * ct, se, ce * st), u: rot(-st, 0, ct), v: rot(-se * ct, ce, -se * st) } +} + +class GyroValue { + value: number + target: number + velocity = 0 + + constructor( + value = 0, + public config = MOVE, + readonly precision = 0.005, + ) { + this.value = value + this.target = value + } + + to(target: number, config?: GyroSpring, immediate = false) { + if (config) this.config = config + this.target = target + + if (!immediate) return + this.value = target + this.velocity = 0 + } + + set(value: number) { + this.value = value + this.target = value + this.velocity = 0 + } + + get settled() { + return Math.abs(this.value - this.target) < this.precision && Math.abs(this.velocity) < this.precision * 10 + } + + // False once settled. + step(dt: number) { + if (this.settled) { + this.value = this.target + this.velocity = 0 + + return false + } + + const [x, v] = this.config.solve(this.value - this.target, this.velocity, dt, scratch) + this.value = this.target + x + this.velocity = v + + return true + } + + clone() { + const next = new GyroValue(this.value, this.config, this.precision) + next.target = this.target + next.velocity = this.velocity + + return next + } +} + +// An unwrapped angle with momentum: it either spins (its speed a spring) or holds a pose. Holding a new pose while +// moving picks the next equivalent angle ahead, far enough that a critically damped spring decelerates into it. +class GyroAngle { + value: number + vel = 0 + mode: "hold" | "spin" = "hold" + anchor: number + cfg = MOVE + speed = new GyroValue(0, MOVE, 1e-3) + last = { angle: 0, period: TAU } + + constructor(value = 0) { + this.value = value + this.anchor = value + this.last = { angle: value, period: TAU } + } + + set(v: number) { + this.value = v + this.anchor = v + this.vel = 0 + this.mode = "hold" + this.speed.set(0) + this.last = { angle: v, period: TAU } + } + + copy(o: GyroAngle) { + this.value = o.value + this.vel = o.vel + this.mode = o.mode + this.anchor = o.anchor + this.cfg = o.cfg + this.speed = o.speed.clone() + this.last = { ...o.last } + } + + // Spin at w rad/s. A spin never reverses a visible motion: against the current direction it takes w's magnitude. + spin(input: number, cfg = MOVE, immediate = false) { + const w = Math.abs(this.vel) > MOVING && input !== 0 && sign(input) !== sign(this.vel) ? -input : input + + if (this.mode !== "spin") { + this.speed.set(this.vel) + this.mode = "spin" + } + + this.speed.to(w, cfg) + + if (!immediate) return + this.speed.set(w) + this.vel = w + } + + // Come to rest on `angle` or any angle `period` away from it: moving, the first equivalent ahead by at least the + // spring's natural stopping distance, approached by a critically damped spring that never overshoots. + hold(angle: number, period = TAU, immediate = false, cfg?: GyroSpring, decel = true) { + if (this.mode === "spin") this.vel = this.speed.value + this.mode = "hold" + this.last = { angle, period } + const v = this.vel + + if (immediate) { + this.anchor = angle + period * Math.round((this.value - angle) / period) + this.value = this.anchor + this.vel = 0 + + return + } + + if (Math.abs(v) < MOVING) { + this.anchor = angle + period * Math.round((this.value - angle) / period) + this.cfg = cfg ?? MOVE + + return + } + + const dir = sign(v) + const lead = Math.abs(v) / W_MOVE + + const k = + dir > 0 ? Math.ceil((this.value + lead - angle) / period) : Math.floor((this.value - lead - angle) / period) + + this.anchor = angle + k * period + const d = Math.abs(this.anchor - this.value) + const base = cfg ? TAU / cfg.response : W_MOVE + const w = Math.max(decel ? clamp((1.5 * Math.abs(v)) / d, W_MIN, W_MAX) : base, (1.05 * Math.abs(v)) / d) + this.cfg = new GyroSpring(TAU / w, 1) + } + + // Start spinning from `value` already moving at `vel`. + launch(value: number, vel: number) { + this.value = value + this.vel = vel + this.mode = "spin" + this.speed.set(vel) + } + + // Track a moving target as a spring. + follow(target: number, cfg = MOVE) { + if (this.mode === "spin") this.vel = this.speed.value + this.mode = "hold" + this.anchor = target + this.cfg = cfg + } + + get moving() { + if (this.mode === "spin") return Math.abs(this.speed.value) > 1e-3 || !this.speed.settled + + return Math.abs(this.value - this.anchor) > 1e-4 || Math.abs(this.vel) > 1e-3 + } + + step(dt: number) { + if (this.mode === "spin") { + const v0 = this.speed.value + this.speed.step(dt) + this.value += 0.5 * (v0 + this.speed.value) * dt + this.vel = this.speed.value + + return + } + + const [x, v] = this.cfg.solve(this.value - this.anchor, this.vel, dt, scratch) + this.value = this.anchor + x + this.vel = v + + if (Math.abs(x) < 1e-4 && Math.abs(v) < 1e-3) { + this.value = this.anchor + this.vel = 0 + } + } +} + +const ANGLE_KEYS = ["theta", "e", "a", "r", "phi", "psi", "psiD", "psiG", "psiN", "rho"] as const + +const SPRING_KEYS = ["w", "k", "pitch", "arc", "floor", "tail", "dash", "glint", "notch", "clip", "cone"] as const + +type AngleKey = (typeof ANGLE_KEYS)[number] + +type SpringKey = (typeof SPRING_KEYS)[number] + +const NEUTRAL: Partial> = { + w: 0.2, + pitch: 0, + arc: 3.6, + floor: 0, + tail: 0, + dash: 0, + glint: 0, + notch: 0, + clip: 2, + cone: 0, +} + +class GyroStroke { + // SAFETY: built from every key of ANGLE_KEYS. + angle = Object.fromEntries(ANGLE_KEYS.map((key) => [key, new GyroAngle()])) as Record + // SAFETY: built from every key of SPRING_KEYS. + spring = Object.fromEntries(SPRING_KEYS.map((key) => [key, new GyroValue(NEUTRAL[key] ?? 0, MOVE, 0.002)])) as Record< + SpringKey, + GyroValue + > + m = 11 + pitch0 = 0 + + constructor() { + this.angle.a.set(0.45) + this.angle.phi.set(Sinv(0)) + } + + copyPose(o: GyroStroke) { + for (const key of ANGLE_KEYS) this.angle[key].copy(o.angle[key]) + + for (const key of SPRING_KEYS) { + if (key === "k") continue + this.spring[key].value = o.spring[key].value + this.spring[key].velocity = o.spring[key].velocity + this.spring[key].target = o.spring[key].target + } + + this.m = o.m + this.pitch0 = o.pitch0 + } + + get s() { + return S(this.angle.phi.value) + } + + get visible() { + return this.spring.k.value > 0.02 + } +} + +// A target for one of a stroke's angles. A spin holds `still` under reduced motion. +type GyroPose = + | { type: "hold"; value: number; period?: number; cfg?: GyroSpring } + | { type: "spin"; speed: number; still?: number; cfg?: GyroSpring } + +const hold = (value: number, period?: number, cfg?: GyroSpring): GyroPose => ({ type: "hold", value, period, cfg }) + +const spin = (speed: number, still?: number, cfg?: GyroSpring): GyroPose => ({ type: "spin", speed, still, cfg }) + +// One stroke's retarget, like the prototype's spec objects. +type GyroSpec = { + angles?: Partial> + // Latitude: a hold keeps it there; a spin rolls it. + s?: GyroPose + springs?: Partial> + k?: number + m?: number + pitch0?: number + cfg?: GyroSpring +} + +// `{ ...base, ...next }`, with `latitude` as a held `s`. +const spec = (base: GyroSpec, next: GyroSpec & { latitude?: number } = {}): GyroSpec => ({ + ...base, + ...next, + angles: { ...base.angles, ...next.angles }, + springs: { ...base.springs, ...next.springs }, + s: next.s ?? (next.latitude === undefined ? base.s : hold(Sinv(next.latitude))), +}) + +const FACE: GyroSpec = { angles: { theta: hold(HALF), e: hold(0), a: hold(0), r: hold(0) } } + +const LEVEL: GyroSpec = { angles: { theta: hold(HALF), e: hold(HALF), a: hold(0), r: hold(0) } } + +const MERIDIAN = (w = TAU / 1.8): GyroSpec => ({ + angles: { theta: spin(w), e: hold(0), a: hold(0.45), r: hold(0) }, + s: hold(Sinv(0)), +}) + +// A phosphor's time constants (seconds): light rises toward the field over `attack` and falls behind it over +// `decay`; after the state, the afterglow itself eases off over `release`. +type GyroAfterglow = { attack: number; decay: number; release?: number } + +// A flash on arrival: each dot is driven hot for a short window, then cools over `decay`. +type GyroFlash = { amount: number; decay: number; spread: "all" | "ripple" | "sweep"; bloom: number } + +const FLASH_START = 0.2 + +const FLASH_WINDOW = 0.1 + +const FLASH_ATTACK = 0.03 + +type GyroPattern = "condense" | "shimmer" + +type GyroDesign = { + id: string + enter: (g: ActivityGyro) => void + tick?: (g: ActivityGyro, age: number) => void + // Where a tick settles under reduced motion. + stillAge?: number + afterglow?: GyroAfterglow + pattern?: GyroPattern + flash?: GyroFlash +} + +const GLOBAL_KEYS = ["body", "flash", "glow", "ring", "comet", "orange", "red", "green", "blue"] as const + +type GlobalKey = (typeof GLOBAL_KEYS)[number] + +// Kit's set, one design per state. +const designs: Record = { + // Shimmer: no band, a sparse slow glitter across a dimmed orb; Done cools into it slowly. + idle: { + id: "shimmer", + enter: (g) => { + g.stroke(0, { angles: { theta: spin(0, 0.55) }, k: 0 }) + g.off(1, 2, 3) + g.global({ body: 0.68, glow: 0.14, ring: 0 }) + }, + afterglow: { attack: 0.15, decay: 0.5 }, + pattern: "shimmer", + }, + // Condense: dots sparkle in at random and gather onto Thinking's band, which turns underneath at Thinking's speed. + startup: { + id: "condense", + enter: (g) => { + g.stroke(0, spec(MERIDIAN(), { k: 0.02 })) + g.off(1, 2, 3) + g.global({ body: 0.8, glow: 0.5, ring: 0 }) + }, + tick: (g, age) => g.strokes[0]!.spring.k.to(0.95 * sstep(0.2, 1.1, age), GyroSpring.smooth(0.25)), + stillAge: 1.4, + afterglow: { attack: 0.05, decay: 0.35 }, + pattern: "condense", + }, + // Comet: the band trails phosphor afterglow behind its motion. + thinking: { + id: "comet", + enter: (g) => { + g.stroke(0, spec(MERIDIAN(), { k: 0.95 })) + g.off(1, 2, 3) + g.global({ body: 1, glow: 0.5, ring: 0.1, comet: 1 }) + }, + }, + // Spiral churn: a three-stripe spiral turns on a tilted axis, its pitch slowly breathing. + longWork: { + id: "helix", + enter: (g) => { + for (let i = 0; i < 3; i++) { + g.stroke(i, { + angles: { theta: hold(HALF), e: hold(HALF), a: hold(0.4), r: hold(0.2) }, + springs: { w: 0.13, pitch: 0.5 }, + k: 0.8, + }) + } + + g.stroke(0, { s: spin(TAU / 3, Sinv(0.2)) }) + g.off(3) + g.global({ body: 0.9, glow: 0.55, ring: 0 }) + }, + tick: (g, age) => { + train(g, 3, TAU / 3) + + for (let i = 0; i < 3; i++) g.strokes[i]!.spring.pitch.to(0.5 + 0.25 * Math.sin(age * 0.7), SLOW) + }, + stillAge: 2, + }, + // Spin kick: a turning band (tool calls would kick it faster). + tool: { + id: "kick", + enter: (g) => { + g.stroke(0, spec(MERIDIAN(), { k: 0.95 })) + g.off(1, 2, 3) + g.global({ body: 1, glow: 0.55, ring: 0.2 }) + }, + }, + // Spiral: tilted stripes rise out of the lower pole and into the upper. + streaming: { + id: "spiral", + enter: (g) => { + for (let i = 0; i < 3; i++) g.stroke(i, spec(LEVEL, { springs: { w: 0.12, pitch: 0.55 }, k: 0.85 })) + g.stroke(0, { s: spin(TAU / 2.2, Sinv(0.3)) }) + g.off(3) + g.global({ body: 0.85, glow: 0.45, ring: 0 }) + }, + tick: (g) => train(g, 3, TAU / 3), + }, + // Rim chase: the band turns face-on and breaks into three bright clusters that chase slowly round the rim. + waiting: { + id: "chase", + enter: (g) => { + // A turning band's front arc moves left for θ increasing; the clusters peel off at the top going the same way, + // at the band's speed, then ease down to the chase. + const b = g.strokes[0]! + const w = b.angle.theta.mode === "spin" ? b.angle.theta.speed.value : b.angle.theta.vel + const dir = Math.abs(w) > MOVING ? sign(w) : -1 + + if (!g.immediate && !g.reduceMotion && b.visible && b.spring.dash.value < 0.05 && Math.abs(w) > MOVING) { + b.angle.psiD.launch(-HALF, dir * Math.min(Math.abs(w), TAU / 0.8)) + } + + g.stroke( + 0, + spec(FACE, { + angles: { psiD: spin((dir * TAU) / 4.5, -HALF, SLOW) }, + latitude: ringS(0.8), + springs: { w: 0.24, dash: 0.8 }, + k: 1, + m: 3, + }), + ) + g.off(1, 2, 3) + g.global({ body: 0.9, glow: 0.45, ring: 0 }) + + if (!g.immediate && !g.reduceMotion) chaseGate(g) + }, + tick: (g) => { + if (!g.reduceMotion) chaseGate(g) + }, + }, + // Slide right: upright bands slide off to the right, one after another. + handoff: { + id: "slide", + enter: (g) => { + const upright = { theta: hold(Math.PI), e: hold(0), a: hold(0), r: hold(0.16) } + g.stroke(0, { angles: upright, s: spin(TAU / 1.15, Sinv(0.2)), springs: { w: 0.17 }, k: 0.9 }) + g.stroke(1, { angles: upright, springs: { w: 0.17 }, k: 0.9 }) + g.off(2, 3) + g.global({ body: 0.9, glow: 0.45, ring: 0 }) + }, + tick: (g) => train(g, 2, Math.PI), + }, + // Ring: the band sweeps on, face-on, into a green ring; a flash sweeps round it. + done: { + id: "ring", + enter: (g) => { + g.stroke(0, spec(FACE, { latitude: 0.5, springs: { w: 0.2 }, k: 1 })) + g.off(1, 2, 3) + g.global({ body: 0.75, glow: 0.6, ring: 0 }) + }, + flash: { amount: 0.8, decay: 0.9, spread: "sweep", bloom: 0.1 }, + }, + // ×: the band levels, splits and rolls into a red ×; a soft ember flash fades slowly. + failed: { + id: "cross", + enter: (g) => { + g.stroke( + 0, + spec(LEVEL, { angles: { r: hold(Math.PI / 4, Math.PI) }, latitude: 0, springs: { w: 0.11 }, k: 0.95 }), + ) + g.stroke( + 1, + spec(LEVEL, { angles: { r: hold(-Math.PI / 4, Math.PI) }, latitude: 0, springs: { w: 0.11 }, k: 0.95 }), + ) + g.off(2, 3) + g.global({ body: 0.8, glow: 0.45, ring: 0 }) + }, + flash: { amount: 0.6, decay: 1.2, spread: "all", bloom: 0.06 }, + }, +} + +const stateAccent: Partial> = { + waiting: "orange", + failed: "red", + done: "green", + handoff: "blue", +} + +// Rim chase entering from a band: the band lies down onto the rim, then draws in to its ring and breaks into +// clusters. Nothing sweeps through the centre. +function chaseGate(g: ActivityGyro) { + const b = g.strokes[0]! + + // Only ever grows, so a band that must turn the long way round doesn't push the ring out and back. + const now = sstep( + 0.55, + 0.97, + Math.cos(wrap(b.angle.theta.value - HALF)) * Math.cos(b.angle.a.value) * Math.cos(b.angle.e.value), + ) + + const facing = g.age === 0 ? now : Math.max(g.chaseFacing ?? 0, now) + g.chaseFacing = facing + + if (g.age === 0 || g.chaseRolls === undefined) g.chaseRolls = Math.abs(b.angle.phi.vel) > MOVING + + if (g.chaseRolls) { + if (b.angle.phi.mode !== "hold" || g.age === 0) b.angle.phi.hold(Sinv(ringS(0.8)), TAU) + } + + if (!g.chaseRolls) { + if (g.age === 0) g.chaseS0 = clamp(b.s, -1, 1) + const s0 = g.chaseS0 ?? 0 + b.angle.phi.follow(near(b.angle.phi, Sinv(s0 + (ringS(0.8) - s0) * facing)), FAST) + } + + b.spring.dash.to(0.8 * sstep(0.4, 1, facing), FAST) +} + +// Strokes 1…n−1 follow stroke 0's latitude, each `offset` further on. Trains only run forward. +function train(g: ActivityGyro, n: number, offset: number, cfg = FAST) { + const lead = g.strokes[0]!.angle.phi.value + const w = TAU / cfg.response + + for (let i = 1; i < n; i++) { + const b = g.strokes[i]!.angle.phi + const target = near(b, lead + i * offset) + b.follow(Math.max(target, b.value + Math.max(0, b.vel) / w), cfg) + } +} + +// One dot of the orb: its place in the grid, the sphere normal under it, a top-left key light, and a size that +// shrinks towards the limb. +export type GyroCell = { + column: number + row: number + normal: Vec + shade: number + size: number +} + +function orb(n: number) { + const half = (n - 1) / 2 + const R = n / 2 + 0.1 + const L: Vec = [-0.42, -0.52, 0.74] + const ln = Math.hypot(...L) + + return Array.from({ length: n * n }, (_, index) => ({ column: index % n, row: Math.floor(index / n) })).flatMap( + ({ column, row }): GyroCell[] => { + const x = column - half + const y = row - half + + if (Math.hypot(x, y) > n / 2) return [] + const nx = x / R + const ny = y / R + const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny)) + const shade = Math.max(0, (nx * L[0] + ny * L[1] + nz * L[2]) / ln) + + return [{ column, row, normal: [nx, ny, nz], shade, size: 0.7 + 0.3 * nz }] + }, + ) +} + +export const CELLS = orb(7) + +// What one frame draws: per dot its light, freshness, accent and size, and the orb's glow and accent weights. +export type GyroDot = { light: number; fresh: number; accent: number; size: number } + +export type GyroField = { + dots: GyroDot[] + glow: number + weights: Record + // How hot the orb's hottest dot is (0…1): the renderer warms its neutral colour toward the flash's. + heat: number +} + +const hash = (i: number) => { + const x = Math.sin(i * 12.9898 + 4.1) * 43758.5453 + + return x - Math.floor(x) +} + +const cellHash = (cell: GyroCell) => hash(cell.row * 7 + cell.column) + +// 0.22 · s¹⁰ of a sine at 0.14–0.24 Hz with its own phase per dot. +const shimmer = (cell: GyroCell, t: number) => { + const i = cell.row * 7 + cell.column + const f = 0.14 + 0.1 * hash(i + 17) + const s = 0.5 + 0.5 * Math.sin(TAU * (t * f + hash(i))) + + return 0.22 * Math.pow(s, 10) +} + +const PATTERN_FADE_IN = 0.06 + +const PATTERN_FADE_OUT = 0.2 + +const patternLight = (pattern: GyroPattern, cell: GyroCell, coverage: number, t: number) => { + if (pattern === "shimmer") return shimmer(cell, t) * sstep(0, 0.6, t) + const phase = t * 3 + cellHash(cell) + const sparkle = gauss(phase - Math.floor(phase) - 0.5, 0.06) + + return sparkle * (1 - sstep(0.1, 1.0, t) * (1 - coverage)) +} + +// The still pose under reduced motion. +const patternStill = (pattern: GyroPattern, cell: GyroCell) => + pattern === "shimmer" ? shimmer(cell, 2.4) : cellHash(cell) > 0.72 ? 0.8 : 0 + +const flashDelay = (flash: GyroFlash, cell: GyroCell) => { + if (flash.spread === "all") return 0 + + if (flash.spread === "ripple") return Math.min(1, Math.hypot(cell.normal[0], cell.normal[1])) * 0.24 + const a = Math.atan2(cell.normal[1], cell.normal[0]) + HALF + + return ((a - TAU * Math.floor(a / TAU)) / TAU) * 0.36 +} + +// How long each spread takes to reach its last dot. +const FLASH_SPREAD: Record = { all: 0, ripple: 0.24, sweep: 0.36 } + +const flashDriven = (flash: GyroFlash) => FLASH_START + FLASH_WINDOW + FLASH_SPREAD[flash.spread] + +// Per-dot afterglow and flash heat over the engine's field. Light follows the field through a phosphor while a +// state has an afterglow; a flash is energy in each dot that rises fast and cools over its decay, overshooting the +// light, warming the colour toward the hot one and blooming the dot. Under reduced motion there is neither. +class GyroPhosphor { + light: number[] = [] + heat: number[] = [] + weights: Record | undefined + attack = 0 + decay = 0 + release = 0.35 + patterns = new Map() + flash: GyroFlash | undefined + flashPending = false + design: GyroDesign | undefined + reduceMotion = false + age = 0 + isSettled = true + + enter(design: GyroDesign, reduceMotion: boolean, immediate: boolean) { + this.design = design + this.reduceMotion = reduceMotion + this.age = 0 + this.isSettled = false + + if (design.afterglow) { + this.attack = design.afterglow.attack + this.decay = design.afterglow.decay + this.release = design.afterglow.release ?? 0.35 + } + + if (design.pattern) { + const current = this.patterns.get(design.pattern) + const amount = immediate || reduceMotion ? 1 : (current?.amount ?? 0) + this.patterns.set(design.pattern, { amount, age: amount < 1e-3 ? 0 : (current?.age ?? 0) }) + } + + if (design.flash) this.flash = design.flash + // First sight is the settled state, never an entrance. + this.flashPending = !!design.flash && !immediate && !reduceMotion + + if (!immediate) return + this.light = [] + this.heat = [] + this.weights = undefined + + for (const key of [...this.patterns.keys()]) if (key !== design.pattern) this.patterns.delete(key) + } + + apply(field: GyroField, dt: number) { + const design = this.design + + if (!design) return + this.age += dt + const rm = this.reduceMotion + + if (!design.afterglow) { + const k = 1 - Math.exp(-dt / this.release) + this.attack -= this.attack * k + this.decay -= this.decay * k + + if (this.decay < 0.005) { + this.attack = 0 + this.decay = 0 + } + } + + for (const [pattern, state] of [...this.patterns]) { + const on = pattern === design.pattern + const target = on ? 1 : 0 + + const amount = rm + ? target + : state.amount + (target - state.amount) * (1 - Math.exp(-dt / (on ? PATTERN_FADE_IN : PATTERN_FADE_OUT))) + + if (!on && amount < 0.002) { + this.patterns.delete(pattern) + continue + } + + this.patterns.set(pattern, { amount, age: state.age + dt }) + } + + if (this.light.length !== field.dots.length) { + this.light = field.dots.map((item) => item.light) + this.heat = field.dots.map(() => 0) + } + + // The accent weights fall over the afterglow's decay, never faster than the light. + const fall = rm || this.decay < 1e-3 ? 1 : 1 - Math.exp(-dt / this.decay) + const held = this.weights ?? field.weights + const weights = { ...held } + + const lagWeights = ACCENTS.reduce((lag, accent) => { + const target = field.weights[accent] + const next = target >= held[accent] ? target : held[accent] + (target - held[accent]) * fall + weights[accent] = next + + return Math.max(lag, next - target) + }, 0) + + this.weights = weights + field.weights = weights + + const tint = clamp( + ACCENTS.reduce((sum, accent) => sum + Math.max(0, weights[accent]), 0), + 0, + 1, + ) + + const maxFresh = field.dots.reduce((max, item) => Math.max(max, item.fresh), 1e-3) + const flashing = this.flashPending && !rm ? design.flash : undefined + const inFlashState = !!design.flash + let lag = lagWeights + let hottest = 0 + + CELLS.forEach((cell, i) => { + const item = field.dots[i] + + if (!item) return + const coverage = item.fresh / maxFresh + let P = item.light + let fresh = item.fresh + + for (const [pattern, state] of this.patterns) { + if (state.amount <= 1e-3) continue + const p = state.amount * (rm ? patternStill(pattern, cell) : patternLight(pattern, cell, coverage, state.age)) + P = Math.min(1.2, P + 0.95 * p) + fresh = Math.max(fresh, 0.8 * p) + } + + const v = this.light[i]! + const tau = rm ? 0 : P > v ? this.attack : this.decay + const next = tau < 1e-3 ? P : v + (P - v) * (1 - Math.exp(-dt / tau)) + this.light[i] = next + lag = Math.max(lag, Math.abs(next - P)) + + const x = flashing ? this.age - FLASH_START - flashDelay(flashing, cell) : -1 + const drive = flashing && x >= 0 && x < FLASH_WINDOW ? 0.15 + 0.85 * coverage : 0 + const h = this.heat[i]! + const ht = drive > h ? FLASH_ATTACK : (this.flash?.decay ?? 1) + const hot = rm ? 0 : h + (drive - h) * (1 - Math.exp(-dt / ht)) + this.heat[i] = hot < 1e-4 && drive === 0 ? 0 : hot + const a = (this.flash?.amount ?? 0) * this.heat[i]! + hottest = Math.max(hottest, a) + item.light = next + 0.7 * a + // Settled, a flash state's dots keep a quieter core, so the colour reads full rather than pale. + item.fresh = inFlashState ? Math.max(fresh * (0.3 + 0.7 * a), a) : Math.max(fresh, a) + // The accent mix follows the afterglowed light, so colour cools with it. + item.accent = tint * sstep(0.3, 0.65, next) * (1 - a) + item.size *= 1 + (this.flash?.bloom ?? 0) * this.heat[i]! + }) + + if (flashing && this.age >= flashDriven(flashing)) this.flashPending = false + field.heat = hottest + field.glow += 0.9 * hottest + this.isSettled = rm || (!this.flashPending && hottest < 0.005 && lag < 0.002 && this.patterns.size === 0) + } +} + +export class ActivityGyro { + op: AgentActivity + design: GyroDesign + readonly strokes = [0, 1, 2, 3].map(() => new GyroStroke()) + // SAFETY: built from every key of GLOBAL_KEYS. + readonly globals = Object.fromEntries(GLOBAL_KEYS.map((key) => [key, new GyroValue(0, FADE, 0.002)])) as Record< + GlobalKey, + GyroValue + > + immediate = false + snap = false + age = 0 + t: number + // Nothing will change until the next `set`. + isStatic = false + chaseFacing: number | undefined + chaseRolls: boolean | undefined + chaseS0: number | undefined + readonly phosphor = new GyroPhosphor() + + constructor( + op: AgentActivity = "idle", + readonly reduceMotion = false, + seed = 0, + ) { + this.op = op + this.design = designs[op] + this.t = seed + this.strokes.forEach((b, i) => b.angle.theta.set(seed + i * 1.1)) + this.globals.flash.config = GyroSpring.smooth(0.32) + this.set(op, true) + } + + set(op: AgentActivity, immediate = false) { + this.op = op + this.design = designs[op] + this.age = 0 + this.immediate = immediate + const accents = { orange: 0, red: 0, green: 0, blue: 0 } + const accent = stateAccent[op] + + if (accent) accents[accent] = 1 + this.global(accents) + // Afterglow decays rather than switching off: it shrinks with the band's speed as it goes. + this.global({ comet: 0 }, SLOW) + + for (const b of this.strokes) { + for (const key of SPRING_KEYS) { + const value = NEUTRAL[key] + + if (value !== undefined) b.spring[key].to(value, this.reduceMotion ? RM : MOVE, immediate) + } + } + + this.design.enter(this) + this.phosphor.enter(this.design, this.reduceMotion, immediate) + + if (this.reduceMotion || immediate) this.design.tick?.(this, this.reduceMotion ? (this.design.stillAge ?? 0.5) : 0) + + if (immediate) { + for (const b of this.strokes) { + for (const key of ANGLE_KEYS) { + const angle = b.angle[key] + + if (angle.mode !== "hold") continue + angle.value = angle.anchor + angle.vel = 0 + } + + for (const key of SPRING_KEYS) b.spring[key].set(b.spring[key].target) + } + } + + this.immediate = false + this.isStatic = false + } + + // Retargets one stroke. A hidden stroke about to show starts as a copy of stroke 0, so new strokes split off the + // band rather than fading in. + stroke(i: number, next: GyroSpec) { + const b = this.strokes[i]! + + if (!b.visible && (next.k ?? 0) > 0 && !this.immediate) { + const lead = this.strokes[0]! + + if (i > 0 && lead.visible) { + b.copyPose(lead) + b.spring.k.set(0) + } + + if (i === 0 || !lead.visible) this.snap = true + } + + const cfg = this.reduceMotion ? RM : (next.cfg ?? MOVE) + const now = this.immediate || this.snap + + if (next.m !== undefined) b.m = next.m + + if (next.pitch0 !== undefined) b.pitch0 = next.pitch0 + + for (const key of ANGLE_KEYS) { + const pose = next.angles?.[key] + + if (pose) this.angle(b.angle[key], pose, cfg, now, i) + } + + if (next.s) { + // A plain hold keeps the latitude with the stroke's spring; anything else rolls it. + if (next.s.type === "hold" && !next.s.cfg) b.angle.phi.hold(next.s.value, TAU, now, cfg) + + if (next.s.type !== "hold" || next.s.cfg) this.angle(b.angle.phi, next.s, cfg, now, i) + } + + for (const key of SPRING_KEYS) { + const value = next.springs?.[key] + + if (value !== undefined) b.spring[key].to(value, cfg, now) + } + + if (next.k !== undefined) b.spring.k.to(next.k, this.reduceMotion ? RM : FADE, this.immediate) + this.snap = false + } + + angle(ang: GyroAngle, pose: GyroPose, cfg: GyroSpring, now: boolean, i: number) { + if (pose.type === "spin") { + if (this.reduceMotion) return ang.hold(pose.still ?? 0.55 + i * 0.9, TAU, now, RM) + + return ang.spin(pose.speed, pose.cfg ?? cfg, now) + } + + ang.hold(pose.value, pose.period ?? TAU, now, pose.cfg ?? (this.reduceMotion ? RM : undefined)) + } + + // Fades strokes out while drawing them toward stroke 0, so they merge rather than vanish in place. + off(...indices: number[]) { + const lead = this.strokes[0]! + + for (const i of indices) { + const b = this.strokes[i]! + b.spring.k.to(0, this.reduceMotion ? RM : FADE, this.immediate) + + if (!b.visible || this.immediate) continue + + for (const key of ["e", "a", "r"] as const) b.angle[key].hold(lead.angle[key].anchor, TAU) + + if (lead.angle.theta.mode === "spin") b.angle.theta.spin(lead.angle.theta.speed.target) + + if (lead.angle.theta.mode !== "spin") b.angle.theta.hold(lead.angle.theta.anchor, TAU) + + // Stripes carry on the way they were going and settle onto the lead's latitude. + if (lead.angle.phi.mode === "hold") b.angle.phi.hold(lead.angle.phi.anchor, TAU) + } + } + + global(values: Partial>, cfg?: GyroSpring) { + for (const key of GLOBAL_KEYS) { + const value = values[key] + + if (value !== undefined) this.globals[key].to(value, this.reduceMotion ? RM : (cfg ?? FADE), this.immediate) + } + } + + // Advances by dt. False once nothing will change until the next `set`. + step(dt: number) { + if (this.isStatic) return false + this.t += dt + this.age += dt + + if (!this.reduceMotion) this.design.tick?.(this, this.age) + let moving = !this.reduceMotion && !!this.design.tick + + for (const b of this.strokes) { + const shown = b.spring.k.value > 0.003 || b.spring.k.target > 0 + + for (const key of ANGLE_KEYS) { + b.angle[key].step(dt) + + if (shown) moving = b.angle[key].moving || moving + } + + for (const key of SPRING_KEYS) moving = b.spring[key].step(dt) || moving + } + + for (const key of GLOBAL_KEYS) moving = this.globals[key].step(dt) || moving + this.isStatic = !moving + + return true + } + + fill(): GyroField { + const comet = Math.max(0, this.globals.comet.value) + + const live = this.strokes.flatMap((b) => { + const k = b.spring.k.value * visS(b.s, b.spring.w.value, b.spring.pitch.value) + + if (k < 0.003) return [] + const cone = b.spring.cone.value + const a = b.angle.a.value + cone * Math.sin(b.angle.rho.value) + const r = b.angle.r.value + cone * Math.cos(b.angle.rho.value) + const f = frame(b.angle.theta.value, b.angle.e.value, a, r) + + const taps = + comet > 0.01 + ? [1, 2, 3].map((j) => { + const lag = j * 0.05 + + return frame( + b.angle.theta.value - b.angle.theta.vel * lag, + b.angle.e.value - b.angle.e.vel * lag, + a - b.angle.a.vel * lag, + r - b.angle.r.vel * lag, + ).n + }) + : [] + + return [ + { + b, + k, + s: b.s, + w: b.spring.w.value, + ...f, + taps, + pitch: b.spring.pitch.value, + arc: b.spring.arc.value, + floor: b.spring.floor.value, + tail: b.spring.tail.value, + dir: sign(b.angle.psi.vel) === 0 ? -1 : sign(b.angle.psi.vel), + dash: b.spring.dash.value, + glint: b.spring.glint.value, + notch: b.spring.notch.value, + clip: b.spring.clip.value, + psi: b.angle.psi.value, + psiD: b.angle.psiD.value, + psiG: b.angle.psiG.value, + psiN: b.angle.psiN.value, + }, + ] + }) + + const ring = this.globals.ring.value + const flash = Math.max(0, this.globals.flash.value) + const body = this.globals.body.value + const ringN = ring > 1e-3 ? frame(0, HALF, this.strokes[0]!.angle.a.value, 0).n : undefined + + const accent = clamp( + ACCENTS.reduce((sum, key) => sum + Math.max(0, this.globals[key].value), 0), + 0, + 1, + ) + + const dots = CELLS.map((cell): GyroDot => { + const p = cell.normal + let lit = 0 + let fresh = 0 + + for (const L of live) { + const dn = dot(p, L.n) + const needLam = L.pitch > 1e-3 || L.arc < 3.4 || L.dash > 1e-3 || L.glint > 1e-3 || L.notch > 1e-3 + const pu = dot(p, L.u) + const pv = dot(p, L.v) + const lam = needLam ? Math.atan2(pv, pu) : 0 + // Angle along the stroke is undefined on its axis; windows fade out there instead of flipping. + const on = needLam ? sstep(0.04, 0.3, Math.sqrt(pu * pu + pv * pv)) : 1 + const d = dn - L.s + (L.pitch > 1e-3 ? 0.5 * on * L.pitch * Math.cos(lam - L.b.pitch0) : 0) + let g = gauss(d, L.w) * L.k * (0.65 + 0.35 * p[2]) + + if (L.arc < 3.4) { + const ds = wrap(lam - L.psi) + const win = sstep(L.arc + 0.12, L.arc - 0.12, Math.abs(ds)) + + const tailed = + L.tail > 1e-3 && ds * L.dir < 0 + ? Math.max(win, L.tail * Math.exp(-Math.max(0, Math.abs(ds) - L.arc) / 0.55)) + : win + + g *= 1 - on * (1 - Math.max(L.floor, tailed)) + } + + // A few dashes are clusters a couple of dots long; many are single dots. + if (L.dash > 1e-3) { + g *= 1 - on * L.dash * (1 - Math.pow(0.5 + 0.5 * Math.cos(L.b.m * (lam - L.psiD)), L.b.m <= 4 ? 1.5 : 4)) + } + + if (L.glint > 1e-3) g *= 1 - on * L.glint * (1 - gauss(wrap(lam - L.psiG), 0.42)) + + if (L.notch > 1e-3) g *= 1 - on * L.notch * gauss(wrap(lam - L.psiN), 0.5) + + if (L.clip < 1.5) g *= sstep(0.12, -0.12, p[0] - L.clip) + + L.taps.forEach((tap, j) => { + g = Math.max(g, gauss(dot(p, tap) - L.s, L.w) * L.k * comet * Math.pow(0.5, j + 1) * 0.9) + }) + lit = 1 - (1 - lit) * (1 - Math.min(1, g)) + fresh = Math.max(fresh, g) + } + + const ringLight = ringN ? ring * Math.exp(-(dot(p, ringN) ** 2) / 0.045) : 0 + + const P = + (0.14 + 0.4 * Math.pow(cell.shade, 1.2)) * body + 0.95 * lit + ringLight + flash * (0.25 + 0.45 * cell.shade) + + return { light: P, fresh: fresh * 0.8, accent: accent * sstep(0.3, 0.65, P), size: cell.size } + }) + + return { + dots, + glow: this.globals.glow.value + 0.6 * flash, + weights: { + orange: Math.max(0, this.globals.orange.value), + red: Math.max(0, this.globals.red.value), + green: Math.max(0, this.globals.green.value), + blue: Math.max(0, this.globals.blue.value), + }, + heat: 0, + } + } + + // The field as drawn: the engine's, through the afterglow and flash, `dt` after the last frame. + render(dt: number) { + const field = this.fill() + this.phosphor.apply(field, dt) + + return field + } + + // Nothing moves or cools until the next state. + get isResting() { + return this.isStatic && this.phosphor.isSettled + } +} diff --git a/packages/app/src/session/agent-glyph/orb.ts b/packages/app/src/session/agent-glyph/orb.ts new file mode 100644 index 00000000000..d68d759d247 --- /dev/null +++ b/packages/app/src/session/agent-glyph/orb.ts @@ -0,0 +1,239 @@ +import { ACCENTS, CELLS, type ActivityAccent, type GyroField } from "./gyro" + +// Draws the orb on a 2D canvas, as the iOS app's `activityOrbField` shader does on the GPU: a soft radial glow, then +// each dot of the pixel-snapped 7 × 7 grid with its halo and anti-aliased disc. Colours come from theme tokens set on +// the canvas as `--agent-glyph-*` custom properties. + +type RGB = [number, number, number] + +export type OrbPalette = { + dark: boolean + base: RGB + core: RGB + accents: Record + hot: Record +} + +const WHITE: RGB = [1, 1, 1] + +const BLACK: RGB = [0, 0, 0] + +const SIGMA = 2.2 + +const GLOW_STRENGTH = 1.5 + +const LIGHT_GLOW = 0.45 + +const SHADER_GLOW = 0.55 + +export const orbMargin = (size: number) => Math.round(size * 0.42) + +const diameter = (size: number) => size - (size >= 24 ? 4 : 2) + +const mix = (a: RGB, b: RGB, t: number): RGB => [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, +] + +const add = (a: RGB, b: RGB, w: number): RGB => [a[0] + b[0] * w, a[1] + b[1] * w, a[2] + b[2] * w] + +const scaled = (a: RGB, k: number): RGB => [a[0] * k, a[1] * k, a[2] * k] + +const clamp01 = (x: number) => (x < 0 ? 0 : x > 1 ? 1 : x) + +const sstep = (a: number, b: number, x: number) => { + const t = clamp01((x - a) / (b - a)) + + return t * t * (3 - 2 * t) +} + +const saturate = (c: RGB, k: number): RGB => { + const l = c[0] * 0.299 + c[1] * 0.587 + c[2] * 0.114 + + return [clamp01(l + (c[0] - l) * k), clamp01(l + (c[1] - l) * k), clamp01(l + (c[2] - l) * k)] +} + +// Glow colour, as the scope derives it from a trace's two colours. +const glowColor = (a: RGB, b: RGB, dark: boolean) => + dark ? saturate(mix(a, b, 0.5), 1.5) : mix(saturate(a, 1.95), WHITE, 0.15) + +const rgba = (c: RGB, a: number) => + `rgba(${Math.round(c[0] * 255)},${Math.round(c[1] * 255)},${Math.round(c[2] * 255)},${clamp01(a)})` + +const resolved = new Map() + +let probe: CanvasRenderingContext2D | undefined | null + +// Any CSS colour the canvas understands, as sRGB. +function resolveColor(css: string): RGB { + const cached = resolved.get(css) + + if (cached) return cached + probe ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true }) + + if (!probe) return [0.5, 0.5, 0.5] + probe.clearRect(0, 0, 1, 1) + probe.fillStyle = "#000" + probe.fillStyle = css + probe.fillRect(0, 0, 1, 1) + const data = probe.getImageData(0, 0, 1, 1).data + const color: RGB = [data[0]! / 255, data[1]! / 255, data[2]! / 255] + resolved.set(css, color) + + return color +} + +export function readPalette(element: Element): OrbPalette { + const style = getComputedStyle(element) + const read = (name: string) => resolveColor(style.getPropertyValue(name).trim() || "currentColor") + const core = read("--agent-glyph-core") + const dark = core[0] * 0.299 + core[1] * 0.587 + core[2] * 0.114 > 0.5 + + const accent = (name: string): [RGB, RGB] => { + const color = read(name) + + return [color, mix(color, core, 0.45)] + } + + const accents = { + orange: accent("--agent-glyph-orange"), + red: accent("--agent-glyph-red"), + green: accent("--agent-glyph-green"), + blue: accent("--agent-glyph-blue"), + } + + // The flash the settled colour cools from: near white on dark, a bright accent on light. + // SAFETY: built from every key of ACCENTS. + const hot = Object.fromEntries( + ACCENTS.map((key) => { + const color = accents[key][0] + + return [key, dark ? [mix(color, WHITE, 0.8), WHITE] : [mix(color, WHITE, 0.3), mix(color, WHITE, 0.15)]] + }), + ) as Record + + return { dark, base: read("--agent-glyph-base"), core, accents, hot } +} + +export function drawOrb( + ctx: CanvasRenderingContext2D, + field: GyroField, + size: number, + scale: number, + palette: OrbPalette, +) { + const side = size + 2 * orbMargin(size) + const dark = palette.dark + ctx.setTransform(scale, 0, 0, scale, 0, 0) + ctx.clearRect(0, 0, side, side) + + // The accent blended by the state's colour weights. + const blend = ACCENTS.reduce( + (sum, key) => { + const weight = field.weights[key] + + if (weight <= 1e-3) return sum + const pair = palette.accents[key] + + return { + weight: sum.weight + weight, + accent: add(sum.accent, pair[0], weight), + core: add(sum.core, pair[1], weight), + } + }, + { weight: 0, accent: BLACK, core: BLACK }, + ) + + const tinted = blend.weight >= 1e-3 + const accent = tinted ? scaled(blend.accent, 1 / blend.weight) : palette.base + const accentCore = tinted ? scaled(blend.core, 1 / blend.weight) : palette.core + const tint = Math.min(1, blend.weight) + const neutralGlow = glowColor(palette.base, palette.core, dark) + const heat = clamp01(field.heat) + const hot = heat > 1e-3 ? hotPair(palette, field.weights) : undefined + // A flash warms the neutral pair toward its hot colour: lit dots cool from it into the accent, dim ones to pearl. + const neutral = hot ? mix(palette.base, hot[0], heat) : palette.base + const neutralCore = hot ? mix(palette.core, hot[1], heat) : palette.core + const baseGlow = mix(neutralGlow, glowColor(accent, accentCore, dark), tinted ? tint : 0) + const glowRGB = hot ? mix(baseGlow, glowColor(hot[0], hot[1], dark), heat) : baseGlow + + // The grid snaps to device pixels: a whole number of pixels per cell. + const pitch = Math.max(2, Math.round((diameter(size) * scale) / 7)) / scale + const gridSide = 7 * pitch + const origin = Math.floor((side * scale - gridSide * scale) / 2) / scale + const centre = origin + gridSide / 2 + const peak = (dark ? 0.3 : 0.19) * SHADER_GLOW * GLOW_STRENGTH * (dark ? 1 : LIGHT_GLOW) + const a0 = dark ? 0.06 : 0.075 + const top = dark ? 0.96 : 1 + + // 1. Central Gaussian glow. + if (field.glow > 1e-3) { + const reach = 3.6 * SIGMA + const gradient = ctx.createRadialGradient(centre, centre, 0, centre, centre, reach * pitch) + + for (let i = 0; i <= 8; i++) { + const cells = (i / 8) * reach + gradient.addColorStop( + i / 8, + rgba(glowRGB, Math.min(1, field.glow * Math.exp(-(cells * cells) / (2 * SIGMA * SIGMA))) * peak), + ) + } + + ctx.fillStyle = gradient + ctx.fillRect(0, 0, side, side) + } + + // 2. Each dot: its halo, then its disc. + CELLS.forEach((cell, i) => { + const dot = field.dots[i] + + if (!dot) return + const P = clamp01(dot.light) + const fresh = clamp01(dot.fresh) + const x = origin + (cell.column + 0.5) * pitch + const y = origin + (cell.row + 0.5) * pitch + const shrink = 1 + (0.82 + 0.18 * fresh - 1) * sstep(0.03, 0.2, P) + const radius = (0.25 + 0.17 * Math.pow(Math.max(P, 1e-5), 0.6)) * shrink * pitch * dot.size + const expPow = (dark ? 0.9 : 0.75) * (1.4 + (1 - 1.4) * fresh) + const alpha = a0 + (top - a0) * Math.pow(Math.max(P, 1e-5), expPow) + const core = Math.min(0.9, P * P * 1.1) * (0.3 + 0.7 * fresh) + const rgb = mix(mix(neutral, neutralCore, core), mix(accent, accentCore, core), clamp01(dot.accent)) + const haloPeak = 0.22 * P * P + + if (haloPeak > 0.008) { + const outer = radius + 0.5 * pitch + const halo = ctx.createRadialGradient(x, y, radius, x, y, outer) + + for (let j = 0; j <= 4; j++) { + halo.addColorStop(j / 4, rgba(rgb, haloPeak * Math.exp(-((j / 4) * 0.5 * pitch) / (0.12 * pitch)))) + } + + ctx.fillStyle = halo + ctx.beginPath() + ctx.arc(x, y, outer, 0, Math.PI * 2) + ctx.fill() + } + + ctx.fillStyle = rgba(rgb, alpha) + ctx.beginPath() + ctx.arc(x, y, radius, 0, Math.PI * 2) + ctx.fill() + }) +} + +// The flash colour for the state's accents, blended by their weights; none when no accent flashes. +function hotPair(palette: OrbPalette, weights: Record): [RGB, RGB] | undefined { + const total = ACCENTS.reduce((sum, key) => sum + (weights[key] > 1e-3 ? weights[key] : 0), 0) + + if (total < 1e-3) return + + return ACCENTS.reduce<[RGB, RGB]>( + (sum, key) => { + const weight = weights[key] > 1e-3 ? weights[key] / total : 0 + + return [add(sum[0], palette.hot[key][0], weight), add(sum[1], palette.hot[key][1], weight)] + }, + [BLACK, BLACK], + ) +} diff --git a/packages/app/src/session/composer/activity-chips.css b/packages/app/src/session/composer/activity-chips.css deleted file mode 100644 index d4ab49a61e5..00000000000 --- a/packages/app/src/session/composer/activity-chips.css +++ /dev/null @@ -1,117 +0,0 @@ -[data-component="session-activity-glyph"] { - display: block; - flex-shrink: 0; - fill: currentColor; -} - -/* One wave runs diagonally across the 5×5 grid, as in the iOS app's agent activity glyph. */ -[data-component="session-activity-glyph"] [data-dot] { - animation: session-activity-glyph 1.1s linear infinite; - animation-delay: calc(var(--session-activity-glyph-phase, 0ms) + (var(--diagonal) / 8 - 1) * 1.1s); -} - -[data-component="session-activity-glyph"] [data-reduced-motion] { - display: none; -} - -@media (prefers-reduced-motion: reduce) { - [data-component="session-activity-glyph"] [data-dot] { - display: none; - } - - [data-component="session-activity-glyph"] [data-reduced-motion] { - display: block; - } -} - -/* opacity = 0.16 + 0.84 * wave³, wave = (1 + cos 2πt) / 2 */ -@keyframes session-activity-glyph { - 0%, - 100% { - opacity: 1; - } - 5%, - 95% { - opacity: 0.94; - } - 10%, - 90% { - opacity: 0.782; - } - 15%, - 85% { - opacity: 0.58; - } - 20%, - 80% { - opacity: 0.396; - } - 25%, - 75% { - opacity: 0.265; - } - 30%, - 70% { - opacity: 0.195; - } - 35%, - 65% { - opacity: 0.167; - } - 40%, - 60% { - opacity: 0.16; - } -} - -/* - * The open panel grows out of the capsule, which stays as its bottom row. Everything sits on the capsule's grid: - * 1px border + 8px padding puts glyphs at x=9; a 15px glyph + 6px gap puts text at x=30. - */ -[data-component="menu-v2-content"][data-slot="session-activity-panel"] { - width: max-content; - min-width: max(var(--kb-popper-anchor-width, 0px), 240px); - max-width: min(360px, calc(100vw - 24px)); - padding: 4px 4px 32px; - border: 1px solid var(--v2-border-border-base); - border-radius: 14px; - background: var(--v2-background-bg-base); - /* Past the 6px gutter and the 28px capsule, so the panel's bottom edge is the capsule's. */ - translate: 0 34px; - - [data-component="menu-v2-item"] { - padding-inline: 4px 8px; - border-radius: 10px; - } - - [data-slot="menu-v2-item-content"] { - gap: 6px; - } - - [data-slot="menu-v2-item-content"] > svg:first-child { - flex: none; - width: 15px; - height: 15px; - } - - [data-slot="menu-v2-group-label"] { - height: 24px; - padding-inline: 4px; - } - - [data-slot="menu-v2-separator"] { - width: calc(100% + 8px); - margin: 4px -4px; - } - - @media (prefers-reduced-motion: reduce) { - animation: none; - } -} - -/* While open, the capsule is the panel's bottom row rather than a pill of its own. */ -[data-slot="session-activity-chip"][data-expanded] { - border-color: transparent; - background: transparent; - box-shadow: none; -} diff --git a/packages/app/src/session/composer/activity-chips.stories.tsx b/packages/app/src/session/composer/activity-chips.stories.tsx deleted file mode 100644 index 70585ec81a8..00000000000 --- a/packages/app/src/session/composer/activity-chips.stories.tsx +++ /dev/null @@ -1,240 +0,0 @@ -import type { SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise" -import type { SessionDocument } from "@opencode/session-ui/document" -import { - CURRENT_SESSION_ID, - STORY_MODEL, - STORY_TIME, - editThenTestDocument, - largeCompletedDocument, -} from "@opencode/session-ui/storybook" -import { timelinePresets } from "@opencode/session-ui/timeline/detail" -import { createMemo, onCleanup, onMount } from "solid-js" -import { createStore } from "solid-js/store" -import { SessionPreview } from "@/session/story-model" -import type { SessionActivityItem } from "./activity-chips" - -// The app's default timeline preset. -const timelineDetail = timelinePresets[2].value - -const subagents = [ - { id: "ses_child_scroll", agent: "general", description: "Investigate Linux scroll jacking" }, - { id: "ses_child_audit", agent: "explore", description: "Audit the timeline projection" }, - { id: "ses_child_search", agent: "explore", description: "Search for shell metadata" }, -] - -const shells = [ - { id: "shl_dev", command: "bun run dev -- --port 4444" }, - { id: "shl_test", command: "bun test --watch src/session" }, -] - -const subagentItem = (index: number): SessionActivityItem => { - const value = subagents[index % subagents.length] - - return { - key: `${value.id}_${index}`, - type: "subagent", - label: value.description, - agent: value.agent, - sessionID: value.id, - target: value.id, - } -} - -const shellItem = (index: number): SessionActivityItem => ({ - key: `${shells[index % shells.length].id}_${index}`, - type: "shell", - label: shells[index % shells.length].command, - target: shells[index % shells.length].id, -}) - -// The timeline follows new work at the bottom, like a pinned session. -// Rows measure after the first frame, so wait past it. -const pin = (behavior: ScrollBehavior) => - setTimeout(() => { - const timeline = document.querySelector('[data-slot="story-timeline"]') - - timeline?.scrollTo({ top: timeline.scrollHeight, behavior }) - }, 150) - -const preview = (stage: number, subagentCount: number, shellCount: number) => () => { - const value = liveDocument(stages[stage]) - - onMount(() => pin("auto")) - - return ( - subagentItem(index)), - shells: Array.from({ length: shellCount }, (_, index) => shellItem(index)), - }} - /> - ) -} - -// Each stage lists the work still running; finished work stays in the timeline as completed calls. -const stages = [ - { started: 0, finished: 0, shells: 0, finishedShells: 0 }, - { started: 1, finished: 0, shells: 0, finishedShells: 0 }, - { started: 2, finished: 0, shells: 0, finishedShells: 0 }, - { started: 2, finished: 0, shells: 1, finishedShells: 0 }, - { started: 2, finished: 0, shells: 2, finishedShells: 0 }, - { started: 2, finished: 1, shells: 2, finishedShells: 0 }, - { started: 2, finished: 2, shells: 2, finishedShells: 0 }, - { started: 2, finished: 2, shells: 2, finishedShells: 1 }, - { started: 2, finished: 2, shells: 2, finishedShells: 2 }, -] - -type Stage = (typeof stages)[number] - -function liveDocument(stage: Stage): SessionDocument { - const done = stage.finished === stage.started && stage.finishedShells === stage.shells && stage.started > 0 - - const tools = [ - ...subagents.slice(0, stage.started).map( - (value, index): SessionMessageAssistantTool => ({ - type: "tool", - id: `tool_${value.id}`, - name: "subagent", - state: - index < stage.finished - ? { - status: "completed", - input: { agent: value.agent, description: value.description, prompt: value.description }, - content: [{ type: "text", text: "No issues found." }], - metadata: { sessionID: value.id, status: "completed" }, - } - : { - status: "running", - input: { agent: value.agent, description: value.description, prompt: value.description }, - metadata: { sessionID: value.id }, - }, - time: { created: STORY_TIME + 301_000 + index * 1_000, ran: STORY_TIME + 301_100 + index * 1_000 }, - }), - ), - ...shells.slice(0, stage.shells).map( - (value, index): SessionMessageAssistantTool => ({ - type: "tool", - id: `tool_${value.id}`, - name: "shell", - state: { - status: "completed", - input: { command: value.command, description: value.command }, - content: [{ type: "text", text: index === 0 ? "Local: http://localhost:4444/" : "Watching src/session" }], - metadata: { shellID: value.id, status: index < stage.finishedShells ? "exited" : "running" }, - }, - time: { created: STORY_TIME + 304_000 + index * 1_000, ran: STORY_TIME + 304_100 + index * 1_000 }, - }), - ), - ] - - const messages: SessionMessageInfo[] = [ - ...editThenTestDocument.messages, - ...largeCompletedDocument.messages.slice(-8), - { - id: "msg_user_activity", - type: "user", - text: "Audit the activity chips and keep the dev server and tests running while you work.", - time: { created: STORY_TIME + 300_000 }, - metadata: { agent: "build", model: STORY_MODEL }, - }, - { - id: "msg_assistant_activity", - type: "assistant", - agent: "build", - model: STORY_MODEL, - content: [ - { - type: "text", - text: "I'll delegate the audit to subagents and keep the dev server and tests running in the background.", - }, - ...tools, - ...(done - ? [{ type: "text" as const, text: "Both audits passed and the background commands have exited." }] - : []), - ], - time: { created: STORY_TIME + 300_500, completed: done ? STORY_TIME + 310_000 : undefined }, - }, - ] - - return { sessionID: CURRENT_SESSION_ID, messages, status: done ? { type: "idle" } : { type: "busy" }, diffs: [] } -} - -// Scripted with `activity-story-stage` events on `document` so a recording can step through the work. -function LiveActivity() { - const [story, setStory] = createStore({ stage: 0 }) - const stage = createMemo(() => stages[story.stage]) - const value = createMemo(() => liveDocument(stage())) - - onMount(() => { - const step = (event: Event) => { - if (!(event instanceof CustomEvent)) return - - setStory("stage", Number(event.detail)) - pin("smooth") - } - - document.addEventListener("activity-story-stage", step) - onCleanup(() => document.removeEventListener("activity-story-stage", step)) - pin("auto") - }) - - return ( - subagentItem(index + stage().finished)), - shells: shells - .slice(stage().finishedShells, stage().shells) - .map((_, index) => shellItem(index + stage().finishedShells)), - onOpen: (item) => { - // The app opens the shell's tool call, or the group holding it, and centers it in the timeline. - const part = document.querySelector( - `[data-slot="story-timeline"] [data-timeline-part-ids*="tool_${item.target}"]`, - ) - - const trigger = part?.querySelector('[data-slot="collapsible-trigger"][aria-expanded="false"]') - - trigger?.click() - requestAnimationFrame(() => part?.scrollIntoView({ block: "center", behavior: "smooth" })) - }, - }} - /> - ) -} - -export default { - title: "OpenCode/Session/Activity chips", - id: "session-activity-chips", - parameters: { - layout: "fullscreen", - docs: { - description: { - component: - "Running subagents and background shells in one capsule above the production Composer. It opens a menu of the work.", - }, - }, - }, -} - -export const NoActivity = { render: preview(0, 0, 0) } - -export const OneSubagent = { render: preview(1, 1, 0) } - -export const TwoSubagents = { render: preview(2, 2, 0) } - -export const OneShell = { render: preview(7, 0, 1) } - -export const SubagentsAndShells = { render: preview(4, 2, 2) } - -export const ManySubagents = { render: preview(4, 12, 2) } - -export const Live = { render: () => } diff --git a/packages/app/src/session/composer/activity-chips.tsx b/packages/app/src/session/composer/activity-chips.tsx deleted file mode 100644 index da7e87664a0..00000000000 --- a/packages/app/src/session/composer/activity-chips.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import { Icon } from "@opencode/ui/icon" -import { Menu } from "@opencode/ui/menu" -import { For, Index, Show } from "solid-js" -import { useLanguage } from "@/runtime/i18n/language" -import "./activity-chips.css" - -export type SessionActivityItem = { - key: string - type: "subagent" | "shell" - label?: string - agent?: string - sessionID?: string - target: string -} - -// Live work above the composer, one capsule like the iOS app's background-work summary. -export function SessionActivityChips(props: { - subagents: readonly SessionActivityItem[] - shells: readonly SessionActivityItem[] - onOpen: (item: SessionActivityItem) => void -}) { - const language = useLanguage() - - // With one kind running, the capsule row already names it. - const both = () => props.subagents.length > 0 && props.shells.length > 0 - - const label = () => language.activitySummary({ subagents: props.subagents.length, shells: props.shells.length }) - - return ( - 0 || props.shells.length > 0}> -
- - - - {label()} - - - - 0}> - - - {language.t("session.activity.section.subagents")} - - - {(item) => ( - props.onOpen(item)}> - - - {item.agent - ? `${item.agent[0].toUpperCase()}${item.agent.slice(1)}` - : language.t("ui.tool.agent.default")} - - - {item.label} - - - )} - - - - - - - 0}> - - - {language.t("session.activity.section.shells")} - - - {(item) => ( - props.onOpen(item)}> - - - {item.label} - - - )} - - - - - - -
-
- ) -} - -// A 5×5 dot matrix with a diagonal wave, ported from the iOS app's AgentActivityGlyph. -function SessionActivityGlyph(props: { class?: string }) { - // Glyphs mounted at different times share one phase, like the iOS glyph's clock-driven wave. - const phase = `${-(performance.now() % 1100)}ms` - - return ( - - ) -} diff --git a/packages/app/src/session/composer/agent-progress-chip.css b/packages/app/src/session/composer/agent-progress-chip.css new file mode 100644 index 00000000000..8fdb6584640 --- /dev/null +++ b/packages/app/src/session/composer/agent-progress-chip.css @@ -0,0 +1,266 @@ +/* + * One shape: the chip, or the panel grown out of it with the chip as its bottom row. The panel and the chip are laid + * out at their final sizes; springs move only the shape's box, which clips them. + */ +[data-component="agent-progress"] { + position: relative; + /* The chip, and the 8px gap to the composer. */ + height: 36px; + container-type: inline-size; + + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-rendering: geometricPrecision; +} + +[data-slot="agent-progress-surface"] { + --agent-progress-open: 0; + --agent-progress-edge: var(--v2-border-border-base); + + position: absolute; + bottom: 8px; + inset-inline-start: 0; + z-index: 20; + box-sizing: border-box; + width: max-content; + height: 28px; + overflow: hidden; + border-radius: 14px; + background: var(--v2-background-bg-base); + box-shadow: + inset 0 0 0 1px var(--agent-progress-edge), + var(--v2-elevation-raised); + transition: box-shadow 200ms ease-out; +} + +/* The amber edge marks the chip; open, the Review row carries it. */ +[data-component="agent-progress"]:not([data-open]) [data-slot="agent-progress-surface"][data-needs-you] { + --agent-progress-edge: var(--v2-state-border-warning); +} + +[data-component="agent-progress"][data-open] [data-slot="agent-progress-surface"] { + box-shadow: + inset 0 0 0 1px var(--agent-progress-edge), + var(--v2-elevation-floating); +} + +[data-slot="agent-progress-panel"] { + position: absolute; + bottom: 28px; + inset-inline-start: 0; + box-sizing: border-box; + width: min(380px, 100cqi); + padding: 2px 2px 0; + opacity: clamp(0, calc((var(--agent-progress-open) - 0.15) * 1.6), 1); +} + +[data-slot="agent-progress-header"] { + display: flex; + align-items: center; + gap: 8px; + height: 28px; + /* Rows and the chip share one grid: glyph centres at 15px, text at 29px. */ + padding-inline: 27px 4px; + font-size: 11px; + font-weight: 530; + letter-spacing: 0.05px; + font-variant-numeric: tabular-nums; + color: var(--v2-text-text-faint); + user-select: none; +} + +[data-slot="agent-progress-stop-all"], +[data-slot="agent-progress-review"] { + display: inline-flex; + flex: none; + align-items: center; + height: 20px; + padding-inline: 6px; + border-radius: 4px; + font-size: 11px; + font-weight: 530; + letter-spacing: 0.05px; + white-space: nowrap; + outline: none; + + &:focus-visible { + outline: 2px solid var(--v2-border-border-focus); + outline-offset: 1px; + } +} + +[data-slot="agent-progress-stop-all"] { + color: var(--v2-text-text-base); + background: var(--v2-background-bg-layer-02); + box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base); + + &:hover { + background: var(--v2-overlay-simple-overlay-hover); + } +} + +[data-slot="agent-progress-review"] { + color: var(--v2-state-fg-warning); + background: var(--v2-state-bg-warning); + box-shadow: inset 0 0 0 0.5px var(--v2-state-border-warning); +} + +[data-slot="agent-progress-rows"] { + display: flex; + flex-direction: column; + max-height: min(360px, 50vh); + overflow-y: auto; + overscroll-behavior: contain; +} + +[data-slot="agent-progress-row"], +[data-slot="agent-progress-done-toggle"] { + display: flex; + flex: none; + align-items: center; + height: 28px; + border-radius: 4px; + + &:hover, + &:has(:focus-visible) { + background: var(--v2-overlay-simple-overlay-hover); + } +} + +[data-slot="agent-progress-row"] { + padding-inline-end: 6px; +} + +[data-slot="agent-progress-row-open"] { + height: 100%; +} + +[data-slot="agent-progress-row-open"], +[data-slot="agent-progress-done-toggle"] { + display: flex; + flex: 1 1 auto; + align-items: center; + gap: 6px; + min-width: 0; + padding-inline: 5px 8px; + font-size: 13px; + font-weight: 440; + line-height: var(--line-height-compact); + letter-spacing: -0.04px; + color: var(--v2-text-text-base); + text-align: start; + outline: none; +} + +[data-slot="agent-progress-title"] { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +[data-slot="agent-progress-meta"] { + flex: 0 10000 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--v2-text-text-faint); +} + +[data-slot="agent-progress-trailing"] { + display: flex; + flex: none; + align-items: center; + gap: 4px; + max-width: 45%; + min-width: 0; +} + +[data-slot="agent-progress-elapsed"] { + flex: none; + font-size: 12px; + font-weight: 440; + font-variant-numeric: tabular-nums; + color: var(--v2-text-text-faint); + white-space: nowrap; +} + +[data-slot="agent-progress-error"] { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + color: var(--v2-state-fg-danger); +} + +[data-slot="agent-progress-done-toggle"] { + color: var(--v2-text-text-muted); +} + +[data-slot="agent-progress-chevron"] { + color: var(--v2-text-text-faint); + transition: rotate 160ms ease-out; +} + +[data-slot="agent-progress-done-toggle"][aria-expanded="true"] [data-slot="agent-progress-chevron"] { + rotate: 90deg; +} + +[data-slot="agent-progress-chip"] { + position: absolute; + inset-inline: 0; + bottom: 0; + display: flex; + align-items: center; + height: 28px; + border-radius: 14px; + outline: none; + color: var(--v2-text-text-base); + text-align: start; + + &:hover { + background: var(--v2-overlay-simple-overlay-hover); + } + + &:focus-visible { + outline: 2px solid var(--v2-border-border-focus); + outline-offset: -2px; + } +} + +[data-component="agent-progress"][data-open] [data-slot="agent-progress-chip"] { + border-radius: 4px; +} + +[data-slot="agent-progress-chip-content"] { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + box-sizing: border-box; + width: max-content; + max-width: min(100cqi, 480px); + height: 28px; + padding-inline: 7px 12px; + font-size: 13px; + font-weight: 530; + line-height: var(--line-height-compact); + letter-spacing: -0.04px; + font-variant-numeric: tabular-nums; + white-space: nowrap; + + [data-slot="agent-progress-elapsed"] { + font-size: 13px; + } +} + +[data-slot="agent-progress-failed"] { + color: var(--v2-state-fg-danger); +} + +[data-slot="agent-progress-needs-you"] { + color: var(--v2-state-fg-warning); +} diff --git a/packages/app/src/session/composer/agent-progress-chip.stories.tsx b/packages/app/src/session/composer/agent-progress-chip.stories.tsx new file mode 100644 index 00000000000..3a727ee9474 --- /dev/null +++ b/packages/app/src/session/composer/agent-progress-chip.stories.tsx @@ -0,0 +1,258 @@ +import type { SessionMessageInfo } from "@opencode/client/promise" +import type { SessionDocument } from "@opencode/session-ui/document" +import { CURRENT_SESSION_ID, STORY_MODEL, STORY_TIME, editThenTestDocument } from "@opencode/session-ui/storybook" +import { timelinePresets } from "@opencode/session-ui/timeline/detail" +import { For, onCleanup, onMount } from "solid-js" +import { createStore, produce } from "solid-js/store" +import { agentGlyphTuning } from "@/session/agent-glyph/agent-glyph" +import { SessionPreview } from "@/session/story-model" +import type { AgentProgressItem, AgentProgressState } from "./agent-progress" +import { agentChipTuning } from "./agent-progress-chip" + +const timelineDetail = timelinePresets[2].value + +const tasks = [ + "Review photo sheet polish", + "Audit drag-to-pin gesture", + "Record synced before/after clips", + "Fix camera double start", + "Trace voice settings rebase", + "Check model picker layout", + "Profile timeline scroll jank", + "Write release notes draft", + "Verify TestFlight build 448", + "Port activity glyph to web", + "Find flaky composer test", + "Compare task panels", + "Reproduce sheet white flash", + "Search for stale feature flags", + "Measure cold start", + "Update board shipped notes", + "Check RTL composer spacing", + "Draft settings cleanup plan", + "Inspect permission dock copy", +] + +const agents = ["general", "explore", "review"] + +const models = ["Alpha", "Beta"] + +const NOW = STORY_TIME + 600_000 + +const item = (index: number, state: AgentProgressState, input: Partial = {}): AgentProgressItem => ({ + key: `ses_story_${index}`, + type: "subagent", + state, + title: tasks[index % tasks.length]!, + agent: agents[index % agents.length], + model: { id: models[index % models.length]!, providerID: "story" }, + sessionID: `ses_story_${index}`, + target: `ses_story_${index}`, + started: NOW - 38_000 - index * 17_000, + ended: state === "done" || state === "failed" || state === "stopped" ? NOW - index * 3_000 : undefined, + error: state === "failed" ? "Provider rate limit" : undefined, + ...input, +}) + +const document: SessionDocument = { + sessionID: CURRENT_SESSION_ID, + status: { type: "busy" }, + diffs: [], + messages: [ + ...editThenTestDocument.messages, + { + id: "msg_user_agents", + type: "user", + text: "Check on the board and keep the agents moving.", + time: { created: STORY_TIME + 300_000 }, + metadata: { agent: "build", model: STORY_MODEL }, + }, + { + id: "msg_assistant_agents", + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: [{ type: "text", text: "I'll split the review across subagents and report back when they finish." }], + time: { created: STORY_TIME + 300_500 }, + }, + ] satisfies SessionMessageInfo[], +} + +const fixture = + (items: AgentProgressItem[], open = false) => + () => ( + NOW }} + /> + ) + +const many = (running: number, done: number, extra: AgentProgressItem[] = []) => [ + ...extra, + ...Array.from({ length: running }, (_, index) => item(index + extra.length, "running")), + ...Array.from({ length: done }, (_, index) => item(index + extra.length + running, "done")), +] + +// Scripted with `agent-chip-story` events on `document` so a recording can drive it, and with the toolbar by hand. +function LiveAgents() { + const [story, setStory] = createStore<{ items: AgentProgressItem[]; open: boolean; next: number }>({ + items: [], + open: false, + next: 0, + }) + + const add = (count: number) => + setStory( + produce((draft) => { + for (let i = 0; i < count; i++) { + const index = draft.next++ + draft.items.push(item(index, "running", { started: Date.now() - (index % 4) * 9_000 })) + } + }), + ) + + const settle = (state: AgentProgressState, from: AgentProgressState[] = ["running"]) => + setStory( + produce((draft) => { + const target = draft.items.find((value) => from.includes(value.state)) + + if (!target) return + target.state = state + target.ended = state === "running" || state === "needs-you" ? undefined : Date.now() + target.error = state === "failed" ? "Provider rate limit" : undefined + }), + ) + + const speed = (value = 1) => { + agentChipTuning.timeScale = value + agentGlyphTuning.speed = value + } + + const finishAll = () => + setStory( + produce((draft) => + draft.items.forEach((value) => { + if (value.state !== "running" && value.state !== "needs-you") return + value.state = "done" + value.ended = Date.now() + }), + ), + ) + + const actions = new Map void>([ + ["reset", () => setStory({ items: [], open: false, next: 0 })], + ["add", (value) => add(value ?? 1)], + ["finish", () => settle("done", ["running", "needs-you"])], + ["fail", () => settle("failed")], + ["needs", () => settle("needs-you")], + ["resolve", () => settle("running", ["needs-you"])], + ["finishAll", finishAll], + ["clear", () => setStory("items", [])], + ["open", () => setStory("open", true)], + ["close", () => setStory("open", false)], + ["speed", speed], + ]) + + onMount(() => { + const run = (event: Event) => { + if (!(event instanceof CustomEvent)) return + actions.get(event.detail.action)?.(event.detail.value) + } + + window.document.addEventListener("agent-chip-story", run) + onCleanup(() => { + window.document.removeEventListener("agent-chip-story", run) + speed(1) + }) + }) + + return ( + <> + setStory("open", open), + onStop: (value) => + setStory( + "items", + (entry) => entry.key === value.key, + produce((draft) => { + draft.state = "stopped" + draft.ended = Date.now() + }), + ), + }} + /> +
+ add(1)], + ["+3", () => add(3)], + ["Finish", () => settle("done", ["running", "needs-you"])], + ["Fail", () => settle("failed")], + ["Needs you", () => settle("needs-you")], + ["Resolve", () => settle("running", ["needs-you"])], + ["All done", finishAll], + ["Clear", () => setStory("items", [])], + ["1×", () => speed(1)], + ["0.25×", () => speed(0.25)], + ] as const + } + > + {([label, run]) => ( + + )} + +
+ + ) +} + +export default { + title: "OpenCode/Session/Agent progress chip", + id: "session-agent-progress-chip", + parameters: { + layout: "fullscreen", + docs: { + description: { + component: + "The current batch of subagents above the production Composer: a progress chip that morphs into a panel of rows, the chip staying as its bottom row.", + }, + }, + }, +} + +export const One = { render: fixture([item(0, "running")]) } + +export const Three = { render: fixture(many(3, 0)) } + +const nineteen = () => many(3, 14, [item(0, "needs-you"), item(1, "failed")]) + +export const Nineteen = { render: fixture(nineteen()) } + +export const NineteenOpen = { render: fixture(nineteen(), true) } + +export const Failed = { render: fixture(many(2, 3, [item(0, "failed")])) } + +export const NeedsYou = { render: fixture(many(2, 0, [item(0, "needs-you")])) } + +export const NeedsYouOpen = { render: fixture(many(2, 0, [item(0, "needs-you")]), true) } + +export const AllDone = { render: fixture(many(0, 5)) } + +export const Live = { render: () => } diff --git a/packages/app/src/session/composer/agent-progress-chip.tsx b/packages/app/src/session/composer/agent-progress-chip.tsx new file mode 100644 index 00000000000..ffcd78f5752 --- /dev/null +++ b/packages/app/src/session/composer/agent-progress-chip.tsx @@ -0,0 +1,580 @@ +import type { ModelRef } from "@opencode/client/promise" +import { Icon } from "@opencode/ui/icon" +import { IconButton } from "@opencode/ui/icon-button" +import { enter, frameLoop, observeReducedMotion, prefersReducedMotion, Spring } from "@opencode/ui/motion" +import { makeEventListener } from "@solid-primitives/event-listener" +import { createEffect, createMemo, createSignal, For, Match, on, onCleanup, onMount, Show, Switch } from "solid-js" +import { createStore } from "solid-js/store" +import { useLanguage } from "@/runtime/i18n/language" +import { AgentGlyph, type AgentActivity } from "@/session/agent-glyph/agent-glyph" +import { + activeState, + agentProgressCounts, + formatElapsed, + type AgentProgressItem, + type AgentProgressState, +} from "./agent-progress" +import "./agent-progress-chip.css" + +// Live-tunable motion (the story and the motion panel set it). Springs are SwiftUI duration and bounce, as on iOS. +export const agentChipTuning = { + // The chip and the panel, one surface morphing both ways. + morph: { duration: 0.34, bounce: 0.12 }, + // The chip following its words as the counts change: glass, words and glyph on one unbouncy spring. + resize: { duration: 0.4, bounce: 0 }, + // Slows every chip spring for review (1 is real time). + timeScale: 1, +} + +const CHIP_HEIGHT = 28 + +const RADIUS_CLOSED = CHIP_HEIGHT / 2 + +const RADIUS_OPEN = 10 + +type AgentProgressProps = { + items: readonly AgentProgressItem[] + modelName?: (model: ModelRef) => string | undefined + onOpen: (item: AgentProgressItem) => void + onStop: (item: AgentProgressItem) => void + // Exposed for the story and the motion panel. + open?: boolean + onOpenChange?: (open: boolean) => void + now?: () => number +} + +// Subagent work above the composer: a chip with the batch's progress that morphs into a panel of its rows, the chip +// staying as the panel's bottom row. Ported from the iOS app's background-work capsule and panel. +export function AgentProgressChip(props: AgentProgressProps) { + // The last batch stays drawn while the chip fades out. + const [mounted, setMounted] = createSignal(props.items.length > 0) + const [held, setHeld] = createSignal(props.items, { equals: false }) + let surface: HTMLElement | undefined + let fade: Animation | undefined + + createEffect( + on( + () => [props.items, props.items.length] as const, + ([items, length]) => { + if (length) { + // Work arriving mid-fade takes the chip back. + fade?.cancel() + fade = undefined + setHeld(items) + setMounted(true) + + return + } + + if (!surface || prefersReducedMotion()) return setMounted(false) + props.onOpenChange?.(false) + fade = surface.animate([{ opacity: 1 }, { opacity: 0, translate: "0 4px" }], { + duration: 160, + easing: "ease-in", + fill: "forwards", + }) + fade.finished.then( + () => setMounted(false), + () => undefined, + ) + }, + { defer: true }, + ), + ) + + return ( + + { + surface = element + }} + /> + + ) +} + +function AgentProgressBody(props: AgentProgressProps & { surface: (element: HTMLElement) => void }) { + const language = useLanguage() + const [local, setLocal] = createStore({ open: false, doneExpanded: false }) + const open = () => props.open ?? local.open + + const setOpen = (next: boolean) => { + setLocal("open", next) + props.onOpenChange?.(next) + } + + const [refs, setRefs] = createStore<{ + root?: HTMLDivElement + surface?: HTMLDivElement + panel?: HTMLDivElement + chip?: HTMLButtonElement + content?: HTMLSpanElement + }>({}) + + const counts = createMemo(() => agentProgressCounts(props.items)) + const group = (states: AgentProgressState[]) => props.items.filter((item) => states.includes(item.state)) + const needsYou = createMemo(() => group(["needs-you"])) + const running = createMemo(() => group(["running", "starting"])) + const failed = createMemo(() => group(["failed"])) + const done = createMemo(() => group(["done", "stopped"])) + const single = () => (props.items.length === 1 ? props.items[0] : undefined) + + // Elapsed times tick only while someone can see one move. + const [tick, setTick] = createSignal(Date.now()) + const now = () => props.now?.() ?? tick() + createEffect(() => { + if (props.now) return + + if (!(open() || single()) || !props.items.some((item) => activeState(item.state))) return + setTick(Date.now()) + const timer = setInterval(() => setTick(Date.now()), 1000) + onCleanup(() => clearInterval(timer)) + }) + + const elapsed = (item: AgentProgressItem) => + item.started === undefined ? undefined : formatElapsed((item.ended ?? now()) - item.started) + + const singleStatus = (item: AgentProgressItem) => { + const key = stateLabel[item.state] + + return key ? language.t(key) : (elapsed(item) ?? "") + } + + // The most telling state, for the chip's glyph. Unlike iOS, running outranks a failure while work continues. + const summary = createMemo(() => { + const value = counts() + + if (value.needsYou) return "waiting" + + if (running().length && running().every((item) => item.state === "starting")) return "handoff" + + if (value.running) return "thinking" + + if (value.failed) return "failed" + + return "done" + }) + + const label = createMemo(() => { + const value = counts() + + if (value.running && !value.done) return language.t("session.agents.running", { count: value.running }) + + if (!value.running && !value.needsYou && !value.failed) + return language.t("session.agents.allDone", { count: value.total }) + + return language.t("session.agents.progress", { done: value.done, total: value.total }) + }) + + // The chip's words as one phrase, for its accessible name. + const summaryText = createMemo(() => + [ + single() ? `${single()!.title} ${singleStatus(single()!)}` : label(), + counts().failed && !single() ? language.t("session.agents.failed", { count: counts().failed }) : undefined, + counts().needsYou ? language.plural("session.agents.needsYou", counts().needsYou) : undefined, + ] + .filter(Boolean) + .join(" · "), + ) + + const header = createMemo(() => + [ + counts().running ? language.t("session.agents.running", { count: counts().running }) : undefined, + counts().done ? language.t("session.agents.done", { count: counts().done }) : undefined, + ] + .filter(Boolean) + .join(" · "), + ) + + const stoppable = (item: AgentProgressItem) => item.type === "shell" || !!item.sessionID + + // Rows are keyed by the work they show, not by item objects, which the data layer rebuilds on every update: a row + // and its glyph live on as its state changes. + const byKey = createMemo(() => new Map(props.items.map((item) => [item.key, item]))) + + const keys = (items: () => AgentProgressItem[]) => + createMemo(() => items().map((item) => item.key), [], { + equals: (a, b) => a.length === b.length && a.every((key, index) => key === b[index]), + }) + + const activeKeys = keys(() => [...needsYou(), ...running(), ...failed()]) + const doneKeys = keys(done) + + const KeyedRow = (row: { key: string }) => ( + + {(item) => ( + openItem(item())} + onStop={() => props.onStop(item())} + /> + )} + + ) + + const stopAll = () => + props.items.filter((item) => activeState(item.state) && stoppable(item)).forEach((item) => props.onStop(item)) + + const openItem = (item: AgentProgressItem) => { + setOpen(false) + props.onOpen(item) + } + + // Closing from inside the panel returns focus to the chip, its own bottom row. + const close = () => { + const inside = !!refs.surface?.contains(document.activeElement) + setOpen(false) + + if (inside) refs.chip?.focus() + } + + createEffect(() => { + if (!open()) return + makeEventListener(document, "pointerdown", (event) => { + if (refs.surface && !event.composedPath().includes(refs.surface)) setOpen(false) + }) + makeEventListener(document, "keydown", (event) => { + if (event.key !== "Escape" || event.defaultPrevented) return + event.preventDefault() + event.stopPropagation() + close() + }) + }) + + onMount(() => { + if (refs.surface) enter(refs.surface, { y: 4, duration: 180 }) + }) + + createSurfaceMotion({ + refs, + open, + watch: () => { + label() + void props.items.length + void local.doneExpanded + void single()?.state + }, + }) + + // Words changing: the old fade and blur out as the new ones come in, like the iOS capsule's counts. + createEffect( + on( + () => [label(), counts().failed, counts().needsYou] as const, + () => { + if (refs.content && !prefersReducedMotion()) { + refs.content.animate( + [ + { opacity: 0.35, filter: "blur(2px)" }, + { opacity: 1, filter: "blur(0)" }, + ], + { duration: 220, easing: "cubic-bezier(.22, 1, .36, 1)" }, + ) + } + }, + { defer: true }, + ), + ) + + return ( +
setRefs("root", element)} + data-component="agent-progress" + data-open={open() ? "" : undefined} + > +
{ + setRefs("surface", element) + props.surface(element) + }} + data-slot="agent-progress-surface" + data-needs-you={counts().needsYou ? "" : undefined} + > +
setRefs("panel", element)} + id="agent-progress-panel" + data-slot="agent-progress-panel" + role="group" + aria-label={language.t("session.agents.panel")} + inert={!open()} + > +
+ {header()} + + + +
+
+ {(key) => } + + + + {(key) => } + + +
+
+ +
+
+ ) +} + +function Row(props: { + item: AgentProgressItem + model?: string + elapsed?: string + paused: boolean + stoppable: boolean + onOpen: () => void + onStop: () => void +}) { + const language = useLanguage() + + const meta = () => + [ + props.item.type === "shell" + ? language.t("ui.tool.shell") + : props.item.agent + ? `${props.item.agent[0]!.toUpperCase()}${props.item.agent.slice(1)}` + : language.t("ui.tool.agent.default"), + props.model, + ] + .filter(Boolean) + .join(" · ") + + const state = () => props.item.state + // A row that only just finished shows its arrival: the glyph starts from running and flashes into place. + const from = props.item.ended !== undefined && Date.now() - props.item.ended < 1500 ? "thinking" : undefined + + return ( +
+ + + + + {state() === "starting" ? language.t("session.agents.state.starting") : props.elapsed} + + + } + aria-label={language.t( + props.item.type === "shell" ? "session.running.stop.shell" : "session.running.stop.subagent", + )} + onClick={props.onStop} + /> + + + } + > + + + + + + {props.item.error ?? language.t("session.agents.state.failed")} + + + + + {state() === "stopped" ? language.t("session.agents.state.stopped") : props.elapsed} + + + + +
+ ) +} + +// Each row's glyph design: the iOS subagent states, without its live event ledger (so no tool or output bursts). +const glyph: Record = { + "needs-you": "waiting", + starting: "handoff", + running: "thinking", + failed: "failed", + done: "done", + stopped: "idle", +} + +// Finished states name themselves; running ones show their elapsed time instead. +const stateLabel: Partial< + Record< + AgentProgressState, + | "session.agents.state.failed" + | "session.agents.state.done" + | "session.agents.state.stopped" + | "session.agents.state.starting" + > +> = { + failed: "session.agents.state.failed", + done: "session.agents.state.done", + stopped: "session.agents.state.stopped", + starting: "session.agents.state.starting", +} + +// One surface, two sizes: the chip's own width, or the panel's measured box. Toggling morphs on `morph`; content +// changes within a state follow on `resize`. Everything is laid out at its final size first and only the surface's +// clip moves, so the panel's height is known before it opens. +function createSurfaceMotion(input: { + refs: { root?: HTMLElement; surface?: HTMLElement; panel?: HTMLElement; content?: HTMLElement } + open: () => boolean + watch: () => void +}) { + const width = new Spring(0) + const height = new Spring(CHIP_HEIGHT) + const progress = new Spring(0) + const springs = [width, height, progress] + let first = true + let wasOpen = input.open() + let reduced = prefersReducedMotion() + let remove: (() => void) | undefined + + const tune = (curve: { duration: number; bounce: number }) => { + const omega = (2 * Math.PI) / curve.duration + springs.forEach((spring) => { + spring.omega = omega + spring.zeta = 1 - curve.bounce + }) + } + + const read = () => { + const { root, panel, content } = input.refs + + if (!root || !panel || !content) return + const open = input.open() + + if (open !== wasOpen) tune(agentChipTuning.morph) + + if (open === wasOpen && width.resting && height.resting) tune(agentChipTuning.resize) + wasOpen = open + const room = root.offsetWidth + width.set(open ? panel.offsetWidth : Math.min(content.offsetWidth, room)) + height.set(open ? panel.offsetHeight + CHIP_HEIGHT : CHIP_HEIGHT) + progress.set(open ? 1 : 0) + } + + const write = (frame: number) => { + const surface = input.refs.surface + + if (!surface) { + remove = undefined + + return false + } + + const dt = frame * agentChipTuning.timeScale + springs.forEach((spring) => (first || reduced ? spring.snap(spring.target) : spring.step(dt))) + first = false + const p = Math.min(1, Math.max(0, progress.value)) + surface.style.width = `${width.value}px` + surface.style.height = `${Math.max(CHIP_HEIGHT, height.value)}px` + surface.style.borderRadius = `${RADIUS_CLOSED + (RADIUS_OPEN - RADIUS_CLOSED) * p}px` + surface.style.setProperty("--agent-progress-open", String(p)) + const moving = springs.some((spring) => !spring.resting) + + if (!moving) remove = undefined + + return moving + } + + const wake = () => { + if (!remove) remove = frameLoop.addMeasured(read, write) + } + + tune(agentChipTuning.resize) + createEffect(() => { + input.open() + input.watch() + wake() + }) + createEffect(() => { + const { root, panel, content } = input.refs + + if (!root || !panel || !content || typeof ResizeObserver === "undefined") return + const observer = new ResizeObserver(wake) + observer.observe(root) + observer.observe(panel) + observer.observe(content) + onCleanup(() => observer.disconnect()) + }) + onCleanup( + observeReducedMotion(() => { + reduced = prefersReducedMotion() + wake() + }), + ) + onCleanup(() => remove?.()) +} diff --git a/packages/app/src/session/composer/agent-progress.test.ts b/packages/app/src/session/composer/agent-progress.test.ts new file mode 100644 index 00000000000..de177e189f9 --- /dev/null +++ b/packages/app/src/session/composer/agent-progress.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, test } from "bun:test" +import type { SessionInfo, SessionMessageInfo } from "@opencode/client/promise" +import { agentProgressCounts, agentProgressItems, formatElapsed } from "./agent-progress" + +const owner = "ses_owner" + +// SAFETY: fixtures fill the fields agentProgressItems reads; the rest of SessionInfo is never touched. +const child = (id: string, input: Partial & { created: number }): SessionInfo => + ({ + id, + parentID: owner, + projectID: "prj", + agent: "general", + title: `Task ${id}`, + cost: 0, + tokens: {}, + location: { directory: "/repo" }, + ...input, + time: { created: input.created, updated: input.created, ...input.time }, + }) as SessionInfo + +const items = (input: { + sessions: SessionInfo[] + running?: string[] + needsYou?: string[] + messages?: SessionMessageInfo[] + errors?: Record +}) => + agentProgressItems({ + owner, + sessions: input.sessions, + status: (id) => (input.running?.includes(id) ? "running" : "idle"), + needsYou: (id) => !!input.needsYou?.includes(id), + messages: input.messages ?? [], + childError: (id) => input.errors?.[id], + shells: [], + }) + +describe("agentProgressItems", () => { + test("reads each child's state from its status, requests and outcome", () => { + const result = items({ + sessions: [ + child("a", { created: 1 }), + child("b", { created: 2 }), + child("c", { created: 3, outcome: "failed", time: { created: 3, updated: 9, idle: 9 } }), + child("d", { created: 4, outcome: "succeeded", time: { created: 4, updated: 8, idle: 8 } }), + child("e", { created: 5, outcome: "interrupted", time: { created: 5, updated: 7, idle: 7 } }), + ], + running: ["a", "b"], + needsYou: ["b"], + errors: { c: "Provider rate limit" }, + }) + + expect(result.map((item) => [item.key, item.state])).toEqual([ + ["a", "running"], + ["b", "needs-you"], + ["c", "failed"], + ["d", "done"], + ["e", "stopped"], + ]) + expect(result.find((item) => item.key === "c")?.error).toBe("Provider rate limit") + expect(agentProgressCounts(result)).toEqual({ total: 5, running: 1, needsYou: 1, failed: 1, done: 2 }) + }) + + test("keeps only the batch since the last moment nothing ran", () => { + const result = items({ + sessions: [ + child("old", { created: 1, outcome: "succeeded", time: { created: 1, updated: 5, idle: 5 } }), + child("new", { created: 10 }), + child("newer", { created: 12, outcome: "succeeded", time: { created: 12, updated: 14, idle: 14 } }), + ], + running: ["new"], + }) + + expect(result.map((item) => item.key)).toEqual(["new", "newer"]) + }) + + test("settles a background call from its completion notice when the child isn't loaded", () => { + const result = items({ + sessions: [], + // SAFETY: an assistant call and its synthetic completion notice, shaped as the server sends them. + messages: [ + { + id: "msg_a", + type: "assistant", + agent: "build", + model: { id: "alpha", providerID: "test" }, + content: [ + { + type: "tool", + id: "prt_call", + name: "subagent", + state: { + status: "completed", + input: { description: "Trace voice settings", agent: "explore" }, + content: [{ type: "text", text: "started" }], + metadata: { sessionID: "ses_bg", status: "running" }, + }, + time: { created: 100, completed: 101 }, + }, + { + type: "tool", + id: "prt_starting", + name: "subagent", + state: { status: "streaming", input: "" }, + time: { created: 102 }, + }, + ], + time: { created: 99 }, + }, + { + id: "msg_notice", + type: "synthetic", + text: '\nProvider rate limit\n', + metadata: { source: "subagent", childID: "ses_bg", state: "error" }, + time: { created: 150 }, + }, + ] as SessionMessageInfo[], + }) + + expect(result).toMatchObject([ + { key: "ses_bg", state: "failed", title: "Trace voice settings", agent: "explore", error: "Provider rate limit" }, + { key: "prt_starting", state: "starting", target: "prt_starting" }, + ]) + }) +}) + +test("formatElapsed", () => { + expect([formatElapsed(38_000), formatElapsed(72_000), formatElapsed(3_840_000)]).toEqual(["38s", "1m 12s", "1h 4m"]) +}) diff --git a/packages/app/src/session/composer/agent-progress.ts b/packages/app/src/session/composer/agent-progress.ts new file mode 100644 index 00000000000..54d22fb1d15 --- /dev/null +++ b/packages/app/src/session/composer/agent-progress.ts @@ -0,0 +1,259 @@ +import type { ModelRef, SessionInfo, SessionMessageInfo } from "@opencode/client/promise" +import { Option, Schema } from "effect" + +export type AgentProgressState = "starting" | "running" | "needs-you" | "done" | "failed" | "stopped" + +export type AgentProgressItem = { + key: string + type: "subagent" | "shell" + state: AgentProgressState + title: string + agent?: string + model?: ModelRef + sessionID?: string + // The tool call or shell the timeline reveals when there is no child session to open. + target: string + started?: number + ended?: number + error?: string +} + +export const activeState = (state: AgentProgressState) => + state === "starting" || state === "running" || state === "needs-you" + +// One row per subagent of `owner`, from its child sessions and the subagent calls in its own messages, plus its +// running background shells. Only the current batch is kept: subagents since the last time none were running. +export function agentProgressItems(input: { + owner: string + sessions: readonly SessionInfo[] + status: (sessionID: string) => "idle" | "running" + needsYou: (sessionID: string) => boolean + // The owner's own messages: subagent calls and their completion notices. + messages: readonly SessionMessageInfo[] + // A child's failure from its own idle marker, when its messages are loaded. + childError: (sessionID: string) => string | undefined + shells: readonly { id: string; label: string; started?: number }[] +}): AgentProgressItem[] { + const calls = subagentCalls(input.messages) + const children = input.sessions.filter((info) => info.parentID === input.owner) + const known = new Set(children.map((info) => info.id)) + + const fromSessions = children.map((info): AgentProgressItem => { + const call = calls.bySession.get(info.id) + const running = input.status(info.id) === "running" + // Created but not yet started: no run has ended either. + const pending = !running && info.outcome === undefined && info.time.idle === undefined && !call?.finished + + const state: AgentProgressState = input.needsYou(info.id) + ? "needs-you" + : running || pending + ? "running" + : call?.finished === "error" || info.outcome === "failed" + ? "failed" + : call?.finished === "cancelled" || info.outcome === "interrupted" + ? "stopped" + : "done" + + return { + key: info.id, + type: "subagent", + state, + title: info.title ?? call?.title ?? info.id, + agent: info.agent ?? call?.agent, + model: info.model, + sessionID: info.id, + target: call?.partID ?? info.id, + // The latest call into the child is this run; a resumed child was created long before it. + started: call?.started ?? info.time.created, + ended: activeState(state) ? undefined : (info.time.idle ?? call?.ended ?? info.time.updated), + error: state === "failed" ? (input.childError(info.id) ?? call?.error) : undefined, + } + }) + + // Calls whose child session this client hasn't loaded, and calls still starting their child. + const fromCalls = calls.list.flatMap((call): AgentProgressItem[] => { + if (call.sessionID && known.has(call.sessionID)) return [] + + const state: AgentProgressState = + call.sessionID && input.needsYou(call.sessionID) + ? "needs-you" + : call.finished === "error" + ? "failed" + : call.finished === "cancelled" + ? "stopped" + : call.finished + ? "done" + : call.sessionID + ? "running" + : "starting" + + return [ + { + key: call.sessionID ?? call.partID, + type: "subagent", + state, + title: call.title, + agent: call.agent, + sessionID: call.sessionID, + target: call.partID, + started: call.started, + ended: activeState(state) ? undefined : call.ended, + error: call.error, + }, + ] + }) + + return [ + ...currentBatch([...fromSessions, ...fromCalls]), + ...input.shells.map( + (shell): AgentProgressItem => ({ + key: shell.id, + type: "shell", + state: "running", + title: shell.label, + target: shell.id, + started: shell.started, + }), + ), + ] +} + +// The subagents since the last moment none was running, in start order. +export function currentBatch(items: readonly AgentProgressItem[]) { + const sorted = items.toSorted((a, b) => (a.started ?? Infinity) - (b.started ?? Infinity)) + + const reach = (item: AgentProgressItem) => + activeState(item.state) ? Infinity : (item.ended ?? item.started ?? Infinity) + + const start = sorted.reduce( + (acc, item, index) => { + const begins = index > 0 && (item.started ?? Infinity) > acc.reach + + return { start: begins ? index : acc.start, reach: Math.max(begins ? -Infinity : acc.reach, reach(item)) } + }, + { start: 0, reach: -Infinity }, + ).start + + return sorted.slice(start) +} + +export type AgentProgressCounts = { + total: number + running: number + needsYou: number + failed: number + done: number +} + +export function agentProgressCounts(items: readonly AgentProgressItem[]): AgentProgressCounts { + return { + total: items.length, + running: items.filter((item) => item.state === "running" || item.state === "starting").length, + needsYou: items.filter((item) => item.state === "needs-you").length, + failed: items.filter((item) => item.state === "failed").length, + done: items.filter((item) => item.state === "done" || item.state === "stopped").length, + } +} + +type SubagentCall = { + partID: string + sessionID?: string + title: string + agent?: string + started: number + ended?: number + finished?: "completed" | "error" | "cancelled" + error?: string +} + +// Subagent tool calls in the owner's messages, settled by their own result (foreground) or by the completion notice +// a background subagent posts to its parent. +function subagentCalls(messages: readonly SessionMessageInfo[]) { + const notices = new Map( + messages.flatMap((message) => { + if (message.type !== "synthetic") return [] + + return Option.match(decodeNotice(message.metadata), { + onNone: () => [], + onSome: (notice) => { + const finished = notice.state === "error" || notice.state === "cancelled" ? notice.state : "completed" + + return [ + [ + notice.childID, + { finished, ended: message.time.created, error: noticeError(message.text, finished) }, + ] as const, + ] + }, + }) + }), + ) + + const list = messages.flatMap((message) => + message.type !== "assistant" + ? [] + : message.content.flatMap((part): SubagentCall[] => { + if (part.type !== "tool" || part.name !== "subagent") return [] + const input = Option.getOrUndefined(decodeCallInput(part.state.input)) + + const metadata = Option.getOrUndefined( + decodeCallMetadata(part.state.status === "streaming" ? undefined : part.state.metadata), + ) + + const sessionID = metadata?.sessionID + const notice = sessionID ? notices.get(sessionID) : undefined + // A background call completes at once with `status: "running"`; its notice settles it later. + const background = part.state.status === "completed" && metadata?.status === "running" + const settled = part.state.status === "error" || (part.state.status === "completed" && !background) + + return [ + { + partID: part.id, + sessionID, + title: input?.description ?? sessionID ?? part.id, + agent: input?.agent, + started: part.time.created, + ended: background ? notice?.ended : (part.time.completed ?? notice?.ended), + finished: settled ? (part.state.status === "error" ? "error" : "completed") : notice?.finished, + error: part.state.status === "error" ? part.state.error.message : notice?.error, + }, + ] + }), + ) + + return { list, bySession: new Map(list.flatMap((call) => (call.sessionID ? [[call.sessionID, call]] : []))) } +} + +const decodeNotice = Schema.decodeUnknownOption( + Schema.Struct({ + source: Schema.Literal("subagent"), + childID: Schema.String, + state: Schema.optional(Schema.String), + }), +) + +const decodeCallInput = Schema.decodeUnknownOption( + Schema.Struct({ description: Schema.optional(Schema.String), agent: Schema.optional(Schema.String) }), +) + +const decodeCallMetadata = Schema.decodeUnknownOption( + Schema.Struct({ sessionID: Schema.optional(Schema.String), status: Schema.optional(Schema.String) }), +) + +// The notice wraps the failure as `\n{error}\n`. +function noticeError(text: string, finished: string) { + if (finished !== "error") return + + return text.match(/^]*>\n([\s\S]*)\n<\/subagent>$/)?.[1]?.trim() || undefined +} + +export function formatElapsed(ms: number) { + const seconds = Math.max(0, Math.floor(ms / 1000)) + + if (seconds < 60) return `${seconds}s` + const minutes = Math.floor(seconds / 60) + + if (minutes < 60) return `${minutes}m ${seconds % 60}s` + + return `${Math.floor(minutes / 60)}h ${minutes % 60}m` +} diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index 8aefbe4a650..b7d03f4f723 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -29,7 +29,11 @@ import { createSessionRevert } from "../revert" import { SessionComposerRegion } from "./session-composer-region" import { createSessionComposerController, type SessionComposerController } from "./controller" import { SessionQueuePanel } from "./queue-panel" -import { SessionActivityChips, type SessionActivityItem } from "./activity-chips" +import { AgentProgressChip } from "./agent-progress-chip" +import { activeState, agentProgressItems, type AgentProgressItem } from "./agent-progress" +import { useStopRunning } from "../header/stop-running" +import { useModels } from "@/providers/models/models" +import type { ModelRef } from "@opencode/client/promise" import { useOpenSessionRoute } from "../session-identity-header" import { resolveSessionComposerSelection } from "./selection" import { createSessionRequestModel } from "../requests/model" @@ -298,7 +302,10 @@ export function ActiveSessionComposerRegion(props: { }) { const location = useWorkspaceLocation() const data = useData() + const models = useModels() const openRoute = useOpenSessionRoute() + const stop = useStopRunning() + const server = useServerSDK() // Only the server's LocationNotFoundError for the session's own Location replaces the composer. const missing = createMemo(() => { @@ -310,43 +317,53 @@ export function ActiveSessionComposerRegion(props: { return { directory: info.location.directory, sessionID: info.id, projectID: info.projectID } }) - // Subagents count while their call still blocks the run; foreground shells stay out, the timeline shows them. - const subagents = createMemo(() => [ - ...props.model.region.state.background.blocking().flatMap((task) => - task.type === "subagent" - ? [ - { - ...task, - key: task.id ?? task.partID, - agent: task.id ? data.session.get(task.id)?.agent : undefined, - sessionID: task.id, - target: task.partID, - }, - ] - : [], - ), - ...props.model.region.state.background.tasks().flatMap((task) => - task.type === "subagent" - ? [ - { - ...task, - key: task.id, - agent: task.agent ?? data.session.get(task.id)?.agent, - sessionID: task.id, - target: task.id, - }, - ] - : [], - ), - ]) + // The current batch of subagents, kept while any runs or the run that started them still works. Background + // shells ride along; foreground shells stay out, the timeline shows them. + const progress = createMemo(() => { + const owner = props.session.identity.params.id - const shells = createMemo(() => - props.model.region.state.background - .tasks() - .flatMap((task) => (task.type === "shell" ? [{ ...task, key: task.id, target: task.id }] : [])), + if (!owner || props.session.data.isChild()) return [] + + const items = agentProgressItems({ + owner, + sessions: data.session.list(), + status: data.session.status, + needsYou: (sessionID) => + !!data.session.permission.list(sessionID)?.length || + !!data.session.form.list(sessionID)?.some((form) => form.metadata?.kind === "question"), + messages: data.session.message.list(owner) ?? [], + childError: (sessionID) => + data.session.message + .list(sessionID) + ?.flatMap((message) => (message.type === "idle" && message.outcome === "failed" ? [message] : [])) + .at(-1)?.error?.message, + shells: props.model.region.state.background + .tasks() + .flatMap((task) => + task.type === "shell" ? [{ ...task, started: data.shell.get(task.id)?.time.started }] : [], + ), + }) + + if (items.some((item) => activeState(item.state)) || data.session.status(owner) === "running") return items + + return [] + }) + + // Requests on running children arrive as events; ones raised before this client connected need a read. + createEffect( + on( + () => + server.connection.status() === "connected" + ? progress().flatMap((item) => (item.sessionID && item.state === "running" ? [item.sessionID] : [])) + : [], + (ids) => ids.forEach((id) => void data.session.permission.sync(id).catch(() => undefined)), + ), ) - const open = (item: SessionActivityItem) => { + const modelName = (model: ModelRef) => + models.find({ providerID: model.providerID, modelID: model.id })?.name ?? model.id + + const open = (item: AgentProgressItem) => { const current = props.session.identity.params.id if (!current) return @@ -358,13 +375,13 @@ export function ActiveSessionComposerRegion(props: { return ( } composer={ -
+ {props.above} diff --git a/packages/app/src/session/header/session-running-menu.tsx b/packages/app/src/session/header/session-running-menu.tsx index 133f9b49999..05b54eea25a 100644 --- a/packages/app/src/session/header/session-running-menu.tsx +++ b/packages/app/src/session/header/session-running-menu.tsx @@ -8,12 +8,10 @@ import { createEffect, createMemo, createUniqueId, For, on, Show } from "solid-j import { createStore } from "solid-js/store" import { createAnimatedPresence } from "@/runtime/animated-presence" import { useLanguage } from "@/runtime/i18n/language" -import { useServerSDK } from "@/runtime/server/client" import { useServer } from "@/runtime/server/current" import { useOpenSessionRoute } from "@/session/session-identity-header" -import { errorMessage } from "@/shell/layout/helpers" -import { showToast } from "@/shell/notifications/toast" import { SessionWorkingIndicator } from "./session-working-indicator" +import { useStopRunning } from "./stop-running" const neutral = "light-dark(var(--v2-text-text-base), #ffffff)" @@ -38,7 +36,6 @@ export function SessionRunningMenu(props: { const language = useLanguage() const openRoute = useOpenSessionRoute() const server = useServer() - const sdk = useServerSDK() const id = createUniqueId() const [menu, setMenu] = createStore({ open: false }) @@ -129,21 +126,7 @@ export function SessionRunningMenu(props: { // A subagent can only be interrupted once its child session exists. const stoppable = (item: RunningItem) => item.type === "shell" || !!item.sessionID - const stop = (item: RunningItem) => { - const request = item.sessionID - ? sdk.api.session.interrupt({ sessionID: item.sessionID }) - : sdk.api.shell.remove({ - id: item.target, - location: { directory: server.ctx.data.shell.get(item.target)?.location.directory }, - }) - - void request.catch((error) => - showToast({ - title: language.t("common.requestFailed"), - description: errorMessage(error, language.t("common.requestFailed")), - }), - ) - } + const stop = useStopRunning() return ( diff --git a/packages/app/src/session/header/stop-running.ts b/packages/app/src/session/header/stop-running.ts new file mode 100644 index 00000000000..901558ef815 --- /dev/null +++ b/packages/app/src/session/header/stop-running.ts @@ -0,0 +1,28 @@ +import { useLanguage } from "@/runtime/i18n/language" +import { useServerSDK } from "@/runtime/server/client" +import { useServer } from "@/runtime/server/current" +import { errorMessage } from "@/shell/layout/helpers" +import { showToast } from "@/shell/notifications/toast" + +// Interrupts a subagent's child session or removes a background shell. +export function useStopRunning() { + const language = useLanguage() + const server = useServer() + const sdk = useServerSDK() + + return (item: { sessionID?: string; target: string }) => { + const request = item.sessionID + ? sdk.api.session.interrupt({ sessionID: item.sessionID }) + : sdk.api.shell.remove({ + id: item.target, + location: { directory: server.ctx.data.shell.get(item.target)?.location.directory }, + }) + + void request.catch((error) => + showToast({ + title: language.t("common.requestFailed"), + description: errorMessage(error, language.t("common.requestFailed")), + }), + ) + } +} diff --git a/packages/app/src/session/story-model.tsx b/packages/app/src/session/story-model.tsx index 892ba29661b..b2b774081a3 100644 --- a/packages/app/src/session/story-model.tsx +++ b/packages/app/src/session/story-model.tsx @@ -6,7 +6,8 @@ import { SessionComposerRegion, type SessionComposerRegionViewController, } from "@/session/composer/session-composer-region" -import { SessionActivityChips, type SessionActivityItem } from "@/session/composer/activity-chips" +import { AgentProgressChip } from "@/session/composer/agent-progress-chip" +import type { AgentProgressItem } from "@/session/composer/agent-progress" import { SessionPanelFrame, SessionRouteFrame } from "@/session/session-frame" import type { FormInfo, PermissionRequest, SessionStatus } from "@opencode/client/promise" import type { SessionDocument } from "@opencode/session-ui/document" @@ -87,9 +88,12 @@ export type SessionPreviewProps = { reviewOpened?: boolean child?: { parentID: string } activity?: { - subagents: SessionActivityItem[] - shells: SessionActivityItem[] - onOpen?: (item: SessionActivityItem) => void + items: readonly AgentProgressItem[] + onOpen?: (item: AgentProgressItem) => void + onStop?: (item: AgentProgressItem) => void + open?: boolean + onOpenChange?: (open: boolean) => void + now?: () => number } timelineDetail?: TimelineDetail } @@ -284,17 +288,27 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
model.id} + open={props.activity?.open} + onOpenChange={props.activity?.onOpenChange} + now={props.activity?.now} + onOpen={(item) => + props.activity?.onOpen + ? props.activity.onOpen(item) + : setState("activity", `Opened ${item.title}`) + } + onStop={(item) => + props.activity?.onStop + ? props.activity.onStop(item) + : setState("activity", `Stopped ${item.title}`) + } + /> + } composer={
- - props.activity?.onOpen - ? props.activity.onOpen(item) - : setState("activity", `Opened ${item.label ?? item.key}`) - } - />