mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-08 10:09:52 -04:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f4241c49b4 |
@@ -1,4 +1,4 @@
|
||||
import { Cause, Context, Effect, Layer, Option, Schema } from "effect"
|
||||
import { Cause, Context, Effect, Layer } from "effect"
|
||||
import {
|
||||
FetchHttpClient,
|
||||
Headers,
|
||||
@@ -198,20 +198,8 @@ const responseBody = (body: string | void, request: HttpClientRequest.HttpClient
|
||||
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true }
|
||||
}
|
||||
|
||||
const decodeProviderBody = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
message: Schema.optionalKey(Schema.String),
|
||||
error: Schema.optionalKey(Schema.Struct({ message: Schema.optionalKey(Schema.String) })),
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
const providerMessage = (status: number, body: { readonly body?: string }) => {
|
||||
if (body.body && body.body.length <= 500) {
|
||||
const decoded = Option.getOrUndefined(decodeProviderBody(body.body))
|
||||
return `Provider request failed with HTTP ${status}: ${decoded?.error?.message ?? decoded?.message ?? body.body}`
|
||||
}
|
||||
if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`
|
||||
return `Provider request failed with HTTP ${status}`
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,6 @@ 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
|
||||
@@ -197,7 +196,6 @@ 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,7 +412,6 @@ 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"],
|
||||
@@ -435,7 +434,6 @@ 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,7 +615,6 @@ 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"],
|
||||
@@ -639,7 +638,6 @@ export function make(options: ClientOptions) {
|
||||
model: input["model"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
delivery: input["delivery"],
|
||||
resume: input["resume"],
|
||||
},
|
||||
|
||||
@@ -1080,8 +1080,6 @@ 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 = {
|
||||
@@ -1567,7 +1565,6 @@ export type SessionMessageUser = {
|
||||
text: string
|
||||
files?: Array<PromptFileAttachment>
|
||||
agents?: Array<PromptAgentAttachment>
|
||||
skills?: Array<PromptSkillAttachment>
|
||||
type: "user"
|
||||
}
|
||||
|
||||
@@ -1575,7 +1572,6 @@ export type SessionPendingUserData = {
|
||||
text: string
|
||||
files?: Array<PromptFileAttachment>
|
||||
agents?: Array<PromptAgentAttachment>
|
||||
skills?: Array<PromptSkillAttachment>
|
||||
metadata?: { [x: string]: JsonValue }
|
||||
}
|
||||
|
||||
@@ -1583,7 +1579,6 @@ export type SessionPendingUserData1 = {
|
||||
text: string
|
||||
files?: Array<PromptFileAttachment>
|
||||
agents?: Array<PromptAgentAttachment>
|
||||
skills?: Array<PromptSkillAttachment>
|
||||
metadata?: { [x: string]: any }
|
||||
}
|
||||
|
||||
@@ -2584,12 +2579,6 @@ 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"
|
||||
}
|
||||
| {
|
||||
@@ -2835,12 +2824,6 @@ 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"
|
||||
}
|
||||
| {
|
||||
@@ -3086,12 +3069,6 @@ 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"
|
||||
}
|
||||
| {
|
||||
@@ -3343,10 +3320,6 @@ 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
|
||||
@@ -3364,10 +3337,6 @@ 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
|
||||
@@ -3385,10 +3354,6 @@ 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
|
||||
@@ -3406,35 +3371,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
|
||||
}["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
|
||||
@@ -3448,10 +3388,6 @@ 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
|
||||
@@ -3469,10 +3405,6 @@ 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
|
||||
@@ -3490,10 +3422,6 @@ 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
|
||||
@@ -3520,10 +3448,6 @@ 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"]
|
||||
@@ -3543,10 +3467,6 @@ 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"]
|
||||
@@ -3566,10 +3486,6 @@ 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"]
|
||||
@@ -3589,10 +3505,6 @@ 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"]
|
||||
@@ -3612,10 +3524,6 @@ 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"]
|
||||
@@ -3635,10 +3543,6 @@ 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"]
|
||||
@@ -3658,36 +3562,9 @@ 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
|
||||
@@ -3704,10 +3581,6 @@ 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"]
|
||||
@@ -3727,10 +3600,6 @@ 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"]
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
export * as Account from "./account"
|
||||
|
||||
import { Schema } from "effect"
|
||||
import type { HttpClientError } from "effect/unstable/http"
|
||||
|
||||
export const ID = Schema.String.pipe(Schema.brand("AccountID"))
|
||||
export type ID = Schema.Schema.Type<typeof ID>
|
||||
|
||||
export const OrgID = Schema.String.pipe(Schema.brand("OrgID"))
|
||||
export type OrgID = Schema.Schema.Type<typeof OrgID>
|
||||
|
||||
export const AccessToken = Schema.String.pipe(Schema.brand("AccessToken"))
|
||||
export type AccessToken = Schema.Schema.Type<typeof AccessToken>
|
||||
|
||||
export const RefreshToken = Schema.String.pipe(Schema.brand("RefreshToken"))
|
||||
export type RefreshToken = Schema.Schema.Type<typeof RefreshToken>
|
||||
|
||||
export const DeviceCode = Schema.String.pipe(Schema.brand("DeviceCode"))
|
||||
export type DeviceCode = Schema.Schema.Type<typeof DeviceCode>
|
||||
|
||||
export const UserCode = Schema.String.pipe(Schema.brand("UserCode"))
|
||||
export type UserCode = Schema.Schema.Type<typeof UserCode>
|
||||
|
||||
export class Info extends Schema.Class<Info>("Account")({
|
||||
id: ID,
|
||||
email: Schema.String,
|
||||
url: Schema.String,
|
||||
active_org_id: Schema.NullOr(OrgID),
|
||||
}) {}
|
||||
|
||||
export class Org extends Schema.Class<Org>("Org")({
|
||||
id: OrgID,
|
||||
name: Schema.String,
|
||||
}) {}
|
||||
|
||||
export class AccountRepoError extends Schema.TaggedErrorClass<AccountRepoError>()("AccountRepoError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export class AccountServiceError extends Schema.TaggedErrorClass<AccountServiceError>()("AccountServiceError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export class AccountTransportError extends Schema.TaggedErrorClass<AccountTransportError>()("AccountTransportError", {
|
||||
method: Schema.String,
|
||||
url: Schema.String,
|
||||
description: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError {
|
||||
return new AccountTransportError({
|
||||
method: error.request.method,
|
||||
url: error.request.url,
|
||||
description: error.description,
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return [
|
||||
`Could not reach ${this.method} ${this.url}.`,
|
||||
`This failed before the server returned an HTTP response.`,
|
||||
this.description,
|
||||
`Check your network, proxy, or VPN configuration and try again.`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
export type AccountError = AccountRepoError | AccountServiceError | AccountTransportError
|
||||
|
||||
export class Login extends Schema.Class<Login>("Login")({
|
||||
code: DeviceCode,
|
||||
user: UserCode,
|
||||
url: Schema.String,
|
||||
server: Schema.String,
|
||||
expiry: Schema.Duration,
|
||||
interval: Schema.Duration,
|
||||
}) {}
|
||||
|
||||
export class PollSuccess extends Schema.TaggedClass<PollSuccess>()("PollSuccess", {
|
||||
email: Schema.String,
|
||||
}) {}
|
||||
|
||||
export class PollPending extends Schema.TaggedClass<PollPending>()("PollPending", {}) {}
|
||||
|
||||
export class PollSlow extends Schema.TaggedClass<PollSlow>()("PollSlow", {}) {}
|
||||
|
||||
export class PollExpired extends Schema.TaggedClass<PollExpired>()("PollExpired", {}) {}
|
||||
|
||||
export class PollDenied extends Schema.TaggedClass<PollDenied>()("PollDenied", {}) {}
|
||||
|
||||
export class PollError extends Schema.TaggedClass<PollError>()("PollError", {
|
||||
cause: Schema.Defect(),
|
||||
}) {}
|
||||
|
||||
export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError])
|
||||
export type PollResult = Schema.Schema.Type<typeof PollResult>
|
||||
@@ -1,21 +1,24 @@
|
||||
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core"
|
||||
|
||||
import { Account } from "../account"
|
||||
import { Timestamps } from "../database/schema.sql"
|
||||
|
||||
export const AccountTable = sqliteTable("account", {
|
||||
id: text().primaryKey(),
|
||||
id: text().$type<Account.ID>().primaryKey(),
|
||||
email: text().notNull(),
|
||||
url: text().notNull(),
|
||||
access_token: text().notNull(),
|
||||
refresh_token: text().notNull(),
|
||||
access_token: text().$type<Account.AccessToken>().notNull(),
|
||||
refresh_token: text().$type<Account.RefreshToken>().notNull(),
|
||||
token_expiry: integer(),
|
||||
...Timestamps,
|
||||
})
|
||||
|
||||
export const AccountStateTable = sqliteTable("account_state", {
|
||||
id: integer().primaryKey(),
|
||||
active_account_id: text().references(() => AccountTable.id, { onDelete: "set null" }),
|
||||
active_org_id: text(),
|
||||
active_account_id: text()
|
||||
.$type<Account.ID>()
|
||||
.references(() => AccountTable.id, { onDelete: "set null" }),
|
||||
active_org_id: text().$type<Account.OrgID>(),
|
||||
})
|
||||
|
||||
// LEGACY
|
||||
@@ -24,8 +27,8 @@ export const ControlAccountTable = sqliteTable(
|
||||
{
|
||||
email: text().notNull(),
|
||||
url: text().notNull(),
|
||||
access_token: text().notNull(),
|
||||
refresh_token: text().notNull(),
|
||||
access_token: text().$type<Account.AccessToken>().notNull(),
|
||||
refresh_token: text().$type<Account.RefreshToken>().notNull(),
|
||||
token_expiry: integer(),
|
||||
active: integer({ mode: "boolean" })
|
||||
.notNull()
|
||||
|
||||
@@ -11,7 +11,6 @@ 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"
|
||||
@@ -297,7 +296,6 @@ 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,
|
||||
}),
|
||||
@@ -312,7 +310,6 @@ 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,
|
||||
|
||||
@@ -218,11 +218,10 @@ 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 | SkillNotFoundError>
|
||||
}) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError>
|
||||
/** Generates text from current Session context without admitting input or mutating history. */
|
||||
readonly generate: (input: {
|
||||
sessionID: SessionSchema.ID
|
||||
@@ -237,17 +236,11 @@ 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
|
||||
| SkillNotFoundError
|
||||
| Command.NotFoundError
|
||||
| Command.EvaluationError
|
||||
NotFoundError | PromptConflictError | AttachmentError | Command.NotFoundError | Command.EvaluationError
|
||||
>
|
||||
readonly shell: (input: {
|
||||
id?: Event.ID
|
||||
@@ -574,11 +567,9 @@ 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, skills: input.skills },
|
||||
{ text: input.text, files: input.files, agents: input.agents },
|
||||
image,
|
||||
skills,
|
||||
).pipe(Effect.provideService(FSUtil.Service, fs))
|
||||
const messageID = input.id ?? SessionMessage.ID.create()
|
||||
const admittedInput = SessionPending.Message.make({
|
||||
@@ -644,7 +635,6 @@ const layer = Layer.effect(
|
||||
text: evaluated.text,
|
||||
files: input.files,
|
||||
agents: input.agents,
|
||||
skills: input.skills,
|
||||
delivery: input.delivery,
|
||||
resume: input.resume,
|
||||
})
|
||||
@@ -907,28 +897,12 @@ 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
|
||||
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 })
|
||||
return Prompt.make({ text: input.text, agents: input.agents, files })
|
||||
})
|
||||
|
||||
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
||||
|
||||
@@ -124,8 +124,7 @@ const serialize = (message: SessionMessage.Info) => {
|
||||
(file) =>
|
||||
`[Attached ${file.mime}: ${file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment")}]`,
|
||||
) ?? []
|
||||
const skills = message.skills?.map((skill) => `[Attached skill: ${skill.name}]\n${skill.text}`) ?? []
|
||||
return [`[User]: ${message.text}`, ...skills, ...files].join("\n")
|
||||
return [`[User]: ${message.text}`, ...files].join("\n")
|
||||
}
|
||||
if (message.type === "assistant") {
|
||||
return message.content
|
||||
|
||||
@@ -453,7 +453,6 @@ 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,7 +184,6 @@ 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,7 +2,6 @@ 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"
|
||||
@@ -220,14 +219,6 @@ 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,25 +38,6 @@ 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),
|
||||
|
||||
@@ -3,6 +3,7 @@ export * as PatchTool from "./patch"
|
||||
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { ToolFailure } from "@opencode-ai/ai"
|
||||
import { FileDiff } from "@opencode-ai/schema/file-diff"
|
||||
import { createTwoFilesPatch, diffLines } from "diff"
|
||||
import { Effect, Result, Schema } from "effect"
|
||||
import path from "path"
|
||||
import { Bom } from "@opencode-ai/util/bom"
|
||||
@@ -14,7 +15,6 @@ import { Location } from "../../location"
|
||||
import { Patch } from "@opencode-ai/util/patch"
|
||||
import { Permission } from "../../permission"
|
||||
import DESCRIPTION from "../patch.txt"
|
||||
import { fileDiff } from "./file-diff"
|
||||
|
||||
export const name = "patch"
|
||||
|
||||
@@ -353,16 +353,22 @@ function errorMessage(error: unknown) {
|
||||
|
||||
function patchFile(change: Prepared, after = change.after): typeof FileDiff.Info.Type {
|
||||
const target = (change.type === "update" ? change.moveTarget : undefined)?.resource ?? change.target.resource
|
||||
const diff = fileDiff(
|
||||
change.target.absolute,
|
||||
change.before,
|
||||
after,
|
||||
change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
|
||||
)
|
||||
const patch = trimDiff(createTwoFilesPatch(change.target.absolute, change.target.absolute, change.before, after))
|
||||
const counts =
|
||||
change.type === "delete"
|
||||
? { additions: 0, deletions: change.before.split("\n").length }
|
||||
: diffLines(change.before, after).reduce(
|
||||
(result, item) => ({
|
||||
additions: result.additions + (item.added ? (item.count ?? 0) : 0),
|
||||
deletions: result.deletions + (item.removed ? (item.count ?? 0) : 0),
|
||||
}),
|
||||
{ additions: 0, deletions: 0 },
|
||||
)
|
||||
return {
|
||||
...diff,
|
||||
file: target,
|
||||
patch: trimDiff(diff.patch),
|
||||
patch,
|
||||
status: change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
|
||||
...counts,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,25 @@ 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")
|
||||
}
|
||||
|
||||
const unableToLoad = (name: string, error?: unknown) =>
|
||||
new ToolFailure({ message: `Unable to load skill ${name}`, error })
|
||||
|
||||
@@ -69,7 +88,7 @@ export const Plugin = {
|
||||
return {
|
||||
name: skill.name,
|
||||
directory,
|
||||
output: Skill.toModelOutput(skill, files),
|
||||
output: toModelOutput(skill, files),
|
||||
}
|
||||
}).pipe(Effect.mapError((error) => unableToLoad(input.id, error)))
|
||||
}).pipe(
|
||||
|
||||
@@ -3,8 +3,7 @@ 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, SkillAttachment } from "@opencode-ai/schema/prompt"
|
||||
import { Skill } from "@opencode-ai/schema/skill"
|
||||
import { AgentAttachment, Base64, FileAttachment } from "@opencode-ai/schema/prompt"
|
||||
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"
|
||||
@@ -185,40 +184,6 @@ 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,7 +15,6 @@ 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"
|
||||
|
||||
@@ -56,41 +55,6 @@ 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
|
||||
|
||||
@@ -215,7 +215,7 @@ describe("PatchTool", () => {
|
||||
file: "remove.txt",
|
||||
status: "deleted",
|
||||
additions: 0,
|
||||
deletions: 1,
|
||||
deletions: 2,
|
||||
patch: expect.stringContaining("-remove"),
|
||||
},
|
||||
],
|
||||
@@ -248,29 +248,6 @@ describe("PatchTool", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.live("counts deleted lines with and without a trailing newline", () =>
|
||||
withTempTool((directory, registry) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.promise(() =>
|
||||
Promise.all([
|
||||
fs.writeFile(path.join(directory, "trailing.txt"), "remove\n"),
|
||||
fs.writeFile(path.join(directory, "unterminated.txt"), "remove"),
|
||||
]),
|
||||
)
|
||||
const settled = yield* executeTool(
|
||||
registry,
|
||||
call("*** Begin Patch\n*** Delete File: trailing.txt\n*** Delete File: unterminated.txt\n*** End Patch"),
|
||||
)
|
||||
expect(settled.status).toBe("completed")
|
||||
if (settled.status !== "completed") return
|
||||
expect(settled.output.files).toMatchObject([
|
||||
{ file: "trailing.txt", additions: 0, deletions: 1 },
|
||||
{ file: "unterminated.txt", additions: 0, deletions: 1 },
|
||||
])
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("serializes concurrent patch transactions", () =>
|
||||
withTempTool((directory, registry) => {
|
||||
const target = path.join(directory, "concurrent.txt")
|
||||
@@ -469,7 +446,7 @@ describe("PatchTool", () => {
|
||||
{
|
||||
file: "renamed/dir/name.txt",
|
||||
status: "modified",
|
||||
patch: expect.stringContaining(`Index: ${source}`),
|
||||
patch: expect.stringContaining("-old content\n+new content"),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
@@ -108,9 +108,9 @@ describe("SkillTool", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "completed",
|
||||
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }],
|
||||
content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
|
||||
})
|
||||
expect(Skill.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
|
||||
expect(SkillTool.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
@@ -119,8 +119,8 @@ describe("SkillTool", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
status: "completed",
|
||||
output: { name: "Effect", directory, output: Skill.toModelOutput(info, [reference]) },
|
||||
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }],
|
||||
output: { name: "Effect", directory, output: SkillTool.toModelOutput(info, [reference]) },
|
||||
content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
|
||||
metadata: { name: "Effect", directory },
|
||||
})
|
||||
expect(assertions).toMatchObject([
|
||||
@@ -171,7 +171,7 @@ describe("SkillTool", () => {
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "completed",
|
||||
content: [{ type: "text", text: Skill.toModelOutput(flat, []) }],
|
||||
content: [{ type: "text", text: SkillTool.toModelOutput(flat, []) }],
|
||||
})
|
||||
}).pipe(Effect.provide(skillToolLayer))
|
||||
}),
|
||||
|
||||
@@ -198,13 +198,13 @@ describe("FlowchartDiagram", () => {
|
||||
B --> A`)
|
||||
|
||||
expectDiagram(output).toEqualDiagram(`
|
||||
╭───────────╮
|
||||
│ │
|
||||
│ │
|
||||
▼ │
|
||||
╭───╮ ╭─┴─╮
|
||||
│ A ├──────▶│ B │
|
||||
╰───╯ ╰───╯
|
||||
╭──────────────╮
|
||||
│ │
|
||||
│ │
|
||||
▼ │
|
||||
╭───╮ ╭─┴─╮
|
||||
│ A ├─────────▶│ B │
|
||||
╰───╯ ╰───╯
|
||||
`)
|
||||
})
|
||||
|
||||
@@ -599,7 +599,7 @@ flowchart LR
|
||||
const output = renderFlowchartDiagram(content)
|
||||
|
||||
expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "thick" }])
|
||||
expect(output).toContain("━━━━━━▶")
|
||||
expect(output).toContain("━━━━━━━━━▶")
|
||||
})
|
||||
|
||||
test("parses and renders Mermaid dashed edges", () => {
|
||||
@@ -611,7 +611,7 @@ flowchart LR
|
||||
const output = renderFlowchartDiagram(content)
|
||||
|
||||
expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "dashed" }])
|
||||
expect(output).toContain("──────▶")
|
||||
expect(output).toContain("─────────▶")
|
||||
})
|
||||
|
||||
test("paints horizontal and vertical dashed routes with solid terminal cells", () => {
|
||||
@@ -689,11 +689,11 @@ graph LR
|
||||
`)
|
||||
|
||||
expectDiagram(output).toEqualDiagram(`
|
||||
╭───────╮
|
||||
╭────────╮ ╭─────╮ ├───────┤
|
||||
│ Client ├──────▶│ API ├──────▶│ Cache │
|
||||
╰────────╯ ╰─────╯ ├───────┤
|
||||
╰───────╯
|
||||
╭───────╮
|
||||
╭────────╮ ╭─────╮ ├───────┤
|
||||
│ Client ├─────────▶│ API ├─────────▶│ Cache │
|
||||
╰────────╯ ╰─────╯ ├───────┤
|
||||
╰───────╯
|
||||
`)
|
||||
})
|
||||
|
||||
@@ -1017,176 +1017,6 @@ flowchart LR
|
||||
}
|
||||
})
|
||||
|
||||
test("separates cross-dependent top-level subgraphs", () => {
|
||||
const content = `flowchart TD
|
||||
subgraph plugins["Plugins — one verb: attach"]
|
||||
chip["pr-indicator<br/>attach(prompt.footer, { after: 'directory' })"]
|
||||
theme["fancy-footer<br/>attach(prompt.footer, { replace: 'right' })"]
|
||||
end
|
||||
|
||||
subgraph host["Host anatomy tree — published, stable part IDs"]
|
||||
footer["prompt.footer"]
|
||||
left["left"]
|
||||
right["right<br/>(container)"]
|
||||
dir["directory"]
|
||||
model["model"]
|
||||
tokens["tokens"]
|
||||
footer --> left
|
||||
footer --> right
|
||||
right --> dir
|
||||
right --> model
|
||||
right --> tokens
|
||||
end
|
||||
|
||||
chip -- "insert after" --> dir
|
||||
theme == "takeover" ==> right
|
||||
theme -. "suppresses guests<br/>in subtree" .-> chip`
|
||||
const layout = layoutFlowchartDiagram(content)
|
||||
const plugins = layout.subgraphBounds.get("plugins")!
|
||||
const host = layout.subgraphBounds.get("host")!
|
||||
const output = renderFlowchartDiagram(content)
|
||||
const lines = output.split("\n")
|
||||
|
||||
expect(host.top).toBeGreaterThanOrEqual(plugins.top + plugins.height)
|
||||
expect(lines.filter((line) => line.includes("Plugins — one verb: attach"))).toHaveLength(1)
|
||||
expect(lines.filter((line) => line.includes("Host anatomy tree — published, stable part IDs"))).toHaveLength(1)
|
||||
expect(lines.findIndex((line) => line.includes("Host anatomy tree"))).toBeGreaterThan(
|
||||
lines.findIndex((line) => line.includes("Plugins — one verb")),
|
||||
)
|
||||
for (const route of layout.routes) {
|
||||
for (let index = 1; index < route.points.length; index++) {
|
||||
const from = route.points[index - 1]!
|
||||
const to = route.points[index]!
|
||||
expect(from.x === to.x || from.y === to.y).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test.each(["TD", "BT", "LR", "RL"] as const)(
|
||||
"keeps parallel top-level subgraphs in the same rank for %s diagrams",
|
||||
(direction) => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart ${direction}
|
||||
subgraph source [Source]
|
||||
A[A]
|
||||
end
|
||||
subgraph left [Left]
|
||||
B[B]
|
||||
end
|
||||
subgraph right [Right]
|
||||
C[C]
|
||||
end
|
||||
A --> B
|
||||
A --> C`)
|
||||
const source = layout.subgraphBounds.get("source")!
|
||||
const left = layout.subgraphBounds.get("left")!
|
||||
const right = layout.subgraphBounds.get("right")!
|
||||
const leftNode = layout.bounds.get("B")!
|
||||
const rightNode = layout.bounds.get("C")!
|
||||
const horizontal = direction === "LR" || direction === "RL"
|
||||
const reversed = direction === "BT" || direction === "RL"
|
||||
const start = (bound: typeof source) => {
|
||||
const value = horizontal ? bound.left : bound.top
|
||||
const size = horizontal ? bound.width : bound.height
|
||||
return reversed ? -(value + size) : value
|
||||
}
|
||||
const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
|
||||
|
||||
expect(horizontal ? leftNode.centerX : leftNode.centerY).toBe(horizontal ? rightNode.centerX : rightNode.centerY)
|
||||
expect(Math.min(start(left), start(right))).toBeGreaterThanOrEqual(start(source) + size(source))
|
||||
},
|
||||
)
|
||||
|
||||
test.each(["TD", "BT", "LR", "RL"] as const)(
|
||||
"separates oversized parallel subgraph labels across %s diagrams",
|
||||
(direction) => {
|
||||
const horizontal = direction === "LR" || direction === "RL"
|
||||
const label = horizontal ? "one<br/>two<br/>three<br/>four<br/>five" : "A very very wide downstream subgraph title"
|
||||
const layout = layoutFlowchartDiagram(`flowchart ${direction}
|
||||
subgraph source [Source]
|
||||
A[A]
|
||||
end
|
||||
subgraph left [${label}]
|
||||
B[B]
|
||||
end
|
||||
subgraph right [Right]
|
||||
C[C]
|
||||
end
|
||||
A --> B
|
||||
A --> C`)
|
||||
const left = layout.subgraphBounds.get("left")!
|
||||
const right = layout.subgraphBounds.get("right")!
|
||||
const overlap =
|
||||
left.left < right.left + right.width &&
|
||||
left.left + left.width > right.left &&
|
||||
left.top < right.top + right.height &&
|
||||
left.top + left.height > right.top
|
||||
|
||||
expect(overlap).toBe(false)
|
||||
},
|
||||
)
|
||||
|
||||
test.each(["TD", "BT", "LR", "RL"] as const)(
|
||||
"ranks nested order-only subgraph dependencies for %s diagrams",
|
||||
(direction) => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart ${direction}
|
||||
subgraph first [First]
|
||||
subgraph firstInner [First inner]
|
||||
A[A]
|
||||
end
|
||||
end
|
||||
subgraph second [Second]
|
||||
subgraph secondInner [Second inner]
|
||||
B[B]
|
||||
end
|
||||
end
|
||||
firstInner ~~~ secondInner`)
|
||||
const first = layout.subgraphBounds.get("first")!
|
||||
const second = layout.subgraphBounds.get("second")!
|
||||
const horizontal = direction === "LR" || direction === "RL"
|
||||
const reversed = direction === "BT" || direction === "RL"
|
||||
const start = (bound: typeof first) => {
|
||||
const value = horizontal ? bound.left : bound.top
|
||||
const size = horizontal ? bound.width : bound.height
|
||||
return reversed ? -(value + size) : value
|
||||
}
|
||||
const size = horizontal ? first.width : first.height
|
||||
|
||||
expect(start(second)).toBeGreaterThanOrEqual(start(first) + size)
|
||||
},
|
||||
)
|
||||
|
||||
test.each(["TD", "BT", "LR", "RL"] as const)(
|
||||
"ranks cyclic top-level subgraphs as one downstream component for %s diagrams",
|
||||
(direction) => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart ${direction}
|
||||
subgraph source [Source]
|
||||
A[A]
|
||||
end
|
||||
subgraph first [First]
|
||||
B[B]
|
||||
end
|
||||
subgraph second [Second]
|
||||
C[C]
|
||||
end
|
||||
A --> B
|
||||
B --> C
|
||||
C --> B`)
|
||||
const source = layout.subgraphBounds.get("source")!
|
||||
const first = layout.subgraphBounds.get("first")!
|
||||
const second = layout.subgraphBounds.get("second")!
|
||||
const horizontal = direction === "LR" || direction === "RL"
|
||||
const reversed = direction === "BT" || direction === "RL"
|
||||
const start = (bound: typeof source) => {
|
||||
const value = horizontal ? bound.left : bound.top
|
||||
const size = horizontal ? bound.width : bound.height
|
||||
return reversed ? -(value + size) : value
|
||||
}
|
||||
const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
|
||||
|
||||
expect(Math.min(start(first), start(second))).toBeGreaterThanOrEqual(start(source) + size(source))
|
||||
},
|
||||
)
|
||||
|
||||
test("moves subgraph labels away from crossing routes", () => {
|
||||
const output = renderFlowchartDiagram(`
|
||||
flowchart TD
|
||||
|
||||
@@ -27,7 +27,7 @@ import type {
|
||||
|
||||
export const DEFAULT_MIN_NODE_GAP = 5
|
||||
export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
|
||||
export const DEFAULT_MIN_RANK_GAP = 7
|
||||
export const DEFAULT_MIN_RANK_GAP = 10
|
||||
export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
|
||||
export const COMPACT_MIN_RANK_GAP = 4
|
||||
export const COMPACT_MIN_VERTICAL_RANK_GAP = 2
|
||||
@@ -499,6 +499,10 @@ function edgeDirection(diagram: FlowchartDiagram, edge: FlowchartEdge): Flowchar
|
||||
return diagram.direction
|
||||
}
|
||||
|
||||
function hasLocalSubgraphDirection(diagram: FlowchartDiagram): boolean {
|
||||
return (diagram.subgraphs ?? []).some((subgraph) => subgraph.direction && subgraph.direction !== diagram.direction)
|
||||
}
|
||||
|
||||
function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string): Set<string> {
|
||||
const nodeIds = new Set<string>()
|
||||
for (const subgraph of diagram.subgraphs ?? []) {
|
||||
@@ -511,200 +515,51 @@ function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string):
|
||||
return nodeIds
|
||||
}
|
||||
|
||||
function rankGraphComponents(ids: readonly string[], outgoing: ReadonlyMap<string, ReadonlySet<string>>): Map<string, number> {
|
||||
const reachable = new Map<string, Set<string>>()
|
||||
for (const id of ids) {
|
||||
const seen = new Set<string>()
|
||||
const queue = [id]
|
||||
for (let index = 0; index < queue.length; index++) {
|
||||
const current = queue[index]!
|
||||
if (seen.has(current)) continue
|
||||
seen.add(current)
|
||||
queue.push(...(outgoing.get(current) ?? []))
|
||||
}
|
||||
reachable.set(id, seen)
|
||||
}
|
||||
|
||||
const componentById = new Map<string, number>()
|
||||
const components: string[][] = []
|
||||
for (const id of ids) {
|
||||
if (componentById.has(id)) continue
|
||||
const component = ids.filter(
|
||||
(candidate) => !componentById.has(candidate) && reachable.get(id)!.has(candidate) && reachable.get(candidate)!.has(id),
|
||||
)
|
||||
const componentIndex = components.length
|
||||
components.push(component)
|
||||
for (const member of component) componentById.set(member, componentIndex)
|
||||
}
|
||||
|
||||
const componentOutgoing = new Map(components.map((_, index) => [index, new Set<number>()]))
|
||||
const incoming = new Map(components.map((_, index) => [index, 0]))
|
||||
for (const [from, targets] of outgoing) {
|
||||
const fromComponent = componentById.get(from)!
|
||||
for (const to of targets) {
|
||||
const toComponent = componentById.get(to)!
|
||||
if (fromComponent === toComponent || componentOutgoing.get(fromComponent)!.has(toComponent)) continue
|
||||
componentOutgoing.get(fromComponent)!.add(toComponent)
|
||||
incoming.set(toComponent, incoming.get(toComponent)! + 1)
|
||||
}
|
||||
}
|
||||
|
||||
const componentRanks = new Map<number, number>()
|
||||
const queue = components.map((_, index) => index).filter((index) => incoming.get(index) === 0)
|
||||
for (const component of queue) componentRanks.set(component, 0)
|
||||
for (let index = 0; index < queue.length; index++) {
|
||||
const component = queue[index]!
|
||||
for (const to of componentOutgoing.get(component)!) {
|
||||
componentRanks.set(to, Math.max(componentRanks.get(to) ?? 0, componentRanks.get(component)! + 1))
|
||||
incoming.set(to, incoming.get(to)! - 1)
|
||||
if (incoming.get(to) === 0) queue.push(to)
|
||||
}
|
||||
}
|
||||
|
||||
return new Map(ids.map((id) => [id, componentRanks.get(componentById.get(id)!) ?? 0]))
|
||||
}
|
||||
|
||||
function separateTopLevelItems(
|
||||
function separateLocalSubgraphItems(
|
||||
diagram: FlowchartDiagram,
|
||||
nodeBounds: Map<string, FlowchartNodeBounds>,
|
||||
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
|
||||
gap: number,
|
||||
): boolean {
|
||||
const hasLocalDirection = (diagram.subgraphs ?? []).some(
|
||||
(subgraph) => subgraph.direction && subgraph.direction !== diagram.direction,
|
||||
)
|
||||
): void {
|
||||
if (!hasLocalSubgraphDirection(diagram)) return
|
||||
|
||||
const coveredNodeIds = new Set<string>()
|
||||
const items: { id: string; bounds: FlowchartBounds; nodeIds: Set<string>; rank: number }[] = []
|
||||
const itemByEndpoint = new Map<string, string>()
|
||||
const subgraphs = diagram.subgraphs ?? []
|
||||
const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
|
||||
const topLevelSubgraphId = (id: string): string => {
|
||||
let current = subgraphById.get(id)
|
||||
while (current?.parentId) current = subgraphById.get(current.parentId)
|
||||
return current?.id ?? id
|
||||
}
|
||||
for (const subgraph of subgraphs) {
|
||||
const items: { bounds: FlowchartBounds; nodeIds: Set<string> }[] = []
|
||||
for (const subgraph of diagram.subgraphs ?? []) {
|
||||
if (subgraph.parentId) continue
|
||||
const bounds = subgraphBounds.get(subgraph.id)
|
||||
const nodeIds = collectSubgraphNodeIds(diagram, subgraph.id)
|
||||
if (!bounds || nodeIds.size === 0) continue
|
||||
items.push({ id: subgraph.id, bounds, nodeIds, rank: 0 })
|
||||
itemByEndpoint.set(subgraph.id, subgraph.id)
|
||||
for (const nodeId of nodeIds) {
|
||||
coveredNodeIds.add(nodeId)
|
||||
itemByEndpoint.set(nodeId, subgraph.id)
|
||||
}
|
||||
items.push({ bounds, nodeIds })
|
||||
for (const nodeId of nodeIds) coveredNodeIds.add(nodeId)
|
||||
}
|
||||
for (const subgraph of subgraphs) itemByEndpoint.set(subgraph.id, topLevelSubgraphId(subgraph.id))
|
||||
|
||||
for (const node of diagram.nodes) {
|
||||
if (coveredNodeIds.has(node.id)) continue
|
||||
const bounds = nodeBounds.get(node.id)
|
||||
if (!bounds) continue
|
||||
items.push({ id: node.id, bounds, nodeIds: new Set([node.id]), rank: 0 })
|
||||
itemByEndpoint.set(node.id, node.id)
|
||||
if (bounds) items.push({ bounds, nodeIds: new Set([node.id]) })
|
||||
}
|
||||
if (items.length < 2) return false
|
||||
|
||||
const horizontal = isHorizontalDirection(diagram.direction)
|
||||
const moveItem = (item: (typeof items)[number], dx: number, dy: number): void => {
|
||||
for (const nodeId of item.nodeIds) {
|
||||
const bounds = nodeBounds.get(nodeId)
|
||||
if (bounds) translateBounds(bounds, dx, dy)
|
||||
}
|
||||
}
|
||||
if (hasLocalDirection) {
|
||||
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
|
||||
let cursor: number | undefined
|
||||
let moved = false
|
||||
for (const item of items) {
|
||||
const start = horizontal ? item.bounds.left : item.bounds.top
|
||||
const size = horizontal ? item.bounds.width : item.bounds.height
|
||||
if (cursor === undefined) {
|
||||
cursor = start + size + gap
|
||||
continue
|
||||
}
|
||||
const shift = cursor - start
|
||||
moved ||= shift !== 0
|
||||
moveItem(item, horizontal ? shift : 0, horizontal ? 0 : shift)
|
||||
cursor = start + shift + size + gap
|
||||
}
|
||||
return moved
|
||||
}
|
||||
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
|
||||
|
||||
const topLevelIds = new Set(subgraphs.filter((subgraph) => !subgraph.parentId).map((subgraph) => subgraph.id))
|
||||
const rankedItems = items.filter((item) => topLevelIds.has(item.id))
|
||||
if (rankedItems.length < 2) return false
|
||||
|
||||
const itemById = new Map(rankedItems.map((item) => [item.id, item]))
|
||||
const outgoing = new Map(rankedItems.map((item) => [item.id, new Set<string>()]))
|
||||
for (const edge of diagram.edges) {
|
||||
const from = itemByEndpoint.get(edge.from)
|
||||
const to = itemByEndpoint.get(edge.to)
|
||||
if (!from || !to || from === to || !itemById.has(from) || !itemById.has(to) || outgoing.get(from)!.has(to)) continue
|
||||
outgoing.get(from)!.add(to)
|
||||
}
|
||||
|
||||
const ranks = rankGraphComponents(
|
||||
rankedItems.map((item) => item.id),
|
||||
outgoing,
|
||||
)
|
||||
for (const item of rankedItems) item.rank = ranks.get(item.id)!
|
||||
|
||||
const reversed = diagram.direction === "RL" || diagram.direction === "BT"
|
||||
const primaryStart = (item: (typeof items)[number]): number => {
|
||||
let cursor: number | undefined
|
||||
for (const item of items) {
|
||||
const start = horizontal ? item.bounds.left : item.bounds.top
|
||||
const size = horizontal ? item.bounds.width : item.bounds.height
|
||||
return reversed ? -(start + size) : start
|
||||
}
|
||||
const itemsByRank = Map.groupBy(rankedItems, (item) => item.rank)
|
||||
const rankKeys = [...itemsByRank.keys()].sort((a, b) => a - b)
|
||||
let cursor: number | undefined
|
||||
let moved = false
|
||||
for (const rank of rankKeys) {
|
||||
const rankItems = itemsByRank.get(rank)!
|
||||
const start = Math.min(...rankItems.map(primaryStart))
|
||||
const end = Math.max(
|
||||
...rankItems.map((item) => primaryStart(item) + (horizontal ? item.bounds.width : item.bounds.height)),
|
||||
)
|
||||
if (cursor === undefined) {
|
||||
cursor = end + gap
|
||||
cursor = start + size + gap
|
||||
continue
|
||||
}
|
||||
const shift = Math.max(0, cursor - start)
|
||||
if (shift > 0) {
|
||||
moved = true
|
||||
for (const item of rankItems) {
|
||||
const offset = reversed ? -shift : shift
|
||||
moveItem(item, horizontal ? offset : 0, horizontal ? 0 : offset)
|
||||
const shift = cursor - start
|
||||
if (shift !== 0) {
|
||||
for (const nodeId of item.nodeIds) {
|
||||
const bounds = nodeBounds.get(nodeId)
|
||||
if (bounds) translateBounds(bounds, horizontal ? shift : 0, horizontal ? 0 : shift)
|
||||
}
|
||||
}
|
||||
cursor = end + shift + gap
|
||||
cursor = start + shift + size + gap
|
||||
}
|
||||
|
||||
for (const rank of rankKeys) {
|
||||
const rankItems = itemsByRank
|
||||
.get(rank)!
|
||||
.toSorted((a, b) =>
|
||||
horizontal ? a.bounds.top - b.bounds.top : a.bounds.left - b.bounds.left,
|
||||
)
|
||||
let crossCursor: number | undefined
|
||||
for (const item of rankItems) {
|
||||
const start = horizontal ? item.bounds.top : item.bounds.left
|
||||
const size = horizontal ? item.bounds.height : item.bounds.width
|
||||
if (crossCursor === undefined) {
|
||||
crossCursor = start + size + gap
|
||||
continue
|
||||
}
|
||||
const shift = Math.max(0, crossCursor - start)
|
||||
if (shift > 0) {
|
||||
moved = true
|
||||
moveItem(item, horizontal ? 0 : shift, horizontal ? shift : 0)
|
||||
}
|
||||
crossCursor = start + shift + size + gap
|
||||
}
|
||||
}
|
||||
return moved
|
||||
}
|
||||
|
||||
function layoutSubgraphs(
|
||||
@@ -759,27 +614,13 @@ function layoutFlowchartWithDirection(
|
||||
const bounds = layoutRankedNodes(diagram, direction, sizes, minNodeGap, requestedMinRankGap)
|
||||
layoutLocalSubgraphDirections(diagram, bounds, sizes, minNodeGap, requestedMinRankGap)
|
||||
|
||||
const subgraphs = diagram.subgraphs ?? []
|
||||
let subgraphBounds = new Map<string, FlowchartSubgraphBounds>()
|
||||
let routes: FlowchartEdgeRoute[]
|
||||
if (subgraphs.length === 0) {
|
||||
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
|
||||
} else {
|
||||
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
|
||||
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
|
||||
const moved = separateTopLevelItems(
|
||||
diagram,
|
||||
bounds,
|
||||
subgraphBounds,
|
||||
Math.max(1, Math.floor(requestedMinRankGap / 2)),
|
||||
)
|
||||
if (moved) {
|
||||
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
|
||||
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
|
||||
}
|
||||
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
|
||||
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
|
||||
}
|
||||
let routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
|
||||
let subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
|
||||
separateLocalSubgraphItems(diagram, bounds, subgraphBounds, Math.max(1, Math.floor(requestedMinRankGap / 2)))
|
||||
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
|
||||
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
|
||||
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
|
||||
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
|
||||
const allBounds = [...bounds.values(), ...subgraphBounds.values(), ...routeRenderBounds(routes)]
|
||||
const dx = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.left)))
|
||||
const dy = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.top)))
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { RGBA } from "@opentui/core"
|
||||
import { createOpenCodeDiagramPalette } from "./palette.js"
|
||||
|
||||
type Rgb = readonly [number, number, number]
|
||||
|
||||
const rgb = (value: Rgb) => RGBA.fromInts(...value)
|
||||
|
||||
describe("OpenCode diagram palette", () => {
|
||||
test.each(
|
||||
[
|
||||
{
|
||||
name: "dark theme",
|
||||
text: [230, 232, 240],
|
||||
subdued: [114, 120, 138],
|
||||
secondary: [172, 176, 189],
|
||||
muted: [149, 154, 169],
|
||||
},
|
||||
{
|
||||
name: "light theme",
|
||||
text: [32, 35, 43],
|
||||
subdued: [119, 125, 138],
|
||||
secondary: [76, 80, 91],
|
||||
muted: [93, 98, 110],
|
||||
},
|
||||
] satisfies ReadonlyArray<{
|
||||
name: string
|
||||
text: Rgb
|
||||
subdued: Rgb
|
||||
secondary: Rgb
|
||||
muted: Rgb
|
||||
}>,
|
||||
)("derives a controlled neutral ladder for a $name", ({ text, subdued, secondary, muted }) => {
|
||||
const primary = rgb(text)
|
||||
const info = RGBA.fromInts(40, 120, 220)
|
||||
const background = RGBA.fromInts(10, 20, 30)
|
||||
const palette = createOpenCodeDiagramPalette({
|
||||
text: primary,
|
||||
subdued: rgb(subdued),
|
||||
info,
|
||||
background,
|
||||
})
|
||||
|
||||
expect(palette.text).toBe(primary)
|
||||
expect(palette.primary).toBe(primary)
|
||||
expect(palette.secondary.equals(rgb(secondary))).toBe(true)
|
||||
expect(palette.muted.equals(rgb(muted))).toBe(true)
|
||||
expect(palette.warning).toBe(info)
|
||||
expect(palette.background).toBe(background)
|
||||
})
|
||||
})
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { RGBA } from "@opentui/core"
|
||||
import { blendColor } from "./core/color/style.js"
|
||||
|
||||
export interface OpenCodeDiagramPaletteInput {
|
||||
readonly text: RGBA
|
||||
readonly subdued: RGBA
|
||||
readonly info: RGBA
|
||||
readonly background: RGBA
|
||||
}
|
||||
|
||||
export function createOpenCodeDiagramPalette(input: OpenCodeDiagramPaletteInput) {
|
||||
return {
|
||||
text: input.text,
|
||||
primary: input.text,
|
||||
secondary: blendColor(input.text, input.subdued, 0.5),
|
||||
muted: blendColor(input.text, input.subdued, 0.7),
|
||||
warning: input.info,
|
||||
background: input.background,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Plugin } from "@opencode-ai/plugin/tui"
|
||||
import { createMermaidCodeBlockRenderer } from "./markdown.js"
|
||||
import { createOpenCodeDiagramPalette } from "./palette.js"
|
||||
|
||||
export default Plugin.define({
|
||||
id: "opencode.merman",
|
||||
@@ -8,12 +7,14 @@ export default Plugin.define({
|
||||
context.markdown.registerCodeBlockRenderer(
|
||||
"mermaid",
|
||||
createMermaidCodeBlockRenderer(context.renderer, () => ({
|
||||
colors: createOpenCodeDiagramPalette({
|
||||
text: context.theme.text.default,
|
||||
subdued: context.theme.text.subdued,
|
||||
info: context.theme.text.feedback.info.default,
|
||||
colors: {
|
||||
text: context.theme.markdown.text,
|
||||
primary: context.theme.text.default,
|
||||
secondary: context.theme.text.subdued,
|
||||
muted: context.theme.border.default,
|
||||
warning: context.theme.text.feedback.info.default,
|
||||
background: context.theme.background.default,
|
||||
}),
|
||||
},
|
||||
})),
|
||||
)
|
||||
},
|
||||
|
||||
@@ -169,6 +169,55 @@ export interface SlotMap {
|
||||
export type SlotName = keyof SlotMap
|
||||
export type Slot<Name extends SlotName = SlotName> = (props: SlotMap[Name]) => JSX.Element
|
||||
|
||||
/**
|
||||
* The host UI's extensible regions. Each region publishes an input (reactive
|
||||
* props passed to every claim render) and a part vocabulary: the stable ids
|
||||
* of host furniture that placements may anchor to. Part ids are documented
|
||||
* API — coarse, few, and kept stable across host refactors.
|
||||
*/
|
||||
export interface RegionMap {
|
||||
readonly app: { readonly input: Readonly<Record<string, never>>; readonly part: never }
|
||||
readonly "home.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
|
||||
readonly "prompt.footer": {
|
||||
readonly input: { readonly sessionID?: string; readonly mode: "normal" | "shell" }
|
||||
readonly part: "status" | "file"
|
||||
}
|
||||
readonly "session.composer.top": { readonly input: { readonly sessionID: string }; readonly part: never }
|
||||
readonly "sidebar.content": { readonly input: { readonly sessionID: string }; readonly part: never }
|
||||
readonly "sidebar.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
|
||||
}
|
||||
export type RegionName = keyof RegionMap
|
||||
|
||||
/**
|
||||
* Where a claim lands in a region's structure. Exactly one of:
|
||||
* - `at`: the region's edge — `"end"` is the ceremony-free default position
|
||||
* - `before` / `after`: adjacent to a host part, wherever the host keeps it
|
||||
* - `replace`: take over one part — or the whole region by naming it.
|
||||
* Replace is takeover: anything anchored inside the replaced subtree is
|
||||
* suppressed and recorded, never silently dropped. At the same target the
|
||||
* last-enabled claim wins; an ancestor takeover beats a descendant one
|
||||
* regardless of order.
|
||||
* A placement aimed at a part the host no longer publishes degrades to the
|
||||
* region's end (after end-edge claims) rather than disappearing.
|
||||
*
|
||||
* The `?: never` fields make the variants mutually exclusive: a claim with
|
||||
* two placement keys is a type error, not a silent priority pick.
|
||||
*/
|
||||
export type RegionPlacement<Name extends RegionName = RegionName> =
|
||||
| { readonly at: "start" | "end"; readonly before?: never; readonly after?: never; readonly replace?: never }
|
||||
| { readonly before: RegionMap[Name]["part"]; readonly at?: never; readonly after?: never; readonly replace?: never }
|
||||
| { readonly after: RegionMap[Name]["part"]; readonly at?: never; readonly before?: never; readonly replace?: never }
|
||||
| {
|
||||
readonly replace: RegionMap[Name]["part"] | Name
|
||||
readonly at?: never
|
||||
readonly before?: never
|
||||
readonly after?: never
|
||||
}
|
||||
|
||||
export type RegionClaim<Name extends RegionName = RegionName> = RegionPlacement<Name> & {
|
||||
readonly render: (input: RegionMap[Name]["input"]) => JSX.Element
|
||||
}
|
||||
|
||||
export interface App {
|
||||
readonly version: string
|
||||
readonly channel: string
|
||||
@@ -394,7 +443,16 @@ export interface UI {
|
||||
/** Closes an open tab, or the active tab when omitted, and returns false when no tab matched. */
|
||||
close(sessionID?: string): boolean
|
||||
}
|
||||
readonly slot: <Name extends SlotName>(name: Name, render: Slot<Name>) => () => void
|
||||
readonly slot: {
|
||||
/**
|
||||
* @deprecated Position-encoded slot names are the legacy surface; use
|
||||
* the region + placement form. `slot("prompt.footer.end", render)` is
|
||||
* `slot("prompt.footer", { at: "end", render })`.
|
||||
*/
|
||||
<Name extends SlotName>(name: Name, render: Slot<Name>): () => void
|
||||
/** Claims a place in a region's structure; see RegionPlacement. */
|
||||
<Name extends RegionName>(region: Name, claim: RegionClaim<Name>): () => void
|
||||
}
|
||||
}
|
||||
|
||||
export interface Context {
|
||||
|
||||
@@ -347,7 +347,6 @@ 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,7 +3,6 @@ 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({
|
||||
@@ -20,15 +19,8 @@ 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,7 +1,6 @@
|
||||
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({
|
||||
@@ -53,31 +52,21 @@ 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" | "skills">) =>
|
||||
fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents">) =>
|
||||
schema.make({
|
||||
text: input.text,
|
||||
...(input.files === undefined ? {} : { files: input.files }),
|
||||
...(input.agents === undefined ? {} : { agents: input.agents }),
|
||||
...(input.skills === undefined ? {} : { skills: input.skills }),
|
||||
}),
|
||||
})),
|
||||
)
|
||||
|
||||
@@ -58,7 +58,6 @@ 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,7 +313,6 @@ 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,
|
||||
@@ -338,9 +337,6 @@ 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" })),
|
||||
),
|
||||
),
|
||||
}
|
||||
}),
|
||||
@@ -359,7 +355,6 @@ 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,
|
||||
})
|
||||
@@ -399,9 +394,6 @@ 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" })),
|
||||
),
|
||||
),
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -13,30 +13,15 @@ trap 'rm -f -- "$pidfile"' EXIT
|
||||
"$@"
|
||||
`
|
||||
|
||||
// Modal's VM runtime accepts process-group signals without delivering them
|
||||
// (kill(-pgid) returns 0 and nothing dies; direct-pid signals work), so the
|
||||
// group is enumerated from /proc and each member is signalled directly. The
|
||||
// second pass catches children forked between scan and signal.
|
||||
const KILL = `
|
||||
pidfile=$1
|
||||
sig=$2
|
||||
i=0
|
||||
while [ ! -s "$pidfile" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
|
||||
[ -s "$pidfile" ] || exit 47
|
||||
target=$(cat "$pidfile")
|
||||
pass=0
|
||||
while [ "$pass" -lt 2 ]; do
|
||||
for stat in /proc/[0-9]*/stat; do
|
||||
[ -e "$stat" ] || continue
|
||||
pid=\${stat#/proc/}
|
||||
pid=\${pid%/stat}
|
||||
set -- $(sed "s/.*) //" "$stat" 2>/dev/null)
|
||||
if [ "\${3:-}" = "$target" ]; then
|
||||
/bin/kill "-$sig" "$pid" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
pass=$((pass + 1))
|
||||
done
|
||||
while [ ! -s "$1" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
|
||||
if [ -s "$1" ]; then
|
||||
pid=$(cat "$1")
|
||||
/bin/kill "-$2" "-$pid" 2>/dev/null || true
|
||||
else
|
||||
exit 47
|
||||
fi
|
||||
`
|
||||
|
||||
export interface ModalImageSpec {
|
||||
@@ -69,15 +54,7 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
||||
const app = await client.apps.fromName(options.app, { createIfMissing: true })
|
||||
const imageSpec = options.image ?? ubuntuImage
|
||||
const image = client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
|
||||
// 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 client.sandboxes.create(app, image, options.sandbox)
|
||||
return {
|
||||
driver: makeModalDriver(sandbox),
|
||||
sandbox,
|
||||
@@ -87,14 +64,12 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
||||
|
||||
/**
|
||||
* Adapts Modal exec to the Environment driver. Files intentionally has no native
|
||||
* overrides: exec latency dominates payload work (VM runtime floor measured
|
||||
* ~285-535ms per exec, Aug 2026), so the derived exec defaults are the simplest
|
||||
* implementation with no measured loss.
|
||||
* overrides: Modal exec and filesystem tools share the same roughly 175ms floor,
|
||||
* so the derived exec defaults are the simplest implementation with no measured loss.
|
||||
*
|
||||
* Modal cannot signal a ContainerProcess. Each command therefore starts a new
|
||||
* process group and records its leader in a unique pid file; kill runs a second
|
||||
* sandbox command that enumerates that group from /proc and signals each member
|
||||
* directly (see KILL). Pid files are removed best-effort.
|
||||
* sandbox command that signals that group. Pid files are removed best-effort.
|
||||
*/
|
||||
export const makeModalDriver = (sandbox: Sandbox): Driver => {
|
||||
const spawn = Effect.fnUntraced(function* (command: Command) {
|
||||
|
||||
@@ -12,7 +12,6 @@ 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,
|
||||
|
||||
@@ -87,7 +87,7 @@ import { PromptRefProvider, usePromptRef } from "./context/prompt"
|
||||
import { Config, ConfigProvider, useConfig } from "./config"
|
||||
import { PluginProvider, usePlugin, type PackageResolver } from "./plugin/context"
|
||||
import { tuiPluginDirectories } from "./plugin/discovery"
|
||||
import { PluginRoute, PluginSlot } from "./plugin/render"
|
||||
import { PluginRoute, Region } from "./plugin/render"
|
||||
import { CommandPaletteDialog } from "./component/command-palette"
|
||||
import { COMMAND_PALETTE_COMMAND, Keymap, type KeymapCommand } from "./context/keymap"
|
||||
|
||||
@@ -1154,6 +1154,15 @@ function App(props: { pair?: DialogPairCredentials }) {
|
||||
}
|
||||
})
|
||||
|
||||
event.on("session.execution.failed", (evt, { workspace }) => {
|
||||
if (workspace !== (location.current?.workspaceID ?? data.location.default().workspaceID)) return
|
||||
toast.show({
|
||||
variant: "error",
|
||||
message: evt.data.error.message,
|
||||
duration: 5000,
|
||||
})
|
||||
})
|
||||
|
||||
// Suppress the full-screen overlay for transient startup and event-stream retry states.
|
||||
// Initial connection gets a longer grace period; retries surface more quickly.
|
||||
const [showReconnecting, setShowReconnecting] = createSignal(false)
|
||||
@@ -1224,7 +1233,7 @@ function App(props: { pair?: DialogPairCredentials }) {
|
||||
</Match>
|
||||
</Switch>
|
||||
</box>
|
||||
<PluginSlot name="app" input={{}} mode="all" />
|
||||
<Region name="app" input={{}} />
|
||||
</Show>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
@@ -51,17 +51,6 @@ export function DialogOpen() {
|
||||
.catch(() => [] as SessionInfo[]),
|
||||
{ initialValue: [] },
|
||||
)
|
||||
const [matched] = createResource(
|
||||
() => {
|
||||
const value = filter().trim()
|
||||
return /^ses_[0-9A-Za-z]{26}$/.test(value) ? value : undefined
|
||||
},
|
||||
(sessionID) =>
|
||||
client.api.session
|
||||
.get({ sessionID })
|
||||
.then((session) => (session.id === sessionID ? session : undefined))
|
||||
.catch(() => undefined),
|
||||
)
|
||||
|
||||
const openTabs = createMemo(
|
||||
() => new Set(sessionTabs.enabled() ? sessionTabs.tabs().map((tab) => tab.sessionID) : []),
|
||||
@@ -71,8 +60,7 @@ export function DialogOpen() {
|
||||
)
|
||||
const sessions = createMemo(() => {
|
||||
const seen = new Set<string>()
|
||||
const match = matched()
|
||||
return [...data.session.list(), ...fetched(), ...(match ? [match] : [])]
|
||||
return [...data.session.list(), ...fetched()]
|
||||
.filter((session) => {
|
||||
if (session.parentID || seen.has(session.id)) return false
|
||||
seen.add(session.id)
|
||||
@@ -99,7 +87,6 @@ export function DialogOpen() {
|
||||
data.session.family(session.id).some((id) => data.session.status(id) === "running")
|
||||
return {
|
||||
title: withTimestampedFallback(session),
|
||||
searchText: session.id,
|
||||
value: { type: "session", sessionID: session.id } as OpenTarget,
|
||||
category: "Sessions",
|
||||
footer: `${name ? `${Locale.truncate(name, 20)} · ` : ""}${timeAgo(session.time.updated)}`,
|
||||
|
||||
@@ -19,9 +19,8 @@ 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, slashTriggerIndex } from "../../prompt/display"
|
||||
import { displayCharAt, mentionTriggerIndex } 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"
|
||||
@@ -40,7 +39,6 @@ export type AutocompleteOption = {
|
||||
isDirectory?: boolean
|
||||
onSelect?: () => void
|
||||
path?: string
|
||||
kind?: "skill"
|
||||
}
|
||||
|
||||
export function Autocomplete(props: {
|
||||
@@ -53,8 +51,6 @@ export function Autocomplete(props: {
|
||||
ref: (ref: AutocompleteRef) => void
|
||||
fileStyleId: number
|
||||
agentStyleId: number
|
||||
skillStyleId: number
|
||||
hasSkill: (id: string) => boolean
|
||||
promptPartTypeId: () => number
|
||||
}) {
|
||||
const editor = useEditorContext()
|
||||
@@ -144,17 +140,14 @@ export function Autocomplete(props: {
|
||||
text: string,
|
||||
part:
|
||||
| { type: "file"; value: NonNullable<PromptInfo["files"]>[number]; path?: string }
|
||||
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] }
|
||||
| { type: "skill"; value: NonNullable<PromptInfo["skills"]>[number] },
|
||||
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[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 prefix = part.type === "skill" ? "/" : "@"
|
||||
const append = prefix + text + (needsSpace ? " " : "")
|
||||
const append = "@" + text + (needsSpace ? " " : "")
|
||||
|
||||
input.cursorOffset = store.index
|
||||
const startCursor = input.logicalCursor
|
||||
@@ -164,12 +157,11 @@ export function Autocomplete(props: {
|
||||
input.deleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col)
|
||||
input.insertText(append)
|
||||
|
||||
const virtualText = prefix + text
|
||||
const virtualText = "@" + text
|
||||
const extmarkStart = store.index
|
||||
const extmarkEnd = extmarkStart + stringWidth(virtualText)
|
||||
|
||||
const styleId =
|
||||
part.type === "file" ? props.fileStyleId : part.type === "skill" ? props.skillStyleId : props.agentStyleId
|
||||
const styleId = part.type === "file" ? props.fileStyleId : props.agentStyleId
|
||||
|
||||
const extmarkId = input.extmarks.create({
|
||||
start: extmarkStart,
|
||||
@@ -203,20 +195,6 @@ 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
|
||||
@@ -455,12 +433,7 @@ export function Autocomplete(props: {
|
||||
results.push({
|
||||
display: "/" + skill.id,
|
||||
description: skill.description,
|
||||
kind: "skill",
|
||||
onSelect: () =>
|
||||
insertPart(skill.id, {
|
||||
type: "skill",
|
||||
value: { id: Skill.ID.make(skill.id), mention: { start: 0, end: 0, text: "" } },
|
||||
}),
|
||||
onSelect: () => insertSlash(skill.id),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -490,11 +463,7 @@ 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()]
|
||||
: store.index === 0
|
||||
? [...commandsValue]
|
||||
: commandsValue.filter((item) => item.kind === "skill")
|
||||
store.visible === "@" ? [...referenceAliasesValue, ...agentsValue, ...mcpResources()] : [...commandsValue]
|
||||
|
||||
if (!searchValue) {
|
||||
return [...nonFileOptions, ...fileOptions]
|
||||
@@ -551,7 +520,7 @@ export function Autocomplete(props: {
|
||||
function select() {
|
||||
const selected = options()[store.selected]
|
||||
if (!selected) return
|
||||
hide(true)
|
||||
hide()
|
||||
selected.onSelect?.()
|
||||
}
|
||||
|
||||
@@ -639,18 +608,14 @@ export function Autocomplete(props: {
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
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)
|
||||
// Sync the prompt store immediately since onContentChange is async
|
||||
props.setPrompt((draft) => {
|
||||
draft.text = input.plainText
|
||||
draft.text = props.input().plainText
|
||||
})
|
||||
}
|
||||
setStore("visible", false)
|
||||
@@ -675,7 +640,9 @@ 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/)
|
||||
props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/) ||
|
||||
// "/<command>" is not the sole content
|
||||
(store.visible === "/" && value.match(/^\S+\s+\S+\s*$/))
|
||||
) {
|
||||
hide()
|
||||
}
|
||||
@@ -686,10 +653,10 @@ export function Autocomplete(props: {
|
||||
const offset = props.input().cursorOffset
|
||||
if (offset === 0) return
|
||||
|
||||
const slash = slashTriggerIndex(value, offset)
|
||||
if (slash !== undefined) {
|
||||
// Check for "/" at position 0 - reopen slash commands
|
||||
if (value.startsWith("/") && !value.slice(0, offset).match(/\s/)) {
|
||||
show("/")
|
||||
setStore("index", slash)
|
||||
setStore("index", 0)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ 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"
|
||||
@@ -53,7 +52,7 @@ import { useData } from "../../context/data"
|
||||
import { useLocation } from "../../context/location"
|
||||
import { Keymap, type KeymapCommand } from "../../context/keymap"
|
||||
import { abbreviateHome } from "../../runtime"
|
||||
import { PluginSlot } from "../../plugin/render"
|
||||
import { Region } from "../../plugin/render"
|
||||
import type { SessionPending } from "@opencode-ai/schema/session-pending"
|
||||
|
||||
export type PromptProps = {
|
||||
@@ -274,7 +273,6 @@ 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()
|
||||
@@ -495,29 +493,12 @@ export function Prompt(props: PromptProps) {
|
||||
<DialogSkill
|
||||
location={currentLocation.current}
|
||||
onSelect={(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.setText(`/${skill} `)
|
||||
setStore("prompt", {
|
||||
...emptyPrompt(),
|
||||
text: `/${skill} `,
|
||||
})
|
||||
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 })
|
||||
}),
|
||||
)
|
||||
input.gotoBufferEnd()
|
||||
}}
|
||||
/>
|
||||
))
|
||||
@@ -658,11 +639,6 @@ 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 },
|
||||
@@ -695,7 +671,6 @@ 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) {
|
||||
@@ -721,16 +696,6 @@ 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
|
||||
@@ -743,7 +708,6 @@ export function Prompt(props: PromptProps) {
|
||||
draft.extmarkToPart = newMap
|
||||
draft.prompt.files = files
|
||||
draft.prompt.agents = agents
|
||||
draft.prompt.skills = skills
|
||||
draft.prompt.pasted = pasted
|
||||
}),
|
||||
)
|
||||
@@ -1019,7 +983,6 @@ 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,
|
||||
@@ -1117,7 +1080,6 @@ 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) => {
|
||||
@@ -1184,7 +1146,6 @@ 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(
|
||||
@@ -1631,76 +1592,93 @@ export function Prompt(props: PromptProps) {
|
||||
/>
|
||||
</box>
|
||||
<box width="100%" flexDirection="row" justifyContent="space-between" gap={2}>
|
||||
<box flexGrow={1} flexShrink={1} minWidth={0}>
|
||||
<Switch>
|
||||
<Match when={status() === "running"}>
|
||||
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
|
||||
<box marginLeft={1}>
|
||||
<Show when={config.animations ?? true} fallback={<text fg={theme.text.subdued}>[⋯]</text>}>
|
||||
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
|
||||
</Show>
|
||||
</box>
|
||||
<text
|
||||
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
|
||||
wrapMode="none"
|
||||
truncate
|
||||
flexShrink={1}
|
||||
>
|
||||
esc{" "}
|
||||
<span
|
||||
style={{
|
||||
fg: store.interrupt > 0 ? theme.background.action.primary.default : theme.text.subdued,
|
||||
}}
|
||||
>
|
||||
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
|
||||
</span>
|
||||
</text>
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={move.progress()}>
|
||||
{(progress) => (
|
||||
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
|
||||
<Spinner color={theme.hue.accent[500]}>
|
||||
{progress()}
|
||||
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
|
||||
</Spinner>
|
||||
</box>
|
||||
)}
|
||||
</Match>
|
||||
<Match when={move.pendingNew()}>
|
||||
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
|
||||
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
|
||||
(new working copy)
|
||||
</text>
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={true}>
|
||||
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
|
||||
{(location) => (
|
||||
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
|
||||
{location()}
|
||||
</text>
|
||||
)}
|
||||
</Show>
|
||||
</Match>
|
||||
</Switch>
|
||||
</box>
|
||||
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
|
||||
{(file) => (
|
||||
<text
|
||||
wrapMode="none"
|
||||
truncate
|
||||
flexShrink={1}
|
||||
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
|
||||
>
|
||||
{file()}
|
||||
</text>
|
||||
)}
|
||||
</Show>
|
||||
<PluginSlot
|
||||
name="prompt.footer.end"
|
||||
<Region
|
||||
name="prompt.footer"
|
||||
input={{ sessionID: props.sessionID, mode: store.mode }}
|
||||
mode="replace"
|
||||
parts={[
|
||||
{
|
||||
id: "status",
|
||||
render: () => (
|
||||
<box flexGrow={1} flexShrink={1} minWidth={0}>
|
||||
<Switch>
|
||||
<Match when={status() === "running"}>
|
||||
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
|
||||
<box marginLeft={1}>
|
||||
<Show
|
||||
when={config.animations ?? true}
|
||||
fallback={<text fg={theme.text.subdued}>[⋯]</text>}
|
||||
>
|
||||
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
|
||||
</Show>
|
||||
</box>
|
||||
<text
|
||||
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
|
||||
wrapMode="none"
|
||||
truncate
|
||||
flexShrink={1}
|
||||
>
|
||||
esc{" "}
|
||||
<span
|
||||
style={{
|
||||
fg:
|
||||
store.interrupt > 0
|
||||
? theme.background.action.primary.default
|
||||
: theme.text.subdued,
|
||||
}}
|
||||
>
|
||||
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
|
||||
</span>
|
||||
</text>
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={move.progress()}>
|
||||
{(progress) => (
|
||||
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
|
||||
<Spinner color={theme.hue.accent[500]}>
|
||||
{progress()}
|
||||
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
|
||||
</Spinner>
|
||||
</box>
|
||||
)}
|
||||
</Match>
|
||||
<Match when={move.pendingNew()}>
|
||||
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
|
||||
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
|
||||
(new working copy)
|
||||
</text>
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={true}>
|
||||
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
|
||||
{(location) => (
|
||||
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
|
||||
{location()}
|
||||
</text>
|
||||
)}
|
||||
</Show>
|
||||
</Match>
|
||||
</Switch>
|
||||
</box>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "file",
|
||||
render: () => (
|
||||
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
|
||||
{(file) => (
|
||||
<text
|
||||
wrapMode="none"
|
||||
truncate
|
||||
flexShrink={1}
|
||||
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
|
||||
>
|
||||
{file()}
|
||||
</text>
|
||||
)}
|
||||
</Show>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</box>
|
||||
</box>
|
||||
@@ -1724,8 +1702,6 @@ 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}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
isExitCommand,
|
||||
isCompactCommand,
|
||||
mentionTriggerIndex,
|
||||
slashTriggerIndex,
|
||||
isNewCommand,
|
||||
movePromptHistory,
|
||||
promptCopy,
|
||||
@@ -51,7 +50,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" | "skill" }>
|
||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
||||
|
||||
type Auto = RunFooterMenuItem & {
|
||||
kind: "mention"
|
||||
@@ -66,12 +65,7 @@ type SlashOption = RunFooterMenuItem & {
|
||||
action?: "skill-menu" | "editor" | "settings"
|
||||
}
|
||||
|
||||
type SkillOption = RunFooterMenuItem & {
|
||||
kind: "skill"
|
||||
id: string
|
||||
}
|
||||
|
||||
type PromptOption = Auto | SlashOption | SkillOption
|
||||
type PromptOption = Auto | SlashOption
|
||||
|
||||
type MenuMode = false | "mention" | "slash"
|
||||
|
||||
@@ -130,9 +124,12 @@ function emptyPrompt(shell: boolean): RunPrompt {
|
||||
}
|
||||
|
||||
function slashQuery(text: string, cursor: number) {
|
||||
const at = slashTriggerIndex(text, cursor)
|
||||
if (at === undefined) return
|
||||
return { at, value: displaySlice(text, at + 1, cursor) }
|
||||
const head = parseSlashHead(text.slice(0, cursor))
|
||||
if (!head || head.end !== cursor) {
|
||||
return
|
||||
}
|
||||
|
||||
return head.name
|
||||
}
|
||||
|
||||
function parseSlashCommand(text: string, commands: RunCommand[] | undefined) {
|
||||
@@ -385,18 +382,10 @@ 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<Array<SlashOption | SkillOption>>(() => {
|
||||
const slashOptions = createMemo<SlashOption[]>(() => {
|
||||
const builtins = [
|
||||
{
|
||||
kind: "slash",
|
||||
@@ -428,7 +417,6 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
}
|
||||
|
||||
return [
|
||||
...skillOptions(),
|
||||
...(showSkillMenu
|
||||
? [
|
||||
{
|
||||
@@ -455,7 +443,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
].sort((a, b) => a.display.localeCompare(b.display))
|
||||
})
|
||||
const options = createMemo<PromptOption[]>(() => {
|
||||
const mixed: PromptOption[] = mode() === "slash" ? (at() === 0 ? slashOptions() : skillOptions()) : mentionOptions()
|
||||
const mixed: PromptOption[] = mode() === "slash" ? slashOptions() : mentionOptions()
|
||||
if (!query()) {
|
||||
return mixed
|
||||
}
|
||||
@@ -471,11 +459,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
|
||||
return fuzzysort
|
||||
.go(next, mixed, {
|
||||
keys: [
|
||||
(item) => (item.kind === "mention" ? item.value : item.kind === "skill" ? item.id : item.name).trimEnd(),
|
||||
"display",
|
||||
"description",
|
||||
],
|
||||
keys: [(item) => (item.kind === "mention" ? item.value : item.name).trimEnd(), "display", "description"],
|
||||
})
|
||||
.map((item) => item.obj)
|
||||
})
|
||||
@@ -532,15 +516,13 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
const prev =
|
||||
part.type === "agent"
|
||||
? (part.source?.value ?? "@" + part.name)
|
||||
: part.type === "skill"
|
||||
? (part.source?.value ?? "/" + part.id)
|
||||
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
|
||||
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
|
||||
if (text !== prev) {
|
||||
continue
|
||||
}
|
||||
|
||||
const copy = structuredClone(part)
|
||||
if (copy.type === "agent" || copy.type === "skill") {
|
||||
if (copy.type === "agent") {
|
||||
copy.source = {
|
||||
start: item.start,
|
||||
end: item.end,
|
||||
@@ -576,7 +558,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" || item.type === "skill")
|
||||
.filter((item): item is Mention => item.type === "file" || item.type === "agent")
|
||||
.map((item) => structuredClone(item))
|
||||
if (!area || area.isDestroyed || type === 0) {
|
||||
return
|
||||
@@ -584,8 +566,8 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
|
||||
const box = area
|
||||
parts.forEach((item, idx) => {
|
||||
const start = item.type === "file" ? item.source?.text.start : item.source?.start
|
||||
const end = item.type === "file" ? item.source?.text.end : item.source?.end
|
||||
const start = item.type === "agent" ? item.source?.start : item.source?.text.start
|
||||
const end = item.type === "agent" ? item.source?.end : item.source?.text.end
|
||||
if (start === undefined || end === undefined) {
|
||||
return
|
||||
}
|
||||
@@ -645,16 +627,16 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
return
|
||||
}
|
||||
|
||||
setAt(slash.at)
|
||||
setQuery(slash.value)
|
||||
setAt(0)
|
||||
setQuery(slash)
|
||||
return
|
||||
}
|
||||
|
||||
if (slash !== undefined) {
|
||||
setAt(slash.at)
|
||||
setAt(0)
|
||||
menu.reset()
|
||||
setMode("slash")
|
||||
setQuery(slash.value)
|
||||
setQuery(slash)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -800,7 +782,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
}
|
||||
|
||||
const cursor = area.cursorOffset
|
||||
const startOffset = at()
|
||||
const startOffset = mode() === "slash" ? 0 : at()
|
||||
area.cursorOffset = startOffset
|
||||
const start = area.logicalCursor
|
||||
area.cursorOffset = cursor
|
||||
@@ -846,39 +828,6 @@ 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({
|
||||
@@ -1244,7 +1193,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
||||
}
|
||||
|
||||
const parsed =
|
||||
command || next.parts.some((part) => part.type === "skill") || next.mode === "shell" || isNewCommand(next.text)
|
||||
command || 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" | "skill" }>
|
||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
||||
|
||||
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" && part.type !== "skill") return
|
||||
if (part.type !== "file" && part.type !== "agent") return
|
||||
return promptPartMention(part)
|
||||
}),
|
||||
)
|
||||
|
||||
return parts.flatMap((part, index) => {
|
||||
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return [part]
|
||||
if (part.type !== "file" && part.type !== "agent") 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 === "file" ? part.source?.text : part.source
|
||||
const source = part.type === "agent" ? part.source : part.source?.text
|
||||
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" || part.type === "skill") {
|
||||
if (part.type === "agent") {
|
||||
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, slashTriggerIndex } from "../prompt/display"
|
||||
export { displayCharAt, displaySlice, mentionTriggerIndex } from "../prompt/display"
|
||||
import { stringWidth } from "../util/string-width"
|
||||
import type { RunPrompt } from "./types"
|
||||
|
||||
|
||||
@@ -288,21 +288,6 @@ 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}`
|
||||
}
|
||||
@@ -373,12 +358,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, skillID = messageID): StreamCommit {
|
||||
function skillCommit(messageID: string, name: string): StreamCommit {
|
||||
return {
|
||||
kind: "system",
|
||||
source: "system",
|
||||
messageID,
|
||||
partID: `skill:${skillID}`,
|
||||
partID: `skill:${messageID}`,
|
||||
text: `→ Skill "${name}"`,
|
||||
phase: "start",
|
||||
}
|
||||
@@ -652,10 +637,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
||||
state.messageIDs.add(message.id)
|
||||
if (!render) return
|
||||
if (reuseVisibleWait && waiting) return
|
||||
write([
|
||||
...(message.skills ?? []).map((skill) => skillCommit(message.id, skill.name, skill.id)),
|
||||
{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id },
|
||||
])
|
||||
write([{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id }])
|
||||
return
|
||||
}
|
||||
if (message.type === "skill") {
|
||||
@@ -1636,7 +1618,6 @@ 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(
|
||||
@@ -1646,7 +1627,6 @@ 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 },
|
||||
@@ -1666,7 +1646,6 @@ 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,7 +47,6 @@ 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,6 +1,24 @@
|
||||
import { PluginContextProvider } from "@opencode-ai/plugin/tui"
|
||||
import type { JSX } from "solid-js"
|
||||
import type { Context, Dialog, Page, Slot, SlotMap, Toast } from "@opencode-ai/plugin/tui/context"
|
||||
import type {
|
||||
Context,
|
||||
Dialog,
|
||||
Page,
|
||||
RegionClaim,
|
||||
RegionName,
|
||||
Slot,
|
||||
SlotMap,
|
||||
SlotName,
|
||||
Toast,
|
||||
} from "@opencode-ai/plugin/tui/context"
|
||||
import type { Placement } from "./structure"
|
||||
|
||||
// A registered claim as stored by the plugin provider's registry.
|
||||
export type SlotClaim = {
|
||||
readonly region: RegionName
|
||||
readonly placement: Placement
|
||||
readonly render: Slot
|
||||
}
|
||||
import { infoStringToFiletype, type MarkdownCodeBlockRenderer } from "@opentui/core"
|
||||
import { useRenderer } from "@opentui/solid"
|
||||
import { useClient } from "../context/client"
|
||||
@@ -29,12 +47,27 @@ export type Dispose = () => Promise<void>
|
||||
export type Registry = {
|
||||
has(kind: "routes" | "slots" | "markdown", name: string): boolean
|
||||
set(kind: "routes", name: string, page: Page): void
|
||||
set(kind: "slots", name: string, slot: Slot): void
|
||||
set(kind: "slots", name: string, claim: SlotClaim): void
|
||||
set(kind: "markdown", name: string, render: MarkdownCodeBlockRenderer): void
|
||||
remove(kind: "routes" | "slots" | "markdown", name: string): void
|
||||
active(): boolean
|
||||
}
|
||||
|
||||
// Position-encoded legacy slot names map onto the region model. Append
|
||||
// slots become end-edge claims. Host-declared "replace" slots on partless
|
||||
// regions become root takeovers, reproducing their old last-registrant-wins
|
||||
// semantics exactly. One deliberate change: "prompt.footer.end" was also
|
||||
// last-registrant-wins, but maps to an end-edge claim — chips from several
|
||||
// plugins now coexist instead of silently shadowing each other.
|
||||
const legacySlots: Record<SlotName, { readonly region: RegionName; readonly placement: Placement }> = {
|
||||
app: { region: "app", placement: { at: "end" } },
|
||||
"home.footer": { region: "home.footer", placement: { replace: "home.footer" } },
|
||||
"prompt.footer.end": { region: "prompt.footer", placement: { at: "end" } },
|
||||
"session.composer.top": { region: "session.composer.top", placement: { at: "end" } },
|
||||
"sidebar.content": { region: "sidebar.content", placement: { at: "end" } },
|
||||
"sidebar.footer": { region: "sidebar.footer", placement: { replace: "sidebar.footer" } },
|
||||
}
|
||||
|
||||
// The host services a plugin context adapts. Collected once by the provider
|
||||
// (hooks must run during component setup) and shared by every activation.
|
||||
export function usePluginHost() {
|
||||
@@ -70,6 +103,7 @@ export function createPluginContext(input: {
|
||||
}): Context {
|
||||
const host = input.host
|
||||
let context: Context
|
||||
let claims = 0
|
||||
// Every dialog and registered render is wrapped so plugin components can
|
||||
// reach their own context through usePlugin().
|
||||
const provide = (render: () => JSX.Element) => (
|
||||
@@ -184,12 +218,45 @@ export function createPluginContext(input: {
|
||||
return true
|
||||
},
|
||||
},
|
||||
slot(name, render) {
|
||||
if (input.registry.has("slots", name)) throw new Error(`Slot already registered: ${name}`)
|
||||
// The registration map erases the slot-specific input type.
|
||||
input.registry.set("slots", name, ((slotInput: SlotMap[typeof name]) =>
|
||||
provide(() => render(slotInput))) as Slot)
|
||||
return registration("slots", name)
|
||||
slot(name: SlotName | RegionName, value: Slot | RegionClaim) {
|
||||
// Legacy form: position-encoded name plus a bare render function.
|
||||
if (typeof value === "function") {
|
||||
if (input.registry.has("slots", name)) throw new Error(`Slot already registered: ${name}`)
|
||||
const mapped = legacySlots[name as SlotName]
|
||||
// Reachable only from untyped plugin code; fail with the name
|
||||
// instead of a property access on undefined.
|
||||
if (!mapped) throw new Error(`Unknown slot: ${name}`)
|
||||
input.registry.set("slots", name, {
|
||||
region: mapped.region,
|
||||
placement: mapped.placement,
|
||||
// The registration map erases the slot-specific input type.
|
||||
render: ((slotInput: SlotMap[SlotName]) => provide(() => value(slotInput))) as Slot,
|
||||
})
|
||||
return registration("slots", name)
|
||||
}
|
||||
// Region form: a placement plus render. Keys are counter-suffixed so
|
||||
// one plugin may claim several places in the same region; order
|
||||
// within the plugin is registration order.
|
||||
const key = `${name}#${claims++}`
|
||||
// Rebuilt field-by-field rather than rest-spread so malformed input
|
||||
// from untyped plugins normalizes to exactly one placement key — a
|
||||
// claim carrying two keys would match twice in the resolver.
|
||||
const placement: Placement =
|
||||
value.at !== undefined
|
||||
? { at: value.at }
|
||||
: value.before !== undefined
|
||||
? { before: value.before }
|
||||
: value.after !== undefined
|
||||
? { after: value.after }
|
||||
: { replace: value.replace }
|
||||
input.registry.set("slots", key, {
|
||||
// The overloads correlate the second argument's shape with the
|
||||
// name: an object value implies a region name.
|
||||
region: name as RegionName,
|
||||
placement,
|
||||
render: ((slotInput: SlotMap[SlotName]) => provide(() => value.render(slotInput))) as Slot,
|
||||
})
|
||||
return registration("slots", key)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -14,15 +14,16 @@ import {
|
||||
import path from "path"
|
||||
import { stat } from "fs/promises"
|
||||
import { fileURLToPath, pathToFileURL } from "url"
|
||||
import type { Page, Slot, SlotName } from "@opencode-ai/plugin/tui/context"
|
||||
import { createStore, produce, reconcile as reconcileStore } from "solid-js/store"
|
||||
import type { Page, Slot } from "@opencode-ai/plugin/tui/context"
|
||||
import type { Claim } from "./structure"
|
||||
import { createStore, produce, reconcile as reconcileStore, unwrap } from "solid-js/store"
|
||||
import { isDeepEqual } from "remeda"
|
||||
import "#runtime-plugin-support"
|
||||
import { useConfig } from "../config"
|
||||
import { useTuiLifecycle } from "../context/runtime"
|
||||
import { errorMessage } from "../util/error"
|
||||
import { builtins } from "./builtins"
|
||||
import { createPluginContext, usePluginHost, type Dispose } from "./api"
|
||||
import { createPluginContext, usePluginHost, type Dispose, type SlotClaim } from "./api"
|
||||
import { createSourceWatcher } from "./watch"
|
||||
import { discoverTuiPlugins, freshSpecifier, localSource } from "./discovery"
|
||||
|
||||
@@ -46,9 +47,7 @@ type Value = {
|
||||
readonly list: () => ReadonlyArray<State>
|
||||
readonly registered: () => ReadonlyArray<RegisteredPlugin>
|
||||
readonly route: (id: string, name: string) => Page["render"] | undefined
|
||||
readonly slot: <Name extends SlotName>(
|
||||
name: Name,
|
||||
) => ReadonlyArray<{ readonly id: string; readonly render: Slot<Name> }>
|
||||
readonly claims: (region: string) => ReadonlyArray<Claim<Slot>>
|
||||
readonly markdown: () => MarkdownOptions["renderNode"]
|
||||
readonly activate: (id: string) => Promise<boolean>
|
||||
readonly deactivate: (id: string) => Promise<boolean>
|
||||
@@ -62,7 +61,7 @@ type Registration = {
|
||||
options?: Readonly<Record<string, any>>
|
||||
active: boolean
|
||||
routes: Record<string, Page>
|
||||
slots: Record<string, Slot>
|
||||
slots: Record<string, SlotClaim>
|
||||
markdown: Record<string, MarkdownCodeBlockRenderer>
|
||||
cleanups: Dispose[]
|
||||
}
|
||||
@@ -119,7 +118,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
|
||||
owned,
|
||||
registry: {
|
||||
has: (kind, name) => Boolean(store.registrations[id]?.[kind][name]),
|
||||
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | Slot | MarkdownCodeBlockRenderer) =>
|
||||
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | SlotClaim | MarkdownCodeBlockRenderer) =>
|
||||
setStore("registrations", id, kind, name, () => value),
|
||||
remove: (kind, name) =>
|
||||
setStore(
|
||||
@@ -387,7 +386,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
|
||||
host.toast.show({ variant: "error", title: "Plugin", message: `${state.target}: ${state.error}` })
|
||||
setStore("states", reconcileStore(states))
|
||||
}
|
||||
const slotItems = new WeakMap<Slot, { readonly id: string; readonly render: Slot }>()
|
||||
const slotItems = new WeakMap<Slot, Claim<Slot>>()
|
||||
createEffect(
|
||||
on(
|
||||
() => JSON.stringify(config.data.plugins ?? []),
|
||||
@@ -436,19 +435,27 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
|
||||
active: plugin.active,
|
||||
})),
|
||||
route: (id, name) => store.registrations[id]?.routes[name]?.render,
|
||||
slot: (name) =>
|
||||
Object.entries(store.registrations).flatMap(([id, registration]) => {
|
||||
const render = registration.active ? registration.slots[name] : undefined
|
||||
if (!render) return []
|
||||
// <For> diffs rows by reference; a stable wrapper per render
|
||||
// function keeps untouched plugins' slot rows (and their state)
|
||||
// alive across other plugins' reloads.
|
||||
const cached = slotItems.get(render)
|
||||
if (cached) return [cached]
|
||||
const item = { id, render }
|
||||
slotItems.set(render, item)
|
||||
return [item]
|
||||
}),
|
||||
// Claims come back in enable order: registration-store key order
|
||||
// across plugins (generations preserve key positions in place), then
|
||||
// registration order within one plugin. The resolver's last-wins
|
||||
// rules depend on it.
|
||||
claims: (region) =>
|
||||
Object.entries(store.registrations).flatMap(([id, registration]) =>
|
||||
Object.entries(registration.active ? registration.slots : {}).flatMap(([key, slot]) => {
|
||||
if (slot.region !== region) return []
|
||||
// <For> diffs rows by reference; a stable claim per render
|
||||
// function keeps untouched plugins' slot rows (and their
|
||||
// state) alive across other plugins' reloads.
|
||||
const cached = slotItems.get(slot.render)
|
||||
if (cached) return [cached]
|
||||
// Placements are immutable once registered; unwrap the store
|
||||
// proxy so the resolver's `in` checks hit plain objects
|
||||
// instead of subscribing tracked scopes to every key probe.
|
||||
const item = { key: `${id}/${key}`, plugin: id, placement: unwrap(slot.placement), render: slot.render }
|
||||
slotItems.set(slot.render, item)
|
||||
return [item]
|
||||
}),
|
||||
),
|
||||
markdown,
|
||||
// Manual dialog toggles join the same chain as reconciles so a
|
||||
// toggle mid-reload cannot mix registrations across generations.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createComponent, createMemo, ErrorBoundary, For, mergeProps, onMount, Show, type JSX, type ParentProps } from "solid-js"
|
||||
import type { SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
|
||||
import type { RegionMap, RegionName, Slot, SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
|
||||
import { resolveStructure, type Entry, type Part } from "./structure"
|
||||
import { useRoute } from "../context/route"
|
||||
import { useToast } from "../ui/toast"
|
||||
import { errorMessage } from "../util/error"
|
||||
@@ -54,31 +55,69 @@ export function PluginRoute(props: { readonly fallback: (id: string, name: strin
|
||||
)
|
||||
}
|
||||
|
||||
export function PluginSlot<Name extends SlotName>(props: {
|
||||
type HostRender = () => JSX.Element
|
||||
|
||||
// One extensible area of the host UI: the host's parts plus every active
|
||||
// plugin claim, resolved into one ordered child list. Placement policy —
|
||||
// takeover suppression, last-enabled-wins, missing-anchor degradation —
|
||||
// lives in resolveStructure; this component only renders the result.
|
||||
export function Region<Name extends RegionName>(props: {
|
||||
readonly name: Name
|
||||
readonly input: SlotMap[Name]
|
||||
readonly mode: "all" | "replace"
|
||||
readonly input: RegionMap[Name]["input"]
|
||||
readonly parts?: ReadonlyArray<Part<HostRender, RegionMap[Name]["part"]>>
|
||||
}) {
|
||||
const plugins = usePlugin()
|
||||
const renderers = createMemo(() => {
|
||||
const items = plugins.slot(props.name)
|
||||
if (props.mode === "replace") return items.slice(-1)
|
||||
return items
|
||||
})
|
||||
// resolveStructure builds fresh entry objects each run, but <For> diffs
|
||||
// rows by reference: cache entries so untouched rows (and the plugin
|
||||
// state inside them) survive unrelated claim changes. Part entries key on
|
||||
// their documented-stable id — render-function identity would break if
|
||||
// the compiled parts prop ever rebuilt its closures. Claim entries key on
|
||||
// the render function (weakly, so hot-reloaded generations collect).
|
||||
const partEntries = new Map<string, Entry<HostRender, Slot>>()
|
||||
const claimEntries = new WeakMap<Slot, Entry<HostRender, Slot>>()
|
||||
const entries = createMemo(
|
||||
() =>
|
||||
resolveStructure<HostRender, Slot>({
|
||||
region: props.name,
|
||||
parts: props.parts ?? [],
|
||||
claims: plugins.claims(props.name),
|
||||
}).entries.map((entry) => {
|
||||
if (entry.kind === "part") {
|
||||
const cached = partEntries.get(entry.id)
|
||||
if (cached) return cached
|
||||
partEntries.set(entry.id, entry)
|
||||
return entry
|
||||
}
|
||||
const cached = claimEntries.get(entry.claim.render)
|
||||
if (cached) return cached
|
||||
claimEntries.set(entry.claim.render, entry)
|
||||
return entry
|
||||
}),
|
||||
[] as ReadonlyArray<Entry<HostRender, Slot>>,
|
||||
// Rows are reference-stable, so an elementwise comparison makes a claim
|
||||
// change in some other region a complete no-op for this one.
|
||||
{ equals: (a, b) => a.length === b.length && a.every((entry, index) => entry === b[index]) },
|
||||
)
|
||||
return (
|
||||
<For each={renderers()}>
|
||||
{(item) => (
|
||||
<PluginBoundary id={item.id} where={`slot ${props.name}`}>
|
||||
{
|
||||
// Component semantics: the render body runs once and untracked, so
|
||||
// signals and intervals created inside are stable, while props stay
|
||||
// reactive through the merged getter. A bare item.render(props.input)
|
||||
// call would run inside the host's tracked scope and re-execute the
|
||||
// whole body (resetting plugin state) on every tracked read.
|
||||
createComponent(item.render, mergeProps(() => props.input) as SlotMap[Name])
|
||||
}
|
||||
</PluginBoundary>
|
||||
)}
|
||||
<For each={entries()}>
|
||||
{(entry) =>
|
||||
// A row's entry object is cached, so its kind never changes within
|
||||
// the row's lifetime — a plain branch is safe here.
|
||||
entry.kind === "part" ? (
|
||||
entry.render()
|
||||
) : (
|
||||
<PluginBoundary id={entry.claim.plugin} where={`region ${props.name}`}>
|
||||
{
|
||||
// Component semantics: the render body runs once and untracked, so
|
||||
// signals and intervals created inside are stable, while props stay
|
||||
// reactive through the merged getter. A bare render(props.input)
|
||||
// call would run inside the host's tracked scope and re-execute the
|
||||
// whole body (resetting plugin state) on every tracked read.
|
||||
createComponent(entry.claim.render, mergeProps(() => props.input) as SlotMap[SlotName])
|
||||
}
|
||||
</PluginBoundary>
|
||||
)
|
||||
}
|
||||
</For>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Pure resolution of a region's structure: the host's part tree plus plugin
|
||||
// claims in, an ordered render list plus suppressions out. No solid, no I/O —
|
||||
// every policy rule (takeover, hierarchy-beats-timeline, last-enabled-wins,
|
||||
// missing-anchor degradation) is testable as a data transform.
|
||||
|
||||
// Mirrors the public RegionPlacement type (plugin package) with part ids
|
||||
// erased to strings so the resolver stays independent of the region map.
|
||||
// Keep the two unions' variants in sync.
|
||||
export type Placement =
|
||||
| { readonly at: "start" | "end" }
|
||||
| { readonly before: string }
|
||||
| { readonly after: string }
|
||||
| { readonly replace: string }
|
||||
|
||||
// One plugin's registered slot, in enable order within the claims array.
|
||||
export type Claim<Render> = {
|
||||
readonly key: string
|
||||
readonly plugin: string
|
||||
readonly placement: Placement
|
||||
readonly render: Render
|
||||
}
|
||||
|
||||
// Host furniture: a leaf renders, a container groups — never both. Part ids
|
||||
// are the stable anchor vocabulary and must be unique within a region.
|
||||
export type Part<Render, Id extends string = string> =
|
||||
| { readonly id: Id; readonly render: Render; readonly parts?: never }
|
||||
| { readonly id: Id; readonly parts: ReadonlyArray<Part<Render, Id>>; readonly render?: never }
|
||||
|
||||
export type Entry<PartRender, ClaimRender> =
|
||||
| { readonly kind: "part"; readonly id: string; readonly render: PartRender }
|
||||
| { readonly kind: "claim"; readonly claim: Claim<ClaimRender> }
|
||||
|
||||
export function resolveStructure<PartRender extends {}, ClaimRender>(input: {
|
||||
readonly region: string
|
||||
readonly parts: ReadonlyArray<Part<PartRender>>
|
||||
readonly claims: ReadonlyArray<Claim<ClaimRender>>
|
||||
}): {
|
||||
readonly entries: ReadonlyArray<Entry<PartRender, ClaimRender>>
|
||||
readonly suppressed: ReadonlyArray<{ readonly claim: Claim<ClaimRender>; readonly by: Claim<ClaimRender> }>
|
||||
readonly degraded: ReadonlyArray<Claim<ClaimRender>>
|
||||
} {
|
||||
// Root takeover: the region's content is the winning claim, full stop.
|
||||
// Every other claim — including edge-anchored ones — is suppressed, so a
|
||||
// theme can never be silently decorated by chips it didn't plan for.
|
||||
const takeover = input.claims
|
||||
.filter((claim) => "replace" in claim.placement && claim.placement.replace === input.region)
|
||||
.at(-1)
|
||||
if (takeover)
|
||||
return {
|
||||
entries: [{ kind: "claim", claim: takeover }],
|
||||
suppressed: input.claims.filter((claim) => claim !== takeover).map((claim) => ({ claim, by: takeover })),
|
||||
degraded: [],
|
||||
}
|
||||
|
||||
const known = new Set<string>()
|
||||
const register = (parts: ReadonlyArray<Part<PartRender>>) => {
|
||||
for (const part of parts) {
|
||||
known.add(part.id)
|
||||
if (part.parts !== undefined) register(part.parts)
|
||||
}
|
||||
}
|
||||
register(input.parts)
|
||||
|
||||
const entries: Entry<PartRender, ClaimRender>[] = []
|
||||
const suppressed: { claim: Claim<ClaimRender>; by: Claim<ClaimRender> }[] = []
|
||||
|
||||
// A container takeover orphans everything anchored to (or replacing) the
|
||||
// parts inside it. Recorded so the host can surface it (plugins dialog,
|
||||
// in a follow-up) — never silently dropped.
|
||||
const suppressSubtree = (parts: ReadonlyArray<Part<PartRender>>, by: Claim<ClaimRender>) => {
|
||||
for (const part of parts) {
|
||||
for (const claim of input.claims) if (anchor(claim.placement) === part.id) suppressed.push({ claim, by })
|
||||
if (part.parts !== undefined) suppressSubtree(part.parts, by)
|
||||
}
|
||||
}
|
||||
|
||||
const walk = (parts: ReadonlyArray<Part<PartRender>>) => {
|
||||
for (const part of parts) {
|
||||
for (const claim of input.claims)
|
||||
if ("before" in claim.placement && claim.placement.before === part.id) entries.push({ kind: "claim", claim })
|
||||
// Replacing keeps the part's position: before/after anchors on the
|
||||
// replaced id stay valid, only the content (and subtree) changes hands.
|
||||
const replacers = input.claims.filter(
|
||||
(claim) => "replace" in claim.placement && claim.placement.replace === part.id,
|
||||
)
|
||||
const winner = replacers.at(-1)
|
||||
if (winner) {
|
||||
for (const loser of replacers.slice(0, -1)) suppressed.push({ claim: loser, by: winner })
|
||||
entries.push({ kind: "claim", claim: winner })
|
||||
// Hierarchy beats timeline: claims into the subtree lose to the
|
||||
// container's winner no matter when they were enabled.
|
||||
if (part.parts !== undefined) suppressSubtree(part.parts, winner)
|
||||
}
|
||||
if (!winner && part.parts !== undefined) walk(part.parts)
|
||||
if (!winner && part.render !== undefined) entries.push({ kind: "part", id: part.id, render: part.render })
|
||||
for (const claim of input.claims)
|
||||
if ("after" in claim.placement && claim.placement.after === part.id) entries.push({ kind: "claim", claim })
|
||||
}
|
||||
}
|
||||
|
||||
for (const claim of input.claims)
|
||||
if ("at" in claim.placement && claim.placement.at === "start") entries.push({ kind: "claim", claim })
|
||||
walk(input.parts)
|
||||
for (const claim of input.claims)
|
||||
if ("at" in claim.placement && claim.placement.at === "end") entries.push({ kind: "claim", claim })
|
||||
|
||||
// A claim aimed at a part the host no longer publishes degrades to the
|
||||
// region's end rather than vanishing: an anchor rename must never silently
|
||||
// cost a plugin its render. Degraded claims land after end-edge claims,
|
||||
// in enable order.
|
||||
const degraded = input.claims.filter((claim) => {
|
||||
const id = anchor(claim.placement)
|
||||
return id !== undefined && !known.has(id)
|
||||
})
|
||||
for (const claim of degraded) entries.push({ kind: "claim", claim })
|
||||
|
||||
return { entries, suppressed, degraded }
|
||||
}
|
||||
|
||||
function anchor(placement: Placement) {
|
||||
if ("before" in placement) return placement.before
|
||||
if ("after" in placement) return placement.after
|
||||
if ("replace" in placement) return placement.replace
|
||||
return undefined
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
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>
|
||||
|
||||
type ProjectedPrompt = Pick<Prompt, "text" | "files" | "agents"> & {
|
||||
readonly skills?: ReadonlyArray<{ readonly id: string; readonly mention?: PromptInput.SkillAttachment["mention"] }>
|
||||
}
|
||||
|
||||
export function projectedPromptInput(input: ProjectedPrompt): EditablePromptInput {
|
||||
export function projectedPromptInput(input: Pick<Prompt, "text" | "files" | "agents">): EditablePromptInput {
|
||||
return {
|
||||
text: input.text,
|
||||
files: input.files?.map((file) => ({
|
||||
@@ -21,9 +16,5 @@ export function projectedPromptInput(input: ProjectedPrompt): EditablePromptInpu
|
||||
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,14 +48,3 @@ 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 { PromptInput } from "@opencode-ai/schema"
|
||||
import type { SessionPromptInput } from "@opencode-ai/client"
|
||||
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<PromptInput.Prompt, "text" | "files" | "agents" | "skills">> & {
|
||||
export type PromptInfo = Types.DeepMutable<Pick<SessionPromptInput, "text" | "files" | "agents">> & {
|
||||
pasted: PastedText[]
|
||||
mode?: "normal" | "shell"
|
||||
}
|
||||
|
||||
export type PromptPartRef = {
|
||||
type: "file" | "agent" | "skill" | "pasted"
|
||||
type: "file" | "agent" | "pasted"
|
||||
index: number
|
||||
}
|
||||
|
||||
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], skills: [], pasted: [] })
|
||||
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], pasted: [] })
|
||||
|
||||
export const MAX_HISTORY_ENTRIES = 50
|
||||
|
||||
|
||||
@@ -54,11 +54,9 @@ 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) => {
|
||||
@@ -71,7 +69,6 @@ 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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +91,6 @@ 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) })),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useEditorContext } from "../context/editor"
|
||||
import { useData } from "../context/data"
|
||||
import { useLocation } from "../context/location"
|
||||
import { FormPrompt } from "./session/form"
|
||||
import { PluginSlot } from "../plugin/render"
|
||||
import { Region } from "../plugin/render"
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
|
||||
let once = false
|
||||
@@ -91,7 +91,7 @@ export function Home() {
|
||||
<box flexGrow={1} minHeight={0} />
|
||||
</box>
|
||||
<box width="100%" flexShrink={0}>
|
||||
<PluginSlot name="home.footer" input={{}} mode="replace" />
|
||||
<Region name="home.footer" input={{}} />
|
||||
</box>
|
||||
<Show when={forms()[0]?.id} keyed>
|
||||
{(_) => {
|
||||
|
||||
@@ -82,7 +82,7 @@ import { collapseToolOutput } from "../../util/collapse-tool-output"
|
||||
import { Keymap, type KeymapCommand } from "../../context/keymap"
|
||||
import { usePathFormatter } from "../../context/path-format"
|
||||
import { useLocation } from "../../context/location"
|
||||
import { PluginSlot } from "../../plugin/render"
|
||||
import { Region } from "../../plugin/render"
|
||||
import { usePlugin } from "../../plugin/context"
|
||||
import {
|
||||
cacheReuseDrop,
|
||||
@@ -1072,7 +1072,7 @@ export function Session() {
|
||||
<Show when={!composer.open && !disabled() && queuedPrompts().length > 0}>
|
||||
<QueuedPromptDock prompts={queuedPrompts()} onOpen={openQueuedPrompts} />
|
||||
</Show>
|
||||
<PluginSlot name="session.composer.top" input={{ sessionID: route.sessionID }} mode="all" />
|
||||
<Region name="session.composer.top" input={{ sessionID: route.sessionID }} />
|
||||
<Composer
|
||||
sessionID={route.sessionID}
|
||||
open={composer.open || (!!session()?.parentID && forms().length === 0)}
|
||||
@@ -1631,13 +1631,21 @@ function AssistantFooter(props: { message: SessionMessageAssistant }) {
|
||||
const interrupted = createMemo(() => props.message.error?.message === "Step interrupted")
|
||||
return (
|
||||
<>
|
||||
<Show when={props.message.error && !interrupted() && !props.message.retry}>
|
||||
<box paddingLeft={3}>
|
||||
<text fg={theme.text.feedback.error.default}>Error: {errorMessage(props.message.error)}</text>
|
||||
<Show when={props.message.error && !interrupted()}>
|
||||
<box
|
||||
border={["left"]}
|
||||
paddingTop={1}
|
||||
paddingBottom={1}
|
||||
paddingLeft={2}
|
||||
backgroundColor={theme.background.default}
|
||||
customBorderChars={SplitBorder.customBorderChars}
|
||||
borderColor={theme.text.feedback.error.default}
|
||||
>
|
||||
<text fg={theme.text.subdued}>{errorMessage(props.message.error)}</text>
|
||||
</box>
|
||||
</Show>
|
||||
<AssistantRetry retry={props.message.retry} />
|
||||
<box paddingLeft={3} marginTop={props.message.retry || (props.message.error && !interrupted()) ? 1 : 0}>
|
||||
<box paddingLeft={3} marginTop={props.message.error && !interrupted() ? 1 : 0}>
|
||||
<text>
|
||||
<span style={{ fg: props.message.error ? theme.text.subdued : local.agent.color(props.message.agent) }}>
|
||||
{Locale.titlecase(props.message.agent)}
|
||||
@@ -1911,7 +1919,6 @@ 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
|
||||
@@ -1927,7 +1934,7 @@ function UserMessage(props: { message: SessionMessageUser }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Show when={props.message.text.trim() || files().length || skills().length}>
|
||||
<Show when={props.message.text.trim() || files().length}>
|
||||
<box
|
||||
border={["left"]}
|
||||
borderColor={delivery() ? theme.border.default : color()}
|
||||
@@ -1972,28 +1979,6 @@ 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()}>
|
||||
@@ -2060,9 +2045,9 @@ function AssistantRetry(props: { retry: SessionMessageAssistant["retry"] }) {
|
||||
return (
|
||||
<Show when={props.retry}>
|
||||
{(retry) => (
|
||||
<box paddingLeft={3}>
|
||||
<text fg={theme.text.feedback.warning.default}>
|
||||
⚠ Retry attempt {retry().attempt} scheduled: {retry().error.message}
|
||||
<box paddingLeft={3} marginTop={1}>
|
||||
<text fg={theme.text.subdued}>
|
||||
Retry attempt {retry().attempt} scheduled: {retry().error.message} [{retry().error.type}]
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useData } from "../../context/data"
|
||||
import { createMemo, Show } from "solid-js"
|
||||
import { useTheme } from "../../context/theme"
|
||||
import { useConfig } from "../../config"
|
||||
import { PluginSlot } from "../../plugin/render"
|
||||
import { Region } from "../../plugin/render"
|
||||
import { withTimestampedFallback } from "@opencode-ai/util/session-title-fallback"
|
||||
|
||||
import { getScrollAcceleration } from "../../util/scroll"
|
||||
@@ -52,12 +52,12 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
|
||||
<text fg={theme.text.subdued}>{session()!.location.workspaceID}</text>
|
||||
</Show>
|
||||
</box>
|
||||
<PluginSlot name="sidebar.content" input={{ sessionID: props.sessionID }} mode="all" />
|
||||
<Region name="sidebar.content" input={{ sessionID: props.sessionID }} />
|
||||
</box>
|
||||
</scrollbox>
|
||||
|
||||
<box flexShrink={0} gap={1} paddingTop={1}>
|
||||
<PluginSlot name="sidebar.footer" input={{}} mode="replace" />
|
||||
<Region name="sidebar.footer" input={{}} />
|
||||
</box>
|
||||
</box>
|
||||
</Show>
|
||||
|
||||
@@ -54,40 +54,6 @@ test("selecting an unhydrated session preserves its location", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("finds and opens an exact session ID outside the recent list", async () => {
|
||||
const sessionID = "ses_04a7a3d82ffeIphUJgd3SnEqiv"
|
||||
const remote = { directory: "/tmp/opencode/archive", workspaceID: "ws_archive" }
|
||||
const fixture = await renderOpen((url) => {
|
||||
if (url.pathname === "/api/session") return json({ data: [], cursor: {} })
|
||||
if (url.pathname !== `/api/session/${sessionID}`) return undefined
|
||||
return json({
|
||||
data: {
|
||||
id: sessionID,
|
||||
projectID: "proj_archive",
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 1, updated: 2 },
|
||||
title: "TUI plugin slot API v2",
|
||||
location: remote,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
try {
|
||||
await fixture.app.waitForFrame((frame) => frame.includes("Search sessions and projects"))
|
||||
await fixture.app.mockInput.typeText(sessionID)
|
||||
await fixture.app.waitForFrame((frame) => frame.includes("TUI plugin slot API v2"))
|
||||
|
||||
fixture.app.mockInput.pressEnter()
|
||||
await fixture.app.waitFor(() => fixture.route.data.type === "session")
|
||||
|
||||
expect(fixture.route.data).toEqual({ type: "session", sessionID })
|
||||
expect(fixture.location.ref).toEqual(remote)
|
||||
} finally {
|
||||
fixture.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("shows the current project and opens its root", async () => {
|
||||
const root = "/tmp/opencode/project"
|
||||
const subfolder = `${root}/packages/tui`
|
||||
|
||||
@@ -1262,44 +1262,6 @@ 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()
|
||||
}
|
||||
})
|
||||
|
||||
// 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 () => {
|
||||
|
||||
@@ -2749,7 +2749,7 @@ describe("V2 mini transport", () => {
|
||||
variant: undefined,
|
||||
prompt: {
|
||||
messageID: "msg_cmd",
|
||||
text: "/deploy prod /api-design",
|
||||
text: "/deploy prod",
|
||||
parts: [
|
||||
{
|
||||
type: "file",
|
||||
@@ -2757,11 +2757,6 @@ describe("V2 mini transport", () => {
|
||||
filename: "mentioned.txt",
|
||||
source: { type: "file", text: { start: 8, end: 12, value: "prod" } },
|
||||
},
|
||||
{
|
||||
type: "skill",
|
||||
id: "api-design",
|
||||
source: { start: 13, end: 24, value: "/api-design" },
|
||||
},
|
||||
],
|
||||
command: { name: "deploy", arguments: "prod" },
|
||||
},
|
||||
@@ -2784,7 +2779,6 @@ describe("V2 mini transport", () => {
|
||||
mention: { start: 8, end: 12, text: "prod" },
|
||||
},
|
||||
],
|
||||
skills: [{ id: "api-design", mention: { start: 13, end: 24, text: "/api-design" } }],
|
||||
delivery: "steer",
|
||||
})
|
||||
// Selection rides the command payload; no separate client-side switch.
|
||||
@@ -2857,75 +2851,6 @@ describe("V2 mini transport", () => {
|
||||
await transport.close()
|
||||
})
|
||||
|
||||
test("sends inline skill attachments with a normal prompt", async () => {
|
||||
const events = feed()
|
||||
events.push(connected())
|
||||
const client = sdk({ streams: [events] })
|
||||
const ui = footer()
|
||||
const transport = await createSessionTransport({
|
||||
sdk: client,
|
||||
sessionID: "ses_1",
|
||||
thinking: false,
|
||||
footer: ui.api,
|
||||
})
|
||||
let request: Parameters<OpenCodeClient["session"]["prompt"]>[0] | undefined
|
||||
spyOn(client.session, "prompt").mockImplementation((input) => {
|
||||
request = input
|
||||
queueMicrotask(() => {
|
||||
events.push({
|
||||
id: "evt_prompted",
|
||||
created: 0,
|
||||
type: "session.input.promoted",
|
||||
durable: durable("ses_1"),
|
||||
data: { sessionID: "ses_1", inputID: "msg_skill_attachment" },
|
||||
})
|
||||
events.push({
|
||||
id: "evt_settled",
|
||||
created: 0,
|
||||
type: "session.execution.succeeded",
|
||||
durable: durable("ses_1"),
|
||||
data: { sessionID: "ses_1" },
|
||||
})
|
||||
})
|
||||
return ok({
|
||||
id: input.id ?? "msg_skill_attachment",
|
||||
sessionID: "ses_1",
|
||||
type: "user" as const,
|
||||
data: { text: input.text },
|
||||
delivery: "steer" as const,
|
||||
timeCreated: 2,
|
||||
})
|
||||
})
|
||||
|
||||
await transport.runPromptTurn({
|
||||
agent: undefined,
|
||||
model: undefined,
|
||||
variant: undefined,
|
||||
prompt: {
|
||||
messageID: "msg_skill_attachment",
|
||||
text: "Review this /api-design",
|
||||
parts: [
|
||||
{
|
||||
type: "skill",
|
||||
id: "api-design",
|
||||
source: { start: 12, end: 23, value: "/api-design" },
|
||||
},
|
||||
],
|
||||
},
|
||||
files: [],
|
||||
includeFiles: false,
|
||||
})
|
||||
|
||||
expect(request).toMatchObject({
|
||||
sessionID: "ses_1",
|
||||
id: "msg_skill_attachment",
|
||||
text: "Review this /api-design",
|
||||
skills: [{ id: "api-design", mention: { start: 12, end: 23, text: "/api-design" } }],
|
||||
delivery: "steer",
|
||||
})
|
||||
await transport.close()
|
||||
})
|
||||
|
||||
test("refreshes catalogs on connection and location-scoped invalidations", async () => {
|
||||
const events = feed()
|
||||
events.push(connected())
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import type { RegionClaim } from "@opencode-ai/plugin/tui/context"
|
||||
import { resolveStructure, type Claim, type Part, type Placement } from "../src/plugin/structure"
|
||||
|
||||
// Type-level canaries, checked by `bun typecheck`: the placement sum and the
|
||||
// part union are exclusive — nonsense shapes must not compile.
|
||||
export const canaries = () => {
|
||||
const claims: RegionClaim<"prompt.footer">[] = []
|
||||
claims.push({ at: "end", render: () => null })
|
||||
// @ts-expect-error two placement keys cannot coexist
|
||||
claims.push({ at: "end", before: "status", render: () => null })
|
||||
// @ts-expect-error replace does not combine with an anchor
|
||||
claims.push({ replace: "status", after: "file", render: () => null })
|
||||
// @ts-expect-error a part is a leaf or a container, never both
|
||||
const hybrid: Part<string> = { id: "x", render: "x", parts: [] }
|
||||
return { claims, hybrid }
|
||||
}
|
||||
|
||||
// The resolver is generic over render types; strings make ordering
|
||||
// assertions read as layouts.
|
||||
function claim(plugin: string, placement: Placement, render?: string): Claim<string> {
|
||||
return { key: `${plugin}/${render ?? JSON.stringify(placement)}`, plugin, placement, render: render ?? plugin }
|
||||
}
|
||||
|
||||
function layout(result: ReturnType<typeof resolveStructure<string, string>>) {
|
||||
return result.entries.map((entry) => (entry.kind === "part" ? entry.id : entry.claim.render))
|
||||
}
|
||||
|
||||
const footer: Part<string>[] = [
|
||||
{ id: "status", render: "status" },
|
||||
{ id: "file", render: "file" },
|
||||
]
|
||||
|
||||
const tree: Part<string>[] = [
|
||||
{ id: "left", parts: [{ id: "mode", render: "mode" }] },
|
||||
{
|
||||
id: "right",
|
||||
parts: [
|
||||
{ id: "directory", render: "directory" },
|
||||
{ id: "model", render: "model" },
|
||||
{ id: "tokens", render: "tokens" },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
test("no claims renders the host parts in order", () => {
|
||||
const result = resolveStructure<string, string>({ region: "prompt.footer", parts: footer, claims: [] })
|
||||
expect(layout(result)).toEqual(["status", "file"])
|
||||
expect(result.suppressed).toEqual([])
|
||||
expect(result.degraded).toEqual([])
|
||||
})
|
||||
|
||||
test("edge claims land at the region's edges, several in enable order", () => {
|
||||
const result = resolveStructure({
|
||||
region: "prompt.footer",
|
||||
parts: footer,
|
||||
claims: [
|
||||
claim("a", { at: "end" }, "a1"),
|
||||
claim("b", { at: "start" }, "b1"),
|
||||
claim("a", { at: "end" }, "a2"),
|
||||
],
|
||||
})
|
||||
expect(layout(result)).toEqual(["b1", "status", "file", "a1", "a2"])
|
||||
})
|
||||
|
||||
test("before and after anchor to a part, wherever the host keeps it", () => {
|
||||
const result = resolveStructure({
|
||||
region: "prompt.footer",
|
||||
parts: footer,
|
||||
claims: [claim("a", { after: "status" }, "chip"), claim("b", { before: "status" }, "vim")],
|
||||
})
|
||||
expect(layout(result)).toEqual(["vim", "status", "chip", "file"])
|
||||
})
|
||||
|
||||
test("a missing anchor degrades to the end instead of disappearing", () => {
|
||||
const result = resolveStructure({
|
||||
region: "prompt.footer",
|
||||
parts: footer,
|
||||
claims: [claim("a", { after: "tokens" }, "chip")],
|
||||
})
|
||||
expect(layout(result)).toEqual(["status", "file", "chip"])
|
||||
expect(result.degraded.map((item) => item.render)).toEqual(["chip"])
|
||||
})
|
||||
|
||||
test("replacing a part swaps content but keeps the position and its anchors", () => {
|
||||
const result = resolveStructure({
|
||||
region: "prompt.footer",
|
||||
parts: footer,
|
||||
claims: [claim("a", { replace: "status" }, "fancy-status"), claim("b", { after: "status" }, "chip")],
|
||||
})
|
||||
expect(layout(result)).toEqual(["fancy-status", "chip", "file"])
|
||||
expect(result.suppressed).toEqual([])
|
||||
})
|
||||
|
||||
test("same target: the last-enabled claim wins and the loser is recorded", () => {
|
||||
const first = claim("a", { replace: "status" }, "first")
|
||||
const second = claim("b", { replace: "status" }, "second")
|
||||
const result = resolveStructure({ region: "prompt.footer", parts: footer, claims: [first, second] })
|
||||
expect(layout(result)).toEqual(["second", "file"])
|
||||
expect(result.suppressed).toEqual([{ claim: first, by: second }])
|
||||
})
|
||||
|
||||
test("container takeover suppresses everything anchored in the subtree", () => {
|
||||
const takeover = claim("theme", { replace: "right" }, "my-right")
|
||||
const chip = claim("pr", { after: "model" }, "chip")
|
||||
const inner = claim("x", { replace: "tokens" }, "cost")
|
||||
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [takeover, chip, inner] })
|
||||
expect(layout(result)).toEqual(["mode", "my-right"])
|
||||
expect(result.suppressed).toEqual([
|
||||
{ claim: chip, by: takeover },
|
||||
{ claim: inner, by: takeover },
|
||||
])
|
||||
})
|
||||
|
||||
test("hierarchy beats timeline: an ancestor takeover wins over a later descendant claim", () => {
|
||||
// The descendant replace was enabled after the container takeover; the
|
||||
// container still wins because its target contains the descendant's.
|
||||
const inner = claim("x", { replace: "model" }, "swap-model")
|
||||
const outer = claim("theme", { replace: "right" }, "my-right")
|
||||
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [outer, inner] })
|
||||
expect(layout(result)).toEqual(["mode", "my-right"])
|
||||
expect(result.suppressed).toEqual([{ claim: inner, by: outer }])
|
||||
})
|
||||
|
||||
test("root takeover: nothing original survives, all other claims suppressed", () => {
|
||||
const theme = claim("powerline", { replace: "prompt.footer" }, "powerline")
|
||||
const chip = claim("pr", { at: "end" }, "chip")
|
||||
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [chip, theme] })
|
||||
expect(layout(result)).toEqual(["powerline"])
|
||||
expect(result.suppressed).toEqual([{ claim: chip, by: theme }])
|
||||
})
|
||||
|
||||
test("root takeover at the same node: last enabled wins", () => {
|
||||
const first = claim("a", { replace: "home.footer" }, "first")
|
||||
const second = claim("b", { replace: "home.footer" }, "second")
|
||||
const result = resolveStructure<string, string>({ region: "home.footer", parts: [], claims: [first, second] })
|
||||
expect(layout(result)).toEqual(["second"])
|
||||
expect(result.suppressed).toEqual([{ claim: first, by: second }])
|
||||
})
|
||||
|
||||
test("containers flatten in order and anchors on a container wrap its whole span", () => {
|
||||
const result = resolveStructure({
|
||||
region: "prompt.footer",
|
||||
parts: tree,
|
||||
claims: [claim("a", { before: "right" }, "divider"), claim("b", { after: "right" }, "clock")],
|
||||
})
|
||||
expect(layout(result)).toEqual(["mode", "divider", "directory", "model", "tokens", "clock"])
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { displayCharAt, displaySlice, mentionTriggerIndex, slashTriggerIndex } from "../../src/prompt/display"
|
||||
import { displayCharAt, displaySlice, mentionTriggerIndex } from "../../src/prompt/display"
|
||||
|
||||
describe("prompt display", () => {
|
||||
test("uses display-width offsets for mentions", () => {
|
||||
@@ -30,14 +30,4 @@ describe("prompt display", () => {
|
||||
expect(mentionTriggerIndex("foo@bar.com")).toBeUndefined()
|
||||
expect(mentionTriggerIndex("中文 @src file")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("finds slash attachments at token boundaries", () => {
|
||||
expect(slashTriggerIndex("/")).toBe(0)
|
||||
expect(slashTriggerIndex("Review this /api-design")).toBe(12)
|
||||
expect(slashTriggerIndex("中文 /api-design")).toBe(5)
|
||||
expect(slashTriggerIndex("Review /api design")).toBeUndefined()
|
||||
expect(slashTriggerIndex("Review /tmp/file.ts")).toBeUndefined()
|
||||
expect(slashTriggerIndex("https://opencode.ai/docs")).toBeUndefined()
|
||||
expect(slashTriggerIndex("src/prompt/index.ts")).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user