Compare commits

...
15 changed files with 412 additions and 158 deletions
-101
View File
@@ -1,101 +0,0 @@
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>
+7 -10
View File
@@ -1,24 +1,21 @@
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().$type<Account.ID>().primaryKey(),
id: text().primaryKey(),
email: text().notNull(),
url: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
token_expiry: integer(),
...Timestamps,
})
export const AccountStateTable = sqliteTable("account_state", {
id: integer().primaryKey(),
active_account_id: text()
.$type<Account.ID>()
.references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text().$type<Account.OrgID>(),
active_account_id: text().references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text(),
})
// LEGACY
@@ -27,8 +24,8 @@ export const ControlAccountTable = sqliteTable(
{
email: text().notNull(),
url: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
token_expiry: integer(),
active: integer({ mode: "boolean" })
.notNull()
+9 -15
View File
@@ -3,7 +3,6 @@ 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"
@@ -15,6 +14,7 @@ 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,22 +353,16 @@ 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 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 },
)
const diff = fileDiff(
change.target.absolute,
change.before,
after,
change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
)
return {
...diff,
file: target,
patch,
status: change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
...counts,
patch: trimDiff(diff.patch),
}
}
+25 -2
View File
@@ -215,7 +215,7 @@ describe("PatchTool", () => {
file: "remove.txt",
status: "deleted",
additions: 0,
deletions: 2,
deletions: 1,
patch: expect.stringContaining("-remove"),
},
],
@@ -248,6 +248,29 @@ 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")
@@ -446,7 +469,7 @@ describe("PatchTool", () => {
{
file: "renamed/dir/name.txt",
status: "modified",
patch: expect.stringContaining("-old content\n+new content"),
patch: expect.stringContaining(`Index: ${source}`),
},
],
})
+5 -3
View File
@@ -163,9 +163,11 @@ function drawRoutedEdge(grid: FlowchartGrid, route: FlowchartEdgeRoute): void {
cornerStyle: "rounded",
lineStyle: edge.style === "thick" ? "heavy" : "single",
})
const end = points[points.length - 1]!
const arrowFrom = points[points.length - 2]!
grid.setCell(end.x, end.y, diagramArrowHeadBetween(arrowFrom, end), style)
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)
}
if (edge.label) {
drawEdgeLabel(grid, route, "label")
}
@@ -424,6 +424,42 @@ 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
@@ -981,6 +1017,51 @@ 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
+80 -18
View File
@@ -499,10 +499,6 @@ 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 ?? []) {
@@ -515,47 +511,113 @@ function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string):
return nodeIds
}
function separateLocalSubgraphItems(
function separateTopLevelItems(
diagram: FlowchartDiagram,
nodeBounds: Map<string, FlowchartNodeBounds>,
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
gap: number,
): void {
if (!hasLocalSubgraphDirection(diagram)) return
const hasLocalDirection = (diagram.subgraphs ?? []).some(
(subgraph) => subgraph.direction && subgraph.direction !== diagram.direction,
)
const coveredNodeIds = new Set<string>()
const items: { bounds: FlowchartBounds; nodeIds: Set<string> }[] = []
const items: { id: string; bounds: FlowchartBounds; nodeIds: Set<string>; rank: number }[] = []
const itemByEndpoint = new Map<string, 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({ bounds, nodeIds })
for (const nodeId of nodeIds) coveredNodeIds.add(nodeId)
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)
}
}
for (const node of diagram.nodes) {
if (coveredNodeIds.has(node.id)) continue
const bounds = nodeBounds.get(node.id)
if (bounds) items.push({ bounds, nodeIds: new Set([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 (items.length < 2) return
const horizontal = isHorizontalDirection(diagram.direction)
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
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))
let cursor: number | undefined
for (const item of items) {
const start = horizontal ? item.bounds.left : item.bounds.top
for (const item of rankedItems) {
const start = primaryStart(item)
const size = horizontal ? item.bounds.width : item.bounds.height
if (cursor === undefined) {
cursor = start + size + gap
continue
}
const shift = cursor - start
if (shift !== 0) {
const shift = Math.max(0, cursor - start)
if (shift > 0) {
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) translateBounds(bounds, horizontal ? shift : 0, horizontal ? 0 : shift)
if (bounds) {
const offset = reversed ? -shift : shift
translateBounds(bounds, horizontal ? offset : 0, horizontal ? 0 : offset)
}
}
}
cursor = start + shift + size + gap
@@ -616,7 +678,7 @@ function layoutFlowchartWithDirection(
let routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
let subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
separateLocalSubgraphItems(diagram, bounds, subgraphBounds, Math.max(1, Math.floor(requestedMinRankGap / 2)))
separateTopLevelItems(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)
+20 -4
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,8 +116,16 @@ function edgeStyleFromArrow(...arrows: string[]): FlowchartEdgeStyle | undefined
return undefined
}
function createEdge(from: string, to: string, label: string, style: FlowchartEdgeStyle | undefined): FlowchartEdge {
return style ? { from, to, label, style } : { from, to, label }
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
}
interface ParsedEdgeOperator {
@@ -125,6 +133,7 @@ interface ParsedEdgeOperator {
end: number
label: string
style: FlowchartEdgeStyle | undefined
arrowhead: boolean
orderOnly: boolean
}
@@ -138,6 +147,7 @@ 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 === "~~~",
}
})
@@ -223,7 +233,13 @@ 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)
const edge = createEdge(
chainNodeIds[index]!,
chainNodeIds[index + 1]!,
operator.label,
operator.style,
operator.arrowhead,
)
edges.push(operator.orderOnly ? { ...edge, orderOnly: true } : edge)
}
continue
+1
View File
@@ -15,6 +15,7 @@ export interface FlowchartEdge {
to: string
label: string
style?: FlowchartEdgeStyle
arrowhead?: false
orderOnly?: boolean
}
+42
View File
@@ -162,6 +162,48 @@ 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
+91 -2
View File
@@ -590,14 +590,103 @@ 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 createStateTransitionRoutePlans(diagram, bounds, feedbackLaneY, feedbackTopY).map(
createStateTransitionRenderPlan,
return placeStateTransitionLabels(
createStateTransitionRoutePlans(diagram, bounds, feedbackLaneY, feedbackTopY).map(createStateTransitionRenderPlan),
diagram,
bounds,
)
}
+2 -2
View File
@@ -22,8 +22,8 @@ describe("parser diagnostics", () => {
expect(() =>
parseMermaidFlowchartDiagram(`flowchart LR
A[Start] --> B[Done]
A --- B`),
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --- B"')
A --o B`),
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --o B"')
})
test("exposes structured syntax errors through top-level rendering", () => {
+14 -1
View File
@@ -51,6 +51,17 @@ 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) : []),
@@ -60,7 +71,8 @@ export function DialogOpen() {
)
const sessions = createMemo(() => {
const seen = new Set<string>()
return [...data.session.list(), ...fetched()]
const match = matched()
return [...data.session.list(), ...fetched(), ...(match ? [match] : [])]
.filter((session) => {
if (session.parentID || seen.has(session.id)) return false
seen.add(session.id)
@@ -87,6 +99,7 @@ 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,6 +54,40 @@ 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,6 +138,7 @@ 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 = () => {}