Compare commits

..
Author SHA1 Message Date
Kit Langton d30ec60481 feat(server): run modal sandboxes on the vm runtime 2026-08-07 21:58:46 -04:00
16 changed files with 194 additions and 423 deletions
+101
View File
@@ -0,0 +1,101 @@
export * as Account from "./account"
import { Schema } from "effect"
import type { HttpClientError } from "effect/unstable/http"
export const ID = Schema.String.pipe(Schema.brand("AccountID"))
export type ID = Schema.Schema.Type<typeof ID>
export const OrgID = Schema.String.pipe(Schema.brand("OrgID"))
export type OrgID = Schema.Schema.Type<typeof OrgID>
export const AccessToken = Schema.String.pipe(Schema.brand("AccessToken"))
export type AccessToken = Schema.Schema.Type<typeof AccessToken>
export const RefreshToken = Schema.String.pipe(Schema.brand("RefreshToken"))
export type RefreshToken = Schema.Schema.Type<typeof RefreshToken>
export const DeviceCode = Schema.String.pipe(Schema.brand("DeviceCode"))
export type DeviceCode = Schema.Schema.Type<typeof DeviceCode>
export const UserCode = Schema.String.pipe(Schema.brand("UserCode"))
export type UserCode = Schema.Schema.Type<typeof UserCode>
export class Info extends Schema.Class<Info>("Account")({
id: ID,
email: Schema.String,
url: Schema.String,
active_org_id: Schema.NullOr(OrgID),
}) {}
export class Org extends Schema.Class<Org>("Org")({
id: OrgID,
name: Schema.String,
}) {}
export class AccountRepoError extends Schema.TaggedErrorClass<AccountRepoError>()("AccountRepoError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class AccountServiceError extends Schema.TaggedErrorClass<AccountServiceError>()("AccountServiceError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class AccountTransportError extends Schema.TaggedErrorClass<AccountTransportError>()("AccountTransportError", {
method: Schema.String,
url: Schema.String,
description: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
}) {
static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError {
return new AccountTransportError({
method: error.request.method,
url: error.request.url,
description: error.description,
cause: error.cause,
})
}
override get message(): string {
return [
`Could not reach ${this.method} ${this.url}.`,
`This failed before the server returned an HTTP response.`,
this.description,
`Check your network, proxy, or VPN configuration and try again.`,
]
.filter(Boolean)
.join("\n")
}
}
export type AccountError = AccountRepoError | AccountServiceError | AccountTransportError
export class Login extends Schema.Class<Login>("Login")({
code: DeviceCode,
user: UserCode,
url: Schema.String,
server: Schema.String,
expiry: Schema.Duration,
interval: Schema.Duration,
}) {}
export class PollSuccess extends Schema.TaggedClass<PollSuccess>()("PollSuccess", {
email: Schema.String,
}) {}
export class PollPending extends Schema.TaggedClass<PollPending>()("PollPending", {}) {}
export class PollSlow extends Schema.TaggedClass<PollSlow>()("PollSlow", {}) {}
export class PollExpired extends Schema.TaggedClass<PollExpired>()("PollExpired", {}) {}
export class PollDenied extends Schema.TaggedClass<PollDenied>()("PollDenied", {}) {}
export class PollError extends Schema.TaggedClass<PollError>()("PollError", {
cause: Schema.Defect(),
}) {}
export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError])
export type PollResult = Schema.Schema.Type<typeof PollResult>
+10 -7
View File
@@ -1,21 +1,24 @@
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core"
import { Account } from "../account"
import { Timestamps } from "../database/schema.sql"
export const AccountTable = sqliteTable("account", {
id: text().primaryKey(),
id: text().$type<Account.ID>().primaryKey(),
email: text().notNull(),
url: text().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
token_expiry: integer(),
...Timestamps,
})
export const AccountStateTable = sqliteTable("account_state", {
id: integer().primaryKey(),
active_account_id: text().references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text(),
active_account_id: text()
.$type<Account.ID>()
.references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text().$type<Account.OrgID>(),
})
// LEGACY
@@ -24,8 +27,8 @@ export const ControlAccountTable = sqliteTable(
{
email: text().notNull(),
url: text().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
token_expiry: integer(),
active: integer({ mode: "boolean" })
.notNull()
+15 -9
View File
@@ -3,6 +3,7 @@ export * as PatchTool from "./patch"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff"
import { createTwoFilesPatch, diffLines } from "diff"
import { Effect, Result, Schema } from "effect"
import path from "path"
import { Bom } from "@opencode-ai/util/bom"
@@ -14,7 +15,6 @@ import { Location } from "../../location"
import { Patch } from "@opencode-ai/util/patch"
import { Permission } from "../../permission"
import DESCRIPTION from "../patch.txt"
import { fileDiff } from "./file-diff"
export const name = "patch"
@@ -353,16 +353,22 @@ function errorMessage(error: unknown) {
function patchFile(change: Prepared, after = change.after): typeof FileDiff.Info.Type {
const target = (change.type === "update" ? change.moveTarget : undefined)?.resource ?? change.target.resource
const diff = fileDiff(
change.target.absolute,
change.before,
after,
change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
)
const patch = trimDiff(createTwoFilesPatch(change.target.absolute, change.target.absolute, change.before, after))
const counts =
change.type === "delete"
? { additions: 0, deletions: change.before.split("\n").length }
: diffLines(change.before, after).reduce(
(result, item) => ({
additions: result.additions + (item.added ? (item.count ?? 0) : 0),
deletions: result.deletions + (item.removed ? (item.count ?? 0) : 0),
}),
{ additions: 0, deletions: 0 },
)
return {
...diff,
file: target,
patch: trimDiff(diff.patch),
patch,
status: change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
...counts,
}
}
+2 -25
View File
@@ -215,7 +215,7 @@ describe("PatchTool", () => {
file: "remove.txt",
status: "deleted",
additions: 0,
deletions: 1,
deletions: 2,
patch: expect.stringContaining("-remove"),
},
],
@@ -248,29 +248,6 @@ describe("PatchTool", () => {
),
)
it.live("counts deleted lines with and without a trailing newline", () =>
withTempTool((directory, registry) =>
Effect.gen(function* () {
yield* Effect.promise(() =>
Promise.all([
fs.writeFile(path.join(directory, "trailing.txt"), "remove\n"),
fs.writeFile(path.join(directory, "unterminated.txt"), "remove"),
]),
)
const settled = yield* executeTool(
registry,
call("*** Begin Patch\n*** Delete File: trailing.txt\n*** Delete File: unterminated.txt\n*** End Patch"),
)
expect(settled.status).toBe("completed")
if (settled.status !== "completed") return
expect(settled.output.files).toMatchObject([
{ file: "trailing.txt", additions: 0, deletions: 1 },
{ file: "unterminated.txt", additions: 0, deletions: 1 },
])
}),
),
)
it.live("serializes concurrent patch transactions", () =>
withTempTool((directory, registry) => {
const target = path.join(directory, "concurrent.txt")
@@ -469,7 +446,7 @@ describe("PatchTool", () => {
{
file: "renamed/dir/name.txt",
status: "modified",
patch: expect.stringContaining(`Index: ${source}`),
patch: expect.stringContaining("-old content\n+new content"),
},
],
})
+3 -5
View File
@@ -163,11 +163,9 @@ function drawRoutedEdge(grid: FlowchartGrid, route: FlowchartEdgeRoute): void {
cornerStyle: "rounded",
lineStyle: edge.style === "thick" ? "heavy" : "single",
})
if (edge.arrowhead !== false) {
const end = points[points.length - 1]!
const arrowFrom = points[points.length - 2]!
grid.setCell(end.x, end.y, diagramArrowHeadBetween(arrowFrom, end), style)
}
const end = points[points.length - 1]!
const arrowFrom = points[points.length - 2]!
grid.setCell(end.x, end.y, diagramArrowHeadBetween(arrowFrom, end), style)
if (edge.label) {
drawEdgeLabel(grid, route, "label")
}
@@ -424,42 +424,6 @@ flowchart TD
])
})
test("parses chained undirected solid edges", () => {
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
A --- B --- C`)
expect(diagram.edges).toEqual([
{ from: "A", to: "B", label: "", arrowhead: false },
{ from: "B", to: "C", label: "", arrowhead: false },
])
})
test("renders the volume persistence diagram with an undirected solid edge", () => {
const content = `flowchart LR
subgraph durable [Durable — survives everything]
V[(Volume ws-wor_abc<br/>mounted at /workspace)]
R[our row: id, provider]
end
subgraph ephemeral [Ephemeral — dies freely]
S1[Sandbox #1] -. mounts .-> V
S2[Sandbox #2<br/>Tuesday] -. mounts same .-> V
X[apt-get installs,<br/>~/.cache, /tmp]
end
S1 --- X
style X stroke-dasharray: 5 5`
const diagram = parseMermaidFlowchartDiagram(content)
const layout = layoutParsedFlowchartDiagram(diagram, { compact: true })
const grid = drawParsedFlowchartDiagramGrid(diagram, { compact: true })
const output = renderFlowchartDiagram(content, { compact: true })
const route = layout.routes.find((route) => route.edge.from === "S1" && route.edge.to === "X")!
const end = route.points.at(-1)!
expect(diagram.edges.at(-1)).toEqual({ from: "S1", to: "X", label: "", arrowhead: false })
expect(route.points.length).toBeGreaterThan(1)
expect(grid.getCell(end.x, end.y)?.char).not.toMatch(/[▶▼◀▲]/)
expectDiagram(output).toContainInOrder("Sandbox #1", "apt-get installs,", "~/.cache, /tmp")
})
test("parses and renders inline dashed edge labels", () => {
const content = `flowchart TD
CS[conformance suite<br/>same test cases pin every driver] -.verifies.-> LS
@@ -1017,51 +981,6 @@ flowchart LR
}
})
test("separates cross-dependent top-level subgraphs", () => {
const content = `flowchart TD
subgraph plugins["Plugins — one verb: attach"]
chip["pr-indicator<br/>attach(prompt.footer, { after: 'directory' })"]
theme["fancy-footer<br/>attach(prompt.footer, { replace: 'right' })"]
end
subgraph host["Host anatomy tree — published, stable part IDs"]
footer["prompt.footer"]
left["left"]
right["right<br/>(container)"]
dir["directory"]
model["model"]
tokens["tokens"]
footer --> left
footer --> right
right --> dir
right --> model
right --> tokens
end
chip -- "insert after" --> dir
theme == "takeover" ==> right
theme -. "suppresses guests<br/>in subtree" .-> chip`
const layout = layoutFlowchartDiagram(content)
const plugins = layout.subgraphBounds.get("plugins")!
const host = layout.subgraphBounds.get("host")!
const output = renderFlowchartDiagram(content)
const lines = output.split("\n")
expect(host.top).toBeGreaterThanOrEqual(plugins.top + plugins.height)
expect(lines.filter((line) => line.includes("Plugins — one verb: attach"))).toHaveLength(1)
expect(lines.filter((line) => line.includes("Host anatomy tree — published, stable part IDs"))).toHaveLength(1)
expect(lines.findIndex((line) => line.includes("Host anatomy tree"))).toBeGreaterThan(
lines.findIndex((line) => line.includes("Plugins — one verb")),
)
for (const route of layout.routes) {
for (let index = 1; index < route.points.length; index++) {
const from = route.points[index - 1]!
const to = route.points[index]!
expect(from.x === to.x || from.y === to.y).toBe(true)
}
}
})
test("moves subgraph labels away from crossing routes", () => {
const output = renderFlowchartDiagram(`
flowchart TD
+18 -80
View File
@@ -499,6 +499,10 @@ function edgeDirection(diagram: FlowchartDiagram, edge: FlowchartEdge): Flowchar
return diagram.direction
}
function hasLocalSubgraphDirection(diagram: FlowchartDiagram): boolean {
return (diagram.subgraphs ?? []).some((subgraph) => subgraph.direction && subgraph.direction !== diagram.direction)
}
function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string): Set<string> {
const nodeIds = new Set<string>()
for (const subgraph of diagram.subgraphs ?? []) {
@@ -511,113 +515,47 @@ function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string):
return nodeIds
}
function separateTopLevelItems(
function separateLocalSubgraphItems(
diagram: FlowchartDiagram,
nodeBounds: Map<string, FlowchartNodeBounds>,
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
gap: number,
): void {
const hasLocalDirection = (diagram.subgraphs ?? []).some(
(subgraph) => subgraph.direction && subgraph.direction !== diagram.direction,
)
if (!hasLocalSubgraphDirection(diagram)) return
const coveredNodeIds = new Set<string>()
const items: { id: string; bounds: FlowchartBounds; nodeIds: Set<string>; rank: number }[] = []
const itemByEndpoint = new Map<string, string>()
const items: { bounds: FlowchartBounds; nodeIds: Set<string> }[] = []
for (const subgraph of diagram.subgraphs ?? []) {
if (subgraph.parentId) continue
const bounds = subgraphBounds.get(subgraph.id)
const nodeIds = collectSubgraphNodeIds(diagram, subgraph.id)
if (!bounds || nodeIds.size === 0) continue
items.push({ id: subgraph.id, bounds, nodeIds, rank: 0 })
itemByEndpoint.set(subgraph.id, subgraph.id)
for (const nodeId of nodeIds) {
coveredNodeIds.add(nodeId)
itemByEndpoint.set(nodeId, subgraph.id)
}
items.push({ bounds, nodeIds })
for (const nodeId of nodeIds) coveredNodeIds.add(nodeId)
}
for (const node of diagram.nodes) {
if (coveredNodeIds.has(node.id)) continue
const bounds = nodeBounds.get(node.id)
if (!bounds) continue
items.push({ id: node.id, bounds, nodeIds: new Set([node.id]), rank: 0 })
itemByEndpoint.set(node.id, node.id)
if (bounds) items.push({ bounds, nodeIds: new Set([node.id]) })
}
if (items.length < 2) return
const horizontal = isHorizontalDirection(diagram.direction)
if (hasLocalDirection) {
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
let cursor: number | undefined
for (const item of items) {
const start = horizontal ? item.bounds.left : item.bounds.top
const size = horizontal ? item.bounds.width : item.bounds.height
if (cursor === undefined) {
cursor = start + size + gap
continue
}
const shift = cursor - start
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) translateBounds(bounds, horizontal ? shift : 0, horizontal ? 0 : shift)
}
cursor = start + shift + size + gap
}
return
}
const topLevelIds = new Set(
(diagram.subgraphs ?? []).filter((subgraph) => !subgraph.parentId).map((subgraph) => subgraph.id),
)
const rankedItems = items.filter((item) => topLevelIds.has(item.id))
if (rankedItems.length < 2) return
const itemById = new Map(rankedItems.map((item) => [item.id, item]))
const outgoing = new Map(rankedItems.map((item) => [item.id, new Set<string>()]))
const incoming = new Map(rankedItems.map((item) => [item.id, 0]))
for (const edge of diagram.edges) {
const from = itemByEndpoint.get(edge.from)
const to = itemByEndpoint.get(edge.to)
if (!from || !to || from === to || !itemById.has(from) || !itemById.has(to) || outgoing.get(from)!.has(to)) continue
outgoing.get(from)!.add(to)
incoming.set(to, incoming.get(to)! + 1)
}
const queue = rankedItems.filter((item) => incoming.get(item.id) === 0)
for (let index = 0; index < queue.length; index++) {
const item = queue[index]!
for (const to of outgoing.get(item.id)!) {
const downstream = itemById.get(to)!
downstream.rank = Math.max(downstream.rank, item.rank + 1)
incoming.set(to, incoming.get(to)! - 1)
if (incoming.get(to) === 0) queue.push(downstream)
}
}
const reversed = diagram.direction === "RL" || diagram.direction === "BT"
const primaryStart = (item: (typeof items)[number]): number => {
const start = horizontal ? item.bounds.left : item.bounds.top
const size = horizontal ? item.bounds.width : item.bounds.height
return reversed ? -(start + size) : start
}
rankedItems.sort((a, b) => a.rank - b.rank || primaryStart(a) - primaryStart(b))
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
let cursor: number | undefined
for (const item of rankedItems) {
const start = primaryStart(item)
for (const item of items) {
const start = horizontal ? item.bounds.left : item.bounds.top
const size = horizontal ? item.bounds.width : item.bounds.height
if (cursor === undefined) {
cursor = start + size + gap
continue
}
const shift = Math.max(0, cursor - start)
if (shift > 0) {
const shift = cursor - start
if (shift !== 0) {
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) {
const offset = reversed ? -shift : shift
translateBounds(bounds, horizontal ? offset : 0, horizontal ? 0 : offset)
}
if (bounds) translateBounds(bounds, horizontal ? shift : 0, horizontal ? 0 : shift)
}
}
cursor = start + shift + size + gap
@@ -678,7 +616,7 @@ function layoutFlowchartWithDirection(
let routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
let subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
separateTopLevelItems(diagram, bounds, subgraphBounds, Math.max(1, Math.floor(requestedMinRankGap / 2)))
separateLocalSubgraphItems(diagram, bounds, subgraphBounds, Math.max(1, Math.floor(requestedMinRankGap / 2)))
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
+4 -20
View File
@@ -29,7 +29,7 @@ const BOX_NODE_RE = new RegExp(`^(${ID_RE})\\[(.+)\\]$`)
const ID_ONLY_RE = new RegExp(`^${ID_RE}$`)
const EXPLICIT_NODE_SHAPE_RE = new RegExp(`^${ID_RE}(?:\\[|\\(|\\{)`)
const EDGE_OPERATOR_RE =
/(-\.(?!->)(.+?)\.->)|(--|==|-\.)\s+(.+?)\s+(-->|==>|\.->|-\.->)|(-->|==>|-\.->|---|~~~)\s*(?:\|([^|]*)\|\s*)?/g
/(-\.(?!->)(.+?)\.->)|(--|==|-\.)\s+(.+?)\s+(-->|==>|\.->|-\.->)|(-->|==>|-\.->|~~~)\s*(?:\|([^|]*)\|\s*)?/g
function normalizeDirection(value?: string): FlowchartDirection {
const upper = value?.toUpperCase()
@@ -116,16 +116,8 @@ function edgeStyleFromArrow(...arrows: string[]): FlowchartEdgeStyle | undefined
return undefined
}
function createEdge(
from: string,
to: string,
label: string,
style: FlowchartEdgeStyle | undefined,
arrowhead: boolean,
): FlowchartEdge {
const edge: FlowchartEdge = style ? { from, to, label, style } : { from, to, label }
if (!arrowhead) edge.arrowhead = false
return edge
function createEdge(from: string, to: string, label: string, style: FlowchartEdgeStyle | undefined): FlowchartEdge {
return style ? { from, to, label, style } : { from, to, label }
}
interface ParsedEdgeOperator {
@@ -133,7 +125,6 @@ interface ParsedEdgeOperator {
end: number
label: string
style: FlowchartEdgeStyle | undefined
arrowhead: boolean
orderOnly: boolean
}
@@ -147,7 +138,6 @@ function parseEdgeOperators(line: string): ParsedEdgeOperator[] {
end: match.index + match[0].length,
label: (match[2] ?? match[4] ?? match[7] ?? "").trim(),
style: edgeStyleFromArrow(startArrow, endArrow),
arrowhead: endArrow !== "---",
orderOnly: endArrow === "~~~",
}
})
@@ -233,13 +223,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
}
for (let index = 0; index < edgeOperators.length; index++) {
const operator = edgeOperators[index]!
const edge = createEdge(
chainNodeIds[index]!,
chainNodeIds[index + 1]!,
operator.label,
operator.style,
operator.arrowhead,
)
const edge = createEdge(chainNodeIds[index]!, chainNodeIds[index + 1]!, operator.label, operator.style)
edges.push(operator.orderOnly ? { ...edge, orderOnly: true } : edge)
}
continue
-1
View File
@@ -15,7 +15,6 @@ export interface FlowchartEdge {
to: string
label: string
style?: FlowchartEdgeStyle
arrowhead?: false
orderOnly?: boolean
}
-42
View File
@@ -162,48 +162,6 @@ stateDiagram-v2
expect(output).toContain("second")
})
test("keeps reciprocal multiline transition labels clear of routes", () => {
const output = renderStateDiagram(`stateDiagram-v2
[*] --> Running: create from base image
Running --> Dormant: 📸 suspend hook fires<br/>(WE must call it on idle)
Dormant --> Running: wake from snapshot image<br/>(apt installs restored!)
Running --> Lost: 💥 sandbox dies BEFORE hook fires<br/>(crash, our bug, race)
Lost --> Running: wake from LAST snapshot<br/>⚠ files since then GONE`)
const labelLines = [
"create from base image",
"📸 suspend hook fires",
"(WE must call it on idle)",
"wake from snapshot image",
"(apt installs restored!)",
"💥 sandbox dies BEFORE hook fires",
"(crash, our bug, race)",
"wake from LAST snapshot",
"⚠ files since then GONE",
]
for (const line of labelLines) expect(output.split(line)).toHaveLength(2)
expect(output).toMatchInlineSnapshot(`
"
create from base image ╭─────────╮
●───────────────────────▶│ Running │
╰──┬──────╯ 💥 sandbox dies BEFORE hook fires
▲ │ ▲ (crash, our bug, race)
╭────────┼─╰───┼───────╮
▼ ╭────┼─────╯ ▼
╭──────┴──╮ │ ╭──────╮
│ Dormant │ │ │ Lost │
╰─────────╯ │ ╰───┬──╯
│ │
📸 suspend hook fires │ │
(WE must call it on idle)│ │
╰───────────────╯
wake from snapshot image
(apt installs restored!)
wake from LAST snapshot
⚠ files since then GONE"
`)
})
test("renders a vertical state diagram", () => {
const output = renderStateDiagram(`
stateDiagram-v2
+2 -91
View File
@@ -590,103 +590,14 @@ function createStateTransitionRenderPlan(route: StateTransitionRoutePlan): State
return builder
}
interface StateTransitionLabelRect {
left: number
top: number
width: number
height: number
}
function labelRect(label: StateTransitionRenderLabel, width: number): StateTransitionLabelRect {
return { left: label.x, top: label.y, width, height: label.lines.length }
}
function rectsOverlap(left: StateTransitionLabelRect, right: StateTransitionLabelRect): boolean {
return (
left.left < right.left + right.width &&
left.left + left.width > right.left &&
left.top < right.top + right.height &&
left.top + left.height > right.top
)
}
function placeStateTransitionLabels(
plans: readonly StateTransitionRenderPlan[],
diagram: StateVisibleDiagram,
bounds: ReadonlyMap<string, BoxBounds>,
): StateTransitionRenderPlan[] {
const routeCells = new Set(plans.flatMap((plan) => plan.cells.map((cell) => `${cell.x}:${cell.y}`)))
const placedLabels: StateTransitionLabelRect[] = []
const stateRects = diagram.states.flatMap((state) => {
const bound = bounds.get(state.id)
return bound && !isHiddenCompositeMarker(state)
? [{ left: bound.left, top: bound.top, width: bound.width, height: bound.height }]
: []
})
return plans.map((plan) => {
if (!plan.label) return plan
const width = Math.max(...plan.label.lines.map(diagramTextWidth))
if (plan.label.lines.length === 1) {
placedLabels.push(labelRect(plan.label, width))
return plan
}
const statePadding = 1
const isClear = (x: number, y: number): boolean => {
if (x < 0 || y < 0) return false
const rect = labelRect({ ...plan.label!, x, y }, width)
if (
stateRects.some((state) =>
rectsOverlap(rect, {
left: state.left - statePadding,
top: state.top - statePadding,
width: state.width + statePadding * 2,
height: state.height + statePadding * 2,
}),
)
)
return false
if (placedLabels.some((label) => rectsOverlap(rect, label))) return false
for (let row = rect.top; row < rect.top + rect.height; row++) {
for (let column = rect.left; column < rect.left + rect.width; column++) {
if (routeCells.has(`${column}:${row}`)) return false
}
}
return true
}
let x = plan.label.x
let y = plan.label.y
if (!isClear(x, y)) {
search: for (let distance = 1; distance < 500; distance++) {
for (let dx = -distance; dx <= distance; dx++) {
const dy = distance - Math.abs(dx)
for (const candidateY of dy === 0 ? [y] : [y - dy, y + dy]) {
const candidateX = x + dx
if (!isClear(candidateX, candidateY)) continue
x = candidateX
y = candidateY
break search
}
}
}
}
placedLabels.push(labelRect({ ...plan.label, x, y }, width))
return { ...plan, label: { ...plan.label, x, y } }
})
}
export function createStateTransitionRenderPlans(
diagram: StateVisibleDiagram,
bounds: ReadonlyMap<string, BoxBounds>,
feedbackLaneY: number,
feedbackTopY?: number,
): StateTransitionRenderPlan[] {
return placeStateTransitionLabels(
createStateTransitionRoutePlans(diagram, bounds, feedbackLaneY, feedbackTopY).map(createStateTransitionRenderPlan),
diagram,
bounds,
return createStateTransitionRoutePlans(diagram, bounds, feedbackLaneY, feedbackTopY).map(
createStateTransitionRenderPlan,
)
}
+2 -2
View File
@@ -22,8 +22,8 @@ describe("parser diagnostics", () => {
expect(() =>
parseMermaidFlowchartDiagram(`flowchart LR
A[Start] --> B[Done]
A --o B`),
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --o B"')
A --- B`),
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --- B"')
})
test("exposes structured syntax errors through top-level rendering", () => {
+36 -11
View File
@@ -13,15 +13,30 @@ trap 'rm -f -- "$pidfile"' EXIT
"$@"
`
// Modal's VM runtime accepts process-group signals without delivering them
// (kill(-pgid) returns 0 and nothing dies; direct-pid signals work), so the
// group is enumerated from /proc and each member is signalled directly. The
// second pass catches children forked between scan and signal.
const KILL = `
pidfile=$1
sig=$2
i=0
while [ ! -s "$1" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
if [ -s "$1" ]; then
pid=$(cat "$1")
/bin/kill "-$2" "-$pid" 2>/dev/null || true
else
exit 47
fi
while [ ! -s "$pidfile" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
[ -s "$pidfile" ] || exit 47
target=$(cat "$pidfile")
pass=0
while [ "$pass" -lt 2 ]; do
for stat in /proc/[0-9]*/stat; do
[ -e "$stat" ] || continue
pid=\${stat#/proc/}
pid=\${pid%/stat}
set -- $(sed "s/.*) //" "$stat" 2>/dev/null)
if [ "\${3:-}" = "$target" ]; then
/bin/kill "-$sig" "$pid" 2>/dev/null || true
fi
done
pass=$((pass + 1))
done
`
export interface ModalImageSpec {
@@ -54,7 +69,15 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
const app = await client.apps.fromName(options.app, { createIfMissing: true })
const imageSpec = options.image ?? ubuntuImage
const image = client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
const sandbox = await client.sandboxes.create(app, image, options.sandbox)
// Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
// with real device nodes, so workspaces can run Docker and other
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
const sandbox = await client.sandboxes.create(app, image, {
...options.sandbox,
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
})
return {
driver: makeModalDriver(sandbox),
sandbox,
@@ -64,12 +87,14 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
/**
* Adapts Modal exec to the Environment driver. Files intentionally has no native
* overrides: Modal exec and filesystem tools share the same roughly 175ms floor,
* so the derived exec defaults are the simplest implementation with no measured loss.
* overrides: exec latency dominates payload work (VM runtime floor measured
* ~285-535ms per exec, Aug 2026), so the derived exec defaults are the simplest
* implementation with no measured loss.
*
* Modal cannot signal a ContainerProcess. Each command therefore starts a new
* process group and records its leader in a unique pid file; kill runs a second
* sandbox command that signals that group. Pid files are removed best-effort.
* sandbox command that enumerates that group from /proc and signals each member
* directly (see KILL). Pid files are removed best-effort.
*/
export const makeModalDriver = (sandbox: Sandbox): Driver => {
const spawn = Effect.fnUntraced(function* (command: Command) {
+1 -14
View File
@@ -51,17 +51,6 @@ export function DialogOpen() {
.catch(() => [] as SessionInfo[]),
{ initialValue: [] },
)
const [matched] = createResource(
() => {
const value = filter().trim()
return /^ses_[0-9A-Za-z]{26}$/.test(value) ? value : undefined
},
(sessionID) =>
client.api.session
.get({ sessionID })
.then((session) => (session.id === sessionID ? session : undefined))
.catch(() => undefined),
)
const openTabs = createMemo(
() => new Set(sessionTabs.enabled() ? sessionTabs.tabs().map((tab) => tab.sessionID) : []),
@@ -71,8 +60,7 @@ export function DialogOpen() {
)
const sessions = createMemo(() => {
const seen = new Set<string>()
const match = matched()
return [...data.session.list(), ...fetched(), ...(match ? [match] : [])]
return [...data.session.list(), ...fetched()]
.filter((session) => {
if (session.parentID || seen.has(session.id)) return false
seen.add(session.id)
@@ -99,7 +87,6 @@ export function DialogOpen() {
data.session.family(session.id).some((id) => data.session.status(id) === "running")
return {
title: withTimestampedFallback(session),
searchText: session.id,
value: { type: "session", sessionID: session.id } as OpenTarget,
category: "Sessions",
footer: `${name ? `${Locale.truncate(name, 20)} · ` : ""}${timeAgo(session.time.updated)}`,
@@ -54,40 +54,6 @@ test("selecting an unhydrated session preserves its location", async () => {
}
})
test("finds and opens an exact session ID outside the recent list", async () => {
const sessionID = "ses_04a7a3d82ffeIphUJgd3SnEqiv"
const remote = { directory: "/tmp/opencode/archive", workspaceID: "ws_archive" }
const fixture = await renderOpen((url) => {
if (url.pathname === "/api/session") return json({ data: [], cursor: {} })
if (url.pathname !== `/api/session/${sessionID}`) return undefined
return json({
data: {
id: sessionID,
projectID: "proj_archive",
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
title: "TUI plugin slot API v2",
location: remote,
},
})
})
try {
await fixture.app.waitForFrame((frame) => frame.includes("Search sessions and projects"))
await fixture.app.mockInput.typeText(sessionID)
await fixture.app.waitForFrame((frame) => frame.includes("TUI plugin slot API v2"))
fixture.app.mockInput.pressEnter()
await fixture.app.waitFor(() => fixture.route.data.type === "session")
expect(fixture.route.data).toEqual({ type: "session", sessionID })
expect(fixture.location.ref).toEqual(remote)
} finally {
fixture.dispose()
}
})
test("shows the current project and opens its root", async () => {
const root = "/tmp/opencode/project"
const subfolder = `${root}/packages/tui`
-1
View File
@@ -138,7 +138,6 @@ export function createFetch(override?: FetchHandler, events?: ReturnType<typeof
if (url.pathname === "/provider") return json({ all: [], default: {}, connected: [] })
if (url.pathname === "/session") return json([])
if (url.pathname === "/vcs") return json({ branch: "main" })
if (url.pathname === "/api/experimental/migration/v1") return json({ status: "completed" })
throw new Error(`unexpected request: ${url.pathname}`)
}
fetch.preconnect = () => {}