mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
feat(app): progress chip for subagent work above the composer
This commit is contained in:
parent
4492fe5e07
commit
80f95c2737
20 changed files with 3377 additions and 554 deletions
50
packages/app/component-tests/agent-progress-chip.spec.ts
Normal file
50
packages/app/component-tests/agent-progress-chip.spec.ts
Normal file
|
|
@ -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)
|
||||
})
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
20
packages/app/src/session/agent-glyph/agent-glyph.css
Normal file
20
packages/app/src/session/agent-glyph/agent-glyph.css
Normal file
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
150
packages/app/src/session/agent-glyph/agent-glyph.tsx
Normal file
150
packages/app/src/session/agent-glyph/agent-glyph.tsx
Normal file
|
|
@ -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 (
|
||||
<span
|
||||
data-component="agent-glyph"
|
||||
data-activity={props.activity}
|
||||
class={props.class}
|
||||
style={{ width: `${size()}px`, height: `${size()}px` }}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<canvas ref={canvas} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
41
packages/app/src/session/agent-glyph/gyro.test.ts
Normal file
41
packages/app/src/session/agent-glyph/gyro.test.ts
Normal file
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
1257
packages/app/src/session/agent-glyph/gyro.ts
Normal file
1257
packages/app/src/session/agent-glyph/gyro.ts
Normal file
File diff suppressed because it is too large
Load diff
239
packages/app/src/session/agent-glyph/orb.ts
Normal file
239
packages/app/src/session/agent-glyph/orb.ts
Normal file
|
|
@ -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<ActivityAccent, [RGB, RGB]>
|
||||
hot: Record<ActivityAccent, [RGB, RGB]>
|
||||
}
|
||||
|
||||
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<string, RGB>()
|
||||
|
||||
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<ActivityAccent, [RGB, RGB]>
|
||||
|
||||
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<ActivityAccent, number>): [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],
|
||||
)
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<SessionPreview
|
||||
title="Run background work"
|
||||
description="opencode · activity chips"
|
||||
document={value}
|
||||
timelineDetail={timelineDetail}
|
||||
activity={{
|
||||
subagents: Array.from({ length: subagentCount }, (_, index) => 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 (
|
||||
<SessionPreview
|
||||
title="Audit the activity chips"
|
||||
description="opencode · activity chips"
|
||||
document={value()}
|
||||
timelineDetail={timelineDetail}
|
||||
activity={{
|
||||
subagents: subagents
|
||||
.slice(stage().finished, stage().started)
|
||||
.map((_, index) => 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<HTMLElement>('[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: () => <LiveActivity /> }
|
||||
|
|
@ -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 (
|
||||
<Show when={props.subagents.length > 0 || props.shells.length > 0}>
|
||||
<div data-component="session-activity-chips" class="flex items-center pb-2">
|
||||
<Menu gutter={6} placement="top-start">
|
||||
<Menu.Trigger
|
||||
as="button"
|
||||
type="button"
|
||||
data-slot="session-activity-chip"
|
||||
class="flex h-7 min-w-0 max-w-full items-center gap-1.5 rounded-full border border-v2-border-border-base bg-v2-background-bg-base ps-2 pe-2.5 text-[13px] font-[530] leading-text-compact tracking-[-0.04px] whitespace-nowrap tabular-nums text-v2-text-text-base shadow-[var(--v2-elevation-raised)] outline-none duration-150 ease-out animate-in fade-in motion-reduce:animate-none hover:bg-v2-background-bg-layer-01 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-v2-border-border-focus"
|
||||
>
|
||||
<SessionActivityGlyph />
|
||||
<span class="truncate">{label()}</span>
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content data-slot="session-activity-panel" aria-label={label()}>
|
||||
<Show when={props.subagents.length > 0}>
|
||||
<Menu.Group>
|
||||
<Show when={both()}>
|
||||
<Menu.GroupLabel>{language.t("session.activity.section.subagents")}</Menu.GroupLabel>
|
||||
</Show>
|
||||
<For each={props.subagents}>
|
||||
{(item) => (
|
||||
<Menu.Item onSelect={() => props.onOpen(item)}>
|
||||
<SessionActivityGlyph class="text-v2-icon-icon-muted" />
|
||||
<span class="shrink-0 font-[530]">
|
||||
{item.agent
|
||||
? `${item.agent[0].toUpperCase()}${item.agent.slice(1)}`
|
||||
: language.t("ui.tool.agent.default")}
|
||||
</span>
|
||||
<span dir="auto" class="me-1.5 min-w-0 flex-1 truncate text-v2-text-text-muted">
|
||||
{item.label}
|
||||
</span>
|
||||
</Menu.Item>
|
||||
)}
|
||||
</For>
|
||||
</Menu.Group>
|
||||
</Show>
|
||||
<Show when={both()}>
|
||||
<Menu.Separator />
|
||||
</Show>
|
||||
<Show when={props.shells.length > 0}>
|
||||
<Menu.Group>
|
||||
<Show when={both()}>
|
||||
<Menu.GroupLabel>{language.t("session.activity.section.shells")}</Menu.GroupLabel>
|
||||
</Show>
|
||||
<For each={props.shells}>
|
||||
{(item) => (
|
||||
<Menu.Item onSelect={() => props.onOpen(item)}>
|
||||
<Icon name="console" class="shrink-0 text-v2-icon-icon-muted" />
|
||||
<span
|
||||
dir="ltr"
|
||||
class="me-1.5 min-w-0 flex-1 truncate font-mono text-[12px] text-v2-text-text-base"
|
||||
>
|
||||
{item.label}
|
||||
</span>
|
||||
</Menu.Item>
|
||||
)}
|
||||
</For>
|
||||
</Menu.Group>
|
||||
</Show>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu>
|
||||
</div>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<svg
|
||||
data-component="session-activity-glyph"
|
||||
class={props.class}
|
||||
width={15}
|
||||
height={15}
|
||||
viewBox="0 0 5 5"
|
||||
aria-hidden="true"
|
||||
style={{ "--session-activity-glyph-phase": phase }}
|
||||
>
|
||||
<Index each={Array.from({ length: 25 })}>
|
||||
{(_, index) => (
|
||||
<circle
|
||||
data-dot
|
||||
cx={(index % 5) + 0.5}
|
||||
cy={Math.floor(index / 5) + 0.5}
|
||||
r={0.31}
|
||||
style={{ "--diagonal": (index % 5) + Math.floor(index / 5) }}
|
||||
/>
|
||||
)}
|
||||
</Index>
|
||||
<circle data-reduced-motion cx={2.5} cy={2.5} r={0.75} />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
266
packages/app/src/session/composer/agent-progress-chip.css
Normal file
266
packages/app/src/session/composer/agent-progress-chip.css
Normal file
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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> = {}): 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) =>
|
||||
() => (
|
||||
<SessionPreview
|
||||
title="Keep the agents moving"
|
||||
description="opencode · agent progress"
|
||||
document={document}
|
||||
timelineDetail={timelineDetail}
|
||||
activity={{ items, open: open || undefined, now: () => 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<string, (value?: number) => 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 (
|
||||
<>
|
||||
<SessionPreview
|
||||
title="Keep the agents moving"
|
||||
description="opencode · agent progress"
|
||||
document={document}
|
||||
timelineDetail={timelineDetail}
|
||||
activity={{
|
||||
items: story.items,
|
||||
open: story.open,
|
||||
onOpenChange: (open) => setStory("open", open),
|
||||
onStop: (value) =>
|
||||
setStory(
|
||||
"items",
|
||||
(entry) => entry.key === value.key,
|
||||
produce((draft) => {
|
||||
draft.state = "stopped"
|
||||
draft.ended = Date.now()
|
||||
}),
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<div data-story-toolbar class="fixed end-3 top-3 z-50 flex flex-wrap gap-1">
|
||||
<For
|
||||
each={
|
||||
[
|
||||
["+1", () => 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]) => (
|
||||
<button
|
||||
type="button"
|
||||
class="h-6 rounded-[4px] bg-v2-background-bg-layer-02 px-2 text-[11px] font-[530] text-v2-text-text-base hover:bg-v2-overlay-simple-overlay-hover"
|
||||
onClick={run}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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: () => <LiveAgents /> }
|
||||
580
packages/app/src/session/composer/agent-progress-chip.tsx
Normal file
580
packages/app/src/session/composer/agent-progress-chip.tsx
Normal file
|
|
@ -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 (
|
||||
<Show when={mounted()}>
|
||||
<AgentProgressBody
|
||||
{...props}
|
||||
items={held()}
|
||||
surface={(element) => {
|
||||
surface = element
|
||||
}}
|
||||
/>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
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<AgentActivity>(() => {
|
||||
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 }) => (
|
||||
<Show when={byKey().get(row.key)}>
|
||||
{(item) => (
|
||||
<Row
|
||||
item={item()}
|
||||
model={item().model ? props.modelName?.(item().model!) : undefined}
|
||||
elapsed={elapsed(item())}
|
||||
paused={!open()}
|
||||
stoppable={stoppable(item())}
|
||||
onOpen={() => openItem(item())}
|
||||
onStop={() => props.onStop(item())}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
|
||||
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 (
|
||||
<div
|
||||
ref={(element) => setRefs("root", element)}
|
||||
data-component="agent-progress"
|
||||
data-open={open() ? "" : undefined}
|
||||
>
|
||||
<div
|
||||
ref={(element) => {
|
||||
setRefs("surface", element)
|
||||
props.surface(element)
|
||||
}}
|
||||
data-slot="agent-progress-surface"
|
||||
data-needs-you={counts().needsYou ? "" : undefined}
|
||||
>
|
||||
<div
|
||||
ref={(element) => setRefs("panel", element)}
|
||||
id="agent-progress-panel"
|
||||
data-slot="agent-progress-panel"
|
||||
role="group"
|
||||
aria-label={language.t("session.agents.panel")}
|
||||
inert={!open()}
|
||||
>
|
||||
<div data-slot="agent-progress-header">
|
||||
<span class="min-w-0 flex-1 truncate">{header()}</span>
|
||||
<Show when={running().some(stoppable) || needsYou().some(stoppable)}>
|
||||
<button type="button" data-slot="agent-progress-stop-all" onClick={stopAll}>
|
||||
{language.t("session.agents.stopAll")}
|
||||
</button>
|
||||
</Show>
|
||||
</div>
|
||||
<div data-slot="agent-progress-rows">
|
||||
<For each={activeKeys()}>{(key) => <KeyedRow key={key} />}</For>
|
||||
<Show when={doneKeys().length}>
|
||||
<button
|
||||
type="button"
|
||||
data-slot="agent-progress-done-toggle"
|
||||
aria-expanded={local.doneExpanded}
|
||||
onClick={() => setLocal("doneExpanded", (value) => !value)}
|
||||
>
|
||||
<Icon name="check-small" class="shrink-0 text-v2-icon-icon-muted" />
|
||||
<span>{language.t("session.agents.done", { count: doneKeys().length })}</span>
|
||||
<Icon name="chevron-right" data-slot="agent-progress-chevron" />
|
||||
</button>
|
||||
<Show when={local.doneExpanded}>
|
||||
<For each={doneKeys()}>{(key) => <KeyedRow key={key} />}</For>
|
||||
</Show>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
ref={(element) => setRefs("chip", element)}
|
||||
type="button"
|
||||
data-slot="agent-progress-chip"
|
||||
aria-expanded={open()}
|
||||
aria-controls="agent-progress-panel"
|
||||
aria-label={summaryText()}
|
||||
onClick={() => setOpen(!open())}
|
||||
>
|
||||
<span ref={(element) => setRefs("content", element)} data-slot="agent-progress-chip-content">
|
||||
<AgentGlyph activity={single() ? glyph[single()!.state] : summary()} size={16} />
|
||||
<Show
|
||||
when={single()}
|
||||
fallback={
|
||||
<>
|
||||
<span>{label()}</span>
|
||||
<Show when={counts().failed}>
|
||||
<span data-slot="agent-progress-failed">
|
||||
· {language.t("session.agents.failed", { count: counts().failed })}
|
||||
</span>
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{(item) => (
|
||||
<>
|
||||
<span dir="auto" class="truncate">
|
||||
{item().title}
|
||||
</span>
|
||||
<span data-slot="agent-progress-elapsed">{singleStatus(item())}</span>
|
||||
</>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={counts().needsYou}>
|
||||
<span data-slot="agent-progress-needs-you">
|
||||
· {language.plural("session.agents.needsYou", counts().needsYou)}
|
||||
</span>
|
||||
</Show>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div data-slot="agent-progress-row" data-state={state()}>
|
||||
<button type="button" data-slot="agent-progress-row-open" onClick={props.onOpen}>
|
||||
<Show
|
||||
when={props.item.type === "subagent"}
|
||||
fallback={<Icon name="console" class="shrink-0 text-v2-icon-icon-muted" />}
|
||||
>
|
||||
<AgentGlyph activity={glyph[state()]} from={from} size={16} paused={props.paused} />
|
||||
</Show>
|
||||
<span dir="auto" data-slot="agent-progress-title">
|
||||
{props.item.title}
|
||||
</span>
|
||||
<span data-slot="agent-progress-meta">{meta()}</span>
|
||||
</button>
|
||||
<span data-slot="agent-progress-trailing">
|
||||
<Switch
|
||||
fallback={
|
||||
<>
|
||||
<span data-slot="agent-progress-elapsed">
|
||||
{state() === "starting" ? language.t("session.agents.state.starting") : props.elapsed}
|
||||
</span>
|
||||
<Show when={props.stoppable}>
|
||||
<IconButton
|
||||
type="button"
|
||||
size="small"
|
||||
variant="ghost-muted"
|
||||
icon={<Icon name="outline-xmark" />}
|
||||
aria-label={language.t(
|
||||
props.item.type === "shell" ? "session.running.stop.shell" : "session.running.stop.subagent",
|
||||
)}
|
||||
onClick={props.onStop}
|
||||
/>
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Match when={state() === "needs-you"}>
|
||||
<button type="button" data-slot="agent-progress-review" onClick={props.onOpen}>
|
||||
{language.t("session.agents.review")}
|
||||
</button>
|
||||
</Match>
|
||||
<Match when={state() === "failed"}>
|
||||
<span data-slot="agent-progress-error" title={props.item.error}>
|
||||
{props.item.error ?? language.t("session.agents.state.failed")}
|
||||
</span>
|
||||
</Match>
|
||||
<Match when={state() === "done" || state() === "stopped"}>
|
||||
<span data-slot="agent-progress-elapsed">
|
||||
{state() === "stopped" ? language.t("session.agents.state.stopped") : props.elapsed}
|
||||
</span>
|
||||
</Match>
|
||||
</Switch>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Each row's glyph design: the iOS subagent states, without its live event ledger (so no tool or output bursts).
|
||||
const glyph: Record<AgentProgressState, AgentActivity> = {
|
||||
"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?.())
|
||||
}
|
||||
130
packages/app/src/session/composer/agent-progress.test.ts
Normal file
130
packages/app/src/session/composer/agent-progress.test.ts
Normal file
|
|
@ -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<SessionInfo> & { 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<string, string>
|
||||
}) =>
|
||||
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: '<subagent sessionID="ses_bg" state="error" description="Trace voice settings">\nProvider rate limit\n</subagent>',
|
||||
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"])
|
||||
})
|
||||
259
packages/app/src/session/composer/agent-progress.ts
Normal file
259
packages/app/src/session/composer/agent-progress.ts
Normal file
|
|
@ -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 `<subagent …>\n{error}\n</subagent>`.
|
||||
function noticeError(text: string, finished: string) {
|
||||
if (finished !== "error") return
|
||||
|
||||
return text.match(/^<subagent[^>]*>\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`
|
||||
}
|
||||
|
|
@ -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<SessionActivityItem[]>(() => [
|
||||
...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<AgentProgressItem[]>(() => {
|
||||
const owner = props.session.identity.params.id
|
||||
|
||||
const shells = createMemo<SessionActivityItem[]>(() =>
|
||||
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 (
|
||||
<SessionComposerRegion
|
||||
controller={props.model.region}
|
||||
above={<AgentProgressChip items={progress()} modelName={modelName} onOpen={open} onStop={stop} />}
|
||||
composer={
|
||||
<Show
|
||||
when={missing()}
|
||||
keyed
|
||||
fallback={
|
||||
<div class="relative">
|
||||
<SessionActivityChips subagents={subagents()} shells={shells()} onOpen={open} />
|
||||
<SessionQueuePanel queue={props.model.queue} />
|
||||
<div class="relative z-10">
|
||||
<Composer
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ export type SessionComposerRegionViewController = Pick<
|
|||
export function SessionComposerRegion(props: {
|
||||
controller: SessionComposerRegionViewController
|
||||
composer: JSX.Element
|
||||
// Above the docks too: work that needs you stays in view while its request asks.
|
||||
above?: JSX.Element
|
||||
}) {
|
||||
const language = useLanguage()
|
||||
const controller = props.controller
|
||||
|
|
@ -34,6 +36,7 @@ export function SessionComposerRegion(props: {
|
|||
"md:max-w-session md:mx-auto": controller.centered(),
|
||||
}}
|
||||
>
|
||||
<Show when={!controller.child()}>{props.above}</Show>
|
||||
<Show when={controller.state.websearch.request()}>
|
||||
<SessionWebSearchDock model={controller.state.websearch} onSubmit={controller.onResponseSubmit} />
|
||||
</Show>
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<Show when={props.title || presence.present()}>
|
||||
|
|
|
|||
28
packages/app/src/session/header/stop-running.ts
Normal file
28
packages/app/src/session/header/stop-running.ts
Normal file
|
|
@ -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")),
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
|||
</div>
|
||||
<SessionComposerRegion
|
||||
controller={region}
|
||||
above={
|
||||
<AgentProgressChip
|
||||
items={props.activity?.items ?? []}
|
||||
modelName={(model) => 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={
|
||||
<div class="relative">
|
||||
<SessionActivityChips
|
||||
subagents={props.activity?.subagents ?? []}
|
||||
shells={props.activity?.shells ?? []}
|
||||
onOpen={(item) =>
|
||||
props.activity?.onOpen
|
||||
? props.activity.onOpen(item)
|
||||
: setState("activity", `Opened ${item.label ?? item.key}`)
|
||||
}
|
||||
/>
|
||||
<div class="relative z-10">
|
||||
<Composer model={prompt.controller} borderUnderlay />
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue