mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-09 10:59:49 -04:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ec126b1963 | |||
| 84fd347afa | |||
| e8f215bfbc | |||
| 445af9ce70 | |||
| bc51baa9a4 | |||
| ff0a0b0786 | |||
| 4eff0ee2db | |||
| cc0061f88b | |||
| f43f2b354c | |||
| c2ba0bef6b | |||
| 83b47693c3 | |||
| 1ca86ad973 |
@@ -577,6 +577,7 @@
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"entities": "7.0.1",
|
||||
"string-width": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -45,35 +45,34 @@ const isToolResultValue = (value: unknown): value is ToolResultValue =>
|
||||
(value.type === "text" || value.type === "json" || value.type === "error" || value.type === "content") &&
|
||||
"value" in value
|
||||
|
||||
export const ToolResultValue = Object.assign(
|
||||
Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("json"),
|
||||
value: Schema.Unknown,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("text"),
|
||||
value: Schema.Unknown,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("error"),
|
||||
value: Schema.Unknown,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("content"),
|
||||
value: Schema.Array(Tool.Content),
|
||||
}),
|
||||
]).annotate({ identifier: "LLM.ToolResult" }),
|
||||
{
|
||||
is: isToolResultValue,
|
||||
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
|
||||
if (isToolResultValue(value)) return value
|
||||
if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
|
||||
return { type, value }
|
||||
},
|
||||
const toolResultValueSchema = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("json"),
|
||||
value: Schema.Unknown,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("text"),
|
||||
value: Schema.Unknown,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("error"),
|
||||
value: Schema.Unknown,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("content"),
|
||||
value: Schema.Array(Tool.Content),
|
||||
}),
|
||||
]).annotate({ identifier: "LLM.ToolResult" })
|
||||
export type ToolResultValue = Schema.Schema.Type<typeof toolResultValueSchema>
|
||||
|
||||
export const ToolResultValue = Object.assign(toolResultValueSchema, {
|
||||
is: isToolResultValue,
|
||||
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
|
||||
if (isToolResultValue(value)) return value
|
||||
if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
|
||||
return { type, value }
|
||||
},
|
||||
)
|
||||
export type ToolResultValue = Schema.Schema.Type<typeof ToolResultValue>
|
||||
})
|
||||
|
||||
export interface ToolOutput {
|
||||
readonly structured: unknown
|
||||
|
||||
@@ -180,6 +180,7 @@ export type Endpoint5_12Input = {
|
||||
readonly text: string
|
||||
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
||||
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
||||
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
readonly delivery?: "steer" | "queue" | undefined
|
||||
readonly resume?: boolean | undefined
|
||||
@@ -196,6 +197,7 @@ export type Endpoint5_13Input = {
|
||||
readonly model?: Model.Ref | undefined
|
||||
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
||||
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
||||
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
|
||||
readonly delivery?: "steer" | "queue" | undefined
|
||||
readonly resume?: boolean | undefined
|
||||
}
|
||||
|
||||
@@ -412,6 +412,7 @@ const Endpoint5_12 = (raw: RawClient["server.session"]) => (input: Endpoint5_12I
|
||||
text: input["text"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
metadata: input["metadata"],
|
||||
delivery: input["delivery"],
|
||||
resume: input["resume"],
|
||||
@@ -434,6 +435,7 @@ const Endpoint5_13 = (raw: RawClient["server.session"]) => (input: Endpoint5_13I
|
||||
model: input["model"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
delivery: input["delivery"],
|
||||
resume: input["resume"],
|
||||
},
|
||||
|
||||
@@ -615,6 +615,7 @@ export function make(options: ClientOptions) {
|
||||
text: input["text"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
metadata: input["metadata"],
|
||||
delivery: input["delivery"],
|
||||
resume: input["resume"],
|
||||
@@ -638,6 +639,7 @@ export function make(options: ClientOptions) {
|
||||
model: input["model"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
delivery: input["delivery"],
|
||||
resume: input["resume"],
|
||||
},
|
||||
|
||||
@@ -1080,6 +1080,8 @@ export type PromptFileAttachment = {
|
||||
|
||||
export type PromptAgentAttachment = { name: string; mention?: PromptMention }
|
||||
|
||||
export type PromptSkillAttachment = { id: string; name: string; text: string; mention?: PromptMention }
|
||||
|
||||
export type SessionMessageAssistantText = { type: "text"; text: string; state?: SessionMessageProviderState }
|
||||
|
||||
export type SessionMessageAssistantReasoning = {
|
||||
@@ -1565,6 +1567,7 @@ export type SessionMessageUser = {
|
||||
text: string
|
||||
files?: Array<PromptFileAttachment>
|
||||
agents?: Array<PromptAgentAttachment>
|
||||
skills?: Array<PromptSkillAttachment>
|
||||
type: "user"
|
||||
}
|
||||
|
||||
@@ -1572,6 +1575,7 @@ export type SessionPendingUserData = {
|
||||
text: string
|
||||
files?: Array<PromptFileAttachment>
|
||||
agents?: Array<PromptAgentAttachment>
|
||||
skills?: Array<PromptSkillAttachment>
|
||||
metadata?: { [x: string]: JsonValue }
|
||||
}
|
||||
|
||||
@@ -1579,6 +1583,7 @@ export type SessionPendingUserData1 = {
|
||||
text: string
|
||||
files?: Array<PromptFileAttachment>
|
||||
agents?: Array<PromptAgentAttachment>
|
||||
skills?: Array<PromptSkillAttachment>
|
||||
metadata?: { [x: string]: any }
|
||||
}
|
||||
|
||||
@@ -2579,6 +2584,12 @@ export type SessionImportInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly name: string
|
||||
readonly text: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly type: "user"
|
||||
}
|
||||
| {
|
||||
@@ -2824,6 +2835,12 @@ export type SessionImportInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly name: string
|
||||
readonly text: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly type: "user"
|
||||
}
|
||||
| {
|
||||
@@ -3069,6 +3086,12 @@ export type SessionImportInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly name: string
|
||||
readonly text: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly type: "user"
|
||||
}
|
||||
| {
|
||||
@@ -3320,6 +3343,10 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
@@ -3337,6 +3364,10 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
@@ -3354,6 +3385,10 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
@@ -3371,10 +3406,35 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["agents"]
|
||||
readonly skills?: {
|
||||
readonly id?: string | null
|
||||
readonly text: string
|
||||
readonly files?: ReadonlyArray<{
|
||||
readonly uri: string
|
||||
readonly name?: string
|
||||
readonly description?: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly agents?: ReadonlyArray<{
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["skills"]
|
||||
readonly metadata?: {
|
||||
readonly id?: string | null
|
||||
readonly text: string
|
||||
@@ -3388,6 +3448,10 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
@@ -3405,6 +3469,10 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
@@ -3422,6 +3490,10 @@ export type SessionPromptInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
@@ -3448,6 +3520,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["id"]
|
||||
@@ -3467,6 +3543,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["command"]
|
||||
@@ -3486,6 +3566,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["arguments"]
|
||||
@@ -3505,6 +3589,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["agent"]
|
||||
@@ -3524,6 +3612,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["model"]
|
||||
@@ -3543,6 +3635,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["files"]
|
||||
@@ -3562,9 +3658,36 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["agents"]
|
||||
readonly skills?: {
|
||||
readonly id?: string | null
|
||||
readonly command: string
|
||||
readonly arguments?: string | null
|
||||
readonly agent?: string | null
|
||||
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
|
||||
readonly files?: ReadonlyArray<{
|
||||
readonly uri: string
|
||||
readonly name?: string
|
||||
readonly description?: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly agents?: ReadonlyArray<{
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["skills"]
|
||||
readonly delivery?: {
|
||||
readonly id?: string | null
|
||||
readonly command: string
|
||||
@@ -3581,6 +3704,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["delivery"]
|
||||
@@ -3600,6 +3727,10 @@ export type SessionCommandInput = {
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly skills?: ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
readonly delivery?: "steer" | "queue" | null
|
||||
readonly resume?: boolean | null
|
||||
}["resume"]
|
||||
|
||||
+58
-99
@@ -1,13 +1,9 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "sqlite",
|
||||
"id": "2d214a71-3b0a-48c1-a667-741952c4e188",
|
||||
"prevIds": ["f14a9b18-8207-487e-a3d3-227e629ba9ad"],
|
||||
"id": "15060ec5-05f7-4b86-b2a5-9108609432b3",
|
||||
"prevIds": ["1551a157-8959-4ba9-a52b-4ea3b7b28cae"],
|
||||
"ddl": [
|
||||
{
|
||||
"name": "workspace",
|
||||
"entityType": "tables"
|
||||
},
|
||||
{
|
||||
"name": "account_state",
|
||||
"entityType": "tables"
|
||||
@@ -73,84 +69,8 @@
|
||||
"entityType": "tables"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "id",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "type",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "''",
|
||||
"generated": null,
|
||||
"name": "name",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "branch",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "directory",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "extra",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "project_id",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "time_used",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
"name": "workspace",
|
||||
"entityType": "tables"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
@@ -1383,14 +1303,53 @@
|
||||
"table": "session_v2"
|
||||
},
|
||||
{
|
||||
"columns": ["project_id"],
|
||||
"tableTo": "project",
|
||||
"columnsTo": ["id"],
|
||||
"onUpdate": "NO ACTION",
|
||||
"onDelete": "CASCADE",
|
||||
"nameExplicit": false,
|
||||
"name": "fk_workspace_project_id_project_id_fk",
|
||||
"entityType": "fks",
|
||||
"type": "text",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "id",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "provider",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "binding",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "created_at",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "last_used_at",
|
||||
"entityType": "columns",
|
||||
"table": "workspace"
|
||||
},
|
||||
{
|
||||
@@ -1513,13 +1472,6 @@
|
||||
"entityType": "pks",
|
||||
"table": "instruction_entry"
|
||||
},
|
||||
{
|
||||
"columns": ["id"],
|
||||
"nameExplicit": false,
|
||||
"name": "workspace_pk",
|
||||
"table": "workspace",
|
||||
"entityType": "pks"
|
||||
},
|
||||
{
|
||||
"columns": ["id"],
|
||||
"nameExplicit": false,
|
||||
@@ -1611,6 +1563,13 @@
|
||||
"table": "session_v2",
|
||||
"entityType": "pks"
|
||||
},
|
||||
{
|
||||
"columns": ["id"],
|
||||
"nameExplicit": false,
|
||||
"name": "workspace_pk",
|
||||
"table": "workspace",
|
||||
"entityType": "pks"
|
||||
},
|
||||
{
|
||||
"columns": [
|
||||
{
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core"
|
||||
import { ProjectTable } from "../project/sql"
|
||||
import { Project } from "../project"
|
||||
import { Workspace } from "../workspace"
|
||||
|
||||
export const WorkspaceTable = sqliteTable("workspace", {
|
||||
id: text().$type<Workspace.ID>().primaryKey(),
|
||||
type: text().notNull(),
|
||||
name: text().notNull().default(""),
|
||||
branch: text(),
|
||||
directory: text(),
|
||||
extra: text({ mode: "json" }),
|
||||
project_id: text()
|
||||
.$type<Project.ID>()
|
||||
.notNull()
|
||||
.references(() => ProjectTable.id, { onDelete: "cascade" }),
|
||||
time_used: integer()
|
||||
.notNull()
|
||||
.$default(() => Date.now()),
|
||||
})
|
||||
+1
@@ -42,5 +42,6 @@ export const migrations: DatabaseMigration.Migration[] = (
|
||||
import("./migration/20260622202450_simplify_session_input"),
|
||||
import("./migration/20260804233008_loose_psylocke"),
|
||||
import("./migration/20260805200742_import_legacy_credentials"),
|
||||
import("./migration/20260808023530_workspace_domain"),
|
||||
])
|
||||
).map((module) => module.default)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Effect } from "effect"
|
||||
import type { DatabaseMigration } from "../migration"
|
||||
|
||||
const migration: DatabaseMigration.Migration = {
|
||||
id: "20260808023530_workspace_domain",
|
||||
up(tx) {
|
||||
return Effect.gen(function* () {
|
||||
yield* tx.run(`DROP TABLE \`workspace\`;`)
|
||||
yield* tx.run(`
|
||||
CREATE TABLE \`workspace\` (
|
||||
\`id\` text PRIMARY KEY,
|
||||
\`provider\` text NOT NULL,
|
||||
\`binding\` text NOT NULL,
|
||||
\`created_at\` integer NOT NULL,
|
||||
\`last_used_at\` integer NOT NULL
|
||||
);
|
||||
`)
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -4,19 +4,6 @@ import type { DatabaseMigration } from "./migration"
|
||||
const schema: Omit<DatabaseMigration.Migration, "id"> = {
|
||||
up(tx) {
|
||||
return Effect.gen(function* () {
|
||||
yield* tx.run(`
|
||||
CREATE TABLE \`workspace\` (
|
||||
\`id\` text PRIMARY KEY,
|
||||
\`type\` text NOT NULL,
|
||||
\`name\` text DEFAULT '' NOT NULL,
|
||||
\`branch\` text,
|
||||
\`directory\` text,
|
||||
\`extra\` text,
|
||||
\`project_id\` text NOT NULL,
|
||||
\`time_used\` integer NOT NULL,
|
||||
CONSTRAINT \`fk_workspace_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
|
||||
);
|
||||
`)
|
||||
yield* tx.run(`
|
||||
CREATE TABLE \`account_state\` (
|
||||
\`id\` integer PRIMARY KEY,
|
||||
@@ -216,6 +203,15 @@ const schema: Omit<DatabaseMigration.Migration, "id"> = {
|
||||
CONSTRAINT \`fk_session_v2_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
|
||||
);
|
||||
`)
|
||||
yield* tx.run(`
|
||||
CREATE TABLE \`workspace\` (
|
||||
\`id\` text PRIMARY KEY,
|
||||
\`provider\` text NOT NULL,
|
||||
\`binding\` text NOT NULL,
|
||||
\`created_at\` integer NOT NULL,
|
||||
\`last_used_at\` integer NOT NULL
|
||||
);
|
||||
`)
|
||||
yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`)
|
||||
yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`)
|
||||
yield* tx.run(
|
||||
|
||||
@@ -5,6 +5,8 @@ import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner
|
||||
import type { Files } from "./files"
|
||||
import { makeFiles } from "./index"
|
||||
import { makeLocalDriver } from "./local"
|
||||
import { Location } from "../location"
|
||||
import { Workspace } from "../workspace"
|
||||
|
||||
export interface Interface {
|
||||
readonly files: Files
|
||||
@@ -17,10 +19,25 @@ const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner
|
||||
return Service.of({ files: makeFiles(makeLocalDriver(spawner)), spawner })
|
||||
const location = yield* Location.Service
|
||||
const workspace = yield* Workspace.Service
|
||||
const driver = location.workspaceID
|
||||
? yield* workspace.connect(location.workspaceID).pipe(
|
||||
// Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.
|
||||
Effect.mapError(
|
||||
(cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),
|
||||
),
|
||||
Effect.orDie,
|
||||
)
|
||||
: makeLocalDriver(spawner)
|
||||
return Service.of({ files: makeFiles(driver), spawner: driver.spawner })
|
||||
}),
|
||||
)
|
||||
|
||||
export const node = makeLocationNode({ service: Service, layer, deps: [CrossSpawnSpawner.node] })
|
||||
export const node = makeLocationNode({
|
||||
service: Service,
|
||||
layer,
|
||||
deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],
|
||||
})
|
||||
|
||||
export * as EnvironmentService from "./environment"
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Provider } from "@opencode-ai/schema/provider"
|
||||
import { AbsolutePath } from "@opencode-ai/schema/schema"
|
||||
import { Session } from "@opencode-ai/schema/session"
|
||||
import { SessionMessage } from "@opencode-ai/schema/session-message"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||
import { WebSearch } from "@opencode-ai/schema/websearch"
|
||||
import { DateTime, Effect, Scope, Stream } from "effect"
|
||||
@@ -296,6 +297,7 @@ export function fromPromise(plugin: Plugin) {
|
||||
...input,
|
||||
sessionID: Session.ID.make(input.sessionID),
|
||||
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
|
||||
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
|
||||
delivery: input.delivery ?? undefined,
|
||||
resume: input.resume ?? undefined,
|
||||
}),
|
||||
@@ -310,6 +312,7 @@ export function fromPromise(plugin: Plugin) {
|
||||
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
|
||||
agent: input.agent == null ? undefined : Agent.ID.make(input.agent),
|
||||
model: input.model == null ? undefined : model(input.model),
|
||||
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
|
||||
arguments: input.arguments ?? undefined,
|
||||
delivery: input.delivery ?? undefined,
|
||||
resume: input.resume ?? undefined,
|
||||
|
||||
@@ -233,7 +233,7 @@ const layer = Layer.effect(
|
||||
const bus = yield* Bus.Service
|
||||
const watcher = yield* Watcher.Service
|
||||
const fs = yield* FSUtil.Service
|
||||
const ready = yield* Deferred.make<void>()
|
||||
const ready = { current: yield* Deferred.make<void>() }
|
||||
let observed = 0
|
||||
|
||||
// Configured local plugin files can live outside config roots, where the
|
||||
@@ -291,7 +291,13 @@ const layer = Layer.effect(
|
||||
bus.subscribe([Event.Updated, SdkPlugins.Updated]),
|
||||
).pipe(
|
||||
// Make accepted work visible to flush before coalescing the burst.
|
||||
Stream.mapEffect(() => Effect.sync(() => ++observed)),
|
||||
Stream.mapEffect(() =>
|
||||
Effect.gen(function* () {
|
||||
observed++
|
||||
if (yield* Deferred.isDone(ready.current)) ready.current = yield* Deferred.make<void>()
|
||||
return observed
|
||||
}),
|
||||
),
|
||||
)
|
||||
yield* Stream.concat(Stream.succeed(0), updates).pipe(
|
||||
// Keep observing updates while activation runs, retaining only the latest generation request.
|
||||
@@ -300,12 +306,12 @@ const layer = Layer.effect(
|
||||
Stream.runForEach((target) =>
|
||||
Effect.gen(function* () {
|
||||
yield* activate()
|
||||
if (observed === target) yield* Deferred.succeed(ready, undefined)
|
||||
if (observed === target) yield* Deferred.succeed(ready.current, undefined)
|
||||
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload plugins", { cause }))),
|
||||
),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
return Service.of({ flush: Deferred.await(ready) })
|
||||
return Service.of({ flush: Effect.suspend(() => Deferred.await(ready.current)) })
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -218,10 +218,11 @@ export interface Interface {
|
||||
text: string
|
||||
files?: PromptInput.Prompt["files"]
|
||||
agents?: PromptInput.Prompt["agents"]
|
||||
skills?: PromptInput.Prompt["skills"]
|
||||
metadata?: Record<string, unknown>
|
||||
delivery?: SessionPending.Delivery
|
||||
resume?: boolean
|
||||
}) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError>
|
||||
}) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError | SkillNotFoundError>
|
||||
/** Generates text from current Session context without admitting input or mutating history. */
|
||||
readonly generate: (input: {
|
||||
sessionID: SessionSchema.ID
|
||||
@@ -236,11 +237,17 @@ export interface Interface {
|
||||
model?: Model.Ref
|
||||
files?: PromptInput.Prompt["files"]
|
||||
agents?: PromptInput.Prompt["agents"]
|
||||
skills?: PromptInput.Prompt["skills"]
|
||||
delivery?: SessionPending.Delivery
|
||||
resume?: boolean
|
||||
}) => Effect.Effect<
|
||||
SessionPending.User,
|
||||
NotFoundError | PromptConflictError | AttachmentError | Command.NotFoundError | Command.EvaluationError
|
||||
| NotFoundError
|
||||
| PromptConflictError
|
||||
| AttachmentError
|
||||
| SkillNotFoundError
|
||||
| Command.NotFoundError
|
||||
| Command.EvaluationError
|
||||
>
|
||||
readonly shell: (input: {
|
||||
id?: Event.ID
|
||||
@@ -565,9 +572,11 @@ const layer = Layer.effect(
|
||||
// Resolved lazily so prompt admission only boots location services when an
|
||||
// image attachment actually needs the resizer.
|
||||
const image = Image.Service.pipe(Effect.provide(locations.get(session.location)))
|
||||
const skills = Skill.Service.pipe(Effect.provide(locations.get(session.location)))
|
||||
const prompt = yield* resolvePrompt(
|
||||
{ text: input.text, files: input.files, agents: input.agents },
|
||||
{ text: input.text, files: input.files, agents: input.agents, skills: input.skills },
|
||||
image,
|
||||
skills,
|
||||
).pipe(Effect.provideService(FSUtil.Service, fs))
|
||||
const messageID = input.id ?? SessionMessage.ID.create()
|
||||
const admittedInput = SessionPending.Message.make({
|
||||
@@ -633,6 +642,7 @@ const layer = Layer.effect(
|
||||
text: evaluated.text,
|
||||
files: input.files,
|
||||
agents: input.agents,
|
||||
skills: input.skills,
|
||||
delivery: input.delivery,
|
||||
resume: input.resume,
|
||||
})
|
||||
@@ -895,12 +905,28 @@ function synthesizeTerminalShellInfo(started: ShellSchema.Info): ShellSchema.Inf
|
||||
const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* (
|
||||
input: PromptInput.Prompt,
|
||||
image: Effect.Effect<Image.Interface>,
|
||||
skills: Effect.Effect<Skill.Interface>,
|
||||
) {
|
||||
const fs = yield* FSUtil.Service
|
||||
const files = input.files
|
||||
? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file, image), { concurrency: 8 })
|
||||
: undefined
|
||||
return Prompt.make({ text: input.text, agents: input.agents, files })
|
||||
const requested = input.skills
|
||||
const selected = yield* Effect.gen(function* () {
|
||||
if (!requested?.length) return undefined
|
||||
const available = yield* (yield* skills).list()
|
||||
return yield* Effect.forEach(requested, (attachment) => {
|
||||
const skill = available.find((item) => item.id === attachment.id)
|
||||
if (!skill) return Effect.fail(new SkillNotFoundError({ skill: attachment.id }))
|
||||
return Effect.succeed({
|
||||
id: skill.id,
|
||||
name: skill.name,
|
||||
text: Skill.toModelOutput(skill, []),
|
||||
mention: attachment.mention,
|
||||
})
|
||||
})
|
||||
})
|
||||
return Prompt.make({ text: input.text, agents: input.agents, files, skills: selected?.length ? selected : undefined })
|
||||
})
|
||||
|
||||
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
||||
|
||||
@@ -124,7 +124,8 @@ const serialize = (message: SessionMessage.Info) => {
|
||||
(file) =>
|
||||
`[Attached ${file.mime}: ${file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment")}]`,
|
||||
) ?? []
|
||||
return [`[User]: ${message.text}`, ...files].join("\n")
|
||||
const skills = message.skills?.map((skill) => `[Attached skill: ${skill.name}]\n${skill.text}`) ?? []
|
||||
return [`[User]: ${message.text}`, ...skills, ...files].join("\n")
|
||||
}
|
||||
if (message.type === "assistant") {
|
||||
return message.content
|
||||
|
||||
@@ -16,7 +16,6 @@ import { SessionPendingTable, SessionMessageTable, SessionTable } from "./sql"
|
||||
import { Slug } from "../util/slug"
|
||||
import { Money } from "@opencode-ai/schema/money"
|
||||
import type { SessionSchema } from "./schema"
|
||||
import { WorkspaceTable } from "../control-plane/workspace.sql"
|
||||
|
||||
type DatabaseService = Database.Interface["db"]
|
||||
type CurrentDurableEvent = Extract<SessionEvent.Event, { readonly durable: object }>
|
||||
@@ -376,13 +375,6 @@ const layer = Layer.effectDiscard(
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!stored) return yield* Effect.die(new SessionAlreadyProjected())
|
||||
if (!event.data.location.workspaceID) return
|
||||
yield* db
|
||||
.update(WorkspaceTable)
|
||||
.set({ time_used: Date.now() })
|
||||
.where(eq(WorkspaceTable.id, event.data.location.workspaceID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Moved, (event) =>
|
||||
@@ -453,6 +445,7 @@ const layer = Layer.effectDiscard(
|
||||
text: input.data.text,
|
||||
files: input.data.files,
|
||||
agents: input.data.agents,
|
||||
skills: input.data.skills,
|
||||
time: { created: event.created },
|
||||
}
|
||||
: {
|
||||
|
||||
@@ -184,6 +184,7 @@ function toLLMMessage(message: SessionMessage.Info, model: Model.Ref, providerMe
|
||||
return []
|
||||
case "user":
|
||||
const content = [
|
||||
...(message.skills ?? []).map((skill) => Message.text(skill.text)),
|
||||
...(message.text === "" ? [] : [Message.text(message.text)]),
|
||||
...(message.files ?? []).flatMap(attachmentContent),
|
||||
]
|
||||
|
||||
@@ -2,6 +2,7 @@ export * as SessionTransfer from "./transfer"
|
||||
|
||||
import { SessionTransfer } from "@opencode-ai/schema/session-transfer"
|
||||
import { Tool } from "@opencode-ai/schema/tool"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import { eq, isNotNull, isNull, ne, or } from "drizzle-orm"
|
||||
import { Context, DateTime, Effect, Layer, Schema } from "effect"
|
||||
import path from "path"
|
||||
@@ -218,6 +219,14 @@ function sanitizeMessage(message: SessionMessage.Info): SessionMessage.Info {
|
||||
? { ...agent.mention, text: redact("agent-mention", String(index), agent.mention.text) }
|
||||
: undefined,
|
||||
})),
|
||||
skills: message.skills?.map((skill, index) => ({
|
||||
...skill,
|
||||
name: Skill.Name.make(redact("skill-name", String(index), skill.name)),
|
||||
text: redact("skill", String(index), skill.text),
|
||||
mention: skill.mention
|
||||
? { ...skill.mention, text: redact("skill-mention", String(index), skill.mention.text) }
|
||||
: undefined,
|
||||
})),
|
||||
}
|
||||
if (message.type === "synthetic")
|
||||
return {
|
||||
|
||||
@@ -38,6 +38,25 @@ export { Event } from "@opencode-ai/schema/skill"
|
||||
export const available = (skills: ReadonlyArray<Info>, agent: Agent.Info) =>
|
||||
skills.filter((skill) => Permission.evaluate("skill", skill.id, agent.permissions).effect !== "deny")
|
||||
|
||||
export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
|
||||
const directory = path.dirname(skill.location)
|
||||
return [
|
||||
`<skill_content name="${skill.name}">`,
|
||||
`# Skill: ${skill.name}`,
|
||||
"",
|
||||
skill.content.trim(),
|
||||
"",
|
||||
`Base directory for this skill: ${directory}`,
|
||||
"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
|
||||
"Note: file list is sampled.",
|
||||
"",
|
||||
"<skill_files>",
|
||||
...files.map((file) => `<file>${file}</file>`),
|
||||
"</skill_files>",
|
||||
"</skill_content>",
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
const Frontmatter = Schema.Struct({
|
||||
name: Schema.String.pipe(Schema.optional),
|
||||
description: Schema.String.pipe(Schema.optional),
|
||||
|
||||
@@ -26,24 +26,7 @@ export const description = [
|
||||
"The skill ID must match one of the available skills in the instructions.",
|
||||
].join("\n")
|
||||
|
||||
export const toModelOutput = (skill: Skill.Info, files: ReadonlyArray<string>) => {
|
||||
const directory = path.dirname(skill.location)
|
||||
return [
|
||||
`<skill_content name="${skill.name}">`,
|
||||
`# Skill: ${skill.name}`,
|
||||
"",
|
||||
skill.content.trim(),
|
||||
"",
|
||||
`Base directory for this skill: ${directory}`,
|
||||
"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
|
||||
"Note: file list is sampled.",
|
||||
"",
|
||||
"<skill_files>",
|
||||
...files.map((file) => `<file>${file}</file>`),
|
||||
"</skill_files>",
|
||||
"</skill_content>",
|
||||
].join("\n")
|
||||
}
|
||||
export const toModelOutput = Skill.toModelOutput
|
||||
|
||||
const unableToLoad = (name: string, error?: unknown) =>
|
||||
new ToolFailure({ message: `Unable to load skill ${name}`, error })
|
||||
@@ -87,7 +70,7 @@ export const Plugin = {
|
||||
return {
|
||||
name: skill.name,
|
||||
directory,
|
||||
output: toModelOutput(skill, files),
|
||||
output: Skill.toModelOutput(skill, files),
|
||||
}
|
||||
}).pipe(Effect.mapError((error) => unableToLoad(input.id, error)))
|
||||
}).pipe(
|
||||
|
||||
@@ -1,6 +1,219 @@
|
||||
export * as Workspace from "./workspace"
|
||||
|
||||
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { Clock, Context, Duration, Effect, Exit, Layer, Ref, Schedule, Schema, Scope } from "effect"
|
||||
import { systemError } from "effect/PlatformError"
|
||||
import { make } from "effect/unstable/process/ChildProcessSpawner"
|
||||
import type { Driver as EnvironmentDriver } from "./environment/driver"
|
||||
import { Database } from "./database/database"
|
||||
import { KeyedMutex } from "./effect/keyed-mutex"
|
||||
import { WorkspaceDriver } from "./workspace/driver"
|
||||
import { WorkspaceTable } from "./workspace/sql"
|
||||
|
||||
export const ID = Workspace.ID
|
||||
export type ID = typeof ID.Type
|
||||
export type ID = Workspace.ID
|
||||
|
||||
export class Info extends Schema.Class<Info>("Workspace.Info")({
|
||||
id: ID,
|
||||
provider: Schema.String,
|
||||
binding: WorkspaceDriver.Binding,
|
||||
createdAt: Schema.Number,
|
||||
lastUsedAt: Schema.Number,
|
||||
}) {}
|
||||
|
||||
export class NotFound extends Schema.TaggedErrorClass<NotFound>()("Workspace.NotFound", { workspaceID: ID }) {}
|
||||
|
||||
export interface Interface {
|
||||
readonly create: (provider: string) => Effect.Effect<Info, WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
|
||||
readonly connect: (
|
||||
workspaceID: ID,
|
||||
) => Effect.Effect<EnvironmentDriver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
|
||||
readonly destroy: (
|
||||
workspaceID: ID,
|
||||
) => Effect.Effect<void, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
|
||||
}
|
||||
|
||||
export interface Options {
|
||||
readonly idleThreshold?: Duration.Input
|
||||
readonly pollInterval?: Duration.Input
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/Workspace") {}
|
||||
|
||||
interface Connection {
|
||||
readonly driver: WorkspaceDriver.Interface
|
||||
readonly environment: EnvironmentDriver
|
||||
readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>
|
||||
readonly lastActivity: Ref.Ref<number>
|
||||
readonly active: Ref.Ref<number>
|
||||
readonly scope: Scope.Closeable
|
||||
}
|
||||
|
||||
export const configured = (options: Options = {}) =>
|
||||
makeGlobalNode({
|
||||
service: Service,
|
||||
layer: layer(options),
|
||||
deps: [Database.node, WorkspaceDriver.node],
|
||||
})
|
||||
|
||||
const layer = (options: Options) =>
|
||||
Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const db = (yield* Database.Service).db
|
||||
const registry = yield* WorkspaceDriver.RegistryService
|
||||
const lifetime = yield* Scope.Scope
|
||||
const connections = new Map<ID, Connection>()
|
||||
const locks = KeyedMutex.makeUnsafe<ID>()
|
||||
const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))
|
||||
|
||||
const load = Effect.fn("Workspace.load")(function* (workspaceID: ID) {
|
||||
const row = yield* db
|
||||
.select()
|
||||
.from(WorkspaceTable)
|
||||
.where(eq(WorkspaceTable.id, workspaceID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return yield* new NotFound({ workspaceID })
|
||||
return row
|
||||
})
|
||||
|
||||
const open = Effect.fn("Workspace.open")(function* (workspaceID: ID) {
|
||||
const existing = connections.get(workspaceID)
|
||||
if (existing) return existing
|
||||
|
||||
const row = yield* load(workspaceID)
|
||||
const driver = yield* registry.get(row.provider)
|
||||
const saveBinding = (value: WorkspaceDriver.Binding) =>
|
||||
db
|
||||
.update(WorkspaceTable)
|
||||
.set({ binding: value })
|
||||
.where(eq(WorkspaceTable.id, workspaceID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
const scope = yield* Scope.fork(lifetime)
|
||||
const environment = yield* driver.connect({ workspaceID, binding: row.binding, saveBinding }).pipe(
|
||||
Effect.provideService(Scope.Scope, scope),
|
||||
Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),
|
||||
)
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const connection: Connection = {
|
||||
driver,
|
||||
environment,
|
||||
saveBinding,
|
||||
lastActivity: yield* Ref.make(now),
|
||||
active: yield* Ref.make(0),
|
||||
scope,
|
||||
}
|
||||
connections.set(workspaceID, connection)
|
||||
yield* db
|
||||
.update(WorkspaceTable)
|
||||
.set({ last_used_at: now })
|
||||
.where(eq(WorkspaceTable.id, workspaceID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
return connection
|
||||
})
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
yield* Effect.forEach(
|
||||
[...connections.entries()],
|
||||
([workspaceID, expected]) =>
|
||||
locks.withLock(workspaceID)(
|
||||
Effect.gen(function* () {
|
||||
const connection = connections.get(workspaceID)
|
||||
if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return
|
||||
const lastActivity = yield* Ref.get(connection.lastActivity)
|
||||
if (now - lastActivity < idleThreshold) return
|
||||
const row = yield* load(workspaceID)
|
||||
// Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.
|
||||
yield* connection.driver.suspendForIdle({
|
||||
workspaceID,
|
||||
binding: row.binding,
|
||||
saveBinding: connection.saveBinding,
|
||||
})
|
||||
yield* db
|
||||
.update(WorkspaceTable)
|
||||
.set({ last_used_at: lastActivity })
|
||||
.where(eq(WorkspaceTable.id, workspaceID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
connections.delete(workspaceID)
|
||||
yield* Scope.close(connection.scope, Exit.void)
|
||||
}).pipe(Effect.catchCause((cause) => Effect.logError("workspace idle suspension failed", cause))),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
)
|
||||
}).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)
|
||||
|
||||
return Service.of({
|
||||
create: Effect.fn("Workspace.create")(function* (provider) {
|
||||
const driver = yield* registry.get(provider)
|
||||
const workspaceID = ID.create()
|
||||
const result = yield* driver.create({ workspaceID })
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
yield* db
|
||||
.insert(WorkspaceTable)
|
||||
.values({ id: workspaceID, provider, binding: result.binding, created_at: now, last_used_at: now })
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
return new Info({ id: workspaceID, provider, binding: result.binding, createdAt: now, lastUsedAt: now })
|
||||
}),
|
||||
connect: Effect.fn("Workspace.connect")(function* (workspaceID) {
|
||||
const spawner = make((command) =>
|
||||
Effect.acquireRelease(
|
||||
locks.withLock(workspaceID)(
|
||||
Effect.gen(function* () {
|
||||
const connection = yield* open(workspaceID).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Workspace",
|
||||
method: "spawn",
|
||||
description: `Failed to wake workspace ${workspaceID}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)
|
||||
yield* Ref.update(connection.active, (active) => active + 1)
|
||||
return connection
|
||||
}),
|
||||
),
|
||||
(connection) =>
|
||||
locks.withLock(workspaceID)(
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.update(connection.active, (active) => active - 1)
|
||||
yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),
|
||||
)
|
||||
// Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.
|
||||
return { spawner }
|
||||
}),
|
||||
destroy: Effect.fn("Workspace.destroy")(function* (workspaceID) {
|
||||
yield* locks.withLock(workspaceID)(
|
||||
Effect.gen(function* () {
|
||||
const row = yield* load(workspaceID)
|
||||
const connection = connections.get(workspaceID)
|
||||
connections.delete(workspaceID)
|
||||
if (connection) yield* Scope.close(connection.scope, Exit.void)
|
||||
const driver = yield* registry.get(row.provider)
|
||||
yield* driver.destroy({ workspaceID, binding: row.binding })
|
||||
yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)
|
||||
}),
|
||||
)
|
||||
}),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
export const node = configured()
|
||||
|
||||
// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.
|
||||
// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.
|
||||
// TODO(workspace-plan): consider RcMap at end-of-series consolidation; idle suspend and destroy need distinct finalizers.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
export * as WorkspaceDriver from "./driver"
|
||||
|
||||
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
|
||||
import { Context, Effect, Layer, Schema } from "effect"
|
||||
import type { Scope } from "effect"
|
||||
import type { Driver as EnvironmentDriver } from "../environment/driver"
|
||||
|
||||
/**
|
||||
* Smallest provider-owned JSON value required to reconnect to the same
|
||||
* provider resource. Core stores it opaquely and hands it back; only the
|
||||
* owning driver reads inside.
|
||||
*/
|
||||
export const Binding = Schema.Record(Schema.String, Schema.Json)
|
||||
export type Binding = typeof Binding.Type
|
||||
|
||||
export class Error extends Schema.TaggedErrorClass<Error>()("WorkspaceDriver.Error", {
|
||||
message: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export class ProviderNotFound extends Schema.TaggedErrorClass<ProviderNotFound>()("WorkspaceDriver.ProviderNotFound", {
|
||||
provider: Schema.String,
|
||||
}) {}
|
||||
|
||||
export interface Interface {
|
||||
readonly create: (input: {
|
||||
readonly workspaceID: Workspace.ID
|
||||
}) => Effect.Effect<{ readonly binding: Binding }, Error>
|
||||
readonly connect: (input: {
|
||||
readonly workspaceID: Workspace.ID
|
||||
readonly binding: Binding
|
||||
readonly saveBinding: (binding: Binding) => Effect.Effect<void>
|
||||
}) => Effect.Effect<EnvironmentDriver, Error, Scope.Scope>
|
||||
readonly suspendForIdle: (input: {
|
||||
readonly workspaceID: Workspace.ID
|
||||
readonly binding: Binding
|
||||
readonly saveBinding: (binding: Binding) => Effect.Effect<void>
|
||||
}) => Effect.Effect<void, Error>
|
||||
readonly destroy: (input: {
|
||||
readonly workspaceID: Workspace.ID
|
||||
readonly binding: Binding
|
||||
}) => Effect.Effect<void, Error>
|
||||
}
|
||||
|
||||
export const make = (driver: Interface) => driver
|
||||
|
||||
export interface Registry {
|
||||
readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>
|
||||
}
|
||||
|
||||
export class RegistryService extends Context.Service<RegistryService, Registry>()(
|
||||
"@opencode/WorkspaceDriverRegistry",
|
||||
) {}
|
||||
|
||||
export const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({
|
||||
get: (provider) => {
|
||||
const driver = drivers[provider]
|
||||
return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))
|
||||
},
|
||||
})
|
||||
|
||||
export const registryNode = (drivers: Readonly<Record<string, Interface>>) =>
|
||||
makeGlobalNode({
|
||||
service: RegistryService,
|
||||
layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),
|
||||
deps: [],
|
||||
})
|
||||
|
||||
export const node = registryNode({})
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
|
||||
import type { WorkspaceDriver } from "./driver"
|
||||
|
||||
export const WorkspaceTable = sqliteTable("workspace", {
|
||||
id: text().$type<Workspace.ID>().primaryKey(),
|
||||
provider: text().notNull(),
|
||||
binding: text({ mode: "json" }).$type<WorkspaceDriver.Binding>().notNull(),
|
||||
created_at: integer().notNull(),
|
||||
last_used_at: integer().notNull(),
|
||||
})
|
||||
@@ -9,11 +9,12 @@ import { Environment } from "@opencode-ai/core/environment"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { LocationMutation } from "@opencode-ai/core/location-mutation"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { type EnvironmentFilesTransform, transformEnvironmentFiles } from "./fixture/environment"
|
||||
import { location } from "./fixture/location"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { it } from "./lib/effect"
|
||||
|
||||
function provide(directory: string, environmentLayer = LayerNode.compile(Environment.node)) {
|
||||
function provide(directory: string, transformFiles: EnvironmentFilesTransform = () => ({})) {
|
||||
const activeLocation = Layer.succeed(
|
||||
Location.Service,
|
||||
Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
|
||||
@@ -21,7 +22,7 @@ function provide(directory: string, environmentLayer = LayerNode.compile(Environ
|
||||
return Effect.provide(
|
||||
AppNodeBuilder.build(LayerNode.group([LocationMutation.node, FileMutation.node]), [
|
||||
[Location.node, activeLocation],
|
||||
[Environment.node, environmentLayer],
|
||||
[Environment.node, transformEnvironmentFiles(activeLocation, transformFiles)],
|
||||
]),
|
||||
)
|
||||
}
|
||||
@@ -240,18 +241,8 @@ describe("FileMutation", () => {
|
||||
)
|
||||
})
|
||||
|
||||
function instrumentWrites(run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>) {
|
||||
return Layer.effect(
|
||||
Environment.Service,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* Environment.Service
|
||||
return Environment.Service.of({
|
||||
...environment,
|
||||
files: {
|
||||
...environment.files,
|
||||
write: (target, content) => run(environment.files.write(target, content), target),
|
||||
},
|
||||
})
|
||||
}),
|
||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
||||
function instrumentWrites(
|
||||
run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>,
|
||||
): EnvironmentFilesTransform {
|
||||
return (files) => ({ write: (target, content) => run(files.write(target, content), target) })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { Environment } from "@opencode-ai/core/environment"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { Effect, Layer } from "effect"
|
||||
|
||||
export type EnvironmentFilesTransform = (files: Environment.Files) => Partial<Environment.Files>
|
||||
|
||||
export function transformEnvironmentFiles(
|
||||
location: Layer.Layer<Location.Service>,
|
||||
transform: EnvironmentFilesTransform = () => ({}),
|
||||
) {
|
||||
return Layer.effect(
|
||||
Environment.Service,
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Environment.Service
|
||||
return Environment.Service.of({
|
||||
...current,
|
||||
files: { ...current.files, ...transform(current.files) },
|
||||
})
|
||||
}),
|
||||
).pipe(Layer.provide(AppNodeBuilder.build(Environment.node, [[Location.node, location]])))
|
||||
}
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -305,11 +305,13 @@ describe("LocationServiceMap", () => {
|
||||
)
|
||||
yield* Deferred.await(started)
|
||||
|
||||
yield* PluginSupervisor.Service.use((supervisor) => supervisor.flush).pipe(
|
||||
const flushFiber = yield* PluginSupervisor.Service.use((supervisor) => supervisor.flush).pipe(
|
||||
Effect.provide(context),
|
||||
Effect.timeout("1 second"),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
)
|
||||
expect(flushFiber.pollUnsafe()).toBeUndefined()
|
||||
yield* Deferred.succeed(release, undefined)
|
||||
yield* Fiber.join(flushFiber)
|
||||
yield* Deferred.await(completed)
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -3,12 +3,15 @@ import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { Effect } from "effect"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { Ripgrep } from "@opencode-ai/core/ripgrep"
|
||||
import { RelativePath } from "@opencode-ai/core/schema"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { tempLocationLayer } from "./fixture/location"
|
||||
|
||||
const it = testEffect(LayerNode.compile(Ripgrep.node))
|
||||
const it = testEffect(AppNodeBuilder.build(Ripgrep.node, [[Location.node, tempLocationLayer]]))
|
||||
|
||||
describe("Ripgrep", () => {
|
||||
it.live("globs files as an array", () =>
|
||||
|
||||
@@ -3,7 +3,8 @@ import { Message } from "@opencode-ai/ai"
|
||||
import { Model } from "@opencode-ai/core/model"
|
||||
import { Provider } from "@opencode-ai/core/provider"
|
||||
import { SessionMessage } from "@opencode-ai/core/session/message"
|
||||
import { AgentAttachment, Base64, FileAttachment } from "@opencode-ai/schema/prompt"
|
||||
import { AgentAttachment, Base64, FileAttachment, SkillAttachment } from "@opencode-ai/schema/prompt"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message"
|
||||
import { Agent } from "@opencode-ai/core/agent"
|
||||
import { Shell } from "@opencode-ai/schema/shell"
|
||||
@@ -184,6 +185,40 @@ Recent work
|
||||
})
|
||||
})
|
||||
|
||||
test("lowers selected skill instructions with the original user prompt", () => {
|
||||
const messages = toLLMMessages(
|
||||
[
|
||||
SessionMessage.User.make({
|
||||
id: id("user-skill"),
|
||||
type: "user",
|
||||
text: "Design this API",
|
||||
skills: [
|
||||
SkillAttachment.make({
|
||||
id: Skill.ID.make("api-design"),
|
||||
name: Skill.Name.make("API design"),
|
||||
text: "Start from the ideal call site.",
|
||||
}),
|
||||
],
|
||||
time: { created },
|
||||
}),
|
||||
],
|
||||
model,
|
||||
)
|
||||
|
||||
expect(messages).toHaveLength(1)
|
||||
expect(messages[0]).toMatchObject({
|
||||
id: id("user-skill"),
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Start from the ideal call site.",
|
||||
},
|
||||
{ type: "text", text: "Design this API" },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
test("decodes inline text attachment content", () => {
|
||||
const messages = toLLMMessages(
|
||||
[
|
||||
|
||||
@@ -15,6 +15,7 @@ import { SessionExecution } from "@opencode-ai/core/session/execution"
|
||||
import { SessionMessage } from "@opencode-ai/core/session/message"
|
||||
import { SessionProjector } from "@opencode-ai/core/session/projector"
|
||||
import { SessionStore } from "@opencode-ai/core/session/store"
|
||||
import { SessionPending } from "@opencode-ai/core/session/pending"
|
||||
import { Skill } from "@opencode-ai/core/skill"
|
||||
import { testEffect } from "./lib/effect"
|
||||
|
||||
@@ -55,6 +56,41 @@ const it = testEffect(
|
||||
)
|
||||
|
||||
describe("Session.skill", () => {
|
||||
it.effect("attaches a resolved skill snapshot to a normal prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
const database = yield* Database.Service
|
||||
const bus = yield* Bus.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
const id = SessionMessage.ID.make("msg_skill_attachment")
|
||||
|
||||
yield* sessions.prompt({
|
||||
id,
|
||||
sessionID: session.id,
|
||||
text: "Apply this guidance",
|
||||
skills: [{ id: Skill.ID.make("effect"), mention: { start: 20, end: 27, text: "/effect" } }],
|
||||
resume: false,
|
||||
})
|
||||
yield* SessionPending.promote(database.db, bus, session.id, "steer")
|
||||
|
||||
expect(yield* sessions.messages({ sessionID: session.id })).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id,
|
||||
type: "user",
|
||||
text: "Apply this guidance",
|
||||
skills: [
|
||||
{
|
||||
id: "effect",
|
||||
name: "Effect",
|
||||
text: expect.stringContaining("Use Effect"),
|
||||
mention: { start: 20, end: 27, text: "/effect" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("projects the caller-supplied message ID", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
|
||||
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Tool } from "@opencode-ai/core/tool"
|
||||
import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
|
||||
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||
import { location } from "./fixture/location"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||
@@ -80,29 +81,6 @@ const reset = () => {
|
||||
formatFile = () => Effect.succeed(false)
|
||||
}
|
||||
|
||||
const environment = Layer.effect(
|
||||
Environment.Service,
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Environment.Service
|
||||
return Environment.Service.of({
|
||||
...current,
|
||||
files: {
|
||||
...current.files,
|
||||
read: (target, range) =>
|
||||
current.files
|
||||
.read(target, range)
|
||||
.pipe(
|
||||
Effect.tap((result) =>
|
||||
Effect.sync(() => reads++).pipe(Effect.andThen(Effect.suspend(() => afterRead(target, result.bytes)))),
|
||||
),
|
||||
),
|
||||
write: (target, content) =>
|
||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(current.files.write(target, content))),
|
||||
},
|
||||
})
|
||||
}),
|
||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
||||
|
||||
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
||||
const activeLocation = Layer.succeed(
|
||||
Location.Service,
|
||||
@@ -115,7 +93,23 @@ const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) =
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, editToolNode]),
|
||||
[
|
||||
[Environment.node, environment],
|
||||
[
|
||||
Environment.node,
|
||||
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||
read: (target, range) =>
|
||||
files
|
||||
.read(target, range)
|
||||
.pipe(
|
||||
Effect.tap((result) =>
|
||||
Effect.sync(() => reads++).pipe(
|
||||
Effect.andThen(Effect.suspend(() => afterRead(target, result.bytes))),
|
||||
),
|
||||
),
|
||||
),
|
||||
write: (target, content) =>
|
||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
|
||||
})),
|
||||
],
|
||||
[Location.node, activeLocation],
|
||||
[Formatter.node, formatter],
|
||||
[Permission.node, permission],
|
||||
|
||||
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Tool } from "@opencode-ai/core/tool"
|
||||
import { PatchTool } from "@opencode-ai/core/tool/plugin/patch"
|
||||
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||
import { location } from "./fixture/location"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||
@@ -82,34 +83,6 @@ const reset = () => {
|
||||
formatFile = () => Effect.succeed(false)
|
||||
}
|
||||
|
||||
const environment = Layer.effect(
|
||||
Environment.Service,
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Environment.Service
|
||||
return Environment.Service.of({
|
||||
...current,
|
||||
files: {
|
||||
...current.files,
|
||||
read: (target, range) =>
|
||||
Effect.sync(() => {
|
||||
if (!editApproved) readsBeforeEditApproval++
|
||||
}).pipe(Effect.andThen(current.files.read(target, range))),
|
||||
remove: (target) => {
|
||||
if (failRemoveTarget && path.basename(target) === failRemoveTarget) return Effect.die("forced remove failure")
|
||||
if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget)
|
||||
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") }))
|
||||
return current.files.remove(target)
|
||||
},
|
||||
write: (target, content) => {
|
||||
if (failWriteTarget && path.basename(target) === failWriteTarget)
|
||||
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") }))
|
||||
return current.files.write(target, content)
|
||||
},
|
||||
},
|
||||
})
|
||||
}),
|
||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
||||
|
||||
const withTool = <A, E, R>(
|
||||
directory: string,
|
||||
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>,
|
||||
@@ -126,7 +99,27 @@ const withTool = <A, E, R>(
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AppNodeBuilder.build(LayerNode.group([Tool.node, FileMutation.node, patchToolNode]), [
|
||||
[Environment.node, environment],
|
||||
[
|
||||
Environment.node,
|
||||
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||
read: (target, range) =>
|
||||
Effect.sync(() => {
|
||||
if (!editApproved) readsBeforeEditApproval++
|
||||
}).pipe(Effect.andThen(files.read(target, range))),
|
||||
remove: (target) => {
|
||||
if (failRemoveTarget && path.basename(target) === failRemoveTarget)
|
||||
return Effect.die("forced remove failure")
|
||||
if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget)
|
||||
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") }))
|
||||
return files.remove(target)
|
||||
},
|
||||
write: (target, content) => {
|
||||
if (failWriteTarget && path.basename(target) === failWriteTarget)
|
||||
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") }))
|
||||
return files.write(target, content)
|
||||
},
|
||||
})),
|
||||
],
|
||||
[Location.node, activeLocation],
|
||||
[Formatter.node, formatter],
|
||||
[Permission.node, permission],
|
||||
|
||||
@@ -105,9 +105,9 @@ describe("SkillTool", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "completed",
|
||||
content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
|
||||
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }],
|
||||
})
|
||||
expect(SkillTool.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
|
||||
expect(Skill.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
@@ -116,8 +116,8 @@ describe("SkillTool", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
status: "completed",
|
||||
output: { name: "Effect", directory, output: SkillTool.toModelOutput(info, [reference]) },
|
||||
content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
|
||||
output: { name: "Effect", directory, output: Skill.toModelOutput(info, [reference]) },
|
||||
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }],
|
||||
metadata: { name: "Effect", directory },
|
||||
})
|
||||
expect(assertions).toMatchObject([
|
||||
@@ -168,7 +168,7 @@ describe("SkillTool", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "completed",
|
||||
content: [{ type: "text", text: SkillTool.toModelOutput(flat, []) }],
|
||||
content: [{ type: "text", text: Skill.toModelOutput(flat, []) }],
|
||||
})
|
||||
}).pipe(Effect.provide(skillToolLayer))
|
||||
}),
|
||||
|
||||
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Tool } from "@opencode-ai/core/tool"
|
||||
import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
|
||||
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||
import { location } from "./fixture/location"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||
@@ -68,21 +69,6 @@ const reset = () => {
|
||||
denyAction = undefined
|
||||
}
|
||||
|
||||
const environment = Layer.effect(
|
||||
Environment.Service,
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Environment.Service
|
||||
return Environment.Service.of({
|
||||
...current,
|
||||
files: {
|
||||
...current.files,
|
||||
write: (target, content) =>
|
||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(current.files.write(target, content))),
|
||||
},
|
||||
})
|
||||
}),
|
||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
||||
|
||||
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
||||
const activeLocation = Layer.succeed(
|
||||
Location.Service,
|
||||
@@ -95,7 +81,13 @@ const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) =
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, writeToolNode]),
|
||||
[
|
||||
[Environment.node, environment],
|
||||
[
|
||||
Environment.node,
|
||||
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||
write: (target, content) =>
|
||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
|
||||
})),
|
||||
],
|
||||
[Location.node, activeLocation],
|
||||
[Formatter.node, formatter],
|
||||
[Permission.node, permission],
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { beforeEach, expect } from "bun:test"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { makeMemoryDriver } from "@opencode-ai/core/environment"
|
||||
import { Workspace } from "@opencode-ai/core/workspace"
|
||||
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||
import { WorkspaceTable } from "@opencode-ai/core/workspace/sql"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { Effect } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { ChildProcess } from "effect/unstable/process"
|
||||
import { testEffect } from "./lib/effect"
|
||||
|
||||
const calls: Array<{ readonly operation: string; readonly binding?: WorkspaceDriver.Binding }> = []
|
||||
const memory = makeMemoryDriver()
|
||||
let failConnect = false
|
||||
|
||||
const driver = WorkspaceDriver.make({
|
||||
create: ({ workspaceID }) => {
|
||||
calls.push({ operation: "create" })
|
||||
return Effect.succeed({ binding: { workspaceID, generation: 0 } })
|
||||
},
|
||||
connect: ({ binding }) => {
|
||||
calls.push({ operation: "connect", binding })
|
||||
if (failConnect) return Effect.fail(new WorkspaceDriver.Error({ message: "wake failed" }))
|
||||
return Effect.succeed(memory)
|
||||
},
|
||||
suspendForIdle: ({ binding, saveBinding }) => {
|
||||
calls.push({ operation: "suspendForIdle", binding })
|
||||
return saveBinding({ ...binding, generation: Number(binding.generation) + 1, suspended: true })
|
||||
},
|
||||
destroy: ({ binding }) => {
|
||||
calls.push({ operation: "destroy", binding })
|
||||
return Effect.void
|
||||
},
|
||||
})
|
||||
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Workspace.configured({ idleThreshold: "5 minutes", pollInterval: "1 minute" })]),
|
||||
[[WorkspaceDriver.node, WorkspaceDriver.registryNode({ fake: driver })]],
|
||||
),
|
||||
)
|
||||
|
||||
beforeEach(() => {
|
||||
calls.splice(0)
|
||||
failConnect = false
|
||||
})
|
||||
|
||||
it.effect("persists the workspace lifecycle and reconnects after idle suspension", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspace = yield* Workspace.Service
|
||||
const created = yield* workspace.create("fake")
|
||||
|
||||
expect(created.id.startsWith("wrk_")).toBe(true)
|
||||
expect(created.binding).toEqual({ workspaceID: created.id, generation: 0 })
|
||||
|
||||
const environment = yield* workspace.connect(created.id)
|
||||
expect(calls.map((call) => call.operation)).toEqual(["create"])
|
||||
|
||||
yield* TestClock.adjust("4 minutes")
|
||||
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("activity"))).pipe(Effect.exit)
|
||||
yield* TestClock.adjust("4 minutes")
|
||||
expect(calls.map((call) => call.operation)).toEqual(["create", "connect"])
|
||||
|
||||
yield* TestClock.adjust("2 minutes")
|
||||
expect(calls.map((call) => call.operation)).toEqual(["create", "connect", "suspendForIdle"])
|
||||
|
||||
const stored = yield* Database.Service.use(({ db }) =>
|
||||
db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, created.id)).get(),
|
||||
).pipe(Effect.orDie)
|
||||
expect(stored?.binding).toEqual({ workspaceID: created.id, generation: 1, suspended: true })
|
||||
expect(stored?.last_used_at).toBe(4 * 60 * 1000)
|
||||
|
||||
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("wake"))).pipe(Effect.exit)
|
||||
expect(calls.map((call) => call.operation)).toEqual(["create", "connect", "suspendForIdle", "connect"])
|
||||
expect(calls.at(-1)?.binding).toEqual({ workspaceID: created.id, generation: 1, suspended: true })
|
||||
|
||||
yield* workspace.destroy(created.id)
|
||||
expect(calls.at(-1)?.operation).toBe("destroy")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("surfaces wake failures through the spawn error channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspace = yield* Workspace.Service
|
||||
const created = yield* workspace.create("fake")
|
||||
const environment = yield* workspace.connect(created.id)
|
||||
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("connect"))).pipe(Effect.exit)
|
||||
|
||||
yield* TestClock.adjust("6 minutes")
|
||||
failConnect = true
|
||||
|
||||
const error = yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("wake"))).pipe(Effect.flip)
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PlatformError",
|
||||
reason: {
|
||||
_tag: "Unknown",
|
||||
module: "Workspace",
|
||||
method: "spawn",
|
||||
description: `Failed to wake workspace ${created.id}`,
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
@@ -1316,7 +1316,15 @@ export function write(
|
||||
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
|
||||
{ concurrency: 8, discard: true },
|
||||
)
|
||||
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
|
||||
// Format the manifest with the same prettier settings as the repo-wide
|
||||
// format pass, so `check:generated` stays clean after the generate bot
|
||||
// reformats the tree.
|
||||
const manifestJson = JSON.stringify(output.files.map((file) => file.path).sort())
|
||||
const manifestContent = yield* Effect.tryPromise({
|
||||
try: () => format(manifestJson, { filepath: manifest, parser: "json", printWidth: 120 }),
|
||||
catch: (error) => new GenerationError({ reason: `Failed to format ${manifest}: ${String(error)}` }),
|
||||
})
|
||||
yield* fs.writeFileString(manifest, manifestContent)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ describe("HttpApiCodegen.write", () => {
|
||||
|
||||
expect(writes).toEqual([
|
||||
{ path: "/generated/session.ts", content: "export const session = {}\n" },
|
||||
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' },
|
||||
{ path: "/generated/.httpapi-codegen.json", content: '["session.ts"]\n' },
|
||||
])
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"entities": "7.0.1",
|
||||
"string-width": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -7,6 +7,18 @@ describe("DiagramCanvas", () => {
|
||||
expect(() => new DiagramCanvas(2_000, 1_000)).toThrow(DiagramCanvasSizeError)
|
||||
})
|
||||
|
||||
test("rejects invalid canvas dimensions", () => {
|
||||
for (const [width, height] of [
|
||||
[-1, 10],
|
||||
[10, -1],
|
||||
[1.5, 10],
|
||||
[Number.NaN, 10],
|
||||
[Number.POSITIVE_INFINITY, 10],
|
||||
]) {
|
||||
expect(() => new DiagramCanvas(width, height)).toThrow(DiagramCanvasSizeError)
|
||||
}
|
||||
})
|
||||
|
||||
test("writes cells and text while clipping out-of-bounds positions", () => {
|
||||
const canvas = new DiagramCanvas<"label">(5, 2)
|
||||
|
||||
@@ -26,6 +38,21 @@ describe("DiagramCanvas", () => {
|
||||
expect(stringWidth(canvas.toString())).toBe(4)
|
||||
})
|
||||
|
||||
test("keeps custom measurement for ASCII text", () => {
|
||||
let measurements = 0
|
||||
const canvas = new DiagramCanvas<"label">(5, 1, {
|
||||
measure: () => {
|
||||
measurements += 1
|
||||
return 2
|
||||
},
|
||||
})
|
||||
|
||||
canvas.setText(0, 0, "ab", "label")
|
||||
|
||||
expect(measurements).toBe(2)
|
||||
expect(canvas.getCell(2, 0)?.char).toBe("b")
|
||||
})
|
||||
|
||||
test("preserves combined graphemes while placing later text", () => {
|
||||
const canvas = new DiagramCanvas<"label">(4, 1)
|
||||
|
||||
@@ -48,6 +75,9 @@ describe("DiagramCanvas", () => {
|
||||
canvas.setCell(1, 0, "│", "line")
|
||||
|
||||
expect(canvas.toString()).toBe(" ┼")
|
||||
|
||||
canvas.replaceCell(1, 0, "│", "line")
|
||||
expect(canvas.toString()).toBe(" │")
|
||||
})
|
||||
|
||||
test("iterates style and metadata runs", () => {
|
||||
@@ -93,4 +123,61 @@ describe("DiagramCanvas", () => {
|
||||
expect(canvas.toString({ trimTop: true })).toBe("end")
|
||||
expect(canvas.getTextSize({ trimTop: true })).toEqual({ width: 3, height: 1 })
|
||||
})
|
||||
|
||||
test("measures trim-aware text height without measuring row width", () => {
|
||||
let measurements = 0
|
||||
const canvas = new DiagramCanvas(8, 5, {
|
||||
measure: (text) => {
|
||||
measurements += 1
|
||||
return stringWidth(text)
|
||||
},
|
||||
})
|
||||
canvas.setText(1, 2, "middle")
|
||||
measurements = 0
|
||||
|
||||
expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(1)
|
||||
expect(measurements).toBe(0)
|
||||
})
|
||||
|
||||
test("updates tracked row extents when the last visible cell is cleared", () => {
|
||||
const canvas = new DiagramCanvas(8, 1)
|
||||
canvas.setText(1, 0, "abc")
|
||||
canvas.setCell(3, 0, " ")
|
||||
|
||||
expect(canvas.toString()).toBe(" ab")
|
||||
expect(canvas.getTextSize()).toEqual({ width: 3, height: 1 })
|
||||
})
|
||||
|
||||
test("keeps tracked extents equivalent to scanning after mixed writes", () => {
|
||||
const canvas = new DiagramCanvas<"line">(20, 10, {
|
||||
mergeCell: (_existing, incoming) => incoming,
|
||||
})
|
||||
let seed = 42
|
||||
const next = (limit: number) => {
|
||||
seed = (seed * 1_664_525 + 1_013_904_223) >>> 0
|
||||
return seed % limit
|
||||
}
|
||||
|
||||
for (let index = 0; index < 200; index++) {
|
||||
const x = next(canvas.width)
|
||||
const y = next(canvas.height)
|
||||
const char = [" ", "x", "─"][next(3)]!
|
||||
if (next(2) === 0) canvas.setCell(x, y, char, "line")
|
||||
else canvas.replaceCell(x, y, char, "line")
|
||||
}
|
||||
|
||||
const scanned = canvas.rows.map((row) => {
|
||||
let end = row.length
|
||||
while (end > 0 && row[end - 1]?.char === " ") end -= 1
|
||||
return row
|
||||
.slice(0, end)
|
||||
.map((cell) => cell.char)
|
||||
.join("")
|
||||
})
|
||||
const first = scanned.findIndex((line) => line.length > 0)
|
||||
const last = scanned.findLastIndex((line) => line.length > 0)
|
||||
|
||||
expect(canvas.toString()).toBe(scanned.join("\n"))
|
||||
expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(first < 0 ? 0 : last - first + 1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -47,7 +47,12 @@ export class DiagramCanvasSizeError extends Error {
|
||||
readonly width: number,
|
||||
readonly height: number,
|
||||
) {
|
||||
super(`Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`)
|
||||
const invalid = !Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0
|
||||
super(
|
||||
invalid
|
||||
? `Diagram canvas dimensions must be non-negative safe integers, received ${width}x${height}`
|
||||
: `Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`,
|
||||
)
|
||||
this.name = "DiagramCanvasSizeError"
|
||||
}
|
||||
}
|
||||
@@ -61,29 +66,31 @@ function sameKey(left: readonly unknown[] | undefined, right: readonly unknown[]
|
||||
}
|
||||
|
||||
export class DiagramCanvas<Style extends string, Metadata extends object = object> {
|
||||
readonly rows: Array<Array<DiagramCanvasCell<Style, Metadata>>>
|
||||
|
||||
private readonly cells: Array<Array<DiagramCanvasCell<Style, Metadata>>>
|
||||
private readonly measure: (text: string) => number
|
||||
private readonly mergeCell?: DiagramCanvasOptions<Style, Metadata>["mergeCell"]
|
||||
private readonly rowEnds: Uint32Array
|
||||
|
||||
constructor(
|
||||
readonly width: number,
|
||||
readonly height: number,
|
||||
options: DiagramCanvasOptions<Style, Metadata> = {},
|
||||
) {
|
||||
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0) {
|
||||
throw new DiagramCanvasSizeError(width, height)
|
||||
}
|
||||
if (width * height > MAX_DIAGRAM_CELLS) throw new DiagramCanvasSizeError(width, height)
|
||||
this.measure = options.measure ?? stringWidth
|
||||
this.mergeCell = options.mergeCell
|
||||
this.rows = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
|
||||
this.cells = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
|
||||
this.rowEnds = new Uint32Array(height)
|
||||
}
|
||||
|
||||
private rowTextEnd(row: Array<DiagramCanvasCell<Style, Metadata>>): number {
|
||||
let rowEnd = row.length
|
||||
while (rowEnd > 0 && row[rowEnd - 1]?.char === " ") rowEnd -= 1
|
||||
return rowEnd
|
||||
get rows(): ReadonlyArray<ReadonlyArray<Readonly<DiagramCanvasCell<Style, Metadata>>>> {
|
||||
return this.cells
|
||||
}
|
||||
|
||||
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd = this.rowTextEnd(row)): string {
|
||||
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd: number): string {
|
||||
return row
|
||||
.slice(0, rowEnd)
|
||||
.map((cell) => cell.char)
|
||||
@@ -92,28 +99,58 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
|
||||
private textRowRange(trimTop: boolean, trimBottom: boolean): { start: number; end: number } {
|
||||
let start = 0
|
||||
let end = this.rows.length
|
||||
if (trimTop) while (start < end && this.rowTextEnd(this.rows[start]!) === 0) start += 1
|
||||
if (trimBottom) while (end > start && this.rowTextEnd(this.rows[end - 1]!) === 0) end -= 1
|
||||
let end = this.cells.length
|
||||
if (trimTop) while (start < end && this.rowEnds[start] === 0) start += 1
|
||||
if (trimBottom) while (end > start && this.rowEnds[end - 1] === 0) end -= 1
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
setCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
|
||||
if (y < 0 || y >= this.rows.length || x < 0 || x >= this.rows[y]!.length) return
|
||||
|
||||
const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
|
||||
this.rows[y]![x] = this.mergeCell?.(this.rows[y]![x]!, incoming) ?? incoming
|
||||
this.writeCell(x, y, char, style, metadata, true)
|
||||
}
|
||||
|
||||
getCell(x: number, y: number): DiagramCanvasCell<Style, Metadata> | undefined {
|
||||
return this.rows[y]?.[x]
|
||||
replaceCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
|
||||
this.writeCell(x, y, char, style, metadata, false)
|
||||
}
|
||||
|
||||
private writeCell(
|
||||
x: number,
|
||||
y: number,
|
||||
char: string,
|
||||
style: Style | undefined,
|
||||
metadata: Partial<Metadata> | undefined,
|
||||
merge: boolean,
|
||||
): void {
|
||||
if (y < 0 || y >= this.cells.length || x < 0 || x >= this.cells[y]!.length) return
|
||||
|
||||
const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
|
||||
const cell = merge ? (this.mergeCell?.(this.cells[y]![x]!, incoming) ?? incoming) : incoming
|
||||
this.cells[y]![x] = cell
|
||||
if (cell.char !== " ") {
|
||||
this.rowEnds[y] = Math.max(this.rowEnds[y]!, x + 1)
|
||||
} else if (this.rowEnds[y] === x + 1) {
|
||||
let end = x
|
||||
while (end > 0 && this.cells[y]![end - 1]?.char === " ") end -= 1
|
||||
this.rowEnds[y] = end
|
||||
}
|
||||
}
|
||||
|
||||
getCell(x: number, y: number): Readonly<DiagramCanvasCell<Style, Metadata>> | undefined {
|
||||
return this.cells[y]?.[x]
|
||||
}
|
||||
|
||||
setText(x: number, y: number, text: string, style?: Style, metadata?: DiagramCanvasTextMetadata<Metadata>): void {
|
||||
const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
|
||||
if (this.measure === stringWidth && /^[\x20-\x7e]*$/.test(text)) {
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
this.setCell(x + index, y, text[index]!, style, metadataAt(x + index))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let offset = 0
|
||||
for (const grapheme of diagramTextGraphemes(text)) {
|
||||
const width = Math.max(1, this.measure(grapheme))
|
||||
const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
|
||||
this.setCell(x + offset, y, grapheme, style, metadataAt(x + offset))
|
||||
for (let continuation = 1; continuation < width; continuation++) {
|
||||
this.setCell(x + offset + continuation, y, "", style, metadataAt(x + offset + continuation))
|
||||
@@ -126,7 +163,7 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
const lines: string[] = []
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
|
||||
lines.push(this.rowText(this.rows[rowIndex]!))
|
||||
lines.push(this.rowText(this.cells[rowIndex]!, this.rowEnds[rowIndex]!))
|
||||
}
|
||||
return lines.join("\n")
|
||||
}
|
||||
@@ -135,13 +172,18 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
let width = 0
|
||||
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
|
||||
const row = this.rows[rowIndex]!
|
||||
const rowEnd = this.rowTextEnd(row)
|
||||
const row = this.cells[rowIndex]!
|
||||
const rowEnd = this.rowEnds[rowIndex]!
|
||||
if (rowEnd > 0) width = Math.max(width, this.measure(this.rowText(row, rowEnd)))
|
||||
}
|
||||
return { width, height: rows.end - rows.start }
|
||||
}
|
||||
|
||||
getTextHeight(options: DiagramCanvasTextOptions = {}): number {
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
return rows.end - rows.start
|
||||
}
|
||||
|
||||
forEachRun(
|
||||
onRun: (run: DiagramCanvasRun<Style, Metadata>) => void,
|
||||
onLineEnd: () => void,
|
||||
@@ -151,8 +193,8 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
|
||||
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
|
||||
const row = this.rows[rowIndex]!
|
||||
const rowEnd = this.rowTextEnd(row)
|
||||
const row = this.cells[rowIndex]!
|
||||
const rowEnd = this.rowEnds[rowIndex]!
|
||||
|
||||
let currentCell: DiagramCanvasCell<Style, Metadata> | undefined
|
||||
let currentKey: readonly unknown[] | undefined
|
||||
|
||||
@@ -27,7 +27,12 @@ export function firstMeaningfulMermaidLine(content: string): string | undefined
|
||||
export function stripMermaidQuotes(value: string): string {
|
||||
const trimmed = value.trim()
|
||||
if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
|
||||
return trimmed.slice(1, -1)
|
||||
return decodeMermaidText(trimmed.slice(1, -1))
|
||||
}
|
||||
return trimmed
|
||||
return decodeMermaidText(trimmed)
|
||||
}
|
||||
|
||||
export function decodeMermaidText(value: string): string {
|
||||
return decodeHTMLStrict(value)
|
||||
}
|
||||
import { decodeHTMLStrict } from "entities"
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "./spatial.js"
|
||||
|
||||
const body = spatialRectClaim("body", "node:A", "body", { left: 2, top: 1, width: 4, height: 3 })
|
||||
const label = spatialRectClaim("label", "edge:A-B", "label", { left: 8, top: 1, width: 5, height: 1 })
|
||||
const route = spatialPathClaim("route", "edge:A-B", "route", [
|
||||
{ x: 5, y: 2 },
|
||||
{ x: 10, y: 2 },
|
||||
])
|
||||
|
||||
describe("SpatialIndex", () => {
|
||||
test("composition is associative, commutative, idempotent, and has an identity", () => {
|
||||
const a = SpatialIndex.empty().add(body)
|
||||
const b = SpatialIndex.empty().add(label)
|
||||
const c = SpatialIndex.empty().add(route)
|
||||
|
||||
expect(SpatialIndex.empty().overlay(a).claims).toEqual(a.claims)
|
||||
expect(a.overlay(b).claims).toEqual(b.overlay(a).claims)
|
||||
expect(a.overlay(b).overlay(c).claims).toEqual(a.overlay(b.overlay(c)).claims)
|
||||
expect(a.overlay(a).claims).toEqual(a.claims)
|
||||
})
|
||||
|
||||
test("routes may share routes but cannot cross unrelated semantic bodies", () => {
|
||||
const index = SpatialIndex.empty().add(body, route)
|
||||
const crossingBody = spatialPathClaim("cross-body", "edge:C-D", "route", [
|
||||
{ x: 0, y: 2 },
|
||||
{ x: 8, y: 2 },
|
||||
])
|
||||
const crossingRoute = spatialPathClaim("cross-route", "edge:C-D", "route", [
|
||||
{ x: 7, y: 0 },
|
||||
{ x: 7, y: 4 },
|
||||
])
|
||||
|
||||
expect(index.isFree(crossingBody)).toBe(false)
|
||||
expect(index.isFree(crossingRoute)).toBe(true)
|
||||
})
|
||||
|
||||
test("declared endpoint contacts do not permit contact elsewhere", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const candidate = spatialPathClaim("candidate", "edge:B-A", "route", [
|
||||
{ x: 0, y: 2 },
|
||||
{ x: 2, y: 2 },
|
||||
])
|
||||
|
||||
expect(index.isFree(candidate)).toBe(false)
|
||||
expect(index.isFree(candidate, { contacts: [{ owner: "node:A", points: [{ x: 2, y: 2 }] }] })).toBe(true)
|
||||
})
|
||||
|
||||
test("firstFit chooses the first collision-free candidate", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const blocked = spatialRectClaim("blocked", "label:B", "label", { left: 3, top: 2, width: 2, height: 1 })
|
||||
const clear = spatialRectClaim("clear", "label:B", "label", { left: 7, top: 2, width: 2, height: 1 })
|
||||
|
||||
expect(index.firstFit([{ claim: blocked }, { claim: clear }])?.claim.id).toBe("clear")
|
||||
})
|
||||
|
||||
test("clearance is symmetric in both axes", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const touchingRight = spatialRectClaim("right", "label:B", "label", { left: 6, top: 1, width: 2, height: 1 })
|
||||
const touchingBelow = spatialRectClaim("below", "label:C", "label", { left: 2, top: 4, width: 2, height: 1 })
|
||||
|
||||
expect(index.isFree(touchingRight)).toBe(true)
|
||||
expect(index.isFree(touchingRight, { clearance: 1 })).toBe(false)
|
||||
expect(index.isFree(touchingBelow)).toBe(true)
|
||||
expect(index.isFree(touchingBelow, { clearance: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
test("axis-specific clearance does not move unrelated rows", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const touchingRight = spatialRectClaim("right", "label:B", "label", { left: 6, top: 1, width: 2, height: 1 })
|
||||
const touchingBelow = spatialRectClaim("below", "label:C", "label", { left: 2, top: 4, width: 2, height: 1 })
|
||||
|
||||
expect(index.isFree(touchingRight, { clearance: { x: 1, y: 0 } })).toBe(false)
|
||||
expect(index.isFree(touchingBelow, { clearance: { x: 1, y: 0 } })).toBe(true)
|
||||
})
|
||||
|
||||
test("rejects malformed geometry instead of weakening collision checks", () => {
|
||||
expect(() => spatialRectClaim("zero", "node", "body", { left: 0, top: 0, width: 0, height: 1 })).toThrow()
|
||||
expect(() =>
|
||||
spatialPathClaim("diagonal", "edge", "route", [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
]),
|
||||
).toThrow()
|
||||
expect(() => SpatialIndex.empty().add(body).isFree(label, { clearance: Number.POSITIVE_INFINITY })).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,242 @@
|
||||
import { orthogonalPathPoints, type DiagramBounds, type DiagramPoint } from "./geometry.js"
|
||||
|
||||
export type SpatialRole = "body" | "boundary" | "terminal" | "route" | "label"
|
||||
|
||||
export interface SpatialSpan {
|
||||
readonly y: number
|
||||
readonly fromX: number
|
||||
readonly toX: number
|
||||
}
|
||||
|
||||
export interface SpatialClaim {
|
||||
readonly id: string
|
||||
readonly owner: string
|
||||
readonly role: SpatialRole
|
||||
readonly spans: readonly SpatialSpan[]
|
||||
}
|
||||
|
||||
export interface SpatialContact {
|
||||
owner: string
|
||||
points: readonly DiagramPoint[]
|
||||
}
|
||||
|
||||
export interface SpatialConflict {
|
||||
moving: SpatialClaim
|
||||
existing: SpatialClaim
|
||||
point: DiagramPoint
|
||||
}
|
||||
|
||||
export interface SpatialClearance {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface SpatialCollisionPolicy {
|
||||
contacts?: readonly SpatialContact[]
|
||||
clearance?: number | SpatialClearance | Partial<Record<SpatialRole, number | SpatialClearance>>
|
||||
}
|
||||
|
||||
function normalizedSpan(y: number, fromX: number, toX: number): SpatialSpan {
|
||||
return { y, fromX: Math.min(fromX, toX), toX: Math.max(fromX, toX) }
|
||||
}
|
||||
|
||||
function assertFiniteInteger(value: number, name: string): void {
|
||||
if (!Number.isFinite(value) || !Number.isInteger(value)) throw new RangeError(`${name} must be a finite integer`)
|
||||
}
|
||||
|
||||
export function spatialRectSpans(bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">): SpatialSpan[] {
|
||||
assertFiniteInteger(bounds.left, "bounds.left")
|
||||
assertFiniteInteger(bounds.top, "bounds.top")
|
||||
assertFiniteInteger(bounds.width, "bounds.width")
|
||||
assertFiniteInteger(bounds.height, "bounds.height")
|
||||
if (bounds.width <= 0 || bounds.height <= 0) throw new RangeError("Spatial bounds must have positive dimensions")
|
||||
return Array.from({ length: bounds.height }, (_, offset) =>
|
||||
normalizedSpan(bounds.top + offset, bounds.left, bounds.left + bounds.width - 1),
|
||||
)
|
||||
}
|
||||
|
||||
export function spatialPathSpans(points: readonly DiagramPoint[]): SpatialSpan[] {
|
||||
for (const [index, point] of points.entries()) {
|
||||
assertFiniteInteger(point.x, `points[${index}].x`)
|
||||
assertFiniteInteger(point.y, `points[${index}].y`)
|
||||
if (index > 0 && point.x !== points[index - 1]!.x && point.y !== points[index - 1]!.y) {
|
||||
throw new RangeError("Spatial paths must be orthogonal")
|
||||
}
|
||||
}
|
||||
const cells = new Map<number, Set<number>>()
|
||||
const add = (point: DiagramPoint): void => {
|
||||
const row = cells.get(point.y) ?? new Set<number>()
|
||||
row.add(point.x)
|
||||
cells.set(point.y, row)
|
||||
}
|
||||
|
||||
if (points.length === 1) add(points[0]!)
|
||||
for (const point of orthogonalPathPoints(points)) add(point)
|
||||
|
||||
return [...cells.entries()]
|
||||
.sort(([left], [right]) => left - right)
|
||||
.flatMap(([y, xs]) => {
|
||||
const sorted = [...xs].sort((left, right) => left - right)
|
||||
const spans: SpatialSpan[] = []
|
||||
let start = sorted[0]
|
||||
let end = start
|
||||
if (start === undefined) return spans
|
||||
for (const x of sorted.slice(1)) {
|
||||
if (x === end! + 1) {
|
||||
end = x
|
||||
continue
|
||||
}
|
||||
spans.push(normalizedSpan(y, start, end!))
|
||||
start = x
|
||||
end = x
|
||||
}
|
||||
spans.push(normalizedSpan(y, start, end!))
|
||||
return spans
|
||||
})
|
||||
}
|
||||
|
||||
export function spatialRectClaim(
|
||||
id: string,
|
||||
owner: string,
|
||||
role: SpatialRole,
|
||||
bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">,
|
||||
): SpatialClaim {
|
||||
return { id, owner, role, spans: spatialRectSpans(bounds) }
|
||||
}
|
||||
|
||||
export function spatialPathClaim(
|
||||
id: string,
|
||||
owner: string,
|
||||
role: Extract<SpatialRole, "boundary" | "route">,
|
||||
points: readonly DiagramPoint[],
|
||||
): SpatialClaim {
|
||||
return { id, owner, role, spans: spatialPathSpans(points) }
|
||||
}
|
||||
|
||||
function compareClaims(left: SpatialClaim, right: SpatialClaim): number {
|
||||
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0
|
||||
}
|
||||
|
||||
function sameClaim(left: SpatialClaim, right: SpatialClaim): boolean {
|
||||
return (
|
||||
left.id === right.id &&
|
||||
left.owner === right.owner &&
|
||||
left.role === right.role &&
|
||||
left.spans.length === right.spans.length &&
|
||||
left.spans.every(
|
||||
(span, index) =>
|
||||
span.y === right.spans[index]!.y &&
|
||||
span.fromX === right.spans[index]!.fromX &&
|
||||
span.toX === right.spans[index]!.toX,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function pointIsContact(point: DiagramPoint, existing: SpatialClaim, contacts: readonly SpatialContact[]): boolean {
|
||||
return contacts.some(
|
||||
(contact) =>
|
||||
contact.owner === existing.owner &&
|
||||
contact.points.some((candidate) => candidate.x === point.x && candidate.y === point.y),
|
||||
)
|
||||
}
|
||||
|
||||
function rolesMayOverlap(moving: SpatialClaim, existing: SpatialClaim): boolean {
|
||||
if (moving.owner === existing.owner) return true
|
||||
return moving.role === "route" && existing.role === "route"
|
||||
}
|
||||
|
||||
function normalizeClearance(clearance: number | SpatialClearance | undefined): SpatialClearance {
|
||||
const x = typeof clearance === "number" ? clearance : (clearance?.x ?? 0)
|
||||
const y = typeof clearance === "number" ? clearance : (clearance?.y ?? 0)
|
||||
assertFiniteInteger(x, "clearance.x")
|
||||
assertFiniteInteger(y, "clearance.y")
|
||||
if (x < 0 || y < 0) throw new RangeError("Spatial clearance cannot be negative")
|
||||
return { x, y }
|
||||
}
|
||||
|
||||
function inflateSpan(span: SpatialSpan, clearance: SpatialClearance): SpatialSpan {
|
||||
return { y: span.y, fromX: span.fromX - clearance.x, toX: span.toX + clearance.x }
|
||||
}
|
||||
|
||||
export class SpatialIndex {
|
||||
static empty(): SpatialIndex {
|
||||
return new SpatialIndex([])
|
||||
}
|
||||
|
||||
readonly claims: readonly SpatialClaim[]
|
||||
|
||||
private constructor(claims: readonly SpatialClaim[]) {
|
||||
this.claims = Object.freeze(
|
||||
claims.map((claim) =>
|
||||
Object.freeze({
|
||||
...claim,
|
||||
spans: Object.freeze(
|
||||
[...claim.spans]
|
||||
.map((span) => Object.freeze({ ...span }))
|
||||
.sort((left, right) => left.y - right.y || left.fromX - right.fromX || left.toX - right.toX),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
add(...claims: readonly SpatialClaim[]): SpatialIndex {
|
||||
return this.overlay(new SpatialIndex(claims))
|
||||
}
|
||||
|
||||
overlay(other: SpatialIndex): SpatialIndex {
|
||||
const claims = new Map(this.claims.map((claim) => [claim.id, claim]))
|
||||
for (const claim of other.claims) {
|
||||
const existing = claims.get(claim.id)
|
||||
if (existing && !sameClaim(existing, claim)) throw new Error(`Conflicting spatial claim id: ${claim.id}`)
|
||||
claims.set(claim.id, claim)
|
||||
}
|
||||
return new SpatialIndex([...claims.values()].sort(compareClaims))
|
||||
}
|
||||
|
||||
conflicts(moving: SpatialClaim, policy: SpatialCollisionPolicy = {}): SpatialConflict[] {
|
||||
const contacts = policy.contacts ?? []
|
||||
const conflicts: SpatialConflict[] = []
|
||||
|
||||
for (const existing of this.claims) {
|
||||
if (rolesMayOverlap(moving, existing)) continue
|
||||
const configuredClearance =
|
||||
typeof policy.clearance === "number" || (policy.clearance && "x" in policy.clearance)
|
||||
? policy.clearance
|
||||
: policy.clearance?.[existing.role]
|
||||
const clearance = normalizeClearance(configuredClearance)
|
||||
for (const movingSpan of moving.spans) {
|
||||
for (let dy = -clearance.y; dy <= clearance.y; dy++) {
|
||||
const inflated = inflateSpan({ ...movingSpan, y: movingSpan.y + dy }, clearance)
|
||||
for (const existingSpan of existing.spans) {
|
||||
if (inflated.y !== existingSpan.y) continue
|
||||
const fromX = Math.max(inflated.fromX, existingSpan.fromX)
|
||||
const toX = Math.min(inflated.toX, existingSpan.toX)
|
||||
for (let x = fromX; x <= toX; x++) {
|
||||
const point = { x, y: inflated.y }
|
||||
const movingOccupiesPoint = moving.spans.some(
|
||||
(span) => span.y === point.y && point.x >= span.fromX && point.x <= span.toX,
|
||||
)
|
||||
if (!(movingOccupiesPoint && pointIsContact(point, existing, contacts))) {
|
||||
conflicts.push({ moving, existing, point })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return conflicts
|
||||
}
|
||||
|
||||
isFree(claim: SpatialClaim, policy: SpatialCollisionPolicy = {}): boolean {
|
||||
return this.conflicts(claim, policy).length === 0
|
||||
}
|
||||
|
||||
firstFit<T extends { claim: SpatialClaim }>(
|
||||
candidates: readonly T[],
|
||||
policy: SpatialCollisionPolicy = {},
|
||||
): T | undefined {
|
||||
return candidates.find((candidate) => this.isFree(candidate.claim, policy))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export type MermaidDiagramKind = "flowchart" | "sequence" | "state"
|
||||
|
||||
/** An otherwise valid diagram contains syntax that merman does not support. */
|
||||
/** An otherwise valid diagram contains syntax that this renderer does not support. */
|
||||
export class MermaidSyntaxError extends Error {
|
||||
readonly _tag = "MermaidSyntaxError"
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ function drawSubgraphLabel(grid: FlowchartGrid, bounds: FlowchartSubgraphBounds)
|
||||
}
|
||||
|
||||
function drawEdgeLabel(grid: FlowchartGrid, route: FlowchartEdgeRoute, style: FlowchartCellStyle): void {
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis)
|
||||
for (const [index, line] of label.lines.entries()) {
|
||||
grid.setText(label.point.x, label.point.y + index, line, style)
|
||||
}
|
||||
@@ -249,15 +249,22 @@ function drawSourceConnectors(
|
||||
if (routeDirection && connectorDirection) {
|
||||
const cell = grid.getCell(sourcePoint.x, sourcePoint.y)
|
||||
if (cell) {
|
||||
cell.char = diagramLineGlyph(
|
||||
new Set([routeDirection, connectorDirection]),
|
||||
"rounded",
|
||||
route.edge.style === "thick" ? "heavy" : "single",
|
||||
grid.replaceCell(
|
||||
sourcePoint.x,
|
||||
sourcePoint.y,
|
||||
diagramLineGlyph(
|
||||
new Set([routeDirection, connectorDirection]),
|
||||
"rounded",
|
||||
route.edge.style === "thick" ? "heavy" : "single",
|
||||
),
|
||||
"edge",
|
||||
)
|
||||
cell.style = "edge"
|
||||
}
|
||||
}
|
||||
fadeSourcePath(grid, connector, route.points, styles, occupancy)
|
||||
if (route.edge.sourceArrowhead && route.points[1]) {
|
||||
grid.setCell(sourcePoint.x, sourcePoint.y, diagramArrowHeadBetween(route.points[1], sourcePoint), "edge")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { parseColor } from "@opentui/core"
|
||||
import stringWidth from "string-width"
|
||||
import { colorsEqual } from "../core/color/style.js"
|
||||
import { expectDiagram } from "../test/diagram.js"
|
||||
import { drawFlowchartDiagramGrid as drawParsedFlowchartDiagramGrid } from "./drawing.js"
|
||||
import {
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
DEFAULT_MIN_VERTICAL_RANK_GAP,
|
||||
layoutFlowchartDiagram as layoutParsedFlowchartDiagram,
|
||||
} from "./layout.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import { parseMermaidFlowchartDiagram } from "./parser.js"
|
||||
import { renderFlowchartDiagram } from "./render.js"
|
||||
import { renderGridStyledText, resolveFlowchartStyleColors } from "./style.js"
|
||||
@@ -55,6 +55,63 @@ function routeRunsAlongVerticalBorder(
|
||||
return false
|
||||
}
|
||||
|
||||
function routeIntersectsBounds(
|
||||
route: { points: readonly { x: number; y: number }[] },
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
for (let index = 1; index < route.points.length; index++) {
|
||||
const from = route.points[index - 1]!
|
||||
const to = route.points[index]!
|
||||
if (from.x === to.x) {
|
||||
if (
|
||||
from.x >= bounds.left &&
|
||||
from.x <= right &&
|
||||
Math.max(from.y, to.y) >= bounds.top &&
|
||||
Math.min(from.y, to.y) <= bottom
|
||||
) {
|
||||
return true
|
||||
}
|
||||
} else if (
|
||||
from.y >= bounds.top &&
|
||||
from.y <= bottom &&
|
||||
Math.max(from.x, to.x) >= bounds.left &&
|
||||
Math.min(from.x, to.x) <= right
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function terminalPointsTowardBounds(
|
||||
route: { points: readonly { x: number; y: number }[] },
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
const before = route.points.at(-2)!
|
||||
const end = route.points.at(-1)!
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
if (end.x === bounds.left - 1 && end.y >= bounds.top && end.y <= bottom) return before.x < end.x && before.y === end.y
|
||||
if (end.x === right + 1 && end.y >= bounds.top && end.y <= bottom) return before.x > end.x && before.y === end.y
|
||||
if (end.y === bounds.top - 1 && end.x >= bounds.left && end.x <= right) return before.y < end.y && before.x === end.x
|
||||
if (end.y === bottom + 1 && end.x >= bounds.left && end.x <= right) return before.y > end.y && before.x === end.x
|
||||
return false
|
||||
}
|
||||
|
||||
function boundsIntersect(
|
||||
left: { left: number; top: number; width: number; height: number },
|
||||
right: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
return (
|
||||
left.left <= right.left + right.width - 1 &&
|
||||
left.left + left.width - 1 >= right.left &&
|
||||
left.top <= right.top + right.height - 1 &&
|
||||
left.top + left.height - 1 >= right.top
|
||||
)
|
||||
}
|
||||
|
||||
describe("FlowchartDiagram", () => {
|
||||
test("renders compact horizontal flowcharts with shorter routes", () => {
|
||||
const output = renderFlowchartDiagram(
|
||||
@@ -208,6 +265,67 @@ describe("FlowchartDiagram", () => {
|
||||
`)
|
||||
})
|
||||
|
||||
test("keeps vertical feedback labels clear of unrelated nodes", () => {
|
||||
const content = `flowchart TD
|
||||
S[Source] --> A[Alpha]
|
||||
S --> B{Beta?}
|
||||
S --> C[(Store)]
|
||||
A --> J[[Join]]
|
||||
B --> J
|
||||
C --> J
|
||||
J -->|cycle back| S`
|
||||
const layout = layoutFlowchartDiagram(content)
|
||||
const feedback = layout.routes.find((route) => route.edge.from === "J" && route.edge.to === "S")!
|
||||
const label = flowchartEdgeLabelLayout(feedback.points, feedback.edge.label, stringWidth)
|
||||
const labelBounds = { left: label.point.x, top: label.point.y, width: label.width, height: label.height }
|
||||
|
||||
for (const id of ["A", "B", "C"]) expect(boundsIntersect(labelBounds, layout.bounds.get(id)!)).toBe(false)
|
||||
expect(renderFlowchartDiagram(content)).toContain("cycle back")
|
||||
})
|
||||
|
||||
test("routes horizontal feedback edges around sibling nodes", () => {
|
||||
for (const direction of ["LR", "RL"] as const) {
|
||||
const layout = layoutFlowchartDiagram(`flowchart ${direction}
|
||||
S[Start] --> D{Ready?}
|
||||
D --> O[Output]
|
||||
D --> R[Retry]
|
||||
R --> S`)
|
||||
const feedback = layout.routes.find((route) => route.edge.from === "R" && route.edge.to === "S")!
|
||||
|
||||
expect(routeIntersectsBounds(feedback, layout.bounds.get("O")!)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps compact vertical fan-in arrowheads pointed at the target", () => {
|
||||
const content = `flowchart TD
|
||||
A[Left] -->|left| C[Merge]
|
||||
B[Right] -->|right| C`
|
||||
const layout = layoutFlowchartDiagram(content, { compact: true })
|
||||
|
||||
for (const route of layout.routes) {
|
||||
const beforeTarget = route.points.at(-2)!
|
||||
const target = route.points.at(-1)!
|
||||
expect(beforeTarget.x).toBe(target.x)
|
||||
expect(beforeTarget.y).toBeLessThan(target.y)
|
||||
}
|
||||
expect(renderFlowchartDiagram(content, { compact: true })).toContain("▼")
|
||||
})
|
||||
|
||||
test("routes same-rank vertical-flow edges into the target side", () => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart TD
|
||||
B[Start] --> D{Choose}
|
||||
D --> E[[Primary]]
|
||||
D --> F[Fallback]
|
||||
E --> B
|
||||
F --> E`)
|
||||
const route = layout.routes.find((candidate) => candidate.edge.from === "F" && candidate.edge.to === "E")!
|
||||
const beforeTarget = route.points.at(-2)!
|
||||
const target = route.points.at(-1)!
|
||||
|
||||
expect(beforeTarget.y).toBe(target.y)
|
||||
expect(beforeTarget.x).toBeGreaterThan(target.x)
|
||||
})
|
||||
|
||||
test("renders parallel same-endpoint edges without losing labels", () => {
|
||||
const content = `flowchart LR
|
||||
A[Source] -->|first| B[Target]
|
||||
@@ -238,6 +356,36 @@ describe("FlowchartDiagram", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps five parallel multiline edge labels distinct", () => {
|
||||
const output = renderFlowchartDiagram(`flowchart TD
|
||||
A[Source] -->|one alpha<br/>one beta| B[Target]
|
||||
A -->|two alpha<br/>two beta| B
|
||||
A -->|three alpha<br/>three beta| B
|
||||
A -->|four alpha<br/>four beta| B
|
||||
A -->|five alpha<br/>five beta| B`)
|
||||
|
||||
for (const number of ["one", "two", "three", "four", "five"]) {
|
||||
expect(output.match(new RegExp(`${number} alpha`, "g"))).toHaveLength(1)
|
||||
expect(output.match(new RegExp(`${number} beta`, "g"))).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("does not reserve label gaps for unlabeled fan-out", () => {
|
||||
const output = renderFlowchartDiagram(`flowchart TD
|
||||
S[The Boss] --> A[A]
|
||||
S --> B[B]
|
||||
S --> C[C]
|
||||
S --> D[D]
|
||||
S --> E[E]
|
||||
S --> F[F]
|
||||
S --> G[G]
|
||||
S --> H[H]
|
||||
S --> I[I]
|
||||
S --> J[J]`)
|
||||
|
||||
expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThanOrEqual(100)
|
||||
})
|
||||
|
||||
test("keeps transitive targets below intermediate vertical stages", () => {
|
||||
const content = `flowchart TD
|
||||
A[Start] --> B[Validate]
|
||||
@@ -389,6 +537,14 @@ flowchart TD
|
||||
])
|
||||
})
|
||||
|
||||
test("decodes HTML entities in node and edge labels", () => {
|
||||
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
|
||||
A[HMAC verify <3s & continue] -->|result ≥ 1| B[Done]`)
|
||||
|
||||
expect(diagram.nodes.find((node) => node.id === "A")?.label).toBe("HMAC verify <3s & continue")
|
||||
expect(diagram.edges[0]?.label).toBe("result ≥ 1")
|
||||
})
|
||||
|
||||
test("parses and renders each edge in a chained flowchart statement", () => {
|
||||
const content = `flowchart LR
|
||||
API --> Worker --> DB[(Database)]`
|
||||
@@ -434,6 +590,25 @@ flowchart TD
|
||||
])
|
||||
})
|
||||
|
||||
test("parses labeled undirected dashed and bidirectional edges", () => {
|
||||
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
|
||||
DB[(Durable Object SQLite)]
|
||||
API[Slack API]
|
||||
DB -. no shared transaction .- API
|
||||
API <--> DB`)
|
||||
|
||||
expect(diagram.edges).toEqual([
|
||||
{ from: "DB", to: "API", label: "no shared transaction", style: "dashed", arrowhead: false },
|
||||
{ from: "API", to: "DB", label: "", sourceArrowhead: true },
|
||||
])
|
||||
const dashedOutput = renderFlowchartDiagram(`flowchart LR
|
||||
DB[(Durable Object SQLite)] -. no shared transaction .- API[Slack API]`)
|
||||
const bidirectionalOutput = renderFlowchartDiagram(`flowchart LR
|
||||
DB[(Durable Object SQLite)] <--> API[Slack API]`)
|
||||
expect(dashedOutput).toContain("no shared transaction")
|
||||
expect(bidirectionalOutput.match(/[◀▶▲▼]/g)?.length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
test("renders the volume persistence diagram with an undirected solid edge", () => {
|
||||
const content = `flowchart LR
|
||||
subgraph durable [Durable — survives everything]
|
||||
@@ -884,6 +1059,94 @@ flowchart TD
|
||||
expect(route.points[0]!.y).toBe(route.points[route.points.length - 1]!.y)
|
||||
})
|
||||
|
||||
test("routes cross-subgraph edges around local-direction siblings", () => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart TD
|
||||
subgraph Workers
|
||||
direction TD
|
||||
A[Worker one] --> B[Worker two]
|
||||
end
|
||||
subgraph Peer
|
||||
direction RL
|
||||
C[Store] --> D[Transform]
|
||||
end
|
||||
B --> D`)
|
||||
const route = layout.routes.find((candidate) => candidate.edge.from === "B" && candidate.edge.to === "D")!
|
||||
|
||||
expect(routeIntersectsBounds(route, layout.bounds.get("C")!)).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["BT", { compact: true }],
|
||||
["LR", { compact: true }],
|
||||
["RL", { compact: true }],
|
||||
] as const)("keeps labeled cross-group routes clear of sibling nodes in %s layouts", (direction, options) => {
|
||||
const content = `flowchart ${direction}
|
||||
subgraph Left
|
||||
direction RL
|
||||
A[API] --> B[Queue]
|
||||
end
|
||||
subgraph Right
|
||||
direction TB
|
||||
C[Transform] --> D[Accept]
|
||||
end
|
||||
B -->|cross group| C
|
||||
D -->|retry group| A`
|
||||
const layout = layoutFlowchartDiagram(content, options)
|
||||
const crossGroup = layout.routes.find((route) => route.edge.from === "B" && route.edge.to === "C")!
|
||||
|
||||
if (direction !== "LR") expect(routeIntersectsBounds(crossGroup, layout.bounds.get("A")!)).toBe(false)
|
||||
expect(renderFlowchartDiagram(content, options)).toContain("cross group")
|
||||
expect(renderFlowchartDiagram(content, options)).toContain("retry group")
|
||||
})
|
||||
|
||||
test.each(["LR", "RL"] as const)(
|
||||
"keeps nested result labels and target-facing entry routes in %s layouts",
|
||||
(direction) => {
|
||||
const content = `flowchart ${direction}
|
||||
I[Input] --> A
|
||||
subgraph Outer
|
||||
direction LR
|
||||
subgraph Inner
|
||||
direction BT
|
||||
A[Parse] --> B[Valid]
|
||||
B --> C[Cache]
|
||||
C --> B
|
||||
end
|
||||
B --> D[Dispatch]
|
||||
end
|
||||
D -->|result path| O[Output]`
|
||||
const layout = layoutFlowchartDiagram(content)
|
||||
const entry = layout.routes.find((route) => route.edge.from === "I" && route.edge.to === "A")!
|
||||
|
||||
expect(renderFlowchartDiagram(content)).toContain("result path")
|
||||
expect(terminalPointsTowardBounds(entry, layout.bounds.get("A")!)).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
test("routes nested RL local edges around outer siblings", () => {
|
||||
const layout = layoutFlowchartDiagram(
|
||||
`flowchart RL
|
||||
I([Input λ]) --> A
|
||||
subgraph Outer [Outer group 長い]
|
||||
direction LR
|
||||
subgraph Inner [Inner<br/>工程]
|
||||
direction BT
|
||||
A[Parse request] -->|inner edge| B{Valid?}
|
||||
B --> C[(Cache Ω)]
|
||||
C --> B
|
||||
end
|
||||
B --> D[[Dispatch work]]
|
||||
end
|
||||
D -.->|result path| O([Output μ])`,
|
||||
{ compact: true },
|
||||
)
|
||||
|
||||
for (const route of layout.routes.filter((route) => ["A", "B", "C"].includes(route.edge.from))) {
|
||||
if (route.edge.to === "D") continue
|
||||
expect(routeIntersectsBounds(route, layout.bounds.get("D")!)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
test("compacts stacked subgraph-local direction rows", () => {
|
||||
const layout = layoutFlowchartDiagram(`
|
||||
flowchart TD
|
||||
@@ -1311,6 +1574,6 @@ flowchart LR
|
||||
const node = parseColor("#ff0000")
|
||||
const styled = renderGridStyledText(grid, resolveFlowchartStyleColors({ node }))
|
||||
|
||||
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && colorsEqual(chunk.fg, node))).toBe(true)
|
||||
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && chunk.fg?.equals(node))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -67,6 +67,22 @@ describe("flowchart edge labels", () => {
|
||||
).toEqual({ x: 151, y: 7 })
|
||||
})
|
||||
|
||||
test("keeps side-route labels on the vertical bus when horizontal arms grow", () => {
|
||||
expect(
|
||||
flowchartEdgeLabelLayout(
|
||||
[
|
||||
{ x: 5, y: 2 },
|
||||
{ x: 30, y: 2 },
|
||||
{ x: 30, y: 10 },
|
||||
{ x: 5, y: 10 },
|
||||
],
|
||||
"parallel label",
|
||||
measure,
|
||||
"y",
|
||||
).point,
|
||||
).toEqual({ x: 31, y: 6 })
|
||||
})
|
||||
|
||||
test("measures br-delimited edge label lines as a block", () => {
|
||||
const layout = flowchartEdgeLabelLayout(
|
||||
[
|
||||
|
||||
@@ -67,14 +67,23 @@ function segmentLabelPoint(segment: DiagramSegment, labelWidth: number, labelHei
|
||||
return clampPoint(shiftPoint(center, "up", Math.floor((labelHeight - 1) / 2)))
|
||||
}
|
||||
|
||||
function bestLabelSegment(points: readonly FlowchartPoint[], labelWidth: number): DiagramSegment | undefined {
|
||||
function bestLabelSegment(
|
||||
points: readonly FlowchartPoint[],
|
||||
labelWidth: number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): DiagramSegment | undefined {
|
||||
const segments = points.slice(1).flatMap((to, index) => {
|
||||
const segment = segmentBetween(points[index]!, to)
|
||||
return segment ? [segment] : []
|
||||
})
|
||||
const preferred = preferredAxis ? segments.find((segment) => segment.axis === preferredAxis) : undefined
|
||||
if (preferred) return preferred
|
||||
|
||||
let roomyHorizontal: DiagramSegment | undefined
|
||||
let verticalBus: DiagramSegment | undefined
|
||||
let longest: DiagramSegment | undefined
|
||||
|
||||
for (let index = 1; index < points.length; index++) {
|
||||
const segment = segmentBetween(points[index - 1]!, points[index]!)
|
||||
if (!segment) continue
|
||||
for (const segment of segments) {
|
||||
if (!roomyHorizontal && segment.axis === "x" && inlineLabelSlot(segment, labelWidth).fits) roomyHorizontal = segment
|
||||
if (!verticalBus && segment.axis === "y") verticalBus = segment
|
||||
if (!longest || segment.length > longest.length) longest = segment
|
||||
@@ -87,8 +96,9 @@ function flowchartLabelPoint(
|
||||
points: readonly FlowchartPoint[],
|
||||
labelWidth: number,
|
||||
labelHeight: number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): FlowchartPoint {
|
||||
const segment = bestLabelSegment(points, labelWidth)
|
||||
const segment = bestLabelSegment(points, labelWidth, preferredAxis)
|
||||
return segment ? segmentLabelPoint(segment, labelWidth, labelHeight) : (points[0] ?? point(0, 0))
|
||||
}
|
||||
|
||||
@@ -96,9 +106,10 @@ export function flowchartEdgeLabelLayout(
|
||||
points: readonly FlowchartPoint[],
|
||||
label: string,
|
||||
measure: (text: string) => number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): FlowchartEdgeLabelLayout {
|
||||
const lines = splitDiagramLines(label).map(flowchartLabelText)
|
||||
const width = flowchartLabelWidth(label, measure)
|
||||
const height = lines.length
|
||||
return { lines, point: flowchartLabelPoint(points, width, height), width, height }
|
||||
return { lines, point: flowchartLabelPoint(points, width, height, preferredAxis), width, height }
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import type {
|
||||
|
||||
export const DEFAULT_MIN_NODE_GAP = 5
|
||||
export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
|
||||
const DEFAULT_MAX_UNLABELED_RANK_WIDTH = 120
|
||||
export const DEFAULT_MIN_RANK_GAP = 7
|
||||
export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
|
||||
export const COMPACT_MIN_RANK_GAP = 4
|
||||
@@ -316,7 +317,7 @@ function pathBounds(points: readonly { x: number; y: number }[]): FlowchartBound
|
||||
|
||||
function labelBounds(route: FlowchartEdgeRoute): FlowchartBounds | undefined {
|
||||
if (!route.edge.label) return undefined
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis)
|
||||
const { point, width, height } = label
|
||||
return {
|
||||
left: point.x,
|
||||
@@ -358,9 +359,6 @@ function layoutRankedNodes(
|
||||
if (edge.label)
|
||||
widestPaddedEdgeLabel = Math.max(widestPaddedEdgeLabel, flowchartLabelWidth(edge.label, visualLength))
|
||||
}
|
||||
const rankNodeGap = horizontal
|
||||
? minNodeGap
|
||||
: Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP, flowchartVerticalBranchLabelGap(widestPaddedEdgeLabel))
|
||||
const ranks = rankNodes(diagram)
|
||||
const maxRank = Math.max(0, ...ranks.values())
|
||||
const ranksByIndex = new Map<number, FlowchartNode[]>()
|
||||
@@ -375,6 +373,23 @@ function layoutRankedNodes(
|
||||
ranksByIndex.set(normalizedRank, nodes)
|
||||
}
|
||||
|
||||
const spaciousNodeGap = Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP)
|
||||
const widestUnlabeledRank = Math.max(
|
||||
0,
|
||||
...[...ranksByIndex.values()].map(
|
||||
(nodes) =>
|
||||
nodes.reduce((total, node) => total + sizes.get(node.id)!.width, 0) +
|
||||
Math.max(0, nodes.length - 1) * spaciousNodeGap,
|
||||
),
|
||||
)
|
||||
const rankNodeGap = horizontal
|
||||
? minNodeGap
|
||||
: widestPaddedEdgeLabel > 0
|
||||
? Math.max(spaciousNodeGap, flowchartVerticalBranchLabelGap(widestPaddedEdgeLabel))
|
||||
: widestUnlabeledRank > DEFAULT_MAX_UNLABELED_RANK_WIDTH
|
||||
? minNodeGap
|
||||
: spaciousNodeGap
|
||||
|
||||
const rankKeys = [...ranksByIndex.keys()].sort((a, b) => a - b)
|
||||
const horizontalGaps = horizontal ? horizontalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap) : []
|
||||
const verticalGaps = horizontal ? [] : verticalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap)
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
} from "./types.js"
|
||||
import { MermaidSyntaxError } from "../diagnostics.js"
|
||||
import {
|
||||
decodeMermaidText,
|
||||
firstMeaningfulMermaidLine,
|
||||
meaningfulNumberedMermaidLines,
|
||||
stripMermaidQuotes as stripQuotes,
|
||||
@@ -28,8 +29,9 @@ const DECISION_NODE_RE = new RegExp(`^(${ID_RE})\\{(.+)\\}$`)
|
||||
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 CIRCLE_NODE_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()
|
||||
@@ -79,6 +81,20 @@ function parseNodeToken(token: string): FlowchartNode {
|
||||
return { id: trimmed, label: trimmed, shape: "box" }
|
||||
}
|
||||
|
||||
function isSupportedNodeToken(token: string): boolean {
|
||||
const trimmed = stripNodeToken(token)
|
||||
if (CIRCLE_NODE_RE.test(trimmed)) return false
|
||||
return (
|
||||
ID_ONLY_RE.test(trimmed) ||
|
||||
DATABASE_NODE_RE.test(trimmed) ||
|
||||
SUBROUTINE_NODE_RE.test(trimmed) ||
|
||||
ROUNDED_BRACKET_NODE_RE.test(trimmed) ||
|
||||
ROUNDED_NODE_RE.test(trimmed) ||
|
||||
DECISION_NODE_RE.test(trimmed) ||
|
||||
BOX_NODE_RE.test(trimmed)
|
||||
)
|
||||
}
|
||||
|
||||
function hasExplicitNodeShape(token: string): boolean {
|
||||
return EXPLICIT_NODE_SHAPE_RE.test(token.trim())
|
||||
}
|
||||
@@ -122,9 +138,11 @@ function createEdge(
|
||||
label: string,
|
||||
style: FlowchartEdgeStyle | undefined,
|
||||
arrowhead: boolean,
|
||||
sourceArrowhead: boolean,
|
||||
): FlowchartEdge {
|
||||
const edge: FlowchartEdge = style ? { from, to, label, style } : { from, to, label }
|
||||
if (!arrowhead) edge.arrowhead = false
|
||||
if (sourceArrowhead) edge.sourceArrowhead = true
|
||||
return edge
|
||||
}
|
||||
|
||||
@@ -134,25 +152,91 @@ interface ParsedEdgeOperator {
|
||||
label: string
|
||||
style: FlowchartEdgeStyle | undefined
|
||||
arrowhead: boolean
|
||||
sourceArrowhead: boolean
|
||||
orderOnly: boolean
|
||||
}
|
||||
|
||||
function parseEdgeOperators(line: string): ParsedEdgeOperator[] {
|
||||
return [...line.matchAll(EDGE_OPERATOR_RE)].map((match) => {
|
||||
return [...maskNodeLabelOperators(line).matchAll(EDGE_OPERATOR_RE)].map((match) => {
|
||||
const inlineDashedArrow = match[1]
|
||||
const startArrow = inlineDashedArrow ?? match[3] ?? match[6]!
|
||||
const endArrow = inlineDashedArrow ?? match[5] ?? match[6]!
|
||||
return {
|
||||
index: match.index,
|
||||
end: match.index + match[0].length,
|
||||
label: (match[2] ?? match[4] ?? match[7] ?? "").trim(),
|
||||
label: decodeMermaidText((match[2] ?? match[4] ?? match[7] ?? "").trim()),
|
||||
style: edgeStyleFromArrow(startArrow, endArrow),
|
||||
arrowhead: endArrow !== "---",
|
||||
arrowhead: endArrow === "~~~" || endArrow.endsWith(">"),
|
||||
sourceArrowhead: startArrow.startsWith("<"),
|
||||
orderOnly: endArrow === "~~~",
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function maskNodeLabelOperators(line: string): string {
|
||||
const characters = line.split("")
|
||||
const stack: string[] = []
|
||||
let quote: '"' | "'" | undefined
|
||||
const closes: Record<string, string> = { "[": "]", "(": ")", "{": "}" }
|
||||
|
||||
for (let index = 0; index < characters.length; index++) {
|
||||
const character = characters[index]!
|
||||
if (quote) {
|
||||
if (character === quote && characters[index - 1] !== "\\") quote = undefined
|
||||
else if (/[<>=.-]/.test(character)) characters[index] = " "
|
||||
continue
|
||||
}
|
||||
if (character === '"' || character === "'") {
|
||||
quote = character
|
||||
continue
|
||||
}
|
||||
if (character in closes) {
|
||||
stack.push(character)
|
||||
continue
|
||||
}
|
||||
if (stack.length > 0 && character === closes[stack.at(-1)!]) {
|
||||
stack.pop()
|
||||
continue
|
||||
}
|
||||
if (stack.length > 0 && /[<>=.-]/.test(character)) characters[index] = " "
|
||||
}
|
||||
return characters.join("")
|
||||
}
|
||||
|
||||
function hasInternalStatementSeparator(line: string): boolean {
|
||||
const stack: string[] = []
|
||||
let quote: '"' | "'" | undefined
|
||||
let edgeLabel = false
|
||||
const closes: Record<string, string> = { "[": "]", "(": ")", "{": "}" }
|
||||
const finalIndex = line.trimEnd().length - 1
|
||||
|
||||
for (let index = 0; index < line.length; index++) {
|
||||
const character = line[index]!
|
||||
if (quote) {
|
||||
if (character === quote && line[index - 1] !== "\\") quote = undefined
|
||||
continue
|
||||
}
|
||||
if (character === '"' || character === "'") {
|
||||
quote = character
|
||||
continue
|
||||
}
|
||||
if (character in closes) {
|
||||
stack.push(character)
|
||||
continue
|
||||
}
|
||||
if (stack.length > 0 && character === closes[stack.at(-1)!]) {
|
||||
stack.pop()
|
||||
continue
|
||||
}
|
||||
if (stack.length === 0 && character === "|") {
|
||||
edgeLabel = !edgeLabel
|
||||
continue
|
||||
}
|
||||
if (character === ";" && index < finalIndex && stack.length === 0 && !edgeLabel) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function isMermaidFlowchartDiagram(content: string): boolean {
|
||||
return FLOWCHART_HEADER_RE.test(firstMeaningfulMermaidLine(content) ?? "")
|
||||
}
|
||||
@@ -166,6 +250,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
|
||||
for (const source of meaningfulNumberedMermaidLines(content)) {
|
||||
const line = source.text
|
||||
if (hasInternalStatementSeparator(line)) throw new MermaidSyntaxError("flowchart", source.lineNumber, line)
|
||||
const header = line.match(FLOWCHART_HEADER_RE)
|
||||
if (header) {
|
||||
direction = normalizeDirection(header[2])
|
||||
@@ -222,6 +307,15 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
]
|
||||
|
||||
if (nodeTokens.every((token) => stripNodeToken(token).length > 0)) {
|
||||
const unsupportedEndpoint = nodeTokens.find((token, index) => {
|
||||
const stripped = stripNodeToken(token)
|
||||
const orderOnlyEndpoint = edgeOperators[index - 1]?.orderOnly || edgeOperators[index]?.orderOnly
|
||||
return (
|
||||
!(orderOnlyEndpoint && subgraphs.some((subgraph) => subgraph.id === stripped)) &&
|
||||
!isSupportedNodeToken(stripped)
|
||||
)
|
||||
})
|
||||
if (unsupportedEndpoint) throw new MermaidSyntaxError("flowchart", source.lineNumber, line)
|
||||
const chainNodeIds = nodeTokens.map((token, index) => {
|
||||
const stripped = stripNodeToken(token)
|
||||
const orderOnlyEndpoint = edgeOperators[index - 1]?.orderOnly || edgeOperators[index]?.orderOnly
|
||||
@@ -239,6 +333,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
operator.label,
|
||||
operator.style,
|
||||
operator.arrowhead,
|
||||
operator.sourceArrowhead,
|
||||
)
|
||||
edges.push(operator.orderOnly ? { ...edge, orderOnly: true } : edge)
|
||||
}
|
||||
@@ -246,7 +341,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
}
|
||||
}
|
||||
|
||||
if (hasExplicitNodeShape(line) || ID_ONLY_RE.test(stripNodeToken(line))) {
|
||||
if (isSupportedNodeToken(line)) {
|
||||
const node = ensureNode(nodes, line)
|
||||
addNodeToSubgraph(currentSubgraph, node.id)
|
||||
continue
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { diagramTextWidth } from "../core/text.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import type { FlowchartDiagram, FlowchartNodeBounds } from "./types.js"
|
||||
import { routeFlowchartEdges } from "./routing.js"
|
||||
|
||||
@@ -21,6 +23,31 @@ function diagram(direction: FlowchartDiagram["direction"], edges: FlowchartDiagr
|
||||
return { direction, nodes: [], edges, subgraphs: [] }
|
||||
}
|
||||
|
||||
function routeIntersectsBounds(
|
||||
points: readonly { x: number; y: number }[],
|
||||
nodeBounds: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
const right = nodeBounds.left + nodeBounds.width - 1
|
||||
const bottom = nodeBounds.top + nodeBounds.height - 1
|
||||
return points.slice(1).some((to, index) => {
|
||||
const from = points[index]!
|
||||
if (from.x === to.x) {
|
||||
return (
|
||||
from.x >= nodeBounds.left &&
|
||||
from.x <= right &&
|
||||
Math.max(from.y, to.y) >= nodeBounds.top &&
|
||||
Math.min(from.y, to.y) <= bottom
|
||||
)
|
||||
}
|
||||
return (
|
||||
from.y >= nodeBounds.top &&
|
||||
from.y <= bottom &&
|
||||
Math.max(from.x, to.x) >= nodeBounds.left &&
|
||||
Math.min(from.x, to.x) <= right
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
describe("flowchart routing", () => {
|
||||
test("routes a simple horizontal edge from source port to target port", () => {
|
||||
const edge = { from: "A", to: "B", label: "" }
|
||||
@@ -269,4 +296,79 @@ describe("flowchart routing", () => {
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
test("does not route a fallback through its own source node", () => {
|
||||
const labeled = { from: "A", to: "B", label: "route" }
|
||||
const crossing = { from: "C", to: "D", label: "" }
|
||||
const nodeBounds = new Map([
|
||||
["A", bounds("A", 0, 0)],
|
||||
["B", bounds("B", 100, 0)],
|
||||
["C", bounds("C", 48, -12)],
|
||||
["D", bounds("D", 48, 12)],
|
||||
])
|
||||
const routes = routeFlowchartEdges(diagram("LR", [labeled, crossing]), nodeBounds, undefined, new Map())
|
||||
const route = routes.find((candidate) => candidate.edge === labeled)!
|
||||
|
||||
expect(routeIntersectsBounds(route.points, nodeBounds.get("A")!)).toBe(false)
|
||||
expect(routeIntersectsBounds(route.points, nodeBounds.get("B")!)).toBe(false)
|
||||
})
|
||||
|
||||
test("ignores zero-width blank label interiors as route obstacles", () => {
|
||||
const blankLabel = { from: "A", to: "B", label: "<br/>" }
|
||||
const crossing = { from: "C", to: "D", label: "" }
|
||||
const routes = routeFlowchartEdges(
|
||||
diagram("TD", [blankLabel, crossing]),
|
||||
new Map([
|
||||
["A", bounds("A", 0, 0)],
|
||||
["B", bounds("B", 0, 100)],
|
||||
["C", bounds("C", -20, 50)],
|
||||
["D", bounds("D", 20, 50)],
|
||||
]),
|
||||
(edge) => (edge === blankLabel ? "TD" : "LR"),
|
||||
new Map(),
|
||||
)
|
||||
|
||||
expect(routes.find((route) => route.edge === blankLabel)!.points).toEqual([
|
||||
{ x: 2, y: 3 },
|
||||
{ x: 2, y: 99 },
|
||||
])
|
||||
})
|
||||
|
||||
test("checks earlier labels against finalized later fallback routes", () => {
|
||||
const edges = [
|
||||
{ from: "C", to: "B", label: "alpha" },
|
||||
{ from: "A", to: "F", label: "beta long" },
|
||||
{ from: "C", to: "D", label: "gamma" },
|
||||
{ from: "A", to: "B", label: "" },
|
||||
]
|
||||
const directions = ["TD", "RL", "LR", "BT"] as const
|
||||
const routes = routeFlowchartEdges(
|
||||
diagram("LR", edges),
|
||||
new Map([
|
||||
["A", bounds("A", -24, 6)],
|
||||
["B", bounds("B", 48, 24)],
|
||||
["C", bounds("C", -24, 24)],
|
||||
["D", bounds("D", -24, -18)],
|
||||
["F", bounds("F", -16, -6)],
|
||||
]),
|
||||
(edge) => directions[edges.indexOf(edge)]!,
|
||||
new Map(),
|
||||
)
|
||||
const labeled = routes.find((route) => route.edge === edges[0])!
|
||||
const laterFallback = routes.find((route) => route.edge === edges[3])!
|
||||
const label = flowchartEdgeLabelLayout(labeled.points, labeled.edge.label, diagramTextWidth)
|
||||
|
||||
expect(labeled.points).toEqual([
|
||||
{ x: -19, y: 25 },
|
||||
{ x: 47, y: 25 },
|
||||
])
|
||||
expect(
|
||||
routeIntersectsBounds(laterFallback.points, {
|
||||
left: label.point.x + 1,
|
||||
top: label.point.y,
|
||||
width: label.width - 2,
|
||||
height: label.height,
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
pathViaLane,
|
||||
sideForDirection,
|
||||
snapCoordinate,
|
||||
shiftPoint,
|
||||
withCoordinate,
|
||||
type DiagramAxis,
|
||||
type DiagramDirection,
|
||||
@@ -22,7 +23,7 @@ import {
|
||||
type DiagramSide,
|
||||
} from "../core/geometry.js"
|
||||
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import { flowchartEdgeLabelLayout, type FlowchartEdgeLabelLayout } from "./labels.js"
|
||||
import type {
|
||||
FlowchartDiagram,
|
||||
FlowchartDirection,
|
||||
@@ -130,7 +131,9 @@ function horizontalEdgePath(
|
||||
|
||||
const travel = horizontalTravel(from, to, direction)
|
||||
const startSide = sideForDirection(travel)
|
||||
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)))
|
||||
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)), {
|
||||
preferredAxis: "x",
|
||||
})
|
||||
}
|
||||
|
||||
function selfEdgePath(bounds: FlowchartNodeBounds): FlowchartPoint[] {
|
||||
@@ -165,7 +168,7 @@ function labelHeight(edge: FlowchartEdge): number {
|
||||
function rightRenderExtent(route: FlowchartEdgeRoute): number {
|
||||
let right = Math.max(...route.points.map((point) => point.x))
|
||||
if (route.edge.label) {
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth, route.labelAxis)
|
||||
right = Math.max(right, label.point.x + label.width - 1)
|
||||
}
|
||||
return right
|
||||
@@ -179,6 +182,14 @@ function edgePath(
|
||||
): FlowchartPoint[] {
|
||||
if (from.id === to.id) return selfEdgePath(from)
|
||||
if (!isVerticalDirection(direction)) return horizontalEdgePath(from, to, direction)
|
||||
const overlapsVertically = from.top < to.top + to.height && to.top < from.top + from.height
|
||||
if (overlapsVertically) {
|
||||
const travel: HorizontalTravel = centerCoordinate(to, "x") >= centerCoordinate(from, "x") ? "right" : "left"
|
||||
return orthogonalPath(
|
||||
boundsSidePoint(from, sideForDirection(travel)),
|
||||
boundsSidePoint(to, oppositeSide(sideForDirection(travel))),
|
||||
)
|
||||
}
|
||||
return isVerticalBackEdge(from, to, direction)
|
||||
? verticalBackEdgePath(from, to, leftBoundary)
|
||||
: verticalForwardEdgePath(from, to)
|
||||
@@ -211,7 +222,7 @@ function targetFanInLane(
|
||||
afterFarthestCoordinate(sourcePorts, axis, travel, NODE_CLEARANCE),
|
||||
travel,
|
||||
)
|
||||
return keepBefore(unclamped, targetCoordinate, travel)
|
||||
return keepBefore(unclamped, advanceCoordinate(targetCoordinate, travel, -1), travel)
|
||||
}
|
||||
|
||||
function portForTravel(bounds: FlowchartNodeBounds, travel: DiagramDirection, role: PortRole): FlowchartPoint {
|
||||
@@ -468,7 +479,11 @@ function routeParallelEdges(
|
||||
Math.max(boundsSidePoint(from, "bottom").y, boundsSidePoint(to, "bottom").y) + BUS_CLEARANCE,
|
||||
Math.max(...previousRoute.points.map((point) => point.y)) + Math.max(2, labelHeight(edge) + 1),
|
||||
)
|
||||
const route = { edge, points: parallelEdgePath(from, to, direction, laneCoordinate) }
|
||||
const route: FlowchartEdgeRoute = {
|
||||
edge,
|
||||
points: parallelEdgePath(from, to, direction, laneCoordinate),
|
||||
labelAxis: isVerticalDirection(direction) ? "y" : "x",
|
||||
}
|
||||
routes.push(route)
|
||||
handled.add(edge)
|
||||
previousRoute = route
|
||||
@@ -571,59 +586,238 @@ function routeHorizontalSubgraphEntries(
|
||||
}
|
||||
}
|
||||
|
||||
function pathIntersectsBounds(points: readonly FlowchartPoint[], bounds: FlowchartNodeBounds): boolean {
|
||||
function pathIntersectsBounds(
|
||||
points: readonly FlowchartPoint[],
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
allowedContact: "source" | "target" | "both" | undefined = undefined,
|
||||
): boolean {
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
for (let index = 1; index < points.length; index++) {
|
||||
const from = points[index - 1]!
|
||||
const to = points[index]!
|
||||
if (from.x === to.x) {
|
||||
if (
|
||||
from.x >= bounds.left &&
|
||||
from.x <= right &&
|
||||
Math.max(from.y, to.y) >= bounds.top &&
|
||||
Math.min(from.y, to.y) <= bottom
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (from.x < bounds.left || from.x > right) continue
|
||||
const overlapTop = Math.max(Math.min(from.y, to.y), bounds.top)
|
||||
const overlapBottom = Math.min(Math.max(from.y, to.y), bottom)
|
||||
if (overlapTop > overlapBottom) continue
|
||||
const sourceContact =
|
||||
(allowedContact === "source" || allowedContact === "both") &&
|
||||
index === 1 &&
|
||||
overlapTop === overlapBottom &&
|
||||
from.x === points[0]!.x &&
|
||||
overlapTop === points[0]!.y
|
||||
const targetContact =
|
||||
(allowedContact === "target" || allowedContact === "both") &&
|
||||
index === points.length - 1 &&
|
||||
overlapTop === overlapBottom &&
|
||||
to.x === points.at(-1)!.x &&
|
||||
overlapTop === points.at(-1)!.y
|
||||
if (!sourceContact && !targetContact) return true
|
||||
continue
|
||||
}
|
||||
if (
|
||||
from.y >= bounds.top &&
|
||||
from.y <= bottom &&
|
||||
Math.max(from.x, to.x) >= bounds.left &&
|
||||
Math.min(from.x, to.x) <= right
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (from.y < bounds.top || from.y > bottom) continue
|
||||
const overlapLeft = Math.max(Math.min(from.x, to.x), bounds.left)
|
||||
const overlapRight = Math.min(Math.max(from.x, to.x), right)
|
||||
if (overlapLeft > overlapRight) continue
|
||||
const sourceContact =
|
||||
(allowedContact === "source" || allowedContact === "both") &&
|
||||
index === 1 &&
|
||||
overlapLeft === overlapRight &&
|
||||
overlapLeft === points[0]!.x &&
|
||||
from.y === points[0]!.y
|
||||
const targetContact =
|
||||
(allowedContact === "target" || allowedContact === "both") &&
|
||||
index === points.length - 1 &&
|
||||
overlapLeft === overlapRight &&
|
||||
overlapLeft === points.at(-1)!.x &&
|
||||
to.y === points.at(-1)!.y
|
||||
if (!sourceContact && !targetContact) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function labelIntersectsBounds(label: FlowchartEdgeLabelLayout | undefined, bounds: FlowchartNodeBounds): boolean {
|
||||
if (!label) return false
|
||||
return (
|
||||
label.point.x <= bounds.left + bounds.width - 1 &&
|
||||
label.point.x + label.width - 1 >= bounds.left &&
|
||||
label.point.y <= bounds.top + bounds.height - 1 &&
|
||||
label.point.y + label.height - 1 >= bounds.top
|
||||
)
|
||||
}
|
||||
|
||||
function labelIntersectsSubgraphFrame(
|
||||
label: FlowchartEdgeLabelLayout | undefined,
|
||||
bounds: FlowchartSubgraphBounds,
|
||||
): boolean {
|
||||
if (!label) return false
|
||||
const labelRight = label.point.x + label.width - 1
|
||||
const labelBottom = label.point.y + label.height - 1
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
return (
|
||||
(label.point.x <= right &&
|
||||
labelRight >= bounds.left &&
|
||||
((label.point.y <= bounds.top && labelBottom >= bounds.top) ||
|
||||
(label.point.y <= bottom && labelBottom >= bottom))) ||
|
||||
(label.point.y <= bottom &&
|
||||
labelBottom >= bounds.top &&
|
||||
((label.point.x <= bounds.left && labelRight >= bounds.left) || (label.point.x <= right && labelRight >= right)))
|
||||
)
|
||||
}
|
||||
|
||||
function routeLength(route: FlowchartEdgeRoute): number {
|
||||
let length = 0
|
||||
for (let index = 1; index < route.points.length; index++) {
|
||||
const from = route.points[index - 1]!
|
||||
const to = route.points[index]!
|
||||
length += Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
|
||||
}
|
||||
return length
|
||||
}
|
||||
|
||||
function labelIntersectsLabels(
|
||||
label: FlowchartEdgeLabelLayout | undefined,
|
||||
otherLabels: readonly FlowchartEdgeLabelLayout[],
|
||||
): boolean {
|
||||
if (!label) return false
|
||||
return otherLabels.some((otherLabel) => {
|
||||
return label.lines.some((line, lineIndex) => {
|
||||
const textLeft = label.point.x + 1
|
||||
const textRight = label.point.x + diagramTextWidth(line) - 2
|
||||
const y = label.point.y + lineIndex
|
||||
return otherLabel.lines.some((otherLine, otherLineIndex) => {
|
||||
const otherLeft = otherLabel.point.x
|
||||
const otherRight = otherLeft + diagramTextWidth(otherLine) - 1
|
||||
return y === otherLabel.point.y + otherLineIndex && textLeft <= otherRight && textRight >= otherLeft
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function labelIntersectsLaterRoutePaths(
|
||||
label: FlowchartEdgeLabelLayout | undefined,
|
||||
laterRoutes: readonly FlowchartEdgeRoute[],
|
||||
): boolean {
|
||||
if (!label) return false
|
||||
return label.lines.some((line, lineIndex) => {
|
||||
const width = diagramTextWidth(line) - 2
|
||||
if (width <= 0) return false
|
||||
return laterRoutes.some((other) =>
|
||||
pathIntersectsBounds(other.points, {
|
||||
left: label.point.x + 1,
|
||||
top: label.point.y + lineIndex,
|
||||
width,
|
||||
height: 1,
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function avoidNodeObstacles(
|
||||
route: FlowchartEdgeRoute,
|
||||
routes: readonly FlowchartEdgeRoute[],
|
||||
bounds: Map<string, FlowchartNodeBounds>,
|
||||
direction: FlowchartDirection,
|
||||
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
|
||||
routeIndex: number,
|
||||
): FlowchartEdgeRoute {
|
||||
const obstacle = [...bounds.values()].some(
|
||||
(bound) => bound.id !== route.edge.from && bound.id !== route.edge.to && pathIntersectsBounds(route.points, bound),
|
||||
const allNodeBounds = [...bounds.values()]
|
||||
const allSubgraphBounds = [...(subgraphBounds?.values() ?? [])]
|
||||
const laterRoutes = routes.slice(routeIndex + 1)
|
||||
const laterLabels = laterRoutes.flatMap((laterRoute) =>
|
||||
laterRoute.edge.label
|
||||
? [flowchartEdgeLabelLayout(laterRoute.points, laterRoute.edge.label, diagramTextWidth, laterRoute.labelAxis)]
|
||||
: [],
|
||||
)
|
||||
if (!obstacle) return route
|
||||
const intersectsObstacle = (candidate: FlowchartEdgeRoute): boolean => {
|
||||
const label = candidate.edge.label
|
||||
? flowchartEdgeLabelLayout(candidate.points, candidate.edge.label, diagramTextWidth, candidate.labelAxis)
|
||||
: undefined
|
||||
return (
|
||||
allNodeBounds.some((bound) => {
|
||||
const isSource = bound.id === route.edge.from
|
||||
const isTarget = bound.id === route.edge.to
|
||||
const allowedContact = isSource && isTarget ? "both" : isSource ? "source" : isTarget ? "target" : undefined
|
||||
return pathIntersectsBounds(candidate.points, bound, allowedContact)
|
||||
}) ||
|
||||
allNodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
|
||||
allSubgraphBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
|
||||
(subgraphBounds !== undefined &&
|
||||
(labelIntersectsLabels(label, laterLabels) || labelIntersectsLaterRoutePaths(label, laterRoutes)))
|
||||
)
|
||||
}
|
||||
if (!intersectsObstacle(route)) return route
|
||||
|
||||
const from = bounds.get(route.edge.from)
|
||||
const to = bounds.get(route.edge.to)
|
||||
if (!from || !to) return route
|
||||
if (isVerticalDirection(direction)) {
|
||||
const start = boundsSidePoint(from, "right")
|
||||
const end = boundsSidePoint(to, "right")
|
||||
const busX = Math.max(...[...bounds.values()].map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
|
||||
return { edge: route.edge, points: pathViaLane(start, lane("x", busX), end) }
|
||||
const routingBounds = [...allNodeBounds, ...allSubgraphBounds]
|
||||
const rightBusX = Math.max(...routingBounds.map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
|
||||
const leftBusX = Math.min(...routingBounds.map((bound) => bound.left)) - BUS_CLEARANCE
|
||||
const topBusY = Math.min(...routingBounds.map((bound) => bound.top)) - BUS_CLEARANCE
|
||||
const bottomBusY = Math.max(...routingBounds.map((bound) => bound.top + bound.height - 1)) + BUS_CLEARANCE
|
||||
const start = route.points[0]!
|
||||
const end = route.points.at(-1)!
|
||||
const targetSide = sideForOutsidePoint(to, end)
|
||||
const approach = shiftPoint(
|
||||
end,
|
||||
targetSide === "left" ? "left" : targetSide === "right" ? "right" : targetSide === "top" ? "up" : "down",
|
||||
)
|
||||
const preservedTargetCandidates: FlowchartEdgeRoute[] = [
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathThrough([start, { x: leftBusX, y: start.y }, { x: leftBusX, y: approach.y }, approach, end]),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathThrough([start, { x: rightBusX, y: start.y }, { x: rightBusX, y: approach.y }, approach, end]),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathThrough([start, { x: start.x, y: topBusY }, { x: approach.x, y: topBusY }, approach, end]),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathThrough([start, { x: start.x, y: bottomBusY }, { x: approach.x, y: bottomBusY }, approach, end]),
|
||||
},
|
||||
]
|
||||
const candidates: FlowchartEdgeRoute[] = [
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathViaLane(boundsSidePoint(from, "right"), lane("x", rightBusX), boundsSidePoint(to, "right")),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathViaLane(boundsSidePoint(from, "left"), lane("x", leftBusX), boundsSidePoint(to, "left")),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathViaLane(boundsSidePoint(from, "top"), lane("y", topBusY), boundsSidePoint(to, "top")),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathViaLane(boundsSidePoint(from, "bottom"), lane("y", bottomBusY), boundsSidePoint(to, "bottom")),
|
||||
},
|
||||
]
|
||||
const shortestValid = (candidateRoutes: FlowchartEdgeRoute[]): FlowchartEdgeRoute | undefined =>
|
||||
candidateRoutes
|
||||
.filter((candidate) => !intersectsObstacle(candidate))
|
||||
.sort((left, right) => routeLength(left) - routeLength(right))[0]
|
||||
if (subgraphBounds) {
|
||||
return shortestValid(preservedTargetCandidates) ?? shortestValid(candidates) ?? route
|
||||
}
|
||||
|
||||
const start = boundsSidePoint(from, "top")
|
||||
const end = boundsSidePoint(to, "top")
|
||||
const busY = Math.min(...[...bounds.values()].map((bound) => bound.top)) - BUS_CLEARANCE
|
||||
return { edge: route.edge, points: pathViaLane(start, lane("y", busY), end) }
|
||||
return (
|
||||
candidates.find((candidate) => !intersectsObstacle(candidate)) ?? shortestValid(preservedTargetCandidates) ?? route
|
||||
)
|
||||
}
|
||||
|
||||
export function routeFlowchartEdges(
|
||||
@@ -671,7 +865,10 @@ export function routeFlowchartEdges(
|
||||
if (!from || !to) continue
|
||||
routes.push({ edge, points: edgePath(from, to, directionForEdge(edge), leftBoundary) })
|
||||
}
|
||||
return routes.map((route) => avoidNodeObstacles(route, bounds, directionForEdge(route.edge)))
|
||||
for (let index = routes.length - 1; index >= 0; index--) {
|
||||
routes[index] = avoidNodeObstacles(routes[index]!, routes, bounds, subgraphBounds, index)
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
function sideForOutsidePoint(bounds: FlowchartNodeBounds, sourcePoint: FlowchartPoint): DiagramSide {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
|
||||
import type { DiagramAxis, DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
|
||||
|
||||
export type FlowchartDirection = "TB" | "TD" | "BT" | "LR" | "RL"
|
||||
export type FlowchartNodeShape = "box" | "rounded" | "database" | "decision" | "subroutine"
|
||||
@@ -16,6 +16,7 @@ export interface FlowchartEdge {
|
||||
label: string
|
||||
style?: FlowchartEdgeStyle
|
||||
arrowhead?: false
|
||||
sourceArrowhead?: true
|
||||
orderOnly?: boolean
|
||||
}
|
||||
|
||||
@@ -55,6 +56,7 @@ export type FlowchartPoint = DiagramPoint
|
||||
export interface FlowchartEdgeRoute {
|
||||
edge: FlowchartEdge
|
||||
points: FlowchartPoint[]
|
||||
labelAxis?: DiagramAxis
|
||||
}
|
||||
|
||||
export type FlowchartEdgeDirection = DiagramDirection
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { diagramTextWidth } from "../core/text.js"
|
||||
import { expectDiagram } from "../test/diagram.js"
|
||||
import { renderSequenceDiagram } from "./diagram.js"
|
||||
import { drawSequenceDiagramGrid } from "./drawing.js"
|
||||
@@ -28,6 +29,18 @@ sequenceDiagram
|
||||
])
|
||||
})
|
||||
|
||||
test("decodes HTML entities in participant, message, and note labels", () => {
|
||||
const diagram = parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
participant A as Worker & signer
|
||||
participant B
|
||||
A->>B: ack <3s
|
||||
Note over A,B: result ≥ 1`)
|
||||
|
||||
expect(diagram.participants[0]?.label).toBe("Worker & signer")
|
||||
expect(diagram.messages[0]?.label).toBe("ack <3s")
|
||||
expect(diagram.steps.find((step) => step.type === "note")?.note.label).toBe("result ≥ 1")
|
||||
})
|
||||
|
||||
test("renders a terminal sequence diagram", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -42,11 +55,11 @@ sequenceDiagram
|
||||
│ Browser │ │ Server │
|
||||
╰────┬────╯ ╰────┬───╯
|
||||
│ │
|
||||
│ GET / │
|
||||
├─────────────────▶
|
||||
│ GET / │
|
||||
├─────────────────►
|
||||
│ │
|
||||
│ 401 WWW-Auth │
|
||||
◀─────────────────┤
|
||||
│ 401 WWW-Auth │
|
||||
◄─────────────────┤
|
||||
│ │
|
||||
`)
|
||||
})
|
||||
@@ -70,15 +83,15 @@ sequenceDiagram
|
||||
expectDiagram(output).toEqualDiagram(`
|
||||
leaf tool LocationMutation FileMutation
|
||||
│ │ │
|
||||
├─ resolve(path) ───────────────────▶ │
|
||||
├───────── resolve(path) ───────────► │
|
||||
│ │ │
|
||||
◀─ Plan(target, authority anchor) ──┤ │
|
||||
◄─ Plan(target, authority anchor) ──┤ │
|
||||
│ │ │
|
||||
├─ commit(plan) ───────────────────────────────────────────────▶
|
||||
├─────────────────────── commit(plan) ─────────────────────────►
|
||||
│ │ │
|
||||
│ ◀─ revalidate(plan) ───────┤
|
||||
│ ◄─── revalidate(plan) ─────┤
|
||||
│ │ │
|
||||
│ ├─ same target or reject ──▶
|
||||
│ ├─ same target or reject ──►
|
||||
│ │ │
|
||||
`)
|
||||
})
|
||||
@@ -109,7 +122,7 @@ sequenceDiagram
|
||||
const lines = output.split("\n")
|
||||
|
||||
expect(lines.findIndex((line) => line.includes("deliberately"))).toBeLessThan(
|
||||
lines.findIndex((line) => line.includes("▶")),
|
||||
lines.findIndex((line) => line.includes("►")),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -245,18 +258,29 @@ sequenceDiagram
|
||||
])
|
||||
})
|
||||
|
||||
test("parses activation syntax without rendering activation bars", () => {
|
||||
test("renders activation syntax as visible intervals", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
Browser->>+Server: request
|
||||
Server-->>-Browser: response
|
||||
`)
|
||||
|
||||
expect(output).not.toContain("┃")
|
||||
expect(output).toContain("┃")
|
||||
expect(output).toContain("request")
|
||||
expect(output).toContain("response")
|
||||
})
|
||||
|
||||
test("renders br-delimited participant aliases on separate lines", () => {
|
||||
const output = renderSequenceDiagram(`sequenceDiagram
|
||||
participant A as First line<br/>Second line
|
||||
participant B as Normal
|
||||
A->>B: hello`)
|
||||
|
||||
expect(output).not.toContain("<br")
|
||||
expect(output).toContain("│ First line │")
|
||||
expect(output).toContain("│ Second line │")
|
||||
})
|
||||
|
||||
test("parses Mermaid arrow head variants", () => {
|
||||
const diagram = parseMermaidSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -294,22 +318,22 @@ sequenceDiagram
|
||||
│ A │ │ B │
|
||||
╰─┬─╯ ╰─┬─╯
|
||||
│ │
|
||||
│ open solid │
|
||||
│ open solid │
|
||||
├─────────────────>│
|
||||
│ │
|
||||
│ open dashed │
|
||||
│ open dashed │
|
||||
│<─────────────────┤
|
||||
│ │
|
||||
│ failed solid │
|
||||
│ failed solid │
|
||||
├─────────────────✕│
|
||||
│ │
|
||||
│ failed dashed │
|
||||
│ failed dashed │
|
||||
│✕─────────────────┤
|
||||
│ │
|
||||
│ async solid │
|
||||
│ async solid │
|
||||
├─────────────────)│
|
||||
│ │
|
||||
│ async dashed │
|
||||
│ async dashed │
|
||||
│(─────────────────┤
|
||||
│ │"
|
||||
`)
|
||||
@@ -533,7 +557,7 @@ sequenceDiagram
|
||||
const fragmentMessageRow = fragment.split("\n").find((line) => line.includes("this non adjacent message"))!
|
||||
expect(groupMessageRow.trimEnd().endsWith("│")).toBe(true)
|
||||
expect(fragmentMessageRow).toContain("this non adjacent message is deliberately much wider than the frame")
|
||||
expect(fragmentMessageRow.match(/│/g)?.length).toBe(3)
|
||||
expect(fragmentMessageRow.match(/│/g)?.length).toBe(2)
|
||||
})
|
||||
|
||||
test("keeps long notes inside groups and nested fragment frames intact", () => {
|
||||
@@ -581,6 +605,42 @@ sequenceDiagram
|
||||
expect(externalHeaderLeft).toBeGreaterThan(groupBorderRight)
|
||||
})
|
||||
|
||||
test("keeps adjacent wide participant group frames separate", () => {
|
||||
const output = renderSequenceDiagram(
|
||||
`sequenceDiagram
|
||||
box First very wide group heading
|
||||
participant A
|
||||
end
|
||||
box Second very wide group heading
|
||||
participant B
|
||||
end
|
||||
A->>B: hi`,
|
||||
{ compact: true },
|
||||
)
|
||||
const topRow = output.split("\n")[0]!
|
||||
|
||||
expect(topRow).toContain("First very wide group heading")
|
||||
expect(topRow).toContain("Second very wide group heading")
|
||||
expect(topRow.indexOf("╮")).toBeLessThan(topRow.lastIndexOf("╭"))
|
||||
})
|
||||
|
||||
test("renders many adjacent wide participant groups without excessive canvas growth", () => {
|
||||
const groupCount = 16
|
||||
const output = renderSequenceDiagram(
|
||||
`sequenceDiagram
|
||||
${Array.from(
|
||||
{ length: groupCount },
|
||||
(_, index) => ` box Group ${index} has a deliberately wide heading
|
||||
participant P${index}
|
||||
end`,
|
||||
).join("\n")}
|
||||
P0->>P15: hi`,
|
||||
{ compact: true },
|
||||
)
|
||||
|
||||
expect(Math.max(...output.split("\n").map(diagramTextWidth))).toBeLessThan(groupCount * 60)
|
||||
})
|
||||
|
||||
test("renders full-height participant group boxes", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -600,11 +660,11 @@ sequenceDiagram
|
||||
│ Browser │ │ │ API │ │ Cache │ │ DB │ │
|
||||
╰────┬────╯ │ ╰──┬──╯ ╰───┬───╯ ╰──┬─╯ │
|
||||
│ │ │ │ │ │
|
||||
│ GET /users/42 │ │ │ │
|
||||
├──────────────────▶ │ │ │
|
||||
│ GET /users/42 │ │ │ │
|
||||
├──────────────────► │ │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ get user:42 │ │ │
|
||||
│ │ ├─────────────────▶ │ │
|
||||
│ │ │ get user:42 │ │ │
|
||||
│ │ ├─────────────────► │ │
|
||||
│ │ │ │ │ │
|
||||
╰────────────────────────────────────────────╯"
|
||||
`)
|
||||
@@ -619,12 +679,25 @@ sequenceDiagram
|
||||
end
|
||||
Browser->>API: GET /users/42
|
||||
`)
|
||||
const arrowLine = output.split("\n").find((line) => line.includes("▶"))!
|
||||
const arrowLine = output.split("\n").find((line) => line.includes("►"))!
|
||||
|
||||
expect(arrowLine).toContain("───────────────▶")
|
||||
expect(arrowLine).toContain("───────────────►")
|
||||
expect(arrowLine).not.toContain("┼")
|
||||
})
|
||||
|
||||
test("keeps filled arrowheads to one terminal column", () => {
|
||||
const output = renderSequenceDiagram(`sequenceDiagram
|
||||
box Backend
|
||||
participant A
|
||||
participant B
|
||||
A->>B: request
|
||||
end`)
|
||||
const lines = output.split("\n")
|
||||
const frameWidth = diagramTextWidth(lines.at(-1)!)
|
||||
|
||||
expect(Math.max(...lines.map(diagramTextWidth))).toBe(frameWidth)
|
||||
})
|
||||
|
||||
test("renders self messages as loopback arrows", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -639,12 +712,12 @@ sequenceDiagram
|
||||
│
|
||||
├────────────────────╮
|
||||
│ Check Permissions │
|
||||
◀────────────────────╯
|
||||
◄────────────────────╯
|
||||
│"
|
||||
`)
|
||||
})
|
||||
|
||||
test("places two spacer rows above note badges and one below", () => {
|
||||
test("frames notes in their reserved rows", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
Browser->>Server: one
|
||||
@@ -656,9 +729,11 @@ sequenceDiagram
|
||||
const nextMessageRow = lines.findIndex((line) => line.includes("two"))
|
||||
|
||||
expect(noteRow).toBeGreaterThan(0)
|
||||
expect(lines[noteRow - 1]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow - 2]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow + 1]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow - 1]).toContain("╭")
|
||||
expect(lines[noteRow - 1]).toContain("╮")
|
||||
expect(lines[noteRow]).toContain("│ phase │")
|
||||
expect(lines[noteRow + 1]).toContain("╰")
|
||||
expect(lines[noteRow + 1]).toContain("╯")
|
||||
expect(nextMessageRow).toBe(noteRow + 2)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BorderChars, type BorderStyle } from "@opentui/core"
|
||||
import { DiagramCanvas } from "../core/canvas.js"
|
||||
import { diagramTextWidth } from "../core/text.js"
|
||||
import { DEFAULT_FRAGMENT_BORDER_STYLE } from "./options.js"
|
||||
import {
|
||||
createSequencePlacementPlan,
|
||||
@@ -19,6 +20,10 @@ import type {
|
||||
|
||||
const SEQUENCE_BORDER = BorderChars.rounded
|
||||
|
||||
function centeredStart(center: number, text: string): number {
|
||||
return center - Math.floor(diagramTextWidth(text) / 2)
|
||||
}
|
||||
|
||||
function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1): string {
|
||||
switch (head) {
|
||||
case "open":
|
||||
@@ -28,7 +33,7 @@ function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1):
|
||||
case "async":
|
||||
return direction === 1 ? ")" : "("
|
||||
default:
|
||||
return direction === 1 ? "▶" : "◀"
|
||||
return direction === 1 ? "►" : "◄"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +190,32 @@ function renderSelfMessage(
|
||||
setCell(grid, rightX, bottomRow, SEQUENCE_BORDER.bottomRight, style)
|
||||
}
|
||||
|
||||
function renderNote(grid: SequenceGrid, placement: Extract<SequenceStepPlacement, { type: "note" }>): void {
|
||||
const width = Math.max(...placement.textLines.map(diagramTextWidth))
|
||||
const left = placement.textX
|
||||
const right = left + width - 1
|
||||
const top = placement.textY - 1
|
||||
const bottom = placement.textY + placement.textLines.length
|
||||
|
||||
for (let x = left + 1; x < right; x++) {
|
||||
setCell(grid, x, top, SEQUENCE_BORDER.horizontal, "note")
|
||||
setCell(grid, x, bottom, SEQUENCE_BORDER.horizontal, "note")
|
||||
}
|
||||
for (let y = top + 1; y < bottom; y++) {
|
||||
setCell(grid, left, y, SEQUENCE_BORDER.vertical, "note")
|
||||
setCell(grid, right, y, SEQUENCE_BORDER.vertical, "note")
|
||||
}
|
||||
setCell(grid, left, top, SEQUENCE_BORDER.topLeft, "note")
|
||||
setCell(grid, right, top, SEQUENCE_BORDER.topRight, "note")
|
||||
setCell(grid, left, bottom, SEQUENCE_BORDER.bottomLeft, "note")
|
||||
setCell(grid, right, bottom, SEQUENCE_BORDER.bottomRight, "note")
|
||||
placement.textLines.forEach((line, index) => setText(grid, left, placement.textY + index, line, "noteBadge"))
|
||||
for (let y = placement.textY; y < bottom; y++) {
|
||||
setCell(grid, left, y, SEQUENCE_BORDER.vertical, "note")
|
||||
setCell(grid, right, y, SEQUENCE_BORDER.vertical, "note")
|
||||
}
|
||||
}
|
||||
|
||||
export function drawSequenceDiagramGrid(
|
||||
diagram: SequenceDiagram,
|
||||
options: SequenceDiagramRenderOptions = {},
|
||||
@@ -197,11 +228,13 @@ export function drawSequenceDiagramGrid(
|
||||
if (plan.groups.length > 0) renderParticipantGroups(grid, plan.groups, plan.height - 1)
|
||||
|
||||
for (const placement of plan.participants) {
|
||||
const { participant, centerX: center, headerLeftX, headerRightX, labelX } = placement
|
||||
const { centerX: center, headerLeftX, headerRightX, labelLines } = placement
|
||||
const { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY } = plan.rows
|
||||
|
||||
if (options.compact) {
|
||||
setText(grid, labelX, participantHeaderY, participant.label, "participant")
|
||||
labelLines.forEach((line, index) =>
|
||||
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
|
||||
)
|
||||
} else {
|
||||
for (let x = headerLeftX; x <= headerRightX; x++) {
|
||||
setCell(grid, x, participantHeaderTopY, SEQUENCE_BORDER.horizontal, "participant")
|
||||
@@ -210,11 +243,15 @@ export function drawSequenceDiagramGrid(
|
||||
|
||||
setCell(grid, headerLeftX, participantHeaderTopY, SEQUENCE_BORDER.topLeft, "participant")
|
||||
setCell(grid, headerRightX, participantHeaderTopY, SEQUENCE_BORDER.topRight, "participant")
|
||||
setCell(grid, headerLeftX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
|
||||
setCell(grid, headerRightX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
|
||||
for (let y = participantHeaderY; y < participantRuleY; y++) {
|
||||
setCell(grid, headerLeftX, y, SEQUENCE_BORDER.vertical, "participant")
|
||||
setCell(grid, headerRightX, y, SEQUENCE_BORDER.vertical, "participant")
|
||||
}
|
||||
setCell(grid, headerLeftX, participantRuleY, SEQUENCE_BORDER.bottomLeft, "participant")
|
||||
setCell(grid, headerRightX, participantRuleY, SEQUENCE_BORDER.bottomRight, "participant")
|
||||
setText(grid, labelX, participantHeaderY, participant.label, "participant")
|
||||
labelLines.forEach((line, index) =>
|
||||
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
|
||||
)
|
||||
setCell(grid, center, participantRuleY, SEQUENCE_BORDER.topT, "participant")
|
||||
}
|
||||
|
||||
@@ -227,9 +264,7 @@ export function drawSequenceDiagramGrid(
|
||||
|
||||
for (const placement of plan.steps) {
|
||||
if (placement.type === "note") {
|
||||
for (let lineIndex = 0; lineIndex < placement.textLines.length; lineIndex++) {
|
||||
setText(grid, placement.textX, placement.textY + lineIndex, placement.textLines[lineIndex]!, "noteBadge")
|
||||
}
|
||||
renderNote(grid, placement)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -270,5 +305,13 @@ export function drawSequenceDiagramGrid(
|
||||
if (placement.inlineLabel) setText(grid, placement.labelX, placement.labelY, placement.inlineLabel, messageStyle)
|
||||
}
|
||||
|
||||
for (const activation of plan.activations) {
|
||||
for (let y = activation.startY; y <= activation.endY; y++) {
|
||||
if (grid.getCell(activation.centerX, y)?.char === SEQUENCE_BORDER.vertical) {
|
||||
setCell(grid, activation.centerX, y, "┃", "lifeline")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return grid
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ const ALT_RE = /^alt\s+(.+)$/i
|
||||
const ELSE_RE = /^else(?:\s+(.+))?$/i
|
||||
const LOOP_RE = /^loop\s+(.+)$/i
|
||||
const AUTONUMBER_RE = /^autonumber(?:\s+(\d+)(?:\s+(\d+))?)?$/i
|
||||
const UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE = /<<-{1,2}>>/
|
||||
const CSS_COLOR_NAMES = new Set([
|
||||
"black",
|
||||
"white",
|
||||
@@ -132,6 +133,9 @@ export function parseMermaidSequenceDiagram(content: string): SequenceDiagram {
|
||||
for (const source of meaningfulNumberedMermaidLines(content)) {
|
||||
const line = source.text
|
||||
if (line.toLowerCase() === "sequencediagram") continue
|
||||
if (UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE.test(line)) {
|
||||
throw new MermaidSyntaxError("sequence", source.lineNumber, line)
|
||||
}
|
||||
|
||||
const autonumberMatch = line.match(AUTONUMBER_RE)
|
||||
if (autonumberMatch) {
|
||||
|
||||
@@ -90,6 +90,25 @@ describe("createSequencePlacementPlan", () => {
|
||||
expect(external.headerLeftX).toBeGreaterThan(group.rightX)
|
||||
})
|
||||
|
||||
test("keeps many adjacent wide groups at a linear width", () => {
|
||||
const groupCount = 16
|
||||
const source = `sequenceDiagram
|
||||
${Array.from(
|
||||
{ length: groupCount },
|
||||
(_, index) => ` box Group ${index} has a deliberately wide heading
|
||||
participant P${index}
|
||||
end`,
|
||||
).join("\n")}
|
||||
P0->>P15: hi`
|
||||
const plan = createSequencePlacementPlan(parseMermaidSequenceDiagram(source), { compact: true })
|
||||
|
||||
expect(plan.groups).toHaveLength(groupCount)
|
||||
for (let index = 1; index < plan.groups.length; index++) {
|
||||
expect(plan.groups[index]!.leftX).toBeGreaterThan(plan.groups[index - 1]!.rightX)
|
||||
}
|
||||
expect(plan.width).toBeLessThan(groupCount * 60)
|
||||
})
|
||||
|
||||
test("expands group and fragment frames around contained long content", () => {
|
||||
const groupPlan = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
@@ -169,4 +188,34 @@ describe("createSequencePlacementPlan", () => {
|
||||
|
||||
expect(starts[0]!.bounds.rightX).toBeGreaterThan(starts[1]!.bounds.rightX)
|
||||
})
|
||||
|
||||
test("aligns explicit and shorthand activation intervals to message events", () => {
|
||||
const shorthand = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
A->>+B: request
|
||||
B-->>-A: response`),
|
||||
)
|
||||
const explicit = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
A->>B: request
|
||||
activate B
|
||||
B-->>A: response
|
||||
deactivate B`),
|
||||
)
|
||||
|
||||
expect(explicit.activations).toEqual(shorthand.activations)
|
||||
})
|
||||
|
||||
test("centers message label blocks over their arrow span", () => {
|
||||
const plan = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
participant A
|
||||
participant B
|
||||
A->>B: short<br/>a much longer line`),
|
||||
)
|
||||
const message = plan.steps.find((step) => step.type === "message")!
|
||||
const labelWidth = Math.max(...message.labelLines.map(diagramTextWidth))
|
||||
|
||||
expect(message.labelX * 2 + labelWidth).toBe(message.leftX + message.rightX)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
SequenceStep,
|
||||
} from "./types.js"
|
||||
|
||||
const NOTE_HORIZONTAL_PADDING = 1
|
||||
const NOTE_HORIZONTAL_PADDING = 2
|
||||
const GROUP_HORIZONTAL_PADDING = 2
|
||||
const FRAGMENT_HORIZONTAL_OVERHANG = 3
|
||||
|
||||
@@ -25,7 +25,7 @@ export interface SequenceParticipantPlacement {
|
||||
centerX: number
|
||||
headerLeftX: number
|
||||
headerRightX: number
|
||||
labelX: number
|
||||
labelLines: string[]
|
||||
}
|
||||
|
||||
export interface SequenceGroupPlacement {
|
||||
@@ -41,6 +41,14 @@ export interface SequenceWallPlacement {
|
||||
endY: number
|
||||
}
|
||||
|
||||
export interface SequenceActivationPlacement {
|
||||
participant: string
|
||||
centerX: number
|
||||
startY: number
|
||||
endY: number
|
||||
depth: number
|
||||
}
|
||||
|
||||
export type SequenceStepPlacement =
|
||||
| { type: "note"; note: SequenceNote; textLines: string[]; textX: number; textY: number }
|
||||
| {
|
||||
@@ -88,6 +96,7 @@ export interface SequencePlacementPlan {
|
||||
}
|
||||
participants: SequenceParticipantPlacement[]
|
||||
groups: SequenceGroupPlacement[]
|
||||
activations: SequenceActivationPlacement[]
|
||||
steps: SequenceStepPlacement[]
|
||||
}
|
||||
|
||||
@@ -132,7 +141,8 @@ function messageLabelText(message: SequenceMessage): string {
|
||||
}
|
||||
|
||||
function participantHeaderWidth(label: string, compact: boolean): number {
|
||||
return compact ? visualLength(label) : Math.max(5, visualLength(label) + 4)
|
||||
const width = labelLinesWidth(mermaidLabelLines(label))
|
||||
return compact ? width : Math.max(5, width + 4)
|
||||
}
|
||||
|
||||
function fragmentLabelText(fragment: SequenceFragment): string {
|
||||
@@ -236,7 +246,9 @@ function getStepContentBounds(
|
||||
if (fromIndex === toIndex) return { leftX: fromX, rightX: fromX + selfMessageLoopWidth(step.message) }
|
||||
const leftX = Math.min(fromX, toX)
|
||||
const rightX = Math.max(fromX, toX)
|
||||
return { leftX, rightX: Math.max(rightX, leftX + 2 + messageWidth(step.message) - 1) }
|
||||
const labelWidth = messageWidth(step.message)
|
||||
const labelLeftX = Math.floor((leftX + rightX - labelWidth) / 2)
|
||||
return { leftX: Math.min(leftX, labelLeftX), rightX: Math.max(rightX, labelLeftX + labelWidth - 1) }
|
||||
}
|
||||
if (step.type !== "note") return undefined
|
||||
const indexes = getParticipantIndexes(participantIndexes, step.note.over)
|
||||
@@ -387,7 +399,9 @@ function resolveParticipantCenters(
|
||||
if (fromIndex === toIndex && fromIndex >= 0 && fromIndex < diagram.participants.length - 1) {
|
||||
gaps[fromIndex] = Math.max(
|
||||
gaps[fromIndex]!,
|
||||
selfMessageLoopWidth(message) + Math.ceil(visualLength(diagram.participants[fromIndex + 1]!.label) / 2) + 2,
|
||||
selfMessageLoopWidth(message) +
|
||||
Math.ceil(labelLinesWidth(mermaidLabelLines(diagram.participants[fromIndex + 1]!.label)) / 2) +
|
||||
2,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -423,37 +437,31 @@ function separateExpandedGroupsFromExternalParticipants(
|
||||
compact: boolean,
|
||||
): number[] {
|
||||
const adjusted = [...centers]
|
||||
for (let pass = 0; pass < Math.max(1, ranges.length * 2); pass++) {
|
||||
let changed = false
|
||||
for (let boundary = 0; boundary < adjusted.length - 1; boundary++) {
|
||||
const groups = resolveGroupBounds(diagram, adjusted, participantIndexes, ranges, compact)
|
||||
const leftWidth = participantHeaderWidth(diagram.participants[boundary]!.label, compact)
|
||||
const rightWidth = participantHeaderWidth(diagram.participants[boundary + 1]!.label, compact)
|
||||
let leftRight = adjusted[boundary]! - Math.floor(leftWidth / 2) + leftWidth - 1
|
||||
let rightLeft = adjusted[boundary + 1]! - Math.floor(rightWidth / 2)
|
||||
let bordersGroup = false
|
||||
|
||||
for (const [index, range] of ranges.entries()) {
|
||||
const group = groups[index]!
|
||||
if (range.startIndex > 0) {
|
||||
const previousIndex = range.startIndex - 1
|
||||
const previousWidth = participantHeaderWidth(diagram.participants[previousIndex]!.label, compact)
|
||||
const previousRight = adjusted[previousIndex]! - Math.floor(previousWidth / 2) + previousWidth - 1
|
||||
const shift = previousRight + GROUP_HORIZONTAL_PADDING + 1 - group.leftX
|
||||
if (shift > 0) {
|
||||
for (let participantIndex = range.startIndex; participantIndex < adjusted.length; participantIndex++) {
|
||||
adjusted[participantIndex]! += shift
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if (range.endIndex === boundary) {
|
||||
leftRight = Math.max(leftRight, groups[index]!.rightX)
|
||||
bordersGroup = true
|
||||
}
|
||||
if (range.endIndex < diagram.participants.length - 1) {
|
||||
const nextIndex = range.endIndex + 1
|
||||
const nextWidth = participantHeaderWidth(diagram.participants[nextIndex]!.label, compact)
|
||||
const nextLeft = adjusted[nextIndex]! - Math.floor(nextWidth / 2)
|
||||
const shift = group.rightX + GROUP_HORIZONTAL_PADDING + 1 - nextLeft
|
||||
if (shift > 0) {
|
||||
for (let participantIndex = nextIndex; participantIndex < adjusted.length; participantIndex++) {
|
||||
adjusted[participantIndex]! += shift
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if (range.startIndex === boundary + 1) {
|
||||
rightLeft = Math.min(rightLeft, groups[index]!.leftX)
|
||||
bordersGroup = true
|
||||
}
|
||||
}
|
||||
if (!changed) return adjusted
|
||||
|
||||
if (!bordersGroup) continue
|
||||
const shift = leftRight + GROUP_HORIZONTAL_PADDING + 1 - rightLeft
|
||||
if (shift <= 0) continue
|
||||
for (let participantIndex = boundary + 1; participantIndex < adjusted.length; participantIndex++) {
|
||||
adjusted[participantIndex]! += shift
|
||||
}
|
||||
}
|
||||
return adjusted
|
||||
}
|
||||
@@ -475,6 +483,7 @@ export function createSequencePlacementPlan(
|
||||
},
|
||||
participants: [],
|
||||
groups: [],
|
||||
activations: [],
|
||||
steps: [],
|
||||
}
|
||||
}
|
||||
@@ -511,9 +520,13 @@ export function createSequencePlacementPlan(
|
||||
fragments = fragmentBounds()
|
||||
}
|
||||
const hasGroups = groups.length > 0
|
||||
const participantLabelHeight = Math.max(
|
||||
1,
|
||||
...diagram.participants.map((participant) => mermaidLabelLines(participant.label).length),
|
||||
)
|
||||
const participantHeaderTopY = hasGroups ? 1 : 0
|
||||
const participantHeaderY = participantHeaderTopY + (compact ? 0 : 1)
|
||||
const participantRuleY = participantHeaderTopY + (compact ? 0 : 2)
|
||||
const participantRuleY = participantHeaderTopY + (compact ? participantLabelHeight - 1 : participantLabelHeight + 1)
|
||||
const lifelineStartY = participantRuleY + 1
|
||||
const stepStartY = lifelineStartY + 1
|
||||
const width = Math.max(contentBounds.rightX + 1, ...groups.map((group) => group.rightX + 1), fragments.rightX + 1)
|
||||
@@ -525,19 +538,46 @@ export function createSequencePlacementPlan(
|
||||
const centerX = centers[index]!
|
||||
const width = participantHeaderWidth(participant.label, compact)
|
||||
const headerLeftX = centerX - Math.floor(width / 2)
|
||||
const labelLines = mermaidLabelLines(participant.label)
|
||||
return {
|
||||
participant,
|
||||
centerX,
|
||||
headerLeftX,
|
||||
headerRightX: headerLeftX + width - 1,
|
||||
labelX: centeredStart(centerX, participant.label),
|
||||
labelLines,
|
||||
}
|
||||
})
|
||||
const steps: SequenceStepPlacement[] = []
|
||||
const activations: SequenceActivationPlacement[] = []
|
||||
const activeByParticipant = new Map<string, Array<{ startY: number; depth: number }>>()
|
||||
const lastEventYByParticipant = new Map<string, number>()
|
||||
const openActivation = (participant: string, y: number): void => {
|
||||
const active = activeByParticipant.get(participant) ?? []
|
||||
active.push({ startY: y, depth: active.length })
|
||||
activeByParticipant.set(participant, active)
|
||||
}
|
||||
const closeActivation = (participant: string, y: number): void => {
|
||||
const active = activeByParticipant.get(participant)
|
||||
const opened = active?.pop()
|
||||
const participantIndex = indexes.get(participant)
|
||||
if (!opened || participantIndex === undefined) return
|
||||
activations.push({
|
||||
participant,
|
||||
centerX: centers[participantIndex]!,
|
||||
startY: opened.startY,
|
||||
endY: y,
|
||||
depth: opened.depth,
|
||||
})
|
||||
}
|
||||
let stepY = stepStartY
|
||||
const activeFrames: ActiveFragmentFrame[] = []
|
||||
for (const [stepIndex, step] of diagram.steps.entries()) {
|
||||
if (step.type === "activation") continue
|
||||
if (step.type === "activation") {
|
||||
const eventY = Math.min(lastEventYByParticipant.get(step.activation.participant) ?? stepY, lifelineEndY)
|
||||
if (step.activation.active) openActivation(step.activation.participant, eventY)
|
||||
else closeActivation(step.activation.participant, eventY)
|
||||
continue
|
||||
}
|
||||
const stepHeight = getStepHeight(step, centers, indexes, compact)
|
||||
if (step.type === "note") {
|
||||
const noteIndexes = getParticipantIndexes(indexes, step.note.over)
|
||||
@@ -588,6 +628,7 @@ export function createSequencePlacementPlan(
|
||||
const labelLines = messageLabelLines(messageLabelText(step.message))
|
||||
if (fromIndex === toIndex) {
|
||||
const centerX = centers[fromIndex]!
|
||||
const bottomY = stepY + labelLines.length + 1
|
||||
steps.push({
|
||||
type: "selfMessage",
|
||||
message: step.message,
|
||||
@@ -595,8 +636,11 @@ export function createSequencePlacementPlan(
|
||||
centerX,
|
||||
rightX: centerX + selfMessageLoopWidthForLines(labelLines),
|
||||
topY: stepY,
|
||||
bottomY: stepY + labelLines.length + 1,
|
||||
bottomY,
|
||||
})
|
||||
if (step.message.activate) openActivation(step.message.activate, bottomY)
|
||||
if (step.message.deactivate) closeActivation(step.message.deactivate, bottomY)
|
||||
lastEventYByParticipant.set(step.message.from, bottomY)
|
||||
} else {
|
||||
const fromX = centers[fromIndex]!
|
||||
const toX = centers[toIndex]!
|
||||
@@ -604,13 +648,16 @@ export function createSequencePlacementPlan(
|
||||
const leftX = Math.min(fromX, toX)
|
||||
const rightX = Math.max(fromX, toX)
|
||||
const inlineLabel = inlineMessageLabel(step.message, labelLines, fromX, toX, compact)
|
||||
const arrowY = inlineLabel ? stepY : stepY + labelLines.length
|
||||
const renderedLabelWidth = inlineLabel ? visualLength(inlineLabel) : labelLinesWidth(labelLines)
|
||||
const labelX = Math.floor((leftX + rightX - renderedLabelWidth) / 2)
|
||||
steps.push({
|
||||
type: "message",
|
||||
message: step.message,
|
||||
labelLines,
|
||||
labelX: leftX + 2,
|
||||
labelX,
|
||||
labelY: stepY,
|
||||
arrowY: inlineLabel ? stepY : stepY + labelLines.length,
|
||||
arrowY,
|
||||
fromX,
|
||||
toX,
|
||||
leftX,
|
||||
@@ -619,15 +666,23 @@ export function createSequencePlacementPlan(
|
||||
headX: arrowHeadX(toX, direction, step.message.head),
|
||||
inlineLabel,
|
||||
})
|
||||
if (step.message.activate) openActivation(step.message.activate, arrowY)
|
||||
if (step.message.deactivate) closeActivation(step.message.deactivate, arrowY)
|
||||
lastEventYByParticipant.set(step.message.from, arrowY)
|
||||
lastEventYByParticipant.set(step.message.to, arrowY)
|
||||
}
|
||||
stepY += stepHeight
|
||||
}
|
||||
for (const [participant, active] of activeByParticipant) {
|
||||
while (active.length > 0) closeActivation(participant, lifelineEndY)
|
||||
}
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
rows: { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY },
|
||||
participants,
|
||||
groups,
|
||||
activations,
|
||||
steps,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,17 @@ stateDiagram-v2
|
||||
})
|
||||
})
|
||||
|
||||
test("decodes HTML entities in state, transition, and note labels", () => {
|
||||
const diagram = parseMermaidStateDiagram(`stateDiagram-v2
|
||||
state "Ready & waiting" as Ready
|
||||
Ready --> Done: elapsed <3s
|
||||
note right of Done: result ≥ 1`)
|
||||
|
||||
expect(diagram.states.find((state) => state.id === "Ready")?.label).toBe("Ready & waiting")
|
||||
expect(diagram.transitions[0]?.label).toBe("elapsed <3s")
|
||||
expect(diagram.notes[0]?.lines).toEqual(["result ≥ 1"])
|
||||
})
|
||||
|
||||
test("parses choice pseudo-states", () => {
|
||||
const diagram = parseMermaidStateDiagram(`
|
||||
stateDiagram-v2
|
||||
@@ -55,7 +66,7 @@ stateDiagram-v2
|
||||
Decision --> Accepted: yes
|
||||
`)
|
||||
|
||||
expect(diagram.states).toContainEqual({ id: "Decision", label: "┼", kind: "choice" })
|
||||
expect(diagram.states).toContainEqual({ id: "Decision", label: "", kind: "choice" })
|
||||
})
|
||||
|
||||
test("parses composite states and notes", () => {
|
||||
@@ -188,7 +199,7 @@ stateDiagram-v2
|
||||
●───────────────────────▶│ Running │
|
||||
╰──┬──────╯ 💥 sandbox dies BEFORE hook fires
|
||||
▲ │ ▲ (crash, our bug, race)
|
||||
╭────────┼─╰───┼───────╮
|
||||
╭────────┼─┴───┼───────╮
|
||||
▼ ╭────┼─────╯ ▼
|
||||
╭──────┴──╮ │ ╭──────╮
|
||||
│ Dormant │ │ │ Lost │
|
||||
@@ -384,7 +395,7 @@ stateDiagram-v2
|
||||
|
||||
expect(output).toMatchInlineSnapshot(`
|
||||
" ╭─────────╮ submit ok ╭───────╮
|
||||
●────────────▶│ Editing ├─────────────┬────────────▶│ Saved │
|
||||
●────────────▶│ Editing ├────────────▶◆────────────▶│ Saved │
|
||||
╰──┬──────╯ │ ╰───────╯
|
||||
▲ │ ▲ type │ fail
|
||||
│ ╰────╯ │
|
||||
@@ -411,7 +422,7 @@ stateDiagram-v2
|
||||
Decision --> Done
|
||||
Done --> [*]`)
|
||||
|
||||
expect(output).toContain("Upper ├─────────────┬────────────▶│ Done")
|
||||
expect(output).toContain("Upper ├────────────▶◆────────────▶│ Done")
|
||||
})
|
||||
|
||||
test("renders self transitions as loops in vertical diagrams", () => {
|
||||
@@ -444,6 +455,65 @@ stateDiagram-v2
|
||||
expect(vertical).toContain("second")
|
||||
})
|
||||
|
||||
test("separates labels on four parallel vertical transitions", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
A --> B: one
|
||||
A --> B: two
|
||||
A --> B: three
|
||||
A --> B: four`)
|
||||
|
||||
expect(output).not.toContain("twothree")
|
||||
for (const label of ["one", "two", "three", "four"]) {
|
||||
expect(output.match(new RegExp(label, "g"))).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps explicit choices visible in choice-only cycles", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
state One <<choice>>
|
||||
state Two <<choice>>
|
||||
state Three <<choice>>
|
||||
One --> Two: clockwise
|
||||
Two --> Three: clockwise
|
||||
Three --> One: clockwise`)
|
||||
|
||||
expect(output.match(/◆/g)).toHaveLength(3)
|
||||
})
|
||||
|
||||
test("routes dense horizontal transitions around unrelated states", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction LR
|
||||
A --> B: ab
|
||||
A --> C: ac
|
||||
A --> D: ad
|
||||
B --> A: ba
|
||||
B --> C: bc
|
||||
B --> D: bd
|
||||
C --> A: ca
|
||||
C --> B: cb
|
||||
C --> D: cd
|
||||
D --> A: da
|
||||
D --> B: db
|
||||
D --> C: dc`)
|
||||
|
||||
for (const state of ["A", "B", "C", "D"]) expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("routes parallel transitions around vertically offset states", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
A --> B: first<br/>line two
|
||||
A --> B: second<br/>another line
|
||||
B --> A: return<br/>with details`)
|
||||
|
||||
expect(output).toContain(" A ")
|
||||
expect(output).toContain("│ B │")
|
||||
expect(output).toContain("first")
|
||||
expect(output).toContain("second")
|
||||
expect(output).toContain("return")
|
||||
})
|
||||
|
||||
test("keeps independent overlapping feedback labels and paths distinct", () => {
|
||||
const content = (direction: "LR" | "RL") => `stateDiagram-v2
|
||||
direction ${direction}
|
||||
@@ -561,15 +631,46 @@ stateDiagram-v2
|
||||
})
|
||||
expect(output).toMatchInlineSnapshot(`
|
||||
" ╭─ Authenticated ──────────────────╮
|
||||
│ │
|
||||
login │ ╭──────╮ open ╭─────────╮ │ save
|
||||
●────────────▶│ Idle ├────────────▶│ Editing ├────────────▶◎
|
||||
│ │ save
|
||||
login │ ╭──────╮ open ╭─────────╮ │ logout
|
||||
●───────────┼▶│ Idle ├────────────▶│ Editing ├─┼──────────▶◎
|
||||
│ ╰──────╯ ╰─────────╯ │
|
||||
│ │
|
||||
╰──────────────────────────────────╯"
|
||||
`)
|
||||
})
|
||||
|
||||
test("keeps nested composite entry and exit routes within the outer frame height", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
state Session {
|
||||
[*] --> Open
|
||||
state Open {
|
||||
[*] --> Clean
|
||||
Clean --> Dirty: edit
|
||||
Dirty --> Clean: save
|
||||
}
|
||||
note right of Open: document lifecycle
|
||||
Open --> [*]: close
|
||||
}
|
||||
[*] --> Session
|
||||
Session --> [*]`)
|
||||
const lines = output.split("\n")
|
||||
const outerFrameTop = lines.find((line) => line.includes("Session"))!
|
||||
const frameLeft = outerFrameTop.indexOf("╭")
|
||||
const frameRight = outerFrameTop.lastIndexOf("╮")
|
||||
const outerFrameBottom = lines.findIndex((line) => line[frameLeft] === "╰" && line[frameRight] === "╯")
|
||||
const startColumn = lines.find((line) => line.includes("●"))!.indexOf("●")
|
||||
const endColumn = lines.find((line) => line.includes("◎"))!.indexOf("◎")
|
||||
|
||||
expect(outerFrameBottom).toBeGreaterThan(0)
|
||||
expect(startColumn).toBeLessThan(frameLeft)
|
||||
expect(endColumn).toBeGreaterThan(frameRight)
|
||||
expect(lines.slice(outerFrameBottom + 1).every((line) => line.trim() === "")).toBe(true)
|
||||
expect(output).toContain("Open")
|
||||
expect(output).toContain("document lifecycle")
|
||||
expect(output).toContain("close")
|
||||
})
|
||||
|
||||
test("renders notes attached to states", () => {
|
||||
const output = renderStateDiagram(`
|
||||
stateDiagram-v2
|
||||
@@ -600,6 +701,91 @@ stateDiagram-v2
|
||||
state Decision <<choice>>
|
||||
Decision --> [*]`)
|
||||
|
||||
expect(output).toContain("╰─────────────┬\n")
|
||||
expect(output).toContain("╰─────────────▼")
|
||||
expect(output).toContain("◆────────────▶◎")
|
||||
})
|
||||
|
||||
test("keeps vertical branch labels from overwriting state labels", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
state "Branch root" as Root
|
||||
state "Upper branch" as Upper
|
||||
state "Lower branch" as Lower
|
||||
state "Merged branch" as Merge
|
||||
Root --> Upper: branch-up
|
||||
Root --> Lower: branch-down
|
||||
Upper --> Merge: merge-up
|
||||
Lower --> Merge: merge-down
|
||||
Merge --> Root: branch-feedback`)
|
||||
|
||||
for (const text of [
|
||||
"Branch root",
|
||||
"Upper branch",
|
||||
"Lower branch",
|
||||
"Merged branch",
|
||||
"branch-up",
|
||||
"branch-down",
|
||||
"merge-up",
|
||||
"merge-down",
|
||||
"branch-feedback",
|
||||
]) {
|
||||
expect(output).toContain(text)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps lifecycle states intact around branches and feedback", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
[*] --> Idle
|
||||
Idle --> MailboxPending: enqueue + setAlarm
|
||||
MailboxPending --> PromptSubmitted: drain mailbox
|
||||
PromptSubmitted --> Polling: prompt admitted
|
||||
Polling --> Polling: execution still active
|
||||
Polling --> Completed: terminal log event
|
||||
Polling --> Polling: retry after transient failure
|
||||
Completed --> Idle: final Slack projection
|
||||
Idle --> Expired: 30 days inactive
|
||||
Expired --> [*]: delete SQLite state`)
|
||||
|
||||
for (const state of ["Idle", "MailboxPending", "PromptSubmitted", "Polling", "Completed", "Expired"]) {
|
||||
expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps composite titles intact under reciprocal composite routes", () => {
|
||||
const source = `stateDiagram-v2
|
||||
direction LR
|
||||
state FirstGroup {
|
||||
[*] --> FirstInner
|
||||
FirstInner --> [*]: first-out
|
||||
}
|
||||
state SecondGroup {
|
||||
[*] --> SecondInner
|
||||
SecondInner --> [*]: second-out
|
||||
}
|
||||
FirstGroup --> SecondGroup: group-next
|
||||
SecondGroup --> FirstGroup: group-back`
|
||||
|
||||
for (const direction of ["LR", "TB"] as const) {
|
||||
const lines = renderStateDiagram(source, { direction }).split("\n")
|
||||
for (const title of ["FirstGroup", "SecondGroup"]) {
|
||||
const top = lines.findIndex((line) => line.includes(title))
|
||||
const left = lines[top]!.lastIndexOf("╭", lines[top]!.indexOf(title))
|
||||
const right = lines[top]!.indexOf("╮", left)
|
||||
const bottom = lines.findIndex((line, index) => index > top && line[left] === "╰" && line[right] === "╯")
|
||||
|
||||
expect(top).toBeGreaterThanOrEqual(0)
|
||||
expect(left).toBeGreaterThanOrEqual(0)
|
||||
expect(right).toBeGreaterThan(left)
|
||||
expect(bottom).toBeGreaterThan(top)
|
||||
expect(
|
||||
lines.slice(top + 1, bottom).every((line) => "│├┤┼".includes(line[left]!) && "│├┤┼".includes(line[right]!)),
|
||||
).toBe(true)
|
||||
expect(
|
||||
lines[bottom]!.slice(left + 1, right)
|
||||
.split("")
|
||||
.every((char) => "─┬┴┼".includes(char)),
|
||||
).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -49,7 +49,9 @@ function translateTransitionPlans(
|
||||
function makeGrid(width: number, height: number): StateGrid {
|
||||
return new DiagramCanvas(width, height, {
|
||||
mergeCell: (existing, incoming): StateCell => {
|
||||
const shouldMerge = existing.style === "transition" && incoming.style === "transition"
|
||||
const existingIsTransition = existing.style === "transition" || existing.style?.startsWith("stateDepartureRamp")
|
||||
const incomingIsTransition = incoming.style === "transition" || incoming.style?.startsWith("stateDepartureRamp")
|
||||
const shouldMerge = incomingIsTransition && (existingIsTransition || existing.style === "composite")
|
||||
return {
|
||||
...incoming,
|
||||
char: shouldMerge
|
||||
@@ -198,7 +200,8 @@ function drawTransitionJunctionPlans(
|
||||
): void {
|
||||
for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
|
||||
const style = plan.kind === "choice" ? "choice" : "transition"
|
||||
setCell(grid, plan.bounds.left, plan.bounds.top, diagramLineGlyph(plan.connections, "rounded"), style)
|
||||
const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
|
||||
setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,14 +40,6 @@ export interface StateDiagramLayoutOptions {
|
||||
minStateGap: number
|
||||
}
|
||||
|
||||
function visualLength(value: string): number {
|
||||
return diagramTextWidth(value)
|
||||
}
|
||||
|
||||
function splitStateDiagramLines(value: string): string[] {
|
||||
return splitDiagramLines(value)
|
||||
}
|
||||
|
||||
function computeRanks(diagram: StateDiagram): Map<string, number> {
|
||||
const ranks = new Map<string, number>()
|
||||
const outgoing = new Map<string, string[]>()
|
||||
@@ -88,8 +80,11 @@ function outgoingTransitions(diagram: StateDiagram): Map<string, StateDiagramTra
|
||||
return outgoing
|
||||
}
|
||||
|
||||
function reaches(diagram: StateDiagram, from: string, target: string): boolean {
|
||||
const outgoing = outgoingTransitions(diagram)
|
||||
function reaches(
|
||||
outgoing: ReadonlyMap<string, readonly StateDiagramTransition[]>,
|
||||
from: string,
|
||||
target: string,
|
||||
): boolean {
|
||||
const visited = new Set<string>()
|
||||
const stack = [from]
|
||||
while (stack.length > 0) {
|
||||
@@ -104,6 +99,7 @@ function reaches(diagram: StateDiagram, from: string, target: string): boolean {
|
||||
|
||||
function computeMainPath(diagram: StateDiagram): string[] {
|
||||
const outgoing = outgoingTransitions(diagram)
|
||||
const statesById = new Map(diagram.states.map((state) => [state.id, state]))
|
||||
const start = diagram.states.find((state) => state.kind === "start")?.id ?? diagram.states[0]?.id
|
||||
if (!start) return []
|
||||
|
||||
@@ -114,9 +110,14 @@ function computeMainPath(diagram: StateDiagram): string[] {
|
||||
const candidates = (outgoing.get(current) ?? []).filter((transition) => !visited.has(transition.to))
|
||||
if (candidates.length === 0) break
|
||||
const next =
|
||||
candidates.find((transition) => diagram.states.find((state) => state.id === transition.to)?.kind === "end") ??
|
||||
candidates.find((transition) => !reaches(diagram, transition.to, current)) ??
|
||||
candidates.find((transition) => !hasReverseTransition(diagram, transition))
|
||||
candidates.find((transition) => statesById.get(transition.to)?.kind === "end") ??
|
||||
candidates.find((transition) => !reaches(outgoing, transition.to, current)) ??
|
||||
candidates.find((transition) => !hasReverseTransition(diagram, transition)) ??
|
||||
candidates.find((transition) => {
|
||||
const fromParent = statesById.get(current)?.parentId
|
||||
const toParent = statesById.get(transition.to)?.parentId
|
||||
return Boolean(fromParent && toParent && fromParent !== toParent)
|
||||
})
|
||||
if (!next) break
|
||||
path.push(next.to)
|
||||
visited.add(next.to)
|
||||
@@ -132,7 +133,7 @@ function stateSize(state: StateDiagramState): { width: number; height: number; l
|
||||
}
|
||||
|
||||
function noteLines(note: StateDiagramNote): string[] {
|
||||
const lines = note.lines.flatMap(splitStateDiagramLines).map((line) => line.trim())
|
||||
const lines = note.lines.flatMap(splitDiagramLines).map((line) => line.trim())
|
||||
return lines.length > 0 ? lines : [""]
|
||||
}
|
||||
|
||||
@@ -202,7 +203,7 @@ function addCompositeBounds(diagram: StateDiagram, layout: StateDiagramLayout):
|
||||
const top = Math.min(...childBounds.map((bound) => bound.top)) - 2
|
||||
const right = Math.max(...childBounds.map((bound) => bound.left + bound.width)) + 2
|
||||
const bottom = Math.max(...childBounds.map((bound) => bound.top + bound.height)) + 2
|
||||
const width = Math.max(right - left, visualLength(composite.label) + 5)
|
||||
const width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
|
||||
const bound = {
|
||||
id: composite.id,
|
||||
left,
|
||||
@@ -349,7 +350,7 @@ function expandCompositeBoundsForNotes(diagram: StateDiagram, layout: StateDiagr
|
||||
|
||||
bound.left = left
|
||||
bound.top = top
|
||||
bound.width = Math.max(right - left, visualLength(composite.label) + 5)
|
||||
bound.width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
|
||||
bound.height = bottom - top
|
||||
bound.centerX = bound.left + Math.floor(bound.width / 2)
|
||||
bound.centerY = bound.top + Math.floor(bound.height / 2)
|
||||
@@ -461,7 +462,8 @@ export function createStateDiagramLayout(
|
||||
x += size.width + options.minStateGap + 8
|
||||
}
|
||||
const labelRows = states.reduce((rows, state) => Math.max(rows, outgoingLabelRows.get(state.id) ?? 0), 0)
|
||||
y += rowHeight + Math.max(4, labelRows + 3)
|
||||
const pseudoStateApproachClearance = states.some((state) => state.kind === "choice") ? 2 : 0
|
||||
y += rowHeight + Math.max(4, labelRows + 3) + pseudoStateApproachClearance
|
||||
}
|
||||
|
||||
return finalizeLayout(diagram, emptyLayout(bounds, sizes))
|
||||
@@ -499,7 +501,10 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
|
||||
const adjacentLabelWidth = diagram.transitions
|
||||
.filter((transition) => transition.from === id && transition.to === nextId)
|
||||
.reduce((width, transition) => Math.max(width, measureStateTransitionLabel(transition.label).width), 0)
|
||||
x += size.width + Math.max(defaultGap, adjacentLabelWidth + 2)
|
||||
const crossesCompositeBoundary = Boolean(
|
||||
nextId && statesById.get(id)?.parentId !== statesById.get(nextId)?.parentId,
|
||||
)
|
||||
x += size.width + Math.max(defaultGap, adjacentLabelWidth + (crossesCompositeBoundary ? 6 : 2))
|
||||
}
|
||||
|
||||
const branchesByParent = new Map<string, string[]>()
|
||||
@@ -550,12 +555,25 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
|
||||
}
|
||||
|
||||
const ranks = computeRanks(diagram)
|
||||
const fallbackStates = diagram.states.filter((state) => !bounds.has(state.id))
|
||||
const fallbackStates = diagram.states
|
||||
.filter((state) => !bounds.has(state.id))
|
||||
.sort((left, right) => (ranks.get(left.id) ?? 0) - (ranks.get(right.id) ?? 0))
|
||||
for (const state of fallbackStates) {
|
||||
const size = sizes.get(state.id)!
|
||||
const rank = ranks.get(state.id) ?? bounds.size
|
||||
const top = baselineY + 5
|
||||
const left = rank * (size.width + defaultGap)
|
||||
const rank = ranks.get(state.id) ?? bounds.size
|
||||
let left = rank * (size.width + defaultGap)
|
||||
while (true) {
|
||||
const collision = [...bounds.values()].find(
|
||||
(bound) =>
|
||||
left < bound.left + bound.width + defaultGap &&
|
||||
left + size.width + defaultGap > bound.left &&
|
||||
top < bound.top + bound.height &&
|
||||
top + size.height > bound.top,
|
||||
)
|
||||
if (!collision) break
|
||||
left = collision.left + collision.width + defaultGap
|
||||
}
|
||||
bounds.set(state.id, {
|
||||
id: state.id,
|
||||
left,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
|
||||
import { decodeMermaidText, firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
|
||||
import { splitDiagramLines } from "../core/text-lines.js"
|
||||
import { MermaidSyntaxError } from "../diagnostics.js"
|
||||
import { normalizeStateDiagramEndpoint, stateDiagramEndMarkerId, stateDiagramStartMarkerId } from "./endpoint.js"
|
||||
@@ -96,7 +96,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
notes.push({
|
||||
target: pendingNote.target,
|
||||
position: pendingNote.position,
|
||||
lines: pendingNote.lines,
|
||||
lines: pendingNote.lines.map(decodeMermaidText),
|
||||
})
|
||||
pendingNote = undefined
|
||||
} else if (line || pendingNote.lines.length > 0) {
|
||||
@@ -119,6 +119,9 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
|
||||
const directionMatch = line.match(DIRECTION_RE)
|
||||
if (directionMatch) {
|
||||
if (parentStack.length > 0) {
|
||||
throw new MermaidSyntaxError("state", source.lineNumber, line, "Composite-local direction is not supported")
|
||||
}
|
||||
direction = normalizeDirection(directionMatch[1])
|
||||
continue
|
||||
}
|
||||
@@ -128,7 +131,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
notes.push({
|
||||
position: inlineNoteMatch[1]!.toLowerCase() as "left" | "right",
|
||||
target: inlineNoteMatch[2]!,
|
||||
lines: splitDiagramLines(inlineNoteMatch[3]!.trim()),
|
||||
lines: splitDiagramLines(decodeMermaidText(inlineNoteMatch[3]!.trim())),
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -150,7 +153,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
const id = compositeMatch[2]!
|
||||
composites.push({
|
||||
id,
|
||||
label: compositeMatch[1] ?? id,
|
||||
label: decodeMermaidText(compositeMatch[1] ?? id),
|
||||
...(parentId ? { parentId } : {}),
|
||||
})
|
||||
parentStack.push({ id, lineNumber: source.lineNumber, sourceLine: line })
|
||||
@@ -159,13 +162,13 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
|
||||
const stateMatch = line.match(STATE_RE)
|
||||
if (stateMatch) {
|
||||
ensureState(states, stateMatch[2]!, stateMatch[1]!, "state", parentId)
|
||||
ensureState(states, stateMatch[2]!, decodeMermaidText(stateMatch[1]!), "state", parentId)
|
||||
continue
|
||||
}
|
||||
|
||||
const choiceMatch = line.match(CHOICE_STATE_RE)
|
||||
if (choiceMatch) {
|
||||
ensureState(states, choiceMatch[1]!, "┼", "choice", parentId)
|
||||
ensureState(states, choiceMatch[1]!, "", "choice", parentId)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -177,7 +180,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
const to = normalizeStateDiagramEndpoint(rawTo, "to", parentId)
|
||||
ensureState(states, from, rawFrom === "[*]" ? "●" : from, rawFrom === "[*]" ? "start" : "state", parentId)
|
||||
ensureState(states, to, rawTo === "[*]" ? "◎" : to, rawTo === "[*]" ? "end" : "state", parentId)
|
||||
transitions.push({ from, to, label: transitionMatch[3]?.trim() ?? "" })
|
||||
transitions.push({ from, to, label: decodeMermaidText(transitionMatch[3]?.trim() ?? "") })
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { StateDiagramBoxBounds } from "./layout.js"
|
||||
import { createStateDiagramLayout } from "./layout.js"
|
||||
import { parseMermaidStateDiagram } from "./parser.js"
|
||||
import {
|
||||
createStateTransitionJunctionPlans,
|
||||
createStateTransitionRenderPlans,
|
||||
createStateTransitionRoutePlans,
|
||||
} from "./routing.js"
|
||||
import { prepareVisibleStateDiagram, type StateVisibleDiagram } from "./visible-model.js"
|
||||
import type { StateVisibleDiagram } from "./visible-model.js"
|
||||
import { prepareVisibleStateDiagram } from "./visible-model.js"
|
||||
|
||||
function bounds(id: string, centerX: number, centerY: number): StateDiagramBoxBounds {
|
||||
return { id, left: centerX - 2, top: centerY - 1, width: 5, height: 3, centerX, centerY }
|
||||
@@ -207,6 +210,39 @@ describe("createStateTransitionRenderPlans", () => {
|
||||
[11, 4],
|
||||
])
|
||||
})
|
||||
|
||||
test("keeps vertical branch routes out of unrelated state bounds", () => {
|
||||
const diagram = prepareVisibleStateDiagram(
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
state "Branch root" as Root
|
||||
state "Upper branch" as Upper
|
||||
state "Lower branch" as Lower
|
||||
state "Merged branch" as Merge
|
||||
Root --> Upper: branch-up
|
||||
Root --> Lower: branch-down
|
||||
Upper --> Merge: merge-up
|
||||
Lower --> Merge: merge-down
|
||||
Merge --> Root: branch-feedback`),
|
||||
)
|
||||
const layout = createStateDiagramLayout(diagram, { minStateGap: 4 })
|
||||
const plans = createStateTransitionRenderPlans(diagram, layout.bounds, 30)
|
||||
|
||||
for (const plan of plans) {
|
||||
const unrelated = diagram.states
|
||||
.filter((state) => state.id !== plan.route.transition.from && state.id !== plan.route.transition.to)
|
||||
.map((state) => layout.bounds.get(state.id)!)
|
||||
expect(
|
||||
plan.path.some(([x, y]) =>
|
||||
unrelated.some(
|
||||
(bound) =>
|
||||
x >= bound.left && x < bound.left + bound.width && y >= bound.top && y < bound.top + bound.height,
|
||||
),
|
||||
),
|
||||
`${plan.route.transition.from} -> ${plan.route.transition.to}`,
|
||||
).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("createStateTransitionJunctionPlans", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BorderChars } from "@opentui/core"
|
||||
import type { DiagramDirection } from "../core/geometry.js"
|
||||
import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "../core/spatial.js"
|
||||
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
|
||||
import type { StateDiagramBoxBounds as BoxBounds } from "./layout.js"
|
||||
import type { StateDiagram, StateDiagramState, StateDiagramTransition } from "./types.js"
|
||||
@@ -10,14 +11,15 @@ interface StateTransitionRoutePlanBase {
|
||||
from: BoxBounds
|
||||
to: BoxBounds
|
||||
targetIsChoice: boolean
|
||||
targetIsHiddenMarker: boolean
|
||||
}
|
||||
|
||||
export type StateTransitionRoutePlan =
|
||||
| (StateTransitionRoutePlanBase & { kind: "self" })
|
||||
| (StateTransitionRoutePlanBase & { kind: "horizontal-forward"; leftToRight: boolean })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number; approachX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "top-feedback"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number; approachX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "vertical-elbow"; hasReverse: boolean; offsetConnector: boolean })
|
||||
| (StateTransitionRoutePlanBase & { kind: "side-parallel"; railX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "vertical" })
|
||||
@@ -192,6 +194,93 @@ function hasOpposingTopConnector(
|
||||
})
|
||||
}
|
||||
|
||||
function verticalCorridorCrossesUnrelatedState(
|
||||
diagram: StateVisibleDiagram,
|
||||
transition: StateVisibleTransition,
|
||||
from: BoxBounds,
|
||||
to: BoxBounds,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
): boolean {
|
||||
const top = Math.min(from.top + from.height, to.top + to.height)
|
||||
const bottom = Math.max(from.top - 1, to.top - 1)
|
||||
return diagram.states.some((state) => {
|
||||
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return false
|
||||
const bound = bounds.get(state.id)
|
||||
return Boolean(
|
||||
bound &&
|
||||
from.centerX >= bound.left &&
|
||||
from.centerX < bound.left + bound.width &&
|
||||
top < bound.top + bound.height &&
|
||||
bottom >= bound.top,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function horizontalCorridorCrossesUnrelatedState(
|
||||
diagram: StateVisibleDiagram,
|
||||
transition: StateVisibleTransition,
|
||||
from: BoxBounds,
|
||||
to: BoxBounds,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
): boolean {
|
||||
const leftToRight = from.centerX <= to.centerX
|
||||
const startX = leftToRight ? from.left + from.width : from.left - 1
|
||||
const endX = leftToRight ? to.left - 1 : to.left + to.width
|
||||
const space = SpatialIndex.empty().add(
|
||||
...diagram.states.flatMap((state) => {
|
||||
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return []
|
||||
const bound = bounds.get(state.id)
|
||||
return bound ? [spatialRectClaim(`state:${state.id}`, `state:${state.id}`, "body", bound)] : []
|
||||
}),
|
||||
)
|
||||
const corridor = spatialPathClaim(
|
||||
`corridor:${transition.from}:${transition.to}`,
|
||||
`transition:${transition.from}:${transition.to}`,
|
||||
"route",
|
||||
[
|
||||
{ x: startX, y: from.centerY },
|
||||
{ x: endX, y: from.centerY },
|
||||
],
|
||||
)
|
||||
return !space.isFree(corridor)
|
||||
}
|
||||
|
||||
function bottomApproachX(
|
||||
diagram: StateVisibleDiagram,
|
||||
transition: StateVisibleTransition,
|
||||
from: BoxBounds,
|
||||
to: BoxBounds,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
railY: number,
|
||||
): number {
|
||||
const targetX = to.width > 1 ? (from.centerX > to.centerX ? to.left + 1 : to.left + to.width - 2) : to.centerX
|
||||
const targetBottomY = to.top + to.height
|
||||
const top = Math.min(targetBottomY, railY)
|
||||
const bottom = Math.max(targetBottomY, railY)
|
||||
const isClear = (x: number): boolean =>
|
||||
!diagram.states.some((state) => {
|
||||
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return false
|
||||
const bound = bounds.get(state.id)
|
||||
return Boolean(
|
||||
bound &&
|
||||
x >= bound.left &&
|
||||
x < bound.left + bound.width &&
|
||||
top < bound.top + bound.height &&
|
||||
bottom >= bound.top,
|
||||
)
|
||||
})
|
||||
|
||||
if (isClear(targetX)) return targetX
|
||||
const maxX = Math.max(targetX, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 1
|
||||
for (let distance = 1; distance <= maxX; distance++) {
|
||||
const right = targetX + distance
|
||||
if (isClear(right)) return right
|
||||
const left = targetX - distance
|
||||
if (left >= 0 && isClear(left)) return left
|
||||
}
|
||||
return targetX
|
||||
}
|
||||
|
||||
export function createStateTransitionRoutePlans(
|
||||
diagram: StateVisibleDiagram,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
@@ -200,16 +289,29 @@ export function createStateTransitionRoutePlans(
|
||||
): StateTransitionRoutePlan[] {
|
||||
const statesById = new Map(diagram.states.map((state) => [state.id, state]))
|
||||
const endpointOccurrences = new Map<string, number>()
|
||||
const maxLabelWidth = Math.max(
|
||||
0,
|
||||
...diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label).width),
|
||||
)
|
||||
const parallelLaneGap = Math.max(
|
||||
3,
|
||||
...diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label).height + 2),
|
||||
)
|
||||
const sideLaneX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + maxLabelWidth + 3
|
||||
let nextSideRailX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 3
|
||||
const feedbackAllocations = createFeedbackAllocations(diagram, bounds, feedbackLaneY, parallelLaneGap, feedbackTopY)
|
||||
let nextBottomRailY =
|
||||
Math.max(
|
||||
feedbackLaneY - parallelLaneGap,
|
||||
...[...feedbackAllocations.values()]
|
||||
.filter((allocation) => allocation.side === "bottom")
|
||||
.map((allocation) => allocation.railY),
|
||||
) + parallelLaneGap
|
||||
const allocateSideRail = (label: string): number => {
|
||||
const railX = nextSideRailX
|
||||
nextSideRailX += Math.max(3, measureStateTransitionLabel(label).width + 2)
|
||||
return railX
|
||||
}
|
||||
const allocateBottomRail = (): number => {
|
||||
const railY = nextBottomRailY
|
||||
nextBottomRailY += parallelLaneGap
|
||||
return railY
|
||||
}
|
||||
|
||||
return diagram.transitions.flatMap((transition): StateTransitionRoutePlan[] => {
|
||||
const from = bounds.get(transition.from)
|
||||
@@ -217,8 +319,9 @@ export function createStateTransitionRoutePlans(
|
||||
if (!from || !to) return []
|
||||
|
||||
const targetState = statesById.get(transition.to)
|
||||
const targetIsChoice = targetState?.kind === "choice" || isHiddenCompositeMarker(targetState)
|
||||
const base = { transition, from, to, targetIsChoice }
|
||||
const targetIsChoice = targetState?.kind === "choice"
|
||||
const targetIsHiddenMarker = isHiddenCompositeMarker(targetState)
|
||||
const base = { transition, from, to, targetIsChoice, targetIsHiddenMarker }
|
||||
if (transition.from === transition.to) return [{ ...base, kind: "self" }]
|
||||
const endpointKey = `${transition.from}\u0000${transition.to}`
|
||||
const parallelIndex = endpointOccurrences.get(endpointKey) ?? 0
|
||||
@@ -227,30 +330,80 @@ export function createStateTransitionRoutePlans(
|
||||
(diagram.direction === "LR" || diagram.direction === "RL") && isStateHorizontalFeedback(diagram, from, to)
|
||||
const feedbackAllocation = feedbackAllocations.get(transition)
|
||||
if (feedbackAllocation) {
|
||||
if (feedbackAllocation.side === "bottom") {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-feedback",
|
||||
railY: feedbackAllocation.railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackAllocation.railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: feedbackAllocation.side === "bottom" ? "bottom-feedback" : "top-feedback",
|
||||
kind: "top-feedback",
|
||||
railY: feedbackAllocation.railY,
|
||||
},
|
||||
]
|
||||
}
|
||||
if (parallelIndex > 0) {
|
||||
if (diagram.direction === "LR" || diagram.direction === "RL") {
|
||||
if ((diagram.direction === "LR" || diagram.direction === "RL") && from.centerY === to.centerY) {
|
||||
const railY = allocateBottomRail()
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY: feedbackLaneY + (parallelIndex - 1) * parallelLaneGap,
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ ...base, kind: "side-parallel", railX: sideLaneX + (parallelIndex - 1) * parallelLaneGap }]
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (diagram.direction !== "LR" && diagram.direction !== "RL") {
|
||||
const fromParent = statesById.get(transition.from)?.parentId
|
||||
const toParent = statesById.get(transition.to)?.parentId
|
||||
if (fromParent && toParent && fromParent !== toParent) {
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (verticalCorridorCrossesUnrelatedState(diagram, transition, from, to, bounds)) {
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (from.centerY > to.centerY) {
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (from.centerY === to.centerY) {
|
||||
if (hasReverseTransition(diagram, transition) && from.centerX > to.centerX) {
|
||||
const railY = allocateBottomRail()
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
|
||||
}
|
||||
if (from.centerX !== to.centerX) {
|
||||
return [{ ...base, kind: "vertical-elbow", hasReverse: false, offsetConnector: false }]
|
||||
}
|
||||
return [{ ...base, kind: "vertical" }]
|
||||
}
|
||||
if (diagram.direction !== "LR" && diagram.direction !== "RL") return [{ ...base, kind: "vertical" }]
|
||||
|
||||
if (from.centerY !== to.centerY) {
|
||||
if (from.centerY > to.centerY && feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
|
||||
if (from.centerY > to.centerY && feedback)
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-feedback",
|
||||
railY: feedbackLaneY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
|
||||
},
|
||||
]
|
||||
const hasReverse = hasReverseTransition(diagram, transition)
|
||||
return [
|
||||
{
|
||||
@@ -261,7 +414,26 @@ export function createStateTransitionRoutePlans(
|
||||
},
|
||||
]
|
||||
}
|
||||
if (feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
|
||||
if (feedback)
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-feedback",
|
||||
railY: feedbackLaneY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
|
||||
},
|
||||
]
|
||||
if (horizontalCorridorCrossesUnrelatedState(diagram, transition, from, to, bounds)) {
|
||||
const railY = allocateBottomRail()
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
|
||||
})
|
||||
}
|
||||
@@ -333,7 +505,7 @@ function addTopDeparture(builder: StateTransitionRenderBuilder, bounds: BoxBound
|
||||
}
|
||||
|
||||
function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, leftToRight, transition } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, leftToRight, transition } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "horizontal-forward" }
|
||||
>
|
||||
@@ -343,9 +515,12 @@ function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
|
||||
const step = leftToRight ? 1 : -1
|
||||
const startX = leftToRight ? from.left + from.width : from.left - 1
|
||||
const endX = leftToRight ? to.left - 1 : to.left + to.width
|
||||
addHorizontalLine(builder, startX, targetIsChoice ? endX : endX - step, y, step)
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, y)
|
||||
else addCell(builder, { x: endX, y, arrowDirection: leftToRight ? "right" : "left" })
|
||||
addHorizontalLine(builder, startX, endX - step, y, step)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker ? { x: endX, y, char: "─" } : { x: endX, y, arrowDirection: leftToRight ? "right" : "left" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, y)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const labelX = Math.min(startX, endX) + Math.max(1, Math.floor((Math.abs(endX - startX) - metrics.width) / 2))
|
||||
@@ -378,14 +553,14 @@ function outsideTopY(bounds: BoxBounds): number {
|
||||
}
|
||||
|
||||
function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY, approachX } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "bottom-feedback" | "bottom-parallel" }
|
||||
>
|
||||
const sourceX = from.centerX
|
||||
const targetX = to.width > 1 ? (sourceX > to.centerX ? to.left + 1 : to.left + to.width - 2) : to.centerX
|
||||
const targetRailCutsSource = targetX >= from.left && targetX <= from.left + from.width - 1
|
||||
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : targetX
|
||||
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : approachX
|
||||
const sourceBottomY = outsideBottomY(from)
|
||||
const targetBottomY = outsideBottomY(to)
|
||||
addBottomDeparture(builder, from, sourceX)
|
||||
@@ -406,8 +581,13 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
addCell(builder, { x, y: targetBottomY, char: "─" })
|
||||
}
|
||||
}
|
||||
addCell(builder, { x: targetX, y: targetBottomY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "up" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker
|
||||
? { x: targetX, y: targetBottomY, char: "│" }
|
||||
: { x: targetX, y: targetBottomY, arrowDirection: "up" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const horizontalRoom = Math.abs(sourceX - railTargetX) - 2
|
||||
@@ -419,7 +599,7 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
|
||||
function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "top-feedback" }
|
||||
>
|
||||
@@ -437,8 +617,13 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
addCell(builder, { x: targetX, y: railY, char: sourceX > targetX ? "╭" : "╮" })
|
||||
for (let y = railY + 1; y < targetTopY; y++) addCell(builder, { x: targetX, y, char: "│" })
|
||||
addCell(builder, { x: targetX, y: targetTopY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "down" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker
|
||||
? { x: targetX, y: targetTopY, char: "│" }
|
||||
: { x: targetX, y: targetTopY, arrowDirection: "down" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const horizontalRoom = Math.abs(sourceX - targetX) - 2
|
||||
@@ -450,7 +635,7 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
|
||||
function addSideParallelTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, transition, railX } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railX } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "side-parallel" }
|
||||
>
|
||||
@@ -465,9 +650,16 @@ function addSideParallelTransition(builder: StateTransitionRenderBuilder): void
|
||||
for (let y = startY + verticalStep; y !== endY; y += verticalStep) addCell(builder, { x: railX, y, char: "│" })
|
||||
addCell(builder, { x: railX, y: endY, char: verticalStep === 1 ? "╯" : "╮" })
|
||||
for (let x = railX - 1; x > endX; x--) addCell(builder, { x, y: endY, char: "─" })
|
||||
addCell(builder, { x: endX, y: endY, ...(targetIsChoice ? { char: "─" } : { arrowDirection: "left" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) addLabel(builder, railX + 2, Math.min(startY, endY) + 1, transition.label)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker ? { x: endX, y: endY, char: "─" } : { x: endX, y: endY, arrowDirection: "left" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) {
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const labelY = Math.max(0, Math.floor((startY + endY - metrics.height + 1) / 2))
|
||||
addLabel(builder, railX + 2, labelY, transition.label)
|
||||
}
|
||||
}
|
||||
|
||||
function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
|
||||
@@ -476,10 +668,8 @@ function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
|
||||
}
|
||||
|
||||
function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, transition, targetIsChoice, hasReverse, offsetConnector } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "vertical-elbow" }
|
||||
>
|
||||
const { from, to, transition, targetIsChoice, targetIsHiddenMarker, hasReverse, offsetConnector } =
|
||||
builder.route as Extract<StateTransitionRoutePlan, { kind: "vertical-elbow" }>
|
||||
const topToBottom = from.centerY < to.centerY
|
||||
const offset = offsetConnector ? (topToBottom ? -2 : 2) : 0
|
||||
const startX = innerConnectorX(from, from.centerX + offset)
|
||||
@@ -513,13 +703,19 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
|
||||
}
|
||||
}
|
||||
}
|
||||
const targetChar = targetIsChoice ? (hasTargetApproach || startX === endX ? "│" : topToBottom ? "┬" : "┴") : undefined
|
||||
const targetChar = targetIsHiddenMarker
|
||||
? hasTargetApproach || startX === endX
|
||||
? "│"
|
||||
: topToBottom
|
||||
? "┬"
|
||||
: "┴"
|
||||
: undefined
|
||||
addCell(builder, {
|
||||
x: endX,
|
||||
y: endY,
|
||||
...(targetChar ? { char: targetChar } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
})
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
if (topToBottom) {
|
||||
@@ -543,7 +739,7 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
|
||||
}
|
||||
|
||||
function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, transition, targetIsChoice } = builder.route
|
||||
const { from, to, transition, targetIsChoice, targetIsHiddenMarker } = builder.route
|
||||
const topToBottom = from.centerY <= to.centerY
|
||||
const x = from.centerX
|
||||
const startY = topToBottom ? from.top + from.height : from.top - 1
|
||||
@@ -555,9 +751,9 @@ function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
|
||||
addCell(builder, {
|
||||
x,
|
||||
y: endY,
|
||||
...(targetIsChoice ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
...(targetIsHiddenMarker ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
})
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) addLabel(builder, x + 2, Math.min(startY, endY) + 1, transition.label)
|
||||
}
|
||||
|
||||
@@ -590,69 +786,47 @@ 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 }]
|
||||
: []
|
||||
})
|
||||
let space = SpatialIndex.empty().add(
|
||||
...diagram.states.flatMap((state) => {
|
||||
const bound = bounds.get(state.id)
|
||||
return bound && !isHiddenCompositeMarker(state)
|
||||
? [spatialRectClaim(`state:${state.id}`, `state:${state.id}`, "body", bound)]
|
||||
: []
|
||||
}),
|
||||
...plans.map((plan, index) =>
|
||||
spatialPathClaim(
|
||||
`route:${index}`,
|
||||
`route:${index}`,
|
||||
"route",
|
||||
plan.path.map(([x, y]) => ({ x, y })),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
return plans.map((plan) => {
|
||||
return plans.map((plan, planIndex) => {
|
||||
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 statePadding = plan.label.lines.length === 1 ? 0 : 1
|
||||
const labelClaim = (x: number, y: number) =>
|
||||
spatialRectClaim(`label:${planIndex}`, `label:${planIndex}`, "label", {
|
||||
left: x,
|
||||
top: y,
|
||||
width,
|
||||
height: plan.label!.lines.length,
|
||||
})
|
||||
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
|
||||
return space.isFree(labelClaim(x, y), {
|
||||
clearance: {
|
||||
body: statePadding,
|
||||
label: { x: 1, y: 0 },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
let x = plan.label.x
|
||||
@@ -672,7 +846,7 @@ function placeStateTransitionLabels(
|
||||
}
|
||||
}
|
||||
|
||||
placedLabels.push(labelRect({ ...plan.label, x, y }, width))
|
||||
space = space.add(labelClaim(x, y))
|
||||
return { ...plan, label: { ...plan.label, x, y } }
|
||||
})
|
||||
}
|
||||
@@ -703,6 +877,7 @@ export function createStateTransitionJunctionPlans(
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
renderPlans: readonly StateTransitionRenderPlan[],
|
||||
): StateTransitionJunctionPlan[] {
|
||||
const renderPlanByTransition = new Map(renderPlans.map((plan) => [plan.route.transition, plan]))
|
||||
return diagram.states.flatMap((state): StateTransitionJunctionPlan[] => {
|
||||
const kind =
|
||||
state.kind === "choice" ? "choice" : isHiddenCompositeMarker(state) ? "hidden-composite-marker" : undefined
|
||||
@@ -713,7 +888,7 @@ export function createStateTransitionJunctionPlans(
|
||||
const connections = new Set<DiagramDirection>()
|
||||
const transitions: StateVisibleTransition[] = []
|
||||
for (const transition of diagram.transitions) {
|
||||
const renderPlan = renderPlans.find((plan) => plan.route.transition === transition)
|
||||
const renderPlan = renderPlanByTransition.get(transition)
|
||||
let connected = false
|
||||
if (transition.to === state.id) {
|
||||
const junction = renderPlan?.path.at(-1)
|
||||
|
||||
@@ -20,6 +20,43 @@ describe("prepareVisibleStateDiagram", () => {
|
||||
expect(visible.states.some((state) => state.id === "Authenticated.__start")).toBe(false)
|
||||
expect(visible.states.some((state) => state.id === "Authenticated.__end")).toBe(false)
|
||||
expect(entry).toMatchObject({ from: "__start", to: "Idle", label: "login" })
|
||||
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save" })
|
||||
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save<br/>logout" })
|
||||
})
|
||||
|
||||
test("collapses nested composite entry chains without retaining scoped markers", () => {
|
||||
const visible = prepareVisibleStateDiagram(
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
state Session {
|
||||
[*] --> Open
|
||||
state Open {
|
||||
[*] --> Clean
|
||||
Clean --> Dirty: edit
|
||||
Dirty --> Clean: save
|
||||
}
|
||||
Open --> [*]: close
|
||||
}
|
||||
[*] --> Session
|
||||
Session --> [*]`),
|
||||
)
|
||||
|
||||
expect(visible.states.map((state) => state.id)).toEqual(["Clean", "Dirty", "__start", "__end"])
|
||||
expect(visible.transitions).toContainEqual({ from: "__start", to: "Clean", label: "" })
|
||||
expect(visible.transitions.some((transition) => transition.from.includes(".__start"))).toBe(false)
|
||||
expect(visible.transitions.some((transition) => transition.to.includes(".__start"))).toBe(false)
|
||||
})
|
||||
|
||||
test("preserves labels on both sides of collapsed composite markers", () => {
|
||||
const visible = prepareVisibleStateDiagram(
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
[*] --> Session: open session
|
||||
state Session {
|
||||
[*] --> Ready: initialize
|
||||
Ready --> [*]: finalize
|
||||
}
|
||||
Session --> [*]: close session`),
|
||||
)
|
||||
|
||||
expect(visible.transitions).toContainEqual({ from: "__start", to: "Ready", label: "open session<br/>initialize" })
|
||||
expect(visible.transitions).toContainEqual({ from: "Ready", to: "__end", label: "finalize<br/>close session" })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ export function isHiddenCompositeMarker(state: StateDiagramState | undefined): b
|
||||
}
|
||||
|
||||
function composeTransitionLabel(incoming: StateDiagramTransition, outgoing: StateDiagramTransition): string {
|
||||
return incoming.label || outgoing.label
|
||||
return [incoming.label, outgoing.label].filter(Boolean).join("<br/>")
|
||||
}
|
||||
|
||||
function collapseHiddenCompositeMarkerTransitionsOnce(
|
||||
@@ -23,33 +23,28 @@ function collapseHiddenCompositeMarkerTransitionsOnce(
|
||||
)
|
||||
if (hiddenMarkers.size === 0) return { transitions: [...transitions], changed: false }
|
||||
|
||||
const skipped = new Set<StateVisibleTransition>()
|
||||
const collapsed: StateVisibleTransition[] = []
|
||||
let changed = false
|
||||
|
||||
for (const markerId of hiddenMarkers) {
|
||||
const incoming = transitions.filter((transition) => transition.to === markerId && transition.from !== markerId)
|
||||
const outgoing = transitions.filter((transition) => transition.from === markerId && transition.to !== markerId)
|
||||
if (incoming.length === 0 || outgoing.length === 0) continue
|
||||
|
||||
changed = true
|
||||
for (const incomingTransition of incoming) {
|
||||
skipped.add(incomingTransition)
|
||||
for (const outgoingTransition of outgoing) {
|
||||
skipped.add(outgoingTransition)
|
||||
collapsed.push({
|
||||
from: incomingTransition.from,
|
||||
to: outgoingTransition.to,
|
||||
label: composeTransitionLabel(incomingTransition, outgoingTransition),
|
||||
})
|
||||
}
|
||||
const skipped = new Set([...incoming, ...outgoing])
|
||||
return {
|
||||
transitions: [
|
||||
...transitions.filter((transition) => !skipped.has(transition)),
|
||||
...incoming.flatMap((incomingTransition) =>
|
||||
outgoing.map((outgoingTransition) => ({
|
||||
from: incomingTransition.from,
|
||||
to: outgoingTransition.to,
|
||||
label: composeTransitionLabel(incomingTransition, outgoingTransition),
|
||||
})),
|
||||
),
|
||||
],
|
||||
changed: true,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
transitions: [...transitions.filter((transition) => !skipped.has(transition)), ...collapsed],
|
||||
changed,
|
||||
}
|
||||
return { transitions: [...transitions], changed: false }
|
||||
}
|
||||
|
||||
function collapseHiddenCompositeMarkerTransitions(diagram: StateDiagram): StateVisibleTransition[] {
|
||||
|
||||
@@ -26,6 +26,21 @@ describe("parser diagnostics", () => {
|
||||
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --o B"')
|
||||
})
|
||||
|
||||
test("does not partially parse unsupported flowchart syntax", () => {
|
||||
for (const statement of ["A & B --> C", "A((Start)) --> B", "A-->B; B-->C"]) {
|
||||
expect(() => parseMermaidFlowchartDiagram(`flowchart LR\n ${statement}`)).toThrow(MermaidSyntaxError)
|
||||
}
|
||||
})
|
||||
|
||||
test("does not treat arrows inside flowchart node labels as edges", () => {
|
||||
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
|
||||
A["send --> receive"] --> B`)
|
||||
|
||||
expect(diagram.nodes.map((node) => node.id)).toEqual(["A", "B"])
|
||||
expect(diagram.nodes[0]?.label).toBe("send --> receive")
|
||||
expect(diagram.edges).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("exposes structured syntax errors through top-level rendering", () => {
|
||||
try {
|
||||
renderSequenceDiagram(`sequenceDiagram
|
||||
@@ -41,6 +56,12 @@ describe("parser diagnostics", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("rejects unsupported bidirectional sequence arrows without phantom participants", () => {
|
||||
for (const message of ["A<<->>B: hello", "A<<-->>B: hello"]) {
|
||||
expect(() => parseMermaidSequenceDiagram(`sequenceDiagram\n ${message}`)).toThrow(MermaidSyntaxError)
|
||||
}
|
||||
})
|
||||
|
||||
test("reports unclosed state constructs at their opening line", () => {
|
||||
expect(() =>
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
@@ -55,6 +76,17 @@ describe("parser diagnostics", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("rejects unsupported composite-local state directions", () => {
|
||||
expect(() =>
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
direction LR
|
||||
state Parent {
|
||||
direction TB
|
||||
A --> B
|
||||
}`),
|
||||
).toThrow("Composite-local direction is not supported")
|
||||
})
|
||||
|
||||
test("reports malformed sequence block endings", () => {
|
||||
expect(() =>
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
|
||||
@@ -1809,6 +1809,12 @@
|
||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||
}
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
@@ -2017,6 +2023,12 @@
|
||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||
}
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
|
||||
}
|
||||
},
|
||||
"delivery": {
|
||||
"anyOf": [
|
||||
{
|
||||
@@ -12841,6 +12853,25 @@
|
||||
"required": ["name"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"Prompt.SkillAttachment": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"mention": {
|
||||
"$ref": "#/components/schemas/Prompt.Mention"
|
||||
}
|
||||
},
|
||||
"required": ["id", "name", "text"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"Session.Message.User": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -12880,6 +12911,12 @@
|
||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||
}
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Prompt.SkillAttachment"
|
||||
}
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["user"]
|
||||
@@ -13837,6 +13874,19 @@
|
||||
"required": ["uri"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"PromptInput.SkillAttachment": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"mention": {
|
||||
"$ref": "#/components/schemas/Prompt.Mention"
|
||||
}
|
||||
},
|
||||
"required": ["id"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"SessionPending.UserData": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -13855,6 +13905,12 @@
|
||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||
}
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Prompt.SkillAttachment"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
}
|
||||
@@ -14764,6 +14820,12 @@
|
||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||
}
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Prompt.SkillAttachment"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
}
|
||||
|
||||
@@ -345,6 +345,7 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLo
|
||||
model: Model.Ref.pipe(Schema.optional),
|
||||
files: PromptInput.Prompt.fields.files,
|
||||
agents: PromptInput.Prompt.fields.agents,
|
||||
skills: PromptInput.Prompt.fields.skills,
|
||||
delivery: SessionPending.Delivery.pipe(Schema.optional),
|
||||
resume: Schema.Boolean.pipe(Schema.optional),
|
||||
}),
|
||||
|
||||
@@ -3,6 +3,7 @@ export * as PromptInput from "./prompt-input.js"
|
||||
import { Schema } from "effect"
|
||||
import { AgentAttachment, PromptMention } from "./prompt.js"
|
||||
import { optional, statics } from "./schema.js"
|
||||
import { Skill } from "./skill.js"
|
||||
|
||||
export interface FileAttachment extends Schema.Schema.Type<typeof FileAttachment> {}
|
||||
export const FileAttachment = Schema.Struct({
|
||||
@@ -19,8 +20,15 @@ export const FileAttachment = Schema.Struct({
|
||||
)
|
||||
|
||||
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
|
||||
export interface SkillAttachment extends Schema.Schema.Type<typeof SkillAttachment> {}
|
||||
export const SkillAttachment = Schema.Struct({
|
||||
id: Skill.ID,
|
||||
mention: PromptMention.pipe(optional),
|
||||
}).annotate({ identifier: "PromptInput.SkillAttachment" })
|
||||
|
||||
export const Prompt = Schema.Struct({
|
||||
text: Schema.String,
|
||||
files: Schema.Array(FileAttachment).pipe(optional),
|
||||
agents: Schema.Array(AgentAttachment).pipe(optional),
|
||||
skills: Schema.Array(SkillAttachment).pipe(optional),
|
||||
}).annotate({ identifier: "PromptInput" })
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Schema } from "effect"
|
||||
import { optional } from "./schema.js"
|
||||
import { statics } from "./schema.js"
|
||||
import { Skill } from "./skill.js"
|
||||
|
||||
export interface PromptMention extends Schema.Schema.Type<typeof PromptMention> {}
|
||||
export const PromptMention = Schema.Struct({
|
||||
@@ -52,21 +53,31 @@ export const AgentAttachment = Schema.Struct({
|
||||
mention: PromptMention.pipe(optional),
|
||||
}).annotate({ identifier: "Prompt.AgentAttachment" })
|
||||
|
||||
export interface SkillAttachment extends Schema.Schema.Type<typeof SkillAttachment> {}
|
||||
export const SkillAttachment = Schema.Struct({
|
||||
id: Skill.ID,
|
||||
name: Skill.Name,
|
||||
text: Schema.String,
|
||||
mention: PromptMention.pipe(optional),
|
||||
}).annotate({ identifier: "Prompt.SkillAttachment" })
|
||||
|
||||
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
|
||||
export const Prompt = Schema.Struct({
|
||||
text: Schema.String,
|
||||
files: Schema.Array(FileAttachment).pipe(optional),
|
||||
agents: Schema.Array(AgentAttachment).pipe(optional),
|
||||
skills: Schema.Array(SkillAttachment).pipe(optional),
|
||||
})
|
||||
.annotate({ identifier: "Prompt" })
|
||||
.pipe(
|
||||
statics((schema) => ({
|
||||
equivalence: Schema.toEquivalence(schema),
|
||||
fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents">) =>
|
||||
fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents" | "skills">) =>
|
||||
schema.make({
|
||||
text: input.text,
|
||||
...(input.files === undefined ? {} : { files: input.files }),
|
||||
...(input.agents === undefined ? {} : { agents: input.agents }),
|
||||
...(input.skills === undefined ? {} : { skills: input.skills }),
|
||||
}),
|
||||
})),
|
||||
)
|
||||
|
||||
@@ -58,6 +58,7 @@ export const User = Schema.Struct({
|
||||
text: Prompt.fields.text,
|
||||
files: Prompt.fields.files,
|
||||
agents: Prompt.fields.agents,
|
||||
skills: Prompt.fields.skills,
|
||||
type: Schema.tag("user"),
|
||||
}).annotate({ identifier: "Session.Message.User" })
|
||||
|
||||
|
||||
@@ -313,6 +313,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
||||
text: ctx.payload.text,
|
||||
files: ctx.payload.files,
|
||||
agents: ctx.payload.agents,
|
||||
skills: ctx.payload.skills,
|
||||
metadata: ctx.payload.metadata,
|
||||
delivery: ctx.payload.delivery,
|
||||
resume: ctx.payload.resume,
|
||||
@@ -337,6 +338,9 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
||||
Effect.catchTag("Session.AttachmentError", (error) =>
|
||||
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
|
||||
),
|
||||
Effect.catchTag("Session.SkillNotFoundError", (error) =>
|
||||
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
|
||||
),
|
||||
),
|
||||
}
|
||||
}),
|
||||
@@ -355,6 +359,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
||||
model: ctx.payload.model,
|
||||
files: ctx.payload.files,
|
||||
agents: ctx.payload.agents,
|
||||
skills: ctx.payload.skills,
|
||||
delivery: ctx.payload.delivery,
|
||||
resume: ctx.payload.resume,
|
||||
})
|
||||
@@ -394,6 +399,9 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
||||
Effect.catchTag("Session.AttachmentError", (error) =>
|
||||
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
|
||||
),
|
||||
Effect.catchTag("Session.SkillNotFoundError", (error) =>
|
||||
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
|
||||
),
|
||||
),
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -28,6 +28,7 @@ import { SessionRestart } from "@opencode-ai/core/session/execution/restart"
|
||||
import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
|
||||
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
|
||||
import { WellKnown } from "@opencode-ai/core/wellknown"
|
||||
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||
import { Watcher } from "@opencode-ai/core/filesystem/watcher"
|
||||
import { HttpRouter } from "effect/unstable/http"
|
||||
import { HttpApiBuilder } from "effect/unstable/httpapi"
|
||||
@@ -43,6 +44,7 @@ import { formLocationLayer } from "./middleware/form-location"
|
||||
import { sessionLocationLayer } from "./middleware/session-location"
|
||||
import { ServerInfo } from "./server-info"
|
||||
import type { ServerOptions } from "./options"
|
||||
import { modalWorkspaceDriver, provider as modalProvider } from "./workspace/modal-workspace"
|
||||
|
||||
const applicationServices = LayerNode.group([
|
||||
Database.node,
|
||||
@@ -115,6 +117,10 @@ function makeRoutes<AuthError, AuthServices>(
|
||||
],
|
||||
[PluginRuntime.node, PluginRuntime.layerWithCell(pluginRuntimeCell)],
|
||||
[PluginRuntime.providerNode, PluginRuntime.providerNodeWithCell(pluginRuntimeCell)],
|
||||
[
|
||||
WorkspaceDriver.node,
|
||||
WorkspaceDriver.registryNode({ [modalProvider]: modalWorkspaceDriver({ app: "opencode-workspaces" }) }),
|
||||
],
|
||||
]
|
||||
const serviceLayer = options.simulation
|
||||
? Layer.unwrap(
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||
import { Effect, Option, Schema } from "effect"
|
||||
import type { App, Image, ModalClient, ModalClientParams, Sandbox } from "modal"
|
||||
import { createModalSandboxWithClient, makeModalDriver, type ModalImageSpec, openModalClient } from "./modal"
|
||||
|
||||
export const provider = "modal"
|
||||
|
||||
export const ModalBinding = Schema.Struct({
|
||||
sandboxId: Schema.optional(Schema.String),
|
||||
snapshotImageId: Schema.optional(Schema.String),
|
||||
})
|
||||
export type ModalBinding = typeof ModalBinding.Type
|
||||
|
||||
export interface ModalWorkspaceOptions {
|
||||
readonly app: string
|
||||
readonly client?: ModalClientParams
|
||||
readonly image?: ModalImageSpec
|
||||
}
|
||||
|
||||
export const modalWorkspaceDriver = (options: ModalWorkspaceOptions): WorkspaceDriver.Interface => {
|
||||
const decodeBinding = Schema.decodeUnknownOption(ModalBinding)
|
||||
let clientPromise: Promise<ModalClient> | undefined
|
||||
let appPromise: Promise<App> | undefined
|
||||
// The SDK client and app handle are shared for the process lifetime of this driver.
|
||||
const client = () => (clientPromise ??= openModalClient(options.client))
|
||||
const app = () =>
|
||||
(appPromise ??= client().then((value) => value.apps.fromName(options.app, { createIfMissing: true })))
|
||||
|
||||
const attempt = <A>(run: () => Promise<A>) =>
|
||||
Effect.tryPromise({ try: run, catch: (cause) => new WorkspaceDriver.Error({ cause }) })
|
||||
|
||||
const binding = (value: WorkspaceDriver.Binding): ModalBinding => Option.getOrElse(decodeBinding(value), () => ({}))
|
||||
|
||||
const live = async (lookup: () => Promise<Sandbox>) => {
|
||||
const { NotFoundError } = await import("modal")
|
||||
const sandbox = await lookup().catch((error) => {
|
||||
if (error instanceof NotFoundError) return undefined
|
||||
throw error
|
||||
})
|
||||
if (sandbox && (await sandbox.poll()) === null) return sandbox
|
||||
}
|
||||
|
||||
const findLive = async (modalClient: ModalClient, value: ModalBinding, workspaceID: string) => {
|
||||
if (value.sandboxId) {
|
||||
const sandboxID = value.sandboxId
|
||||
const sandbox = await live(() => modalClient.sandboxes.fromId(sandboxID))
|
||||
if (sandbox) return sandbox
|
||||
}
|
||||
// Name fallback is valid only before the first snapshot; afterward a live named sandbox is stale by design.
|
||||
if (value.snapshotImageId) return
|
||||
return live(() => modalClient.sandboxes.fromName(options.app, workspaceID))
|
||||
}
|
||||
|
||||
const createSandbox = async (workspaceID: string, image?: Image) => {
|
||||
const { AlreadyExistsError } = await import("modal")
|
||||
const modalClient = await client()
|
||||
return createModalSandboxWithClient(
|
||||
modalClient,
|
||||
await app(),
|
||||
{
|
||||
image: options.image,
|
||||
sandbox: {
|
||||
name: workspaceID,
|
||||
tags: { workspace: workspaceID },
|
||||
timeoutMs: 24 * 60 * 60 * 1000,
|
||||
},
|
||||
},
|
||||
image,
|
||||
).catch((error) => {
|
||||
if (error instanceof AlreadyExistsError) return modalClient.sandboxes.fromName(options.app, workspaceID)
|
||||
throw error
|
||||
})
|
||||
}
|
||||
|
||||
const deleteImage = (modalClient: ModalClient, imageID?: string) =>
|
||||
imageID ? attempt(() => modalClient.images.delete(imageID)).pipe(Effect.ignore) : Effect.void
|
||||
|
||||
const terminate = (sandbox?: Sandbox) =>
|
||||
sandbox ? attempt(() => sandbox.terminate({ wait: true })).pipe(Effect.ignore) : Effect.void
|
||||
|
||||
return WorkspaceDriver.make({
|
||||
create: ({ workspaceID }) =>
|
||||
attempt(async () => {
|
||||
const sandbox = await createSandbox(workspaceID)
|
||||
return { binding: { sandboxId: sandbox.sandboxId } }
|
||||
}),
|
||||
connect: ({ workspaceID, binding: value, saveBinding }) =>
|
||||
Effect.gen(function* () {
|
||||
const modalBinding = binding(value)
|
||||
const modalClient = yield* attempt(client)
|
||||
const sandbox = yield* attempt(async () => {
|
||||
const existing = await findLive(modalClient, modalBinding, workspaceID)
|
||||
const image =
|
||||
existing || !modalBinding.snapshotImageId
|
||||
? undefined
|
||||
: await modalClient.images.fromId(modalBinding.snapshotImageId)
|
||||
return existing ?? createSandbox(workspaceID, image)
|
||||
})
|
||||
if (modalBinding.sandboxId !== sandbox.sandboxId) {
|
||||
yield* saveBinding({ ...modalBinding, sandboxId: sandbox.sandboxId })
|
||||
}
|
||||
return makeModalDriver(sandbox)
|
||||
}),
|
||||
suspendForIdle: ({ workspaceID, binding: value, saveBinding }) =>
|
||||
Effect.gen(function* () {
|
||||
const modalBinding = binding(value)
|
||||
const modalClient = yield* attempt(client)
|
||||
const sandbox = yield* attempt(() => findLive(modalClient, modalBinding, workspaceID))
|
||||
if (!sandbox) return
|
||||
const snapshot = yield* attempt(() => sandbox.snapshotFilesystem({ ttlMs: null }))
|
||||
yield* saveBinding({ snapshotImageId: snapshot.imageId })
|
||||
yield* Effect.all([deleteImage(modalClient, modalBinding.snapshotImageId), terminate(sandbox)], {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
})
|
||||
}),
|
||||
destroy: ({ workspaceID, binding: value }) =>
|
||||
Effect.gen(function* () {
|
||||
const modalBinding = binding(value)
|
||||
const modalClient = yield* attempt(client)
|
||||
const sandbox = yield* attempt(() => findLive(modalClient, modalBinding, workspaceID))
|
||||
yield* Effect.all([terminate(sandbox), deleteImage(modalClient, modalBinding.snapshotImageId)], {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
})
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { systemError } from "effect/PlatformError"
|
||||
import type { Command, KillOptions } from "effect/unstable/process/ChildProcess"
|
||||
import { ExitCode, make, makeHandle, ProcessId } from "effect/unstable/process/ChildProcessSpawner"
|
||||
import type { Driver } from "@opencode-ai/core/environment"
|
||||
import type { ModalClientParams, Sandbox, SandboxCreateParams } from "modal"
|
||||
import type { App, Image, ModalClient, ModalClientParams, Sandbox, SandboxCreateParams } from "modal"
|
||||
|
||||
const INNER_WRAPPER = `
|
||||
pidfile=$1
|
||||
@@ -44,13 +44,16 @@ export interface ModalImageSpec {
|
||||
readonly dockerfileCommands: ReadonlyArray<string>
|
||||
}
|
||||
|
||||
export interface ModalSandboxOptions {
|
||||
readonly app: string
|
||||
readonly client?: ModalClientParams
|
||||
export interface ModalSandboxCreateOptions {
|
||||
readonly image?: ModalImageSpec
|
||||
readonly sandbox?: SandboxCreateParams
|
||||
}
|
||||
|
||||
export interface ModalSandboxOptions extends ModalSandboxCreateOptions {
|
||||
readonly app: string
|
||||
readonly client?: ModalClientParams
|
||||
}
|
||||
|
||||
/**
|
||||
* Ubuntu supplies the GNU coreutils and findutils required by the derived Files
|
||||
* scripts. Busybox images do not satisfy the Environment contract.
|
||||
@@ -64,19 +67,11 @@ export const ubuntuImage: ModalImageSpec = {
|
||||
|
||||
/** Creates a Modal sandbox lazily, keeping the SDK off the server startup path when Modal is unused. */
|
||||
export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
||||
const { ModalClient } = await import("modal")
|
||||
const client = new ModalClient(options.client)
|
||||
const client = await openModalClient(options.client)
|
||||
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])
|
||||
// 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 },
|
||||
const sandbox = await createModalSandboxWithClient(client, app, {
|
||||
image: options.image,
|
||||
sandbox: options.sandbox,
|
||||
})
|
||||
return {
|
||||
driver: makeModalDriver(sandbox),
|
||||
@@ -85,6 +80,32 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
||||
}
|
||||
}
|
||||
|
||||
export const openModalClient = async (params?: ModalClientParams) => {
|
||||
const { ModalClient } = await import("modal")
|
||||
return new ModalClient(params)
|
||||
}
|
||||
|
||||
export const createModalSandboxWithClient = async (
|
||||
client: ModalClient,
|
||||
app: App,
|
||||
options: ModalSandboxCreateOptions,
|
||||
existingImage?: Image,
|
||||
) => {
|
||||
const imageSpec = options.image ?? ubuntuImage
|
||||
const image =
|
||||
existingImage ??
|
||||
client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
|
||||
// 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).
|
||||
return client.sandboxes.create(app, image, {
|
||||
...options.sandbox,
|
||||
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapts Modal exec to the Environment driver. Files intentionally has no native
|
||||
* overrides: exec latency dominates payload work (VM runtime floor measured
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { expect, test } from "bun:test"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { makeFiles } from "@opencode-ai/core/environment"
|
||||
import { Workspace } from "@opencode-ai/core/workspace"
|
||||
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { modalWorkspaceDriver, provider } from "../src/workspace/modal-workspace"
|
||||
|
||||
const enabled =
|
||||
!!process.env.OPENCODE_TEST_MODAL &&
|
||||
((!!process.env.MODAL_TOKEN_ID && !!process.env.MODAL_TOKEN_SECRET) ||
|
||||
fs.existsSync(path.join(os.homedir(), ".modal.toml")))
|
||||
|
||||
const testLayer = Layer.provideMerge(
|
||||
AppNodeBuilder.build(Workspace.configured({ idleThreshold: "1 minute", pollInterval: "1 minute" }), [
|
||||
[
|
||||
WorkspaceDriver.node,
|
||||
WorkspaceDriver.registryNode({ [provider]: modalWorkspaceDriver({ app: "opencode-workspace-tests" }) }),
|
||||
],
|
||||
]),
|
||||
TestClock.layer(),
|
||||
)
|
||||
const modalTest = enabled ? test : test.skip
|
||||
|
||||
modalTest(
|
||||
"wakes a workspace from its filesystem snapshot",
|
||||
() =>
|
||||
Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const workspace = yield* Workspace.Service
|
||||
yield* Effect.acquireUseRelease(
|
||||
workspace.create(provider),
|
||||
(created) =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* workspace.connect(created.id)
|
||||
const files = makeFiles(environment)
|
||||
const file = `/tmp/opencode-workspace-${crypto.randomUUID()}.txt`
|
||||
yield* files.write(file, new TextEncoder().encode("survived snapshot"))
|
||||
|
||||
yield* TestClock.adjust("2 minutes")
|
||||
|
||||
const restored = yield* files.read(file)
|
||||
expect(new TextDecoder().decode(restored.bytes)).toBe("survived snapshot")
|
||||
}),
|
||||
(created) => workspace.destroy(created.id).pipe(Effect.ignore),
|
||||
)
|
||||
}).pipe(Effect.scoped, Effect.provide(testLayer)),
|
||||
),
|
||||
180_000,
|
||||
)
|
||||
@@ -12,6 +12,7 @@ export function generateSyntax(theme: ResolvedThemeTokens, mode: Mode) {
|
||||
rule(["prompt"], theme.hue.accent[step]),
|
||||
rule(["extmark.file"], feedback.warning.default, { bold: true }),
|
||||
rule(["extmark.agent"], theme.categorical[0][step], { bold: true }),
|
||||
rule(["extmark.skill"], theme.categorical[1][step], { bold: true }),
|
||||
// V1 migration preserves its selected/inverse foreground in this action state.
|
||||
rule(["extmark.paste"], theme.text.action.primary.focused, {
|
||||
background: feedback.warning.default,
|
||||
|
||||
@@ -118,6 +118,7 @@ const sessionTabBindingCommands = [
|
||||
"session.tab.select.7",
|
||||
"session.tab.select.8",
|
||||
"session.tab.select.9",
|
||||
"session.tab.select.10",
|
||||
] as const
|
||||
|
||||
const pinnedSessionBindingCommands = [
|
||||
@@ -714,7 +715,7 @@ function App(props: { pair?: DialogPairCredentials }) {
|
||||
enabled: sessionTabs.enabled,
|
||||
run: () => sessionTabs.reopen(),
|
||||
},
|
||||
...Array.from({ length: 9 }, (_, i) => ({
|
||||
...Array.from({ length: 10 }, (_, i) => ({
|
||||
name: `session.tab.select.${i + 1}`,
|
||||
title: `Switch to tab ${i + 1}`,
|
||||
category: "Session",
|
||||
|
||||
@@ -19,8 +19,9 @@ import { Locale } from "../../util/locale"
|
||||
import type { PromptInfo, PromptPartRef } from "../../prompt/history"
|
||||
import { useFrecency } from "../../prompt/frecency"
|
||||
import { Keymap } from "../../context/keymap"
|
||||
import { displayCharAt, mentionTriggerIndex } from "../../prompt/display"
|
||||
import { displayCharAt, mentionTriggerIndex, slashTriggerIndex } from "../../prompt/display"
|
||||
import type { FileSystemEntry } from "@opencode-ai/client"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import { stringWidth } from "../../util/string-width"
|
||||
import { parseFileLineRange, stripFileLineRange } from "../../prompt/parse"
|
||||
import { moveSelection, revealSelectionOffset } from "../../ui/select-controller"
|
||||
@@ -39,6 +40,7 @@ export type AutocompleteOption = {
|
||||
isDirectory?: boolean
|
||||
onSelect?: () => void
|
||||
path?: string
|
||||
kind?: "skill"
|
||||
}
|
||||
|
||||
export function Autocomplete(props: {
|
||||
@@ -51,6 +53,8 @@ export function Autocomplete(props: {
|
||||
ref: (ref: AutocompleteRef) => void
|
||||
fileStyleId: number
|
||||
agentStyleId: number
|
||||
skillStyleId: number
|
||||
hasSkill: (id: string) => boolean
|
||||
promptPartTypeId: () => number
|
||||
}) {
|
||||
const editor = useEditorContext()
|
||||
@@ -140,14 +144,17 @@ export function Autocomplete(props: {
|
||||
text: string,
|
||||
part:
|
||||
| { type: "file"; value: NonNullable<PromptInfo["files"]>[number]; path?: string }
|
||||
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] },
|
||||
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] }
|
||||
| { type: "skill"; value: NonNullable<PromptInfo["skills"]>[number] },
|
||||
) {
|
||||
if (part.type === "skill" && props.hasSkill(part.value.id)) return
|
||||
const input = props.input()
|
||||
const currentCursorOffset = input.cursorOffset
|
||||
|
||||
const charAfterCursor = displayCharAt(props.value, currentCursorOffset)
|
||||
const needsSpace = charAfterCursor !== " "
|
||||
const append = "@" + text + (needsSpace ? " " : "")
|
||||
const prefix = part.type === "skill" ? "/" : "@"
|
||||
const append = prefix + text + (needsSpace ? " " : "")
|
||||
|
||||
input.cursorOffset = store.index
|
||||
const startCursor = input.logicalCursor
|
||||
@@ -157,11 +164,12 @@ export function Autocomplete(props: {
|
||||
input.deleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col)
|
||||
input.insertText(append)
|
||||
|
||||
const virtualText = "@" + text
|
||||
const virtualText = prefix + text
|
||||
const extmarkStart = store.index
|
||||
const extmarkEnd = extmarkStart + stringWidth(virtualText)
|
||||
|
||||
const styleId = part.type === "file" ? props.fileStyleId : props.agentStyleId
|
||||
const styleId =
|
||||
part.type === "file" ? props.fileStyleId : part.type === "skill" ? props.skillStyleId : props.agentStyleId
|
||||
|
||||
const extmarkId = input.extmarks.create({
|
||||
start: extmarkStart,
|
||||
@@ -195,6 +203,20 @@ export function Autocomplete(props: {
|
||||
return
|
||||
}
|
||||
|
||||
if (part.type === "skill") {
|
||||
const skills = (draft.skills ??= [])
|
||||
if (skills.some((skill) => skill.id === part.value.id)) return
|
||||
if (part.value.mention) {
|
||||
part.value.mention.start = extmarkStart
|
||||
part.value.mention.end = extmarkEnd
|
||||
part.value.mention.text = virtualText
|
||||
}
|
||||
const index = skills.length
|
||||
skills.push(part.value)
|
||||
props.setExtmark({ type: "skill", index }, extmarkId)
|
||||
return
|
||||
}
|
||||
|
||||
const agents = (draft.agents ??= [])
|
||||
if (part.value.mention) {
|
||||
part.value.mention.start = extmarkStart
|
||||
@@ -433,7 +455,12 @@ export function Autocomplete(props: {
|
||||
results.push({
|
||||
display: "/" + skill.id,
|
||||
description: skill.description,
|
||||
onSelect: () => insertSlash(skill.id),
|
||||
kind: "skill",
|
||||
onSelect: () =>
|
||||
insertPart(skill.id, {
|
||||
type: "skill",
|
||||
value: { id: Skill.ID.make(skill.id), mention: { start: 0, end: 0, text: "" } },
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -463,7 +490,11 @@ export function Autocomplete(props: {
|
||||
// it shouldn't be additionally sorted by fuzzysort as it will loose the results
|
||||
const fileOptions: AutocompleteOption[] = store.visible === "@" ? fileSearch.options : []
|
||||
const nonFileOptions: AutocompleteOption[] =
|
||||
store.visible === "@" ? [...referenceAliasesValue, ...agentsValue, ...mcpResources()] : [...commandsValue]
|
||||
store.visible === "@"
|
||||
? [...referenceAliasesValue, ...agentsValue, ...mcpResources()]
|
||||
: store.index === 0
|
||||
? [...commandsValue]
|
||||
: commandsValue.filter((item) => item.kind === "skill")
|
||||
|
||||
if (!searchValue) {
|
||||
return [...nonFileOptions, ...fileOptions]
|
||||
@@ -520,7 +551,7 @@ export function Autocomplete(props: {
|
||||
function select() {
|
||||
const selected = options()[store.selected]
|
||||
if (!selected) return
|
||||
hide()
|
||||
hide(true)
|
||||
selected.onSelect?.()
|
||||
}
|
||||
|
||||
@@ -608,14 +639,18 @@ export function Autocomplete(props: {
|
||||
})
|
||||
}
|
||||
|
||||
function hide() {
|
||||
const text = props.input().plainText
|
||||
if (store.visible === "/" && !text.endsWith(" ") && text.startsWith("/")) {
|
||||
const cursor = props.input().logicalCursor
|
||||
props.input().deleteRange(0, 0, cursor.row, cursor.col)
|
||||
function hide(removeToken = false) {
|
||||
if (removeToken && store.visible === "/") {
|
||||
const input = props.input()
|
||||
const cursorOffset = input.cursorOffset
|
||||
input.cursorOffset = store.index
|
||||
const start = input.logicalCursor
|
||||
input.cursorOffset = cursorOffset
|
||||
const end = input.logicalCursor
|
||||
input.deleteRange(start.row, start.col, end.row, end.col)
|
||||
// Sync the prompt store immediately since onContentChange is async
|
||||
props.setPrompt((draft) => {
|
||||
draft.text = props.input().plainText
|
||||
draft.text = input.plainText
|
||||
})
|
||||
}
|
||||
setStore("visible", false)
|
||||
@@ -640,9 +675,7 @@ export function Autocomplete(props: {
|
||||
// Typed text before the trigger
|
||||
props.input().cursorOffset <= store.index ||
|
||||
// There is a space between the trigger and the cursor
|
||||
props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/) ||
|
||||
// "/<command>" is not the sole content
|
||||
(store.visible === "/" && value.match(/^\S+\s+\S+\s*$/))
|
||||
props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/)
|
||||
) {
|
||||
hide()
|
||||
}
|
||||
@@ -653,10 +686,10 @@ export function Autocomplete(props: {
|
||||
const offset = props.input().cursorOffset
|
||||
if (offset === 0) return
|
||||
|
||||
// Check for "/" at position 0 - reopen slash commands
|
||||
if (value.startsWith("/") && !value.slice(0, offset).match(/\s/)) {
|
||||
const slash = slashTriggerIndex(value, offset)
|
||||
if (slash !== undefined) {
|
||||
show("/")
|
||||
setStore("index", 0)
|
||||
setStore("index", slash)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import { parseSlashHead } from "../../prompt/parse"
|
||||
import { stringWidth } from "../../util/string-width"
|
||||
import { createStore, produce, unwrap } from "solid-js/store"
|
||||
import { emptyPrompt, usePromptHistory, type PromptInfo, type PromptPartRef } from "../../prompt/history"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import { computePromptTraits } from "../../prompt/traits"
|
||||
import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part"
|
||||
import { usePromptStash } from "../../prompt/stash"
|
||||
@@ -273,6 +274,7 @@ export function Prompt(props: PromptProps) {
|
||||
}
|
||||
const fileStyleId = syntax().getStyleId("extmark.file")!
|
||||
const agentStyleId = syntax().getStyleId("extmark.agent")!
|
||||
const skillStyleId = syntax().getStyleId("extmark.skill")!
|
||||
const pasteStyleId = syntax().getStyleId("extmark.paste")!
|
||||
let promptPartTypeId = 0
|
||||
const event = useEvent()
|
||||
@@ -493,12 +495,29 @@ export function Prompt(props: PromptProps) {
|
||||
<DialogSkill
|
||||
location={currentLocation.current}
|
||||
onSelect={(skill) => {
|
||||
input.setText(`/${skill} `)
|
||||
setStore("prompt", {
|
||||
...emptyPrompt(),
|
||||
text: `/${skill} `,
|
||||
if (store.prompt.skills?.some((item) => item.id === skill)) return
|
||||
const text = `/${skill}`
|
||||
const start = input.cursorOffset
|
||||
input.insertText(text + " ")
|
||||
const extmarkId = input.extmarks.create({
|
||||
start,
|
||||
end: start + promptOffsetWidth(text),
|
||||
virtual: true,
|
||||
styleId: skillStyleId,
|
||||
typeId: promptPartTypeId,
|
||||
})
|
||||
input.gotoBufferEnd()
|
||||
setStore(
|
||||
produce((draft) => {
|
||||
draft.prompt.text = input.plainText
|
||||
const skills = (draft.prompt.skills ??= [])
|
||||
const index = skills.length
|
||||
skills.push({
|
||||
id: Skill.ID.make(skill),
|
||||
mention: { start, end: start + promptOffsetWidth(text), text },
|
||||
})
|
||||
draft.extmarkToPart.set(extmarkId, { type: "skill", index })
|
||||
}),
|
||||
)
|
||||
}}
|
||||
/>
|
||||
))
|
||||
@@ -639,6 +658,11 @@ export function Prompt(props: PromptProps) {
|
||||
ref: { type: "agent" as const, index },
|
||||
styleId: agentStyleId,
|
||||
})),
|
||||
...(prompt.skills ?? []).map((part, index) => ({
|
||||
mention: part.mention,
|
||||
ref: { type: "skill" as const, index },
|
||||
styleId: skillStyleId,
|
||||
})),
|
||||
...prompt.pasted.map((part, index) => ({
|
||||
mention: part.source,
|
||||
ref: { type: "pasted" as const, index },
|
||||
@@ -671,6 +695,7 @@ export function Prompt(props: PromptProps) {
|
||||
const newMap = new Map<number, PromptPartRef>()
|
||||
const files: NonNullable<PromptInfo["files"]> = []
|
||||
const agents: NonNullable<PromptInfo["agents"]> = []
|
||||
const skills: NonNullable<PromptInfo["skills"]> = []
|
||||
const pasted: PromptInfo["pasted"] = []
|
||||
|
||||
for (const extmark of allExtmarks) {
|
||||
@@ -696,6 +721,16 @@ export function Prompt(props: PromptProps) {
|
||||
newMap.set(extmark.id, { type: "agent", index })
|
||||
continue
|
||||
}
|
||||
if (ref.type === "skill") {
|
||||
const part = draft.prompt.skills?.[ref.index]
|
||||
if (!part?.mention) continue
|
||||
part.mention.start = extmark.start
|
||||
part.mention.end = extmark.end
|
||||
const index = skills.length
|
||||
skills.push(part)
|
||||
newMap.set(extmark.id, { type: "skill", index })
|
||||
continue
|
||||
}
|
||||
const part = draft.prompt.pasted[ref.index]
|
||||
if (!part) continue
|
||||
part.source.start = extmark.start
|
||||
@@ -708,6 +743,7 @@ export function Prompt(props: PromptProps) {
|
||||
draft.extmarkToPart = newMap
|
||||
draft.prompt.files = files
|
||||
draft.prompt.agents = agents
|
||||
draft.prompt.skills = skills
|
||||
draft.prompt.pasted = pasted
|
||||
}),
|
||||
)
|
||||
@@ -983,6 +1019,7 @@ export function Prompt(props: PromptProps) {
|
||||
)
|
||||
const slashHead = parseSlashHead(inputText, /\s/)
|
||||
const isSkill =
|
||||
!(store.prompt.skills?.length ?? 0) &&
|
||||
slashHead !== undefined &&
|
||||
(data.location.skill.list(currentLocation.ref) ?? []).some(
|
||||
(skill) => skill.slash === true && skill.id === slashHead.name,
|
||||
@@ -1080,6 +1117,7 @@ export function Prompt(props: PromptProps) {
|
||||
model,
|
||||
files: store.prompt.files,
|
||||
agents: store.prompt.agents,
|
||||
skills: store.prompt.skills?.length ? store.prompt.skills : undefined,
|
||||
delivery,
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -1146,6 +1184,7 @@ export function Prompt(props: PromptProps) {
|
||||
text: inputText,
|
||||
files: store.prompt.files,
|
||||
agents: store.prompt.agents,
|
||||
skills: store.prompt.skills?.length ? store.prompt.skills : undefined,
|
||||
delivery,
|
||||
})
|
||||
.then(
|
||||
@@ -1685,6 +1724,8 @@ export function Prompt(props: PromptProps) {
|
||||
value={store.prompt.text}
|
||||
fileStyleId={fileStyleId}
|
||||
agentStyleId={agentStyleId}
|
||||
skillStyleId={skillStyleId}
|
||||
hasSkill={(id) => store.prompt.skills?.some((skill) => skill.id === id) ?? false}
|
||||
promptPartTypeId={() => promptPartTypeId}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
moveSessionTab,
|
||||
NEW_SESSION_TAB_TITLE,
|
||||
sessionTabComplete,
|
||||
sessionTabShortcutLabel,
|
||||
seedSessionTabMotion,
|
||||
sessionTabOverflowWidth,
|
||||
type SessionTab,
|
||||
@@ -140,7 +141,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
const value = session()
|
||||
return value ? data.project.get(value.projectID) : undefined
|
||||
})
|
||||
const numberWidth = () => String(index() + 1).length + 1
|
||||
const numberWidth = () => 2
|
||||
const titleWidth = () => Math.max(1, width() - numberWidth() - 2 - (hovered() === tab.sessionID ? 1 : 0))
|
||||
const title = () => tab.title ?? "Untitled session"
|
||||
const visibleTitle = createMemo(() => Locale.takeWidth(title(), titleWidth()))
|
||||
@@ -311,7 +312,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
selectable={false}
|
||||
attributes={selected() ? TextAttributes.BOLD : undefined}
|
||||
>
|
||||
{index() + 1}
|
||||
{sessionTabShortcutLabel(index())}
|
||||
</text>
|
||||
<text
|
||||
width={titleWidth()}
|
||||
@@ -555,8 +556,8 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
const glows = () => !selected() && (status().attention || (!status().busy && status().unread !== undefined))
|
||||
const title = () => tab.title ?? "Untitled session"
|
||||
const tabNumber = createMemo(() => items().findIndex((item) => item.sessionID === tab.sessionID) + 1)
|
||||
// The number cell keeps one trailing space, even for double-digit tabs.
|
||||
const numberWidth = () => String(tabNumber()).length + 1
|
||||
// Shortcut labels stay one cell wide: 1-9, 0 for ten, then a neutral dot.
|
||||
const numberWidth = () => 2
|
||||
// Hovering reveals the close mark, so the title's right bound shifts left of it.
|
||||
const availableTitleWidth = () =>
|
||||
Math.max(1, width() - 1 - numberWidth() - (hovered() === tab.sessionID ? 2 : 0))
|
||||
@@ -639,7 +640,7 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
{" "}
|
||||
</text>
|
||||
<text width={numberWidth()} fg={numberColor()} selectable={false} attributes={bold()}>
|
||||
{tabNumber()}
|
||||
{sessionTabShortcutLabel(tabNumber() - 1)}
|
||||
</text>
|
||||
<text
|
||||
width={availableTitleWidth()}
|
||||
|
||||
@@ -126,6 +126,7 @@ export const Definitions = {
|
||||
session_tab_select_7: keybind("<leader>7,ctrl+7", "Switch to tab 7"),
|
||||
session_tab_select_8: keybind("<leader>8,ctrl+8", "Switch to tab 8"),
|
||||
session_tab_select_9: keybind("<leader>9,ctrl+9", "Switch to tab 9"),
|
||||
session_tab_select_10: keybind("<leader>0,ctrl+0", "Switch to tab 10"),
|
||||
|
||||
stash_delete: keybind("ctrl+d", "Delete stash entry"),
|
||||
model_provider_list: keybind("ctrl+a", "Open provider list from model dialog"),
|
||||
@@ -329,6 +330,7 @@ export const CommandMap = {
|
||||
session_tab_select_7: "session.tab.select.7",
|
||||
session_tab_select_8: "session.tab.select.8",
|
||||
session_tab_select_9: "session.tab.select.9",
|
||||
session_tab_select_10: "session.tab.select.10",
|
||||
stash_delete: "stash.delete",
|
||||
model_provider_list: "model.dialog.provider",
|
||||
model_favorite_toggle: "model.dialog.favorite",
|
||||
|
||||
@@ -7,6 +7,12 @@ export type SessionTabUnread = "activity" | "error"
|
||||
|
||||
export const NEW_SESSION_TAB_TITLE = "New session"
|
||||
|
||||
export function sessionTabShortcutLabel(index: number) {
|
||||
if (index >= 0 && index < 9) return String(index + 1)
|
||||
if (index === 9) return "0"
|
||||
return "·"
|
||||
}
|
||||
|
||||
export type SessionTabHistory = {
|
||||
entries: readonly string[]
|
||||
index: number
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
isExitCommand,
|
||||
isCompactCommand,
|
||||
mentionTriggerIndex,
|
||||
slashTriggerIndex,
|
||||
isNewCommand,
|
||||
movePromptHistory,
|
||||
promptCopy,
|
||||
@@ -50,7 +51,7 @@ export const TEXTAREA_MIN_ROWS = 1
|
||||
const TEXTAREA_MAX_ROWS = 6
|
||||
export const PROMPT_MAX_ROWS = TEXTAREA_MAX_ROWS + AUTOCOMPLETE_ROWS - 1 + AUTOCOMPLETE_BOTTOM_ROWS
|
||||
|
||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" | "skill" }>
|
||||
|
||||
type Auto = RunFooterMenuItem & {
|
||||
kind: "mention"
|
||||
@@ -65,7 +66,12 @@ type SlashOption = RunFooterMenuItem & {
|
||||
action?: "skill-menu" | "editor" | "settings"
|
||||
}
|
||||
|
||||
type PromptOption = Auto | SlashOption
|
||||
type SkillOption = RunFooterMenuItem & {
|
||||
kind: "skill"
|
||||
id: string
|
||||
}
|
||||
|
||||
type PromptOption = Auto | SlashOption | SkillOption
|
||||
|
||||
type MenuMode = false | "mention" | "slash"
|
||||
|
||||
@@ -124,12 +130,9 @@ function emptyPrompt(shell: boolean): RunPrompt {
|
||||
}
|
||||
|
||||
function slashQuery(text: string, cursor: number) {
|
||||
const head = parseSlashHead(text.slice(0, cursor))
|
||||
if (!head || head.end !== cursor) {
|
||||
return
|
||||
}
|
||||
|
||||
return head.name
|
||||
const at = slashTriggerIndex(text, cursor)
|
||||
if (at === undefined) return
|
||||
return { at, value: displaySlice(text, at + 1, cursor) }
|
||||
}
|
||||
|
||||
function parseSlashCommand(text: string, commands: RunCommand[] | undefined) {
|
||||
@@ -382,10 +385,18 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
)
|
||||
const mentionOptions = createMemo(() => [...agents(), ...files(), ...references()])
|
||||
const skillCommands = createMemo(() => (input.commands() ?? []).filter((item) => item.source === "skill"))
|
||||
const skillOptions = createMemo<SkillOption[]>(() =>
|
||||
skillCommands().map((item) => ({
|
||||
kind: "skill",
|
||||
id: item.name,
|
||||
display: `/${item.name}`,
|
||||
description: item.description,
|
||||
})),
|
||||
)
|
||||
const hasSkillsCommand = createMemo(() =>
|
||||
(input.commands() ?? []).some((item) => item.source !== "skill" && item.name === "skills"),
|
||||
)
|
||||
const slashOptions = createMemo<SlashOption[]>(() => {
|
||||
const slashOptions = createMemo<Array<SlashOption | SkillOption>>(() => {
|
||||
const builtins = [
|
||||
{
|
||||
kind: "slash",
|
||||
@@ -417,6 +428,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
}
|
||||
|
||||
return [
|
||||
...skillOptions(),
|
||||
...(showSkillMenu
|
||||
? [
|
||||
{
|
||||
@@ -443,7 +455,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
].sort((a, b) => a.display.localeCompare(b.display))
|
||||
})
|
||||
const options = createMemo<PromptOption[]>(() => {
|
||||
const mixed: PromptOption[] = mode() === "slash" ? slashOptions() : mentionOptions()
|
||||
const mixed: PromptOption[] = mode() === "slash" ? (at() === 0 ? slashOptions() : skillOptions()) : mentionOptions()
|
||||
if (!query()) {
|
||||
return mixed
|
||||
}
|
||||
@@ -459,7 +471,11 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
|
||||
return fuzzysort
|
||||
.go(next, mixed, {
|
||||
keys: [(item) => (item.kind === "mention" ? item.value : item.name).trimEnd(), "display", "description"],
|
||||
keys: [
|
||||
(item) => (item.kind === "mention" ? item.value : item.kind === "skill" ? item.id : item.name).trimEnd(),
|
||||
"display",
|
||||
"description",
|
||||
],
|
||||
})
|
||||
.map((item) => item.obj)
|
||||
})
|
||||
@@ -512,17 +528,19 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
continue
|
||||
}
|
||||
|
||||
const text = area.plainText.slice(item.start, item.end)
|
||||
const text = displaySlice(area.plainText, item.start, item.end)
|
||||
const prev =
|
||||
part.type === "agent"
|
||||
? (part.source?.value ?? "@" + part.name)
|
||||
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
|
||||
: part.type === "skill"
|
||||
? (part.source?.value ?? "/" + part.id)
|
||||
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
|
||||
if (text !== prev) {
|
||||
continue
|
||||
}
|
||||
|
||||
const copy = structuredClone(part)
|
||||
if (copy.type === "agent") {
|
||||
if (copy.type === "agent" || copy.type === "skill") {
|
||||
copy.source = {
|
||||
start: item.start,
|
||||
end: item.end,
|
||||
@@ -558,7 +576,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
const restoreParts = (value: RunPromptPart[]) => {
|
||||
clearParts()
|
||||
parts = value
|
||||
.filter((item): item is Mention => item.type === "file" || item.type === "agent")
|
||||
.filter((item): item is Mention => item.type === "file" || item.type === "agent" || item.type === "skill")
|
||||
.map((item) => structuredClone(item))
|
||||
if (!area || area.isDestroyed || type === 0) {
|
||||
return
|
||||
@@ -566,8 +584,8 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
|
||||
const box = area
|
||||
parts.forEach((item, idx) => {
|
||||
const start = item.type === "agent" ? item.source?.start : item.source?.text.start
|
||||
const end = item.type === "agent" ? item.source?.end : item.source?.text.end
|
||||
const start = item.type === "file" ? item.source?.text.start : item.source?.start
|
||||
const end = item.type === "file" ? item.source?.text.end : item.source?.end
|
||||
if (start === undefined || end === undefined) {
|
||||
return
|
||||
}
|
||||
@@ -627,16 +645,16 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
return
|
||||
}
|
||||
|
||||
setAt(0)
|
||||
setQuery(slash)
|
||||
setAt(slash.at)
|
||||
setQuery(slash.value)
|
||||
return
|
||||
}
|
||||
|
||||
if (slash !== undefined) {
|
||||
setAt(0)
|
||||
setAt(slash.at)
|
||||
menu.reset()
|
||||
setMode("slash")
|
||||
setQuery(slash)
|
||||
setQuery(slash.value)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -782,7 +800,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
}
|
||||
|
||||
const cursor = area.cursorOffset
|
||||
const startOffset = mode() === "slash" ? 0 : at()
|
||||
const startOffset = at()
|
||||
area.cursorOffset = startOffset
|
||||
const start = area.logicalCursor
|
||||
area.cursorOffset = cursor
|
||||
@@ -828,6 +846,39 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
return
|
||||
}
|
||||
|
||||
if (next.kind === "skill") {
|
||||
if (parts.some((part) => part.type === "skill" && part.id === next.id)) {
|
||||
cancelAutocomplete()
|
||||
return
|
||||
}
|
||||
const cursor = area.cursorOffset
|
||||
const tail = displayCharAt(area.plainText, cursor)
|
||||
const append = `/${next.id}${tail === " " ? "" : " "}`
|
||||
area.cursorOffset = at()
|
||||
const start = area.logicalCursor
|
||||
area.cursorOffset = cursor
|
||||
const end = area.logicalCursor
|
||||
area.deleteRange(start.row, start.col, end.row, end.col)
|
||||
area.insertText(append)
|
||||
|
||||
const text = `/${next.id}`
|
||||
const startOffset = at()
|
||||
const endOffset = startOffset + stringWidth(text)
|
||||
const part: Extract<RunPromptPart, { type: "skill" }> = {
|
||||
type: "skill",
|
||||
id: next.id,
|
||||
source: { start: startOffset, end: endOffset, value: text },
|
||||
}
|
||||
const id = area.extmarks.create({ start: startOffset, end: endOffset, virtual: true, typeId: type })
|
||||
marks.set(id, parts.length)
|
||||
parts.push(part)
|
||||
hide()
|
||||
syncDraft()
|
||||
scheduleRows()
|
||||
area.focus()
|
||||
return
|
||||
}
|
||||
|
||||
if (next.kind === "slash") {
|
||||
if (next.action === "editor") {
|
||||
void openEditor({
|
||||
@@ -1193,7 +1244,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
}
|
||||
|
||||
const parsed =
|
||||
command || next.mode === "shell" || isNewCommand(next.text)
|
||||
command || next.parts.some((part) => part.type === "skill") || next.mode === "shell" || isNewCommand(next.text)
|
||||
? undefined
|
||||
: parseSlashCommand(next.text, input.commands())
|
||||
if (parsed?.type === "pending") {
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { RunPromptPart } from "./types"
|
||||
import { realignPromptMentions } from "../prompt/mention"
|
||||
import { parseSlashHead } from "../prompt/parse"
|
||||
|
||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" | "skill" }>
|
||||
|
||||
export function resolveEditorSlashValue(text: string) {
|
||||
const head = parseSlashHead(text)
|
||||
@@ -17,13 +17,13 @@ export function realignEditorPromptParts(content: string, parts: RunPromptPart[]
|
||||
const matches = realignPromptMentions(
|
||||
content,
|
||||
parts.map((part) => {
|
||||
if (part.type !== "file" && part.type !== "agent") return
|
||||
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return
|
||||
return promptPartMention(part)
|
||||
}),
|
||||
)
|
||||
|
||||
return parts.flatMap((part, index) => {
|
||||
if (part.type !== "file" && part.type !== "agent") return [part]
|
||||
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return [part]
|
||||
const mention = promptPartMention(part)
|
||||
if (!mention?.text) return [part]
|
||||
const match = matches[index]
|
||||
@@ -32,13 +32,13 @@ export function realignEditorPromptParts(content: string, parts: RunPromptPart[]
|
||||
}
|
||||
|
||||
function promptPartMention(part: Mention) {
|
||||
const source = part.type === "agent" ? part.source : part.source?.text
|
||||
const source = part.type === "file" ? part.source?.text : part.source
|
||||
if (!source) return
|
||||
return { start: source.start, end: source.end, text: source.value }
|
||||
}
|
||||
|
||||
function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention {
|
||||
if (part.type === "agent") {
|
||||
if (part.type === "agent" || part.type === "skill") {
|
||||
return {
|
||||
...part,
|
||||
source: {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// the current browse position. When the user arrows up at cursor offset 0,
|
||||
// the current draft is saved and history begins. Arrowing past the end
|
||||
// restores the draft.
|
||||
export { displayCharAt, displaySlice, mentionTriggerIndex } from "../prompt/display"
|
||||
export { displayCharAt, displaySlice, mentionTriggerIndex, slashTriggerIndex } from "../prompt/display"
|
||||
import { stringWidth } from "../util/string-width"
|
||||
import type { RunPrompt } from "./types"
|
||||
|
||||
|
||||
@@ -288,6 +288,21 @@ function promptAgents(next: SessionTurnInput) {
|
||||
)
|
||||
}
|
||||
|
||||
function promptSkills(next: SessionTurnInput) {
|
||||
return next.prompt.parts.flatMap((part) =>
|
||||
part.type === "skill"
|
||||
? [
|
||||
{
|
||||
id: part.id,
|
||||
mention: part.source
|
||||
? { start: part.source.start, end: part.source.end, text: part.source.value }
|
||||
: undefined,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
function streamPartKey(messageID: string, partID: string) {
|
||||
return `${messageID}\u0000${partID}`
|
||||
}
|
||||
@@ -358,12 +373,12 @@ const catalogEvents = new Set([
|
||||
// briefly so the output commit renders inside it.
|
||||
const SHELL_OUTPUT_GRACE_MS = 1500
|
||||
|
||||
function skillCommit(messageID: string, name: string): StreamCommit {
|
||||
function skillCommit(messageID: string, name: string, skillID = messageID): StreamCommit {
|
||||
return {
|
||||
kind: "system",
|
||||
source: "system",
|
||||
messageID,
|
||||
partID: `skill:${messageID}`,
|
||||
partID: `skill:${skillID}`,
|
||||
text: `→ Skill "${name}"`,
|
||||
phase: "start",
|
||||
}
|
||||
@@ -637,7 +652,10 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
||||
state.messageIDs.add(message.id)
|
||||
if (!render) return
|
||||
if (reuseVisibleWait && waiting) return
|
||||
write([{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id }])
|
||||
write([
|
||||
...(message.skills ?? []).map((skill) => skillCommit(message.id, skill.name, skill.id)),
|
||||
{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id },
|
||||
])
|
||||
return
|
||||
}
|
||||
if (message.type === "skill") {
|
||||
@@ -1615,6 +1633,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
||||
const command = next.prompt.command
|
||||
const attachments = await prepareAttachments(next, command ? "command" : "prompt", input.readTextFile)
|
||||
const agents = promptAgents(next)
|
||||
const skills = promptSkills(next)
|
||||
if (!command) {
|
||||
input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID, delivery })
|
||||
return client.session.prompt(
|
||||
@@ -1624,6 +1643,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
||||
text: [next.prompt.text, ...attachments.text].join("\n\n"),
|
||||
files: attachments.files.length ? attachments.files : undefined,
|
||||
agents: agents.length ? agents : undefined,
|
||||
skills: skills.length ? skills : undefined,
|
||||
delivery,
|
||||
},
|
||||
{ signal: next.signal },
|
||||
@@ -1643,6 +1663,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
||||
model: selected,
|
||||
files: attachments.files.length ? attachments.files : undefined,
|
||||
agents: agents.length ? agents : undefined,
|
||||
skills: skills.length ? skills : undefined,
|
||||
delivery,
|
||||
},
|
||||
{ signal: next.signal },
|
||||
|
||||
@@ -47,6 +47,7 @@ export type RunPromptPart =
|
||||
}
|
||||
}
|
||||
| { type: "agent"; name: string; source?: { start: number; end: number; value: string } }
|
||||
| { type: "skill"; id: string; source?: { start: number; end: number; value: string } }
|
||||
|
||||
export type RunCommand = {
|
||||
name: string
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { Prompt, PromptInput } from "@opencode-ai/schema"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import type { Types } from "effect"
|
||||
|
||||
export type EditablePromptInput = Types.DeepMutable<PromptInput.Prompt>
|
||||
|
||||
export function projectedPromptInput(input: Pick<Prompt, "text" | "files" | "agents">): EditablePromptInput {
|
||||
type ProjectedPrompt = Pick<Prompt, "text" | "files" | "agents"> & {
|
||||
readonly skills?: ReadonlyArray<{ readonly id: string; readonly mention?: PromptInput.SkillAttachment["mention"] }>
|
||||
}
|
||||
|
||||
export function projectedPromptInput(input: ProjectedPrompt): EditablePromptInput {
|
||||
return {
|
||||
text: input.text,
|
||||
files: input.files?.map((file) => ({
|
||||
@@ -16,5 +21,9 @@ export function projectedPromptInput(input: Pick<Prompt, "text" | "files" | "age
|
||||
name: agent.name,
|
||||
mention: agent.mention ? { ...agent.mention } : undefined,
|
||||
})),
|
||||
skills: input.skills?.map((skill) => ({
|
||||
id: Skill.ID.make(skill.id),
|
||||
mention: skill.mention ? { ...skill.mention } : undefined,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,3 +48,14 @@ export function mentionTriggerIndex(value: string, offset = promptOffsetWidth(va
|
||||
return promptOffsetWidth(text.slice(0, index))
|
||||
}
|
||||
}
|
||||
|
||||
export function slashTriggerIndex(value: string, offset = promptOffsetWidth(value)) {
|
||||
const text = displaySlice(value, 0, offset)
|
||||
for (let index = text.lastIndexOf("/"); index >= 0; index = text.lastIndexOf("/", index - 1)) {
|
||||
const before = index === 0 ? undefined : text[index - 1]
|
||||
const query = text.slice(index)
|
||||
if (before !== undefined && !/\s/.test(before)) continue
|
||||
if (/\s/.test(query) || query.slice(1).includes("/")) return
|
||||
return promptOffsetWidth(text.slice(0, index))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from "path"
|
||||
import { onMount } from "solid-js"
|
||||
import { createStore, produce, unwrap } from "solid-js/store"
|
||||
import type { SessionPromptInput } from "@opencode-ai/client"
|
||||
import type { PromptInput } from "@opencode-ai/schema"
|
||||
import type { Types } from "effect"
|
||||
import { createSimpleContext } from "../context/helper"
|
||||
import { useTuiPaths } from "../context/runtime"
|
||||
@@ -16,17 +16,17 @@ export type PastedText = {
|
||||
}
|
||||
}
|
||||
|
||||
export type PromptInfo = Types.DeepMutable<Pick<SessionPromptInput, "text" | "files" | "agents">> & {
|
||||
export type PromptInfo = Types.DeepMutable<Pick<PromptInput.Prompt, "text" | "files" | "agents" | "skills">> & {
|
||||
pasted: PastedText[]
|
||||
mode?: "normal" | "shell"
|
||||
}
|
||||
|
||||
export type PromptPartRef = {
|
||||
type: "file" | "agent" | "pasted"
|
||||
type: "file" | "agent" | "skill" | "pasted"
|
||||
index: number
|
||||
}
|
||||
|
||||
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], pasted: [] })
|
||||
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], skills: [], pasted: [] })
|
||||
|
||||
export const MAX_HISTORY_ENTRIES = 50
|
||||
|
||||
|
||||
@@ -52,9 +52,11 @@ export function realignPromptMentions(
|
||||
export function realignPromptInputMentions(content: string, input: PromptInput.Prompt): EditablePromptInput {
|
||||
const files = input.files ?? []
|
||||
const agents = input.agents ?? []
|
||||
const skills = input.skills ?? []
|
||||
const mentions = realignPromptMentions(content, [
|
||||
...files.map((file) => file.mention),
|
||||
...agents.map((agent) => agent.mention),
|
||||
...skills.map((skill) => skill.mention),
|
||||
])
|
||||
const align = <T extends { mention?: PromptMention }>(items: readonly T[] | undefined, offset = 0) =>
|
||||
items?.flatMap((item, index) => {
|
||||
@@ -67,6 +69,7 @@ export function realignPromptInputMentions(content: string, input: PromptInput.P
|
||||
text: content,
|
||||
files: align(input.files),
|
||||
agents: align(input.agents, files.length),
|
||||
skills: align(input.skills, files.length + agents.length),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +92,7 @@ export function expandPromptInputPastedText(
|
||||
text: expandTrackedPastedText(input.text, ranges),
|
||||
files: input.files?.map((file) => ({ ...file, mention: shift(file.mention) })),
|
||||
agents: input.agents?.map((agent) => ({ ...agent, mention: shift(agent.mention) })),
|
||||
skills: input.skills?.map((skill) => ({ ...skill, mention: shift(skill.mention) })),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1893,6 +1893,7 @@ function UserMessage(props: { message: SessionMessageUser }) {
|
||||
const data = useData()
|
||||
const local = useLocal()
|
||||
const files = createMemo(() => props.message.files ?? [])
|
||||
const skills = createMemo(() => props.message.skills ?? [])
|
||||
const themes = useThemes()
|
||||
const theme = useTheme("elevated")
|
||||
const mode = themes.mode
|
||||
@@ -1908,7 +1909,7 @@ function UserMessage(props: { message: SessionMessageUser }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Show when={props.message.text.trim() || files().length}>
|
||||
<Show when={props.message.text.trim() || files().length || skills().length}>
|
||||
<box
|
||||
border={["left"]}
|
||||
borderColor={delivery() ? theme.border.default : color()}
|
||||
@@ -1953,6 +1954,28 @@ function UserMessage(props: { message: SessionMessageUser }) {
|
||||
flexShrink={0}
|
||||
>
|
||||
<text fg={theme.text.default}>{props.message.text}</text>
|
||||
<Show when={skills().length}>
|
||||
<box flexDirection="row" paddingTop={1} gap={1} flexWrap="wrap">
|
||||
<For each={skills()}>
|
||||
{(skill) => (
|
||||
<text fg={theme.text.default}>
|
||||
<span
|
||||
style={{
|
||||
bg: theme.hue.accent[mode() === "light" ? 700 : 200],
|
||||
fg: theme.background.default,
|
||||
bold: true,
|
||||
}}
|
||||
>
|
||||
{" skill "}
|
||||
</span>
|
||||
<span style={{ bg: theme.raise(theme.background.default), fg: theme.text.subdued }}>
|
||||
{` ${skill.name} `}
|
||||
</span>
|
||||
</text>
|
||||
)}
|
||||
</For>
|
||||
</box>
|
||||
</Show>
|
||||
<Show when={files().length}>
|
||||
<box flexDirection="row" paddingTop={1} gap={1} flexWrap="wrap">
|
||||
<For each={files()}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, mock, test } from "bun:test"
|
||||
import { expect, test } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { Effect, FileSystem } from "effect"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
@@ -7,8 +7,6 @@ import { createEventStream, createFetch, directory, json } from "./fixture/tui-c
|
||||
|
||||
test("SIGHUP clears title and disposes scoped resources once", async () => {
|
||||
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
|
||||
const core = await import("@opentui/core")
|
||||
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
|
||||
const titles: string[] = []
|
||||
let started!: () => void
|
||||
const ready = new Promise<void>((resolve) => {
|
||||
@@ -32,6 +30,7 @@ test("SIGHUP clears title and disposes scoped resources once", async () => {
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: { get: async () => ({}), update: async () => ({}) },
|
||||
packages: { resolve: async () => undefined },
|
||||
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
|
||||
args: {},
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
|
||||
@@ -46,14 +45,11 @@ test("SIGHUP clears title and disposes scoped resources once", async () => {
|
||||
} finally {
|
||||
if (!setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
await server.stop()
|
||||
mock.restore()
|
||||
}
|
||||
})
|
||||
|
||||
test("session lifecycle updates the terminal title and prints the epilogue after cleanup", async () => {
|
||||
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
|
||||
const core = await import("@opentui/core")
|
||||
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
|
||||
let initialTitle!: () => void
|
||||
const initialTitleSet = new Promise<void>((resolve) => {
|
||||
initialTitle = resolve
|
||||
@@ -110,6 +106,7 @@ test("session lifecycle updates the terminal title and prints the epilogue after
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: { get: async () => ({}), update: async () => ({}) },
|
||||
packages: { resolve: async () => undefined },
|
||||
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
|
||||
args: { sessionID: "dummy" },
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
|
||||
@@ -134,14 +131,11 @@ test("session lifecycle updates the terminal title and prints the epilogue after
|
||||
process.stdout.write = originalWrite
|
||||
if (!setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
await server.stop()
|
||||
mock.restore()
|
||||
}
|
||||
})
|
||||
|
||||
test("session title generated while an untitled session is loading remains visible", async () => {
|
||||
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
|
||||
const core = await import("@opentui/core")
|
||||
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
|
||||
const titles: string[] = []
|
||||
const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer)
|
||||
const generatedTitle = Promise.withResolvers<void>()
|
||||
@@ -186,6 +180,7 @@ test("session title generated while an untitled session is loading remains visib
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: { get: async () => ({}), update: async () => ({}) },
|
||||
packages: { resolve: async () => undefined },
|
||||
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
|
||||
args: { sessionID: "dummy" },
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
|
||||
@@ -222,14 +217,11 @@ test("session title generated while an untitled session is loading remains visib
|
||||
} finally {
|
||||
if (!setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
await server.stop()
|
||||
mock.restore()
|
||||
}
|
||||
})
|
||||
|
||||
test("session startup prompt is submitted exactly once", async () => {
|
||||
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
|
||||
const core = await import("@opentui/core")
|
||||
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
|
||||
const events = createEventStream()
|
||||
const cwd = process.cwd()
|
||||
const location = { directory: cwd, project: { id: "project", directory: cwd } }
|
||||
@@ -279,6 +271,7 @@ test("session startup prompt is submitted exactly once", async () => {
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: { get: async () => ({}), update: async () => ({}) },
|
||||
packages: { resolve: async () => undefined },
|
||||
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
|
||||
args: { sessionID: "dummy", prompt: "RESUME_READY" },
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
|
||||
@@ -299,6 +292,5 @@ test("session startup prompt is submitted exactly once", async () => {
|
||||
} finally {
|
||||
if (!setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
await server.stop()
|
||||
mock.restore()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -86,6 +86,7 @@ test.each([
|
||||
let themes: ReturnType<typeof useThemes> | undefined
|
||||
let failure: ThemeError | undefined
|
||||
let unsubscribe: (() => void) | undefined
|
||||
const discovery = Promise.withResolvers<Record<string, unknown>>()
|
||||
|
||||
function Probe() {
|
||||
const value = useThemes()
|
||||
@@ -97,7 +98,7 @@ test.each([
|
||||
const app = await testRender(
|
||||
() => (
|
||||
<ConfigProvider config={createTuiResolvedConfig({ theme: { name: "invalid" } })}>
|
||||
<ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({ invalid: source }) }}>
|
||||
<ThemeProvider mode="dark" source={{ discover: () => discovery.promise }}>
|
||||
<Probe />
|
||||
</ThemeProvider>
|
||||
</ConfigProvider>
|
||||
@@ -105,6 +106,7 @@ test.each([
|
||||
{ width: 20, height: 2 },
|
||||
)
|
||||
app.renderer.start()
|
||||
discovery.resolve({ invalid: source })
|
||||
|
||||
try {
|
||||
await wait(() => themes?.ready === true)
|
||||
|
||||
@@ -131,6 +131,7 @@ test("preserves pinned session bindings alongside tab bindings", () => {
|
||||
expect(config.keybinds.get("session.pin.toggle")).toMatchObject([{ key: "ctrl+f" }])
|
||||
expect(config.keybinds.get("session.quick_switch.1")).toMatchObject([{ key: "<leader>1" }])
|
||||
expect(config.keybinds.get("session.tab.select.1")).toMatchObject([{ key: "<leader>1,ctrl+1" }])
|
||||
expect(config.keybinds.get("session.tab.select.10")).toMatchObject([{ key: "<leader>0,ctrl+0" }])
|
||||
})
|
||||
|
||||
test("disables suspend and assigns ctrl+z to undo when unsupported", () => {
|
||||
|
||||
@@ -12,9 +12,27 @@ import {
|
||||
seedSessionTabMotion,
|
||||
sessionTabComplete,
|
||||
sessionTabOverflowWidth,
|
||||
sessionTabShortcutLabel,
|
||||
} from "../../src/context/session-tabs-model"
|
||||
|
||||
describe("session tabs", () => {
|
||||
test("labels direct shortcut tabs and marks unbound tabs with a dot", () => {
|
||||
expect(Array.from({ length: 12 }, (_, index) => sessionTabShortcutLabel(index))).toEqual([
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
"6",
|
||||
"7",
|
||||
"8",
|
||||
"9",
|
||||
"0",
|
||||
"·",
|
||||
"·",
|
||||
])
|
||||
})
|
||||
|
||||
test("moves a tab to a clamped index and returns the same tabs for no-ops", () => {
|
||||
const tabs = ["a", "b", "c"].map((sessionID) => ({ sessionID }))
|
||||
expect(moveSessionTab(tabs, "a", 2).map((tab) => tab.sessionID)).toEqual(["b", "c", "a"])
|
||||
|
||||
@@ -1262,6 +1262,75 @@ test("direct footer tags skill slash submissions with their catalog source", asy
|
||||
}
|
||||
})
|
||||
|
||||
test("direct footer submits a selected leading skill as a prompt attachment", async () => {
|
||||
const submits: RunPrompt[] = []
|
||||
const app = await renderFooter({
|
||||
commands: [command({ name: "formatter", description: "Apply formatter fixes", source: "skill" })],
|
||||
onSubmit(prompt) {
|
||||
submits.push(prompt)
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
await app.renderOnce()
|
||||
"/forma".split("").forEach((key) => app.mockInput.pressKey(key))
|
||||
await app.renderOnce()
|
||||
app.mockInput.pressEnter()
|
||||
await app.renderOnce()
|
||||
"src".split("").forEach((key) => app.mockInput.pressKey(key))
|
||||
app.mockInput.pressEnter()
|
||||
await app.renderOnce()
|
||||
|
||||
expect(submits).toEqual([
|
||||
{
|
||||
text: "/formatter src",
|
||||
parts: [
|
||||
{
|
||||
type: "skill",
|
||||
id: "formatter",
|
||||
source: { start: 0, end: 10, value: "/formatter" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
},
|
||||
])
|
||||
} finally {
|
||||
app.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test("direct footer preserves a selected skill after wide text", async () => {
|
||||
const submits: RunPrompt[] = []
|
||||
const app = await renderFooter({
|
||||
commands: [command({ name: "formatter", description: "Apply formatter fixes", source: "skill" })],
|
||||
onSubmit(prompt) {
|
||||
submits.push(prompt)
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
await app.renderOnce()
|
||||
"中 /forma".split("").forEach((key) => app.mockInput.pressKey(key))
|
||||
await app.renderOnce()
|
||||
app.mockInput.pressEnter()
|
||||
await app.renderOnce()
|
||||
app.mockInput.pressEnter()
|
||||
await app.renderOnce()
|
||||
|
||||
expect(submits[0]?.parts).toEqual([
|
||||
{
|
||||
type: "skill",
|
||||
id: "formatter",
|
||||
source: { start: 3, end: 13, value: "/formatter" },
|
||||
},
|
||||
])
|
||||
} finally {
|
||||
app.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
// OpenTUI currently segfaults Bun while tearing down this composer-to-skill-panel transition.
|
||||
// Re-enable after the upstream renderer teardown fix lands.
|
||||
test.skip("direct footer skill picker inserts an editable bound skill command", async () => {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user