mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-06 09:10:47 -04:00
Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a0c77b71ae | |||
| e62918224f | |||
| 30d140008f | |||
| a38d44265b | |||
| 0cce215de4 | |||
| a15ec425de | |||
| ae494ffce5 | |||
| 25c2150baf | |||
| 9314992f98 | |||
| 0fbe489e35 | |||
| 03e9789064 | |||
| 0c558a6856 | |||
| f297bd3b8b | |||
| 1bfc23f503 | |||
| 3839aafa25 | |||
| bd2f37bc90 | |||
| 120e4e7388 | |||
| 6f91bc7415 | |||
| c46f6ae112 | |||
| 285444aab4 | |||
| 56c33e84a3 | |||
| 73581b3c3b | |||
| 6e4d01f846 | |||
| 8646587c95 | |||
| fb47f06228 | |||
| 3acaa5a359 | |||
| 0726a25142 | |||
| 0df96ddeb0 | |||
| 887673310b | |||
| 693a1bff81 | |||
| b40ed3aa85 | |||
| 732bb9c3cb | |||
| 2fd1660b4d | |||
| 681526d348 | |||
| e78869c849 | |||
| 934935963d | |||
| f3912a2a8a | |||
| 45d58717a4 | |||
| 74e3155ef0 | |||
| 0af6c82563 | |||
| 686127f809 | |||
| 5256655c4d | |||
| d10b652637 | |||
| b03ca0d4e2 | |||
| 25aaea3d31 | |||
| cae7a139bc | |||
| 5ea62ab05f | |||
| faadc05c88 |
@@ -64,7 +64,6 @@
|
|||||||
"@opencode-ai/client": "workspace:*",
|
"@opencode-ai/client": "workspace:*",
|
||||||
"@opencode-ai/core": "workspace:*",
|
"@opencode-ai/core": "workspace:*",
|
||||||
"@opencode-ai/schema": "workspace:*",
|
"@opencode-ai/schema": "workspace:*",
|
||||||
"@opencode-ai/sdk": "file:vendor/opencode-ai-sdk-1.18.8-dev.tgz",
|
|
||||||
"@opencode-ai/session-ui": "workspace:*",
|
"@opencode-ai/session-ui": "workspace:*",
|
||||||
"@opencode-ai/ui": "workspace:*",
|
"@opencode-ai/ui": "workspace:*",
|
||||||
"@opencode-ai/util": "workspace:*",
|
"@opencode-ai/util": "workspace:*",
|
||||||
@@ -112,6 +111,7 @@
|
|||||||
"@types/luxon": "catalog:",
|
"@types/luxon": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"@typescript/native-preview": "catalog:",
|
"@typescript/native-preview": "catalog:",
|
||||||
|
"happy-dom": "20.11.1",
|
||||||
"tw-animate-css": "1.4.0",
|
"tw-animate-css": "1.4.0",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vite": "catalog:",
|
"vite": "catalog:",
|
||||||
@@ -489,18 +489,6 @@
|
|||||||
"@typescript/native-preview": "catalog:",
|
"@typescript/native-preview": "catalog:",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"packages/effect-sqlite-node": {
|
|
||||||
"name": "@opencode-ai/effect-sqlite-node",
|
|
||||||
"version": "1.18.8",
|
|
||||||
"dependencies": {
|
|
||||||
"effect": "catalog:",
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@tsconfig/bun": "catalog:",
|
|
||||||
"@types/node": "catalog:",
|
|
||||||
"@typescript/native-preview": "catalog:",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"packages/enterprise": {
|
"packages/enterprise": {
|
||||||
"name": "@opencode-ai/enterprise",
|
"name": "@opencode-ai/enterprise",
|
||||||
"version": "1.18.8",
|
"version": "1.18.8",
|
||||||
@@ -2067,8 +2055,6 @@
|
|||||||
|
|
||||||
"@opencode-ai/effect-drizzle-sqlite": ["@opencode-ai/effect-drizzle-sqlite@workspace:packages/effect-drizzle-sqlite"],
|
"@opencode-ai/effect-drizzle-sqlite": ["@opencode-ai/effect-drizzle-sqlite@workspace:packages/effect-drizzle-sqlite"],
|
||||||
|
|
||||||
"@opencode-ai/effect-sqlite-node": ["@opencode-ai/effect-sqlite-node@workspace:packages/effect-sqlite-node"],
|
|
||||||
|
|
||||||
"@opencode-ai/enterprise": ["@opencode-ai/enterprise@workspace:packages/enterprise"],
|
"@opencode-ai/enterprise": ["@opencode-ai/enterprise@workspace:packages/enterprise"],
|
||||||
|
|
||||||
"@opencode-ai/function": ["@opencode-ai/function@workspace:packages/function"],
|
"@opencode-ai/function": ["@opencode-ai/function@workspace:packages/function"],
|
||||||
@@ -6333,8 +6319,6 @@
|
|||||||
|
|
||||||
"@openauthjs/openauth/jose": ["jose@5.9.6", "", {}, "sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ=="],
|
"@openauthjs/openauth/jose": ["jose@5.9.6", "", {}, "sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ=="],
|
||||||
|
|
||||||
"@opencode-ai/app/@opencode-ai/sdk": ["@opencode-ai/sdk@vendor/opencode-ai-sdk-1.18.8-dev.tgz", { "dependencies": { "cross-spawn": "7.0.6" } }, "sha512-C2nfk4x0sPINwE5V6DPkFSuH3PkUmKPWHPzxpXC1j+3Ui5hslLCWJbkk8WcOG1Lyt3C0+yp4ea64v/kmtYCO4w=="],
|
|
||||||
|
|
||||||
"@opencode-ai/cli/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
"@opencode-ai/cli/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||||
|
|
||||||
"@opencode-ai/console-app/@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.2.7", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.11.0", "@smithy/util-hex-encoding": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-DrpkEoM3j9cBBWhufqBwnbbn+3nf1N9FP6xuVJ+e220jbactKuQgaZwjwP5CP1t+O94brm2JgVMD2atMGX3xIQ=="],
|
"@opencode-ai/console-app/@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.2.7", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.11.0", "@smithy/util-hex-encoding": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-DrpkEoM3j9cBBWhufqBwnbbn+3nf1N9FP6xuVJ+e220jbactKuQgaZwjwP5CP1t+O94brm2JgVMD2atMGX3xIQ=="],
|
||||||
|
|||||||
@@ -5,8 +5,27 @@
|
|||||||
- Use the `dev` branch database schema and migration registry as the V1 baseline.
|
- Use the `dev` branch database schema and migration registry as the V1 baseline.
|
||||||
- Remove migrations that exist only on the V2 branch.
|
- Remove migrations that exist only on the V2 branch.
|
||||||
- Generate one canonical migration from the `dev` schema to the final V2 schema.
|
- Generate one canonical migration from the `dev` schema to the final V2 schema.
|
||||||
- Add explicit data operations to that migration where generated DDL is insufficient.
|
- Keep the canonical migration focused on schema changes and dropping obsolete tables.
|
||||||
- Test the migration against a populated database at the exact `dev` schema.
|
- Run the V1 history backfill through an experimental server endpoint invoked by the CLI before it opens the TUI.
|
||||||
|
- Show committed session progress while the endpoint runs.
|
||||||
|
|
||||||
|
Expose `GET /api/experimental/migration/v1` for status and a blocking `POST /api/experimental/migration/v1` to run or
|
||||||
|
resume the backfill. The status is `required`, `running`, or `completed`. On startup, the CLI checks status first and
|
||||||
|
renders no migration UI when it is already complete. For required or running status, it shows a spinner and waits for the
|
||||||
|
blocking POST without a request timeout. While migration runs, poll GET once per second and render completed and total
|
||||||
|
session counts. GET derives total from all session rows and completed from rows through the stored cursor; the count
|
||||||
|
advances only after a session transaction commits. The POST returns `{ status: "completed" }`. Do not add a background
|
||||||
|
job or streaming progress protocol. Interrupted calls resume from the stored cursor.
|
||||||
|
Initially, only interactive TUI startup performs this check; noninteractive run, ACP, raw API, service, health, version,
|
||||||
|
and help flows do not trigger the backfill.
|
||||||
|
|
||||||
|
Keep migration behavior in Core: status, semaphore, checkpointing, V1 decoding, transformation, and database writes.
|
||||||
|
Protocol owns the experimental GET/POST contracts, Server handlers delegate to Core, and the interactive CLI owns only
|
||||||
|
the status check and spinner presentation.
|
||||||
|
|
||||||
|
Guard the endpoint with one process-local Effect `Semaphore`. Concurrent callers wait; after the active call completes,
|
||||||
|
waiting callers acquire the permit, observe the completion key, and return immediately. No distributed lock is required
|
||||||
|
for the current single elected server process.
|
||||||
|
|
||||||
## Preserve
|
## Preserve
|
||||||
|
|
||||||
@@ -15,20 +34,35 @@ The canonical V1 data remains in its existing tables. In particular, preserve `s
|
|||||||
Preserve `workspace` rows and existing `session.workspace_id` values unchanged. The migration must not clear or rebuild
|
Preserve `workspace` rows and existing `session.workspace_id` values unchanged. The migration must not clear or rebuild
|
||||||
workspace relationships.
|
workspace relationships.
|
||||||
|
|
||||||
Keep the `todo` table and its data unchanged. V2 does not currently migrate todos into another representation, and the
|
Preserve existing non-null `session.agent` and `session.model` selections. Fill missing values from the latest ordinary
|
||||||
generated migration must not drop the table.
|
V1 user message ordered by `time_created` and `id`, excluding compaction and subtask-only messages. Copy agent, provider
|
||||||
|
ID, model ID, and variant, normalizing an absent variant to `default`.
|
||||||
|
|
||||||
## Truncate
|
Recompute session usage aggregates from all canonical V1 assistant messages, including compaction or other internal
|
||||||
|
assistants omitted from the V2 projection. Overwrite session cost and input, output, reasoning, cache-read, and
|
||||||
|
cache-write token totals with those sums.
|
||||||
|
|
||||||
Truncate these pre-launch V2 tables before applying schema changes:
|
Clear persisted `session.revert` state. A staged revert is transient operational state and may refer to omitted projection
|
||||||
|
rows or unavailable snapshots; it must not resume automatically after upgrading. Preserve the underlying messages,
|
||||||
|
parts, and file history.
|
||||||
|
|
||||||
- `event`
|
Clear `session.time_compacting`, leave the new `time_suspended` column as `NULL`, and preserve session creation, update,
|
||||||
- `event_sequence`
|
and archive timestamps. Preserve project `time_initialized`; it is unrelated durable state.
|
||||||
- `session_message`
|
|
||||||
|
|
||||||
These rows are not canonical V1 data. Truncating `event` before adding the required `event.created` column means the
|
Keep the legacy `todo` table and its data physically unchanged, but do not include it in the final V2 Drizzle schema.
|
||||||
column needs neither a backfill nor a default. After truncation, rebuild `session_message` from canonical V1 `message`
|
After generation, remove the generated `DROP TABLE todo` statement from the canonical migration so the table remains as
|
||||||
and `part` rows rather than retaining its pre-launch V2 contents.
|
unmanaged legacy storage.
|
||||||
|
|
||||||
|
## Per-Session Replacement
|
||||||
|
|
||||||
|
Do not truncate `event`, `event_sequence`, or `session_message` globally before the backfill. A whole-table delete can
|
||||||
|
hold SQLite's writer lock long enough to block the running TUI.
|
||||||
|
|
||||||
|
Replace each legacy session's V2 state inside that session's checkpointed migration transaction. Delete `event` rows for
|
||||||
|
the session aggregate, delete its `session_message` rows, rebuild its projection from canonical V1 `message` and `part`
|
||||||
|
rows, and overwrite its `event_sequence` watermark. If migration of that session fails, all replacements roll back and
|
||||||
|
the durable cursor remains at the previously committed session. Rows owned by sessions outside the legacy migration set
|
||||||
|
remain untouched.
|
||||||
|
|
||||||
## Message Backfill
|
## Message Backfill
|
||||||
|
|
||||||
@@ -36,9 +70,23 @@ Backfill canonical V1 history from `message` and `part` into `session_message`.
|
|||||||
the migration. Preserving the V1 tables alone keeps the data safe but does not make existing history visible through the
|
the migration. Preserving the V1 tables alone keeps the data safe but does not make existing history visible through the
|
||||||
V2 session APIs, which read `session_message`.
|
V2 session APIs, which read `session_message`.
|
||||||
|
|
||||||
|
Do not fail the whole migration when a V1 message or part payload cannot be decoded. Skip an undecodable message's V2
|
||||||
|
projection and log its session and message IDs. Skip an undecodable part while continuing to map its message, and perform
|
||||||
|
special-message pairing only with decoded rows. Assign sequences after filtering. Leave every malformed source row
|
||||||
|
untouched in the V1 tables.
|
||||||
|
|
||||||
|
Skip and log orphan parts whose source message does not exist and parts with unknown or unsupported types. Continue
|
||||||
|
migrating the owning message and other valid parts. Include session, message, part ID, and observed type in warnings, and
|
||||||
|
leave skipped source rows unchanged.
|
||||||
|
|
||||||
Reuse each V1 `message.id` as the corresponding `session_message.id`. Stable IDs keep the migration deterministic and
|
Reuse each V1 `message.id` as the corresponding `session_message.id`. Stable IDs keep the migration deterministic and
|
||||||
avoid rewriting other persisted state that may refer to a message.
|
avoid rewriting other persisted state that may refer to a message.
|
||||||
|
|
||||||
|
For ordinary user and assistant rows, preserve source `message.time_created` and `message.time_updated`. Entirely
|
||||||
|
synthetic messages preserve their source timestamps, and synthetic rows split from mixed messages use the source user
|
||||||
|
timestamps. A collapsed compaction uses the compaction user creation time and the later update time of the compaction
|
||||||
|
user and summary assistant. Keep payload creation/completion times consistent with row timestamps.
|
||||||
|
|
||||||
Within each session, order V1 messages by `time_created` and then `id`, matching the existing V1 message index. Assign
|
Within each session, order V1 messages by `time_created` and then `id`, matching the existing V1 message index. Assign
|
||||||
contiguous `session_message.seq` values starting at `0`.
|
contiguous `session_message.seq` values starting at `0`.
|
||||||
|
|
||||||
@@ -46,15 +94,122 @@ Map ordinary V1 messages one-to-one by role. Each ordinary V1 user message becom
|
|||||||
V1 assistant message becomes one V2 `assistant` row. Fold the source message's ordered V1 parts into that row's V2
|
V1 assistant message becomes one V2 `assistant` row. Fold the source message's ordered V1 parts into that row's V2
|
||||||
payload.
|
payload.
|
||||||
|
|
||||||
|
Keep ordinary messages even when their transformed payload becomes empty after filtering. Preserve an empty V2 user row
|
||||||
|
with `text: ""` and an empty V2 assistant row with `content: []` so IDs, chronology, and conversation structure remain
|
||||||
|
stable. Omit only explicitly dropped internal concepts and undecodable messages.
|
||||||
|
|
||||||
Handle semantic marker parts before applying the ordinary mapping. In particular, a V1 user message containing a
|
Handle semantic marker parts before applying the ordinary mapping. In particular, a V1 user message containing a
|
||||||
`compaction` part and its paired assistant summary represent one compaction operation, not two ordinary messages. Special
|
`compaction` part and its paired assistant summary represent one compaction operation, not two ordinary messages. Special
|
||||||
part mappings must be decided explicitly before implementing the backfill.
|
part mappings must be decided explicitly before implementing the backfill.
|
||||||
|
|
||||||
|
Do not carry the V1 subtask concept into the V2 projection. Omit user messages containing only `subtask` parts and omit
|
||||||
|
the paired assistant task-tool messages generated from those markers. For mixed user messages, ignore the `subtask`
|
||||||
|
parts while preserving ordinary content, and still omit assistant task-tool messages generated by the skipped subtasks.
|
||||||
|
Keep all source rows unchanged in the V1 `message` and `part` tables.
|
||||||
|
|
||||||
|
Map ordinary V1 assistant `text` and `reasoning` parts into the V2 assistant `content` array in part order. Preserve text,
|
||||||
|
including empty assistant text parts used as structural separators. Map V1 part metadata to optional V2 provider state.
|
||||||
|
For reasoning, map `time.start` to `time.created` and optional `time.end` to `time.completed`.
|
||||||
|
|
||||||
|
Preserve V1 tool parts that are `pending` or `running`, but convert them to terminal V2 tool error states. Preserve the
|
||||||
|
call ID, tool name, parsed input, metadata, and available start time. Use the assistant message creation time when the V1
|
||||||
|
state has no start time. Set the error to type `tool.interrupted` with message
|
||||||
|
`Tool execution was interrupted before V2 migration`. Never resume migrated tool executions.
|
||||||
|
|
||||||
|
For a completed V1 tool part, use `callID` as the V2 tool content ID and preserve the tool name and parsed input. Set the
|
||||||
|
state to `completed`. Convert V1 output into the first text content item and convert stored output attachments into
|
||||||
|
following file content items with their URI, MIME type, and filename. Preserve state metadata. Map `time.start` to
|
||||||
|
`time.created` and `time.end` to `time.completed`. When `time.compacted` exists, use
|
||||||
|
`[Old tool result content cleared]` as the only output and omit attachments.
|
||||||
|
|
||||||
|
For a failed V1 tool part, preserve the call ID, tool name, parsed input, metadata, and timestamps, and set the V2 state
|
||||||
|
to `error`. Convert the V1 error string to a structured error with type `tool.execution`. If V1 metadata contains a string
|
||||||
|
`output`, preserve it as optional V2 text content. Map `time.start` to `time.created` and `time.end` to `time.completed`.
|
||||||
|
|
||||||
|
For an ordinary V1 assistant message, preserve agent, provider ID, model ID, optional variant, creation and completion
|
||||||
|
times, cost, and input/output/reasoning/cache token counts. Use `default` when the V1 variant is absent. Ignore V1
|
||||||
|
`tokens.total` because it is derivable and V2 does not persist it.
|
||||||
|
|
||||||
|
Use V1 assistant `parentID` only while pairing compactions and skipped subtasks with their originating user messages. Do
|
||||||
|
not persist it in ordinary V2 assistant rows; V2 uses ordered history rather than user/assistant parent links.
|
||||||
|
|
||||||
|
Ignore the optional V1 assistant `structured` output value. V2 has no equivalent top-level assistant field, and visible
|
||||||
|
text and tool content are migrated separately. Retain the original structured value only in the V1 `message` row.
|
||||||
|
|
||||||
|
Ignore V1 assistant `mode` and historical `path` (`cwd` and `root`). Mode is redundant with the preserved assistant
|
||||||
|
agent, and historical filesystem paths do not belong to the V2 assistant message contract. Retain them only in the V1
|
||||||
|
`message` row.
|
||||||
|
|
||||||
|
For assistant finish reasons, preserve `stop`, `length`, `tool-calls`, `content-filter`, `error`, and `unknown`. Map every
|
||||||
|
other nonempty V1 finish value to `unknown`, and leave the field absent when V1 omitted it. Do not retain unrecognized raw
|
||||||
|
finish values in metadata.
|
||||||
|
|
||||||
|
Map V1 assistant errors into the current V2 `{ type, message }` storage shape. Normalize Auth, content-filter, context
|
||||||
|
overflow, structured-output, output-length, aborted, API, and unknown errors to the established V2 string conventions,
|
||||||
|
preserve the message, and discard V1-only retryability and raw provider details.
|
||||||
|
|
||||||
|
Ignore V1 `retry` parts. Do not populate the V2 assistant `retry` field during migration; historical retry state is not
|
||||||
|
useful enough to preserve. The original retry rows remain in the V1 `part` table.
|
||||||
|
|
||||||
|
Do not emit V2 assistant content for V1 `step-start` and `step-finish` parts. Use the first available
|
||||||
|
`step-start.snapshot` as `assistant.snapshot.start` and the last available `step-finish.snapshot` as
|
||||||
|
`assistant.snapshot.end`. Continue to source finish, cost, and tokens from the assistant message itself. Ignore step
|
||||||
|
markers without snapshots.
|
||||||
|
|
||||||
|
Do not emit assistant content for standalone V1 `snapshot` or `patch` parts. If no start snapshot came from `step-start`,
|
||||||
|
use the first standalone snapshot value, then the first patch hash as a final fallback. Only `step-finish.snapshot` may
|
||||||
|
populate the end snapshot. Merge patch file lists into `assistant.snapshot.files` in first-seen order with duplicates
|
||||||
|
removed.
|
||||||
|
|
||||||
|
V2 follow-up: replace the open `SessionError.Error` string shape with a properly typed persisted error union. This is not
|
||||||
|
a blocker for the V1 migration, which should target the current storage contract.
|
||||||
|
|
||||||
V1 synthetic content is represented by user text parts with `synthetic: true`, not by a separate message role. A V1 user
|
V1 synthetic content is represented by user text parts with `synthetic: true`, not by a separate message role. A V1 user
|
||||||
message whose visible text parts are all synthetic should become a V2 `synthetic` message. If a V1 user message mixes
|
message whose visible text parts are all synthetic should become a V2 `synthetic` message. If a V1 user message mixes
|
||||||
ordinary and synthetic content, preserve the ordinary content in the V2 `user` row and emit the synthetic content as an
|
ordinary and synthetic content, preserve the ordinary content in the V2 `user` row and emit the synthetic content as an
|
||||||
adjacent V2 `synthetic` row. Ignore text parts marked `ignored`, matching V1 model-history behavior.
|
adjacent V2 `synthetic` row. Ignore text parts marked `ignored`, matching V1 model-history behavior.
|
||||||
|
|
||||||
|
For an ordinary V2 user message, take visible V1 text parts that are neither ignored nor synthetic, preserve part order,
|
||||||
|
and join their text with `"\n\n"`. Use an empty string when the message contains attachments but no ordinary text.
|
||||||
|
|
||||||
|
Ignore the optional V1 user-message `system` override. Do not create a V2 system message or preserve the override in
|
||||||
|
metadata. The original value remains in the V1 `message` row.
|
||||||
|
|
||||||
|
Ignore the optional V1 user-message `tools` map. It represented request-time tool enablement for a historical step and
|
||||||
|
must not affect future V2 execution. The original value remains in the V1 `message` row.
|
||||||
|
|
||||||
|
Ignore the optional V1 user-message `format` field and its schema. It controlled structured-output behavior for a
|
||||||
|
historical request and must not affect future V2 runs. Preserve visible assistant text normally; retain the original
|
||||||
|
format only in the V1 `message` row.
|
||||||
|
|
||||||
|
Ignore V1 user-message `summary` metadata, including title, body, and diffs. V2 user messages have no equivalent field,
|
||||||
|
and session-level summary data is already persisted separately. Retain the original summary only in the V1 `message`
|
||||||
|
row.
|
||||||
|
|
||||||
|
Map V1 `agent` parts into the V2 user message's `agents` array in part order. Preserve `name`. When the V1 part has
|
||||||
|
`source`, map its `value`, `start`, and `end` into the V2 attachment's `mention.text`, `mention.start`, and `mention.end`.
|
||||||
|
Omit `agents` when there are no agent parts.
|
||||||
|
|
||||||
|
Do not read the filesystem or network while migrating V1 file attachments. Attachment migration must be deterministic
|
||||||
|
from database contents alone. Convert persisted `data:` URLs; represent non-embedded `file:`, HTTP, and other external
|
||||||
|
URLs with deterministic text rather than fetching them. Keep the original V1 `part` rows unchanged.
|
||||||
|
|
||||||
|
For a V1 file backed by a `data:` URL, decode the URL and normalize its payload to base64 for the V2 attachment's `data`.
|
||||||
|
Preserve `mime` and optional `filename` as `name`. Use a V2 `uri` source with the original URI for a V1 resource source;
|
||||||
|
otherwise use an `inline` source. When V1 source text metadata exists, map its `value`, `start`, and `end` into the V2
|
||||||
|
attachment mention. Leave `description` unset and preserve file-part order in the V2 `files` array.
|
||||||
|
|
||||||
|
For a non-embedded V1 file, do not create a V2 file attachment. Append
|
||||||
|
`[Attachment unavailable after migration: <name-or-url> (<mime>)]` to the V2 user text in original part order, separated
|
||||||
|
by blank lines. Prefer the V1 filename, then resource URI, then part URL for the label. The original URL remains only in
|
||||||
|
the preserved V1 `part` row.
|
||||||
|
|
||||||
|
For a synthetic row split from a mixed user message, derive a generated-looking ID from the source message ID. Preserve
|
||||||
|
the source ID's 12-character timestamp component and replace its 14-character random component with a deterministic
|
||||||
|
base-62 encoding of a hash of `v1-synthetic:` plus the source message ID. If that candidate collides with an existing or
|
||||||
|
derived message ID, deterministically retry with an incrementing salt. Place the synthetic row immediately after its
|
||||||
|
source user row. Entirely synthetic messages continue to reuse their original message ID.
|
||||||
|
|
||||||
Use the V1 compaction user message ID as the ID of the collapsed V2 compaction message. This matches V2's use of the
|
Use the V1 compaction user message ID as the ID of the collapsed V2 compaction message. This matches V2's use of the
|
||||||
admitted compaction input ID and preserves references to the initiating message.
|
admitted compaction input ID and preserves references to the initiating message.
|
||||||
|
|
||||||
@@ -64,9 +219,13 @@ serialize the retained V1 tail beginning at `tail_start_id` for `recent`. Use an
|
|||||||
retained, and use the compaction user message creation time. Do not emit the paired summary assistant as a separate V2
|
retained, and use the compaction user message creation time. Do not emit the paired summary assistant as a separate V2
|
||||||
assistant row.
|
assistant row.
|
||||||
|
|
||||||
After rebuilding `session_message`, seed `event_sequence` with one row per migrated session. Set its watermark to that
|
Do not project incomplete or failed V1 compactions into `session_message`. Omit both the internal compaction user marker
|
||||||
session's maximum backfilled `session_message.seq`. This prevents new V2 events from reusing sequence numbers or sorting
|
and its paired summary assistant when no successful summary was completed. Assign final sequence numbers after filtering
|
||||||
before migrated history. The `event` table remains empty.
|
so omitted compactions leave no gaps. Their source rows remain preserved in the V1 `message` and `part` tables.
|
||||||
|
|
||||||
|
After rebuilding a session's `session_message`, replace its `event_sequence` watermark with that session's maximum
|
||||||
|
backfilled `session_message.seq`. This prevents new V2 events from reusing sequence numbers or sorting before migrated
|
||||||
|
history. The migrated session's prior `event` rows are removed in the same transaction.
|
||||||
|
|
||||||
## Drop
|
## Drop
|
||||||
|
|
||||||
@@ -74,6 +233,7 @@ Drop these pre-launch V2 tables without preserving or transforming their rows:
|
|||||||
|
|
||||||
- `session_input`
|
- `session_input`
|
||||||
- `session_context_epoch`
|
- `session_context_epoch`
|
||||||
|
- `data_migration`
|
||||||
|
|
||||||
Do not transfer `session_input` rows into `session_pending`.
|
Do not transfer `session_input` rows into `session_pending`.
|
||||||
|
|
||||||
@@ -103,16 +263,36 @@ schema.
|
|||||||
New nullable session columns, including `fork_session_id`, `fork_boundary`, and `time_suspended`, require no explicit
|
New nullable session columns, including `fork_session_id`, `fork_boundary`, and `time_suspended`, require no explicit
|
||||||
backfill. Existing rows naturally receive `NULL` when the generated migration adds the columns.
|
backfill. Existing rows naturally receive `NULL` when the generated migration adds the columns.
|
||||||
|
|
||||||
## Verification
|
## Execution
|
||||||
|
|
||||||
The canonical migration test should seed representative V1 sessions, messages, parts, todos, projects, accounts,
|
Before transforming V1 rows, look for `opencode-next.db` in the data directory. This file was used by pre-launch V2
|
||||||
credentials, permissions, shares, and workspaces. After migration, it should verify:
|
builds. Open it read-only with Bun SQLite and copy its `project`, `session`, and `session_message` rows directly into the
|
||||||
|
current `project`, `session_v2`, and `session_message` tables. Existing current projects and Sessions win ID collisions.
|
||||||
|
Do not copy its durable events or runtime caches; initialize each imported Session's `event_sequence` watermark from its
|
||||||
|
maximum message sequence. Commit each imported Session independently and leave the source database untouched.
|
||||||
|
|
||||||
- Preserved rows and encoded values remain unchanged.
|
The previous V2 import is part of this migration and uses the same completion marker. It needs no source-specific cursor:
|
||||||
- Todo rows remain available in the unchanged `todo` table.
|
the destination Session row is the per-Session idempotency boundary, so a retry skips transactions that already committed.
|
||||||
- `event` is empty, and stale pre-launch rows are absent from the rebuilt projections.
|
|
||||||
- Backfilled `session_message` rows represent the canonical V1 `message` and `part` history.
|
Store V1 backfill state in `kv`; do not retain a dedicated `data_migration` table. Store the last successfully migrated
|
||||||
- Each migrated session's `event_sequence` watermark matches its maximum backfilled message sequence.
|
session ID under `migration.v1-v2.session.cursor` and write `migration.v1-v2.completed` with value `true` after every
|
||||||
- Dropped tables no longer exist.
|
session finishes. Delete the cursor key on completion and return immediately on later calls when the completion key
|
||||||
- New tables exist and are empty.
|
exists.
|
||||||
- The final schema has no ungenerated changes.
|
|
||||||
|
Absence of the completion key means migration is required, including on a fresh database. Running the endpoint against a
|
||||||
|
database with no sessions completes immediately and writes the completion key; fresh database initialization does not
|
||||||
|
seed migration state specially.
|
||||||
|
|
||||||
|
Process sessions in stable ID order. Rebuild one session in one transaction, including its `session_message` rows,
|
||||||
|
session-level backfills, `event_sequence` watermark, and cursor update. If interrupted during a session, that transaction
|
||||||
|
rolls back and the next endpoint call retries the same session. If it committed, the next call continues after the stored
|
||||||
|
cursor. Mark the migration complete after the final session and return immediately on later calls.
|
||||||
|
|
||||||
|
Ensure the global project exists using the current platform's filesystem root as its worktree. Process every `session`
|
||||||
|
row, including archived, root, child, and empty sessions, as well as sessions whose messages are all skipped or internal.
|
||||||
|
Reassign beta and V1 Sessions whose referenced project row is missing to the global project and log a warning. Each
|
||||||
|
successfully committed session advances the cursor.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Detailed migration test design is deferred until after the canonical migration is implemented.
|
||||||
|
|||||||
@@ -211,43 +211,11 @@ export type StreamItem = Schema.Schema.Type<typeof StreamItem>
|
|||||||
// event-level `error` envelope, so accept all three shapes here.
|
// event-level `error` envelope, so accept all three shapes here.
|
||||||
// https://www.openresponses.org/specification
|
// https://www.openresponses.org/specification
|
||||||
const OpenResponsesErrorPayload = Schema.Struct({
|
const OpenResponsesErrorPayload = Schema.Struct({
|
||||||
type: optionalNull(Schema.String),
|
|
||||||
code: optionalNull(Schema.String),
|
code: optionalNull(Schema.String),
|
||||||
message: optionalNull(Schema.String),
|
message: optionalNull(Schema.String),
|
||||||
param: optionalNull(Schema.String),
|
param: optionalNull(Schema.String),
|
||||||
})
|
})
|
||||||
|
|
||||||
const WebSocketErrorHeader = Schema.Union([Schema.String, Schema.Number, Schema.Boolean])
|
|
||||||
export const WebSocketErrorEvent = Schema.StructWithRest(
|
|
||||||
Schema.Struct({
|
|
||||||
type: Schema.tag("error"),
|
|
||||||
status: Schema.optional(Schema.Number),
|
|
||||||
status_code: Schema.optional(Schema.Number),
|
|
||||||
code: optionalNull(Schema.String),
|
|
||||||
message: Schema.optional(Schema.String),
|
|
||||||
param: optionalNull(Schema.String),
|
|
||||||
error: optionalNull(OpenResponsesErrorPayload),
|
|
||||||
headers: Schema.optional(Schema.Record(Schema.String, WebSocketErrorHeader)),
|
|
||||||
}),
|
|
||||||
[Schema.Record(Schema.String, Schema.Unknown)],
|
|
||||||
)
|
|
||||||
const decodeWebSocketErrorEvent = Schema.decodeUnknownEffect(WebSocketErrorEvent)
|
|
||||||
|
|
||||||
const decodeKnownErrorEvent = (event: Event) =>
|
|
||||||
decodeWebSocketErrorEvent({
|
|
||||||
...event,
|
|
||||||
status: typeof event.status === "number" ? event.status : undefined,
|
|
||||||
status_code: typeof event.status_code === "number" ? event.status_code : undefined,
|
|
||||||
headers: ProviderShared.isRecord(event.headers)
|
|
||||||
? Object.fromEntries(
|
|
||||||
Object.entries(event.headers).filter(
|
|
||||||
(entry): entry is [string, string | number | boolean] =>
|
|
||||||
typeof entry[1] === "string" || typeof entry[1] === "number" || typeof entry[1] === "boolean",
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: undefined,
|
|
||||||
})
|
|
||||||
|
|
||||||
export const Event = Schema.StructWithRest(
|
export const Event = Schema.StructWithRest(
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
type: Schema.String,
|
type: Schema.String,
|
||||||
@@ -272,9 +240,6 @@ export const Event = Schema.StructWithRest(
|
|||||||
message: Schema.optional(Schema.String),
|
message: Schema.optional(Schema.String),
|
||||||
param: optionalNull(Schema.String),
|
param: optionalNull(Schema.String),
|
||||||
error: optionalNull(OpenResponsesErrorPayload),
|
error: optionalNull(OpenResponsesErrorPayload),
|
||||||
status: Schema.optional(Schema.Unknown),
|
|
||||||
status_code: Schema.optional(Schema.Unknown),
|
|
||||||
headers: Schema.optional(Schema.Unknown),
|
|
||||||
}),
|
}),
|
||||||
[Schema.Record(Schema.String, Schema.Unknown)],
|
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||||
)
|
)
|
||||||
@@ -667,9 +632,9 @@ export type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
|
|||||||
const NO_EVENTS: StepResult["1"] = []
|
const NO_EVENTS: StepResult["1"] = []
|
||||||
|
|
||||||
// `response.completed` / `response.incomplete` are clean finishes that emit a
|
// `response.completed` / `response.incomplete` are clean finishes that emit a
|
||||||
// `finish` event; `response.failed` and `error` are hard failures. All four end
|
// `finish` event; `response.failed` is a hard failure. All three end the stream,
|
||||||
// the stream, so keep this set aligned with `step` and the protocol's terminal predicate.
|
// so keep this set aligned with `step` and the protocol's terminal predicate.
|
||||||
const TERMINAL_TYPES = new Set(["error", "response.completed", "response.incomplete", "response.failed"])
|
const TERMINAL_TYPES = new Set(["response.completed", "response.incomplete", "response.failed"])
|
||||||
export const terminal = (event: Event) => TERMINAL_TYPES.has(event.type)
|
export const terminal = (event: Event) => TERMINAL_TYPES.has(event.type)
|
||||||
|
|
||||||
const onOutputTextDelta = (state: ParserState, event: Event, id: string): StepResult => {
|
const onOutputTextDelta = (state: ParserState, event: Event, id: string): StepResult => {
|
||||||
@@ -1004,16 +969,10 @@ const providerErrorMessage = (event: Event, fallback: string): string => {
|
|||||||
const providerError = (state: ParserState, event: Event, fallback: string) => {
|
const providerError = (state: ParserState, event: Event, fallback: string) => {
|
||||||
const code = event.code || event.error?.code || event.response?.error?.code || undefined
|
const code = event.code || event.error?.code || event.response?.error?.code || undefined
|
||||||
const message = providerErrorMessage(event, fallback)
|
const message = providerErrorMessage(event, fallback)
|
||||||
const status =
|
|
||||||
typeof event.status === "number"
|
|
||||||
? event.status
|
|
||||||
: typeof event.status_code === "number"
|
|
||||||
? event.status_code
|
|
||||||
: undefined
|
|
||||||
return new AIError({
|
return new AIError({
|
||||||
module: state.id,
|
module: state.id,
|
||||||
method: "stream",
|
method: "stream",
|
||||||
reason: classifyProviderFailure({ message, code, status }),
|
reason: classifyProviderFailure({ message, code }),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1056,11 +1015,7 @@ export const step = (state: ParserState, event: Event) => {
|
|||||||
if (event.type === "response.completed" || event.type === "response.incomplete")
|
if (event.type === "response.completed" || event.type === "response.incomplete")
|
||||||
return Effect.succeed(onResponseFinish(state, event))
|
return Effect.succeed(onResponseFinish(state, event))
|
||||||
if (event.type === "response.failed") return providerError(state, event, `${state.name} response failed`)
|
if (event.type === "response.failed") return providerError(state, event, `${state.name} response failed`)
|
||||||
if (event.type === "error")
|
if (event.type === "error") return providerError(state, event, `${state.name} stream error`)
|
||||||
return decodeKnownErrorEvent(event).pipe(
|
|
||||||
Effect.mapError(() => ProviderShared.eventError(state.id, `${state.name} returned a malformed error event`)),
|
|
||||||
Effect.flatMap(() => providerError(state, event, `${state.name} stream error`)),
|
|
||||||
)
|
|
||||||
return Effect.succeed<StepResult>([state, NO_EVENTS])
|
return Effect.succeed<StepResult>([state, NO_EVENTS])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -67,6 +67,12 @@ const OpenAIChatAssistantToolCall = Schema.Struct({
|
|||||||
})
|
})
|
||||||
type OpenAIChatAssistantToolCall = Schema.Schema.Type<typeof OpenAIChatAssistantToolCall>
|
type OpenAIChatAssistantToolCall = Schema.Schema.Type<typeof OpenAIChatAssistantToolCall>
|
||||||
|
|
||||||
|
// Intentionally omit Gemini's provider-specific `extra_content.google.thought_signature`
|
||||||
|
// extension until direct Google OpenAI-compatible routing is supported here:
|
||||||
|
// https://github.com/vercel/ai/issues/11590
|
||||||
|
// https://github.com/vercel/ai/pull/11745
|
||||||
|
// https://ai.google.dev/gemini-api/docs/thought-signatures#openai
|
||||||
|
|
||||||
const OpenAIChatUserContent = Schema.Union([
|
const OpenAIChatUserContent = Schema.Union([
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
type: Schema.Literal("text"),
|
type: Schema.Literal("text"),
|
||||||
@@ -145,22 +151,33 @@ export type OpenAIChatBody = Schema.Schema.Type<typeof OpenAIChatBody>
|
|||||||
// The event schema is one decoded SSE `data:` payload. `Framing.sse` splits the
|
// The event schema is one decoded SSE `data:` payload. `Framing.sse` splits the
|
||||||
// byte stream into strings, then `Protocol.jsonEvent` decodes each string into
|
// byte stream into strings, then `Protocol.jsonEvent` decodes each string into
|
||||||
// this provider-native event shape.
|
// this provider-native event shape.
|
||||||
const OpenAIChatUsage = Schema.Struct({
|
const OpenAIChatUsage = Schema.StructWithRest(
|
||||||
prompt_tokens: Schema.optional(Schema.Number),
|
Schema.Struct({
|
||||||
completion_tokens: Schema.optional(Schema.Number),
|
prompt_tokens: optionalNull(Schema.Number),
|
||||||
total_tokens: Schema.optional(Schema.Number),
|
completion_tokens: optionalNull(Schema.Number),
|
||||||
prompt_tokens_details: optionalNull(
|
total_tokens: optionalNull(Schema.Number),
|
||||||
Schema.Struct({
|
prompt_tokens_details: optionalNull(
|
||||||
cached_tokens: Schema.optional(Schema.Number),
|
Schema.StructWithRest(
|
||||||
cache_write_tokens: Schema.optional(Schema.Number),
|
Schema.Struct({
|
||||||
}),
|
cached_tokens: optionalNull(Schema.Number),
|
||||||
),
|
cache_write_tokens: optionalNull(Schema.Number),
|
||||||
completion_tokens_details: optionalNull(
|
}),
|
||||||
Schema.Struct({
|
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||||
reasoning_tokens: Schema.optional(Schema.Number),
|
),
|
||||||
}),
|
),
|
||||||
),
|
completion_tokens_details: optionalNull(
|
||||||
})
|
Schema.StructWithRest(
|
||||||
|
Schema.Struct({
|
||||||
|
reasoning_tokens: optionalNull(Schema.Number),
|
||||||
|
accepted_prediction_tokens: optionalNull(Schema.Number),
|
||||||
|
rejected_prediction_tokens: optionalNull(Schema.Number),
|
||||||
|
}),
|
||||||
|
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
[Schema.Record(Schema.String, Schema.Unknown)],
|
||||||
|
)
|
||||||
|
|
||||||
const OpenAIChatToolCallDeltaFunction = Schema.Struct({
|
const OpenAIChatToolCallDeltaFunction = Schema.Struct({
|
||||||
name: optionalNull(Schema.String),
|
name: optionalNull(Schema.String),
|
||||||
@@ -168,7 +185,7 @@ const OpenAIChatToolCallDeltaFunction = Schema.Struct({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const OpenAIChatToolCallDelta = Schema.Struct({
|
const OpenAIChatToolCallDelta = Schema.Struct({
|
||||||
index: Schema.Number,
|
index: optionalNull(Schema.Number),
|
||||||
id: optionalNull(Schema.String),
|
id: optionalNull(Schema.String),
|
||||||
function: optionalNull(OpenAIChatToolCallDeltaFunction),
|
function: optionalNull(OpenAIChatToolCallDeltaFunction),
|
||||||
})
|
})
|
||||||
@@ -222,6 +239,8 @@ export interface ParserState {
|
|||||||
readonly reasoningDetails: Array<unknown>
|
readonly reasoningDetails: Array<unknown>
|
||||||
readonly reasoningDetailsObserved: boolean
|
readonly reasoningDetailsObserved: boolean
|
||||||
readonly reasoningEmitted: boolean
|
readonly reasoningEmitted: boolean
|
||||||
|
readonly latestToolIndex?: number
|
||||||
|
readonly nextToolIndex: number
|
||||||
}
|
}
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
@@ -559,22 +578,34 @@ const mapFinishReason = (reason: string | null | undefined): FinishReason => {
|
|||||||
// satisfied on both sides.
|
// satisfied on both sides.
|
||||||
const mapUsage = (usage: OpenAIChatEvent["usage"]): Usage | undefined => {
|
const mapUsage = (usage: OpenAIChatEvent["usage"]): Usage | undefined => {
|
||||||
if (!usage) return undefined
|
if (!usage) return undefined
|
||||||
const cached = usage.prompt_tokens_details?.cached_tokens
|
const input = usage.prompt_tokens ?? undefined
|
||||||
const cacheWrite = usage.prompt_tokens_details?.cache_write_tokens
|
const output = usage.completion_tokens ?? undefined
|
||||||
const reasoning = usage.completion_tokens_details?.reasoning_tokens
|
const cached = usage.prompt_tokens_details?.cached_tokens ?? undefined
|
||||||
const nonCached = ProviderShared.subtractTokens(usage.prompt_tokens, ProviderShared.sumTokens(cached, cacheWrite))
|
const cacheWrite = usage.prompt_tokens_details?.cache_write_tokens ?? undefined
|
||||||
|
const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? undefined
|
||||||
|
const nonCached = ProviderShared.subtractTokens(input, ProviderShared.sumTokens(cached, cacheWrite))
|
||||||
return new Usage({
|
return new Usage({
|
||||||
inputTokens: usage.prompt_tokens,
|
inputTokens: input,
|
||||||
outputTokens: usage.completion_tokens,
|
outputTokens: output,
|
||||||
nonCachedInputTokens: nonCached,
|
nonCachedInputTokens: nonCached,
|
||||||
cacheReadInputTokens: cached,
|
cacheReadInputTokens: cached,
|
||||||
cacheWriteInputTokens: cacheWrite,
|
cacheWriteInputTokens: cacheWrite,
|
||||||
reasoningTokens: reasoning,
|
reasoningTokens: reasoning,
|
||||||
totalTokens: ProviderShared.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),
|
totalTokens: ProviderShared.totalTokens(input, output, usage.total_tokens ?? undefined),
|
||||||
providerMetadata: { openai: usage },
|
providerMetadata: { openai: usage },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const toolIndexByID = (
|
||||||
|
tools: ParserState["tools"],
|
||||||
|
pendingTools: ParserState["pendingTools"],
|
||||||
|
id: string | undefined,
|
||||||
|
) => {
|
||||||
|
if (!id) return undefined
|
||||||
|
const entry = Object.entries({ ...pendingTools, ...tools }).find(([, tool]) => tool?.id === id)
|
||||||
|
return entry ? Number(entry[0]) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
const reasoningDelta = (
|
const reasoningDelta = (
|
||||||
delta: Schema.Schema.Type<typeof OpenAIChatDelta> | null | undefined,
|
delta: Schema.Schema.Type<typeof OpenAIChatDelta> | null | undefined,
|
||||||
configuredField?: string,
|
configuredField?: string,
|
||||||
@@ -657,17 +688,34 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
const usage = mapUsage(event.usage) ?? state.usage
|
const usage = mapUsage(event.usage) ?? state.usage
|
||||||
const choice = event.choices?.[0]
|
const choice = event.choices?.[0]
|
||||||
const finishReason = choice?.finish_reason
|
const rawFinishReason = choice?.finish_reason
|
||||||
? { normalized: mapFinishReason(choice.finish_reason), raw: choice.native_finish_reason ?? choice.finish_reason }
|
const finishReason =
|
||||||
: state.finishReason
|
rawFinishReason !== undefined && rawFinishReason !== null
|
||||||
|
? { normalized: mapFinishReason(rawFinishReason), raw: choice?.native_finish_reason ?? rawFinishReason }
|
||||||
|
: state.finishReason
|
||||||
const delta = choice?.delta
|
const delta = choice?.delta
|
||||||
const toolDeltas = delta?.tool_calls ?? []
|
const toolDeltas = delta?.tool_calls ?? []
|
||||||
let tools = state.tools
|
let tools = state.tools
|
||||||
let pendingTools = state.pendingTools
|
let pendingTools = state.pendingTools
|
||||||
|
let latestToolIndex = state.latestToolIndex
|
||||||
|
let nextToolIndex = state.nextToolIndex
|
||||||
|
|
||||||
let lifecycle = state.lifecycle
|
let lifecycle = state.lifecycle
|
||||||
|
|
||||||
const reasoning = reasoningDelta(delta, state.reasoningField)
|
const reasoning = reasoningDelta(delta, state.reasoningField)
|
||||||
|
const hasLateContent =
|
||||||
|
Boolean(delta?.content) ||
|
||||||
|
reasoning !== undefined ||
|
||||||
|
(Array.isArray(delta?.reasoning_details) && delta.reasoning_details.length > 0) ||
|
||||||
|
toolDeltas.some(
|
||||||
|
(tool) => Boolean(tool.id) || Boolean(tool.function?.name) || Boolean(tool.function?.arguments),
|
||||||
|
)
|
||||||
|
if (state.finishReason !== undefined) {
|
||||||
|
if (hasLateContent)
|
||||||
|
return yield* ProviderShared.eventError(ADAPTER, "OpenAI Chat received content after the finish reason")
|
||||||
|
return [{ ...state, usage }, events] as const
|
||||||
|
}
|
||||||
|
|
||||||
const reasoningField = state.reasoningField ?? (!state.lifecycle.text.has("text-0") ? reasoning?.field : undefined)
|
const reasoningField = state.reasoningField ?? (!state.lifecycle.text.has("text-0") ? reasoning?.field : undefined)
|
||||||
const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined
|
const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined
|
||||||
if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
|
if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
|
||||||
@@ -694,24 +742,37 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content)
|
lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content)
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const tool of toolDeltas) {
|
// Compatible providers may omit indexes. Prefer durable identity, then use
|
||||||
const current = tools[tool.index]
|
// batch position for parallel deltas or the latest call for sparse chunks.
|
||||||
const pending = pendingTools[tool.index]
|
for (const [position, tool] of toolDeltas.entries()) {
|
||||||
|
const matched = toolIndexByID(tools, pendingTools, tool.id || undefined)
|
||||||
|
const fallback = toolDeltas.length > 1 ? position : (latestToolIndex ?? position)
|
||||||
|
const fallbackTool = tools[fallback] ?? pendingTools[fallback]
|
||||||
|
const index =
|
||||||
|
tool.index ?? matched ??
|
||||||
|
(tool.id && fallbackTool?.id && fallbackTool.id !== tool.id ? nextToolIndex : fallback)
|
||||||
|
const current = tools[index]
|
||||||
|
const pending = pendingTools[index]
|
||||||
const id = current?.id ?? pending?.id ?? (tool.id || undefined)
|
const id = current?.id ?? pending?.id ?? (tool.id || undefined)
|
||||||
const name = current?.name ?? pending?.name ?? (tool.function?.name || undefined)
|
const name = current?.name ?? pending?.name ?? (tool.function?.name || undefined)
|
||||||
const text = `${pending?.input ?? ""}${tool.function?.arguments ?? ""}`
|
const text = `${pending?.input ?? ""}${tool.function?.arguments ?? ""}`
|
||||||
|
latestToolIndex = index
|
||||||
|
nextToolIndex = Math.max(nextToolIndex, index + 1)
|
||||||
if (!current && (!id || !name)) {
|
if (!current && (!id || !name)) {
|
||||||
pendingTools = { ...pendingTools, [tool.index]: { id: id || undefined, name: name || undefined, input: text } }
|
pendingTools = {
|
||||||
|
...pendingTools,
|
||||||
|
[index]: { id: id || undefined, name: name || undefined, input: text },
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (pending) {
|
if (pending) {
|
||||||
pendingTools = { ...pendingTools }
|
pendingTools = { ...pendingTools }
|
||||||
delete pendingTools[tool.index]
|
delete pendingTools[index]
|
||||||
}
|
}
|
||||||
const result = ToolStream.appendOrStart(
|
const result = ToolStream.appendOrStart(
|
||||||
ADAPTER,
|
ADAPTER,
|
||||||
tools,
|
tools,
|
||||||
tool.index,
|
index,
|
||||||
{ id: id || undefined, name: name || undefined, text },
|
{ id: id || undefined, name: name || undefined, text },
|
||||||
"OpenAI Chat tool call delta is missing id or name",
|
"OpenAI Chat tool call delta is missing id or name",
|
||||||
)
|
)
|
||||||
@@ -743,6 +804,8 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
reasoningDetails: state.reasoningDetails,
|
reasoningDetails: state.reasoningDetails,
|
||||||
reasoningDetailsObserved,
|
reasoningDetailsObserved,
|
||||||
reasoningEmitted,
|
reasoningEmitted,
|
||||||
|
latestToolIndex,
|
||||||
|
nextToolIndex,
|
||||||
},
|
},
|
||||||
events,
|
events,
|
||||||
] as const
|
] as const
|
||||||
@@ -799,6 +862,7 @@ export const protocol = Protocol.make({
|
|||||||
reasoningDetails: [],
|
reasoningDetails: [],
|
||||||
reasoningDetailsObserved: false,
|
reasoningDetailsObserved: false,
|
||||||
reasoningEmitted: false,
|
reasoningEmitted: false,
|
||||||
|
nextToolIndex: 0,
|
||||||
}),
|
}),
|
||||||
step,
|
step,
|
||||||
onHalt: finishEvents,
|
onHalt: finishEvents,
|
||||||
|
|||||||
@@ -67,7 +67,6 @@ const SERVER_CODES = new Set([
|
|||||||
"overloaded_error",
|
"overloaded_error",
|
||||||
"server_error",
|
"server_error",
|
||||||
"server_is_overloaded",
|
"server_is_overloaded",
|
||||||
"slow_down",
|
|
||||||
"serviceunavailableexception",
|
"serviceunavailableexception",
|
||||||
])
|
])
|
||||||
const INVALID_REQUEST_CODES = new Set(["invalid_prompt", "invalid_request_error", "validationexception"])
|
const INVALID_REQUEST_CODES = new Set(["invalid_prompt", "invalid_request_error", "validationexception"])
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { ProviderPackage } from "../provider-package"
|
|||||||
import { ProviderID, type ModelID } from "../schema"
|
import { ProviderID, type ModelID } from "../schema"
|
||||||
import * as OpenAIChat from "../protocols/openai-chat"
|
import * as OpenAIChat from "../protocols/openai-chat"
|
||||||
import * as OpenAIResponses from "../protocols/openai-responses"
|
import * as OpenAIResponses from "../protocols/openai-responses"
|
||||||
|
import { ProviderShared } from "../protocols/shared"
|
||||||
import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
|
import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
|
||||||
|
|
||||||
export const id = ProviderID.make("azure")
|
export const id = ProviderID.make("azure")
|
||||||
@@ -19,7 +20,7 @@ export type LanguageModelOptions = AzureURL &
|
|||||||
ProviderAuthOption<"optional"> & {
|
ProviderAuthOption<"optional"> & {
|
||||||
readonly apiVersion?: string
|
readonly apiVersion?: string
|
||||||
readonly queryParams?: Record<string, string>
|
readonly queryParams?: Record<string, string>
|
||||||
readonly useCompletionUrls?: boolean
|
readonly useDeploymentBasedUrls?: boolean
|
||||||
readonly providerOptions?: OpenAIProviderOptionsInput
|
readonly providerOptions?: OpenAIProviderOptionsInput
|
||||||
}
|
}
|
||||||
export type Config = LanguageModelOptions
|
export type Config = LanguageModelOptions
|
||||||
@@ -29,27 +30,22 @@ export type Settings = ProviderPackage.Settings &
|
|||||||
readonly apiKey?: string
|
readonly apiKey?: string
|
||||||
readonly apiVersion?: string
|
readonly apiVersion?: string
|
||||||
readonly queryParams?: Readonly<Record<string, string>>
|
readonly queryParams?: Readonly<Record<string, string>>
|
||||||
|
readonly useDeploymentBasedUrls?: boolean
|
||||||
readonly providerOptions?: OpenAIProviderOptionsInput
|
readonly providerOptions?: OpenAIProviderOptionsInput
|
||||||
}
|
}
|
||||||
|
|
||||||
const resourceBaseURL = (resourceName: string) => `https://${resourceName.trim()}.openai.azure.com/openai/v1`
|
const resourceBaseURL = (resourceName: string) => `https://${resourceName.trim()}.openai.azure.com/openai`
|
||||||
|
|
||||||
const responsesRoute = OpenAIResponses.route.with({
|
const responsesRoute = OpenAIResponses.route.with({
|
||||||
id: "azure-openai-responses",
|
id: "azure-openai-responses",
|
||||||
provider: id,
|
provider: id,
|
||||||
auth: routeAuth,
|
auth: routeAuth,
|
||||||
endpoint: {
|
|
||||||
query: { "api-version": "v1" },
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const chatRoute = OpenAIChat.route.with({
|
const chatRoute = OpenAIChat.route.with({
|
||||||
id: "azure-openai-chat",
|
id: "azure-openai-chat",
|
||||||
provider: id,
|
provider: id,
|
||||||
auth: routeAuth,
|
auth: routeAuth,
|
||||||
endpoint: {
|
|
||||||
query: { "api-version": "v1" },
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
export const routes = [responsesRoute, chatRoute]
|
export const routes = [responsesRoute, chatRoute]
|
||||||
@@ -59,7 +55,7 @@ const defaults = (input: Config) => {
|
|||||||
apiKey: _,
|
apiKey: _,
|
||||||
apiVersion: _apiVersion,
|
apiVersion: _apiVersion,
|
||||||
resourceName: _resourceName,
|
resourceName: _resourceName,
|
||||||
useCompletionUrls: _useCompletionUrls,
|
useDeploymentBasedUrls: _useDeploymentBasedUrls,
|
||||||
baseURL: _baseURL,
|
baseURL: _baseURL,
|
||||||
queryParams: _queryParams,
|
queryParams: _queryParams,
|
||||||
...rest
|
...rest
|
||||||
@@ -80,37 +76,39 @@ const auth = (input: Config) => {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const configuredRoute = <Body, Prepared>(route: RouteDef<Body, Prepared>, input: Config) =>
|
const configuredRoute = <Body, Prepared>(route: RouteDef<Body, Prepared>, input: Config, modelID: string | ModelID) =>
|
||||||
route.with({
|
route.with({
|
||||||
auth: auth(input),
|
auth: auth(input),
|
||||||
endpoint: {
|
endpoint: endpoint(input, modelID),
|
||||||
// AtLeastOne guarantees at least one is set; baseURL wins if both are.
|
|
||||||
baseURL: input.baseURL ?? resourceBaseURL(input.resourceName!),
|
|
||||||
query: {
|
|
||||||
...(input.apiVersion ? { "api-version": input.apiVersion } : {}),
|
|
||||||
...input.queryParams,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function endpoint(input: Config, modelID: string | ModelID) {
|
||||||
|
const baseURL = ProviderShared.trimBaseUrl(input.baseURL ?? resourceBaseURL(input.resourceName!))
|
||||||
|
const query = { "api-version": input.apiVersion ?? "v1", ...input.queryParams }
|
||||||
|
|
||||||
|
if (input.useDeploymentBasedUrls) return { baseURL: `${baseURL}/deployments/${modelID}`, query }
|
||||||
|
if (input.baseURL !== undefined && !new URL(input.baseURL).hostname.endsWith(".openai.azure.com")) {
|
||||||
|
return { baseURL, query: input.queryParams }
|
||||||
|
}
|
||||||
|
return { baseURL: `${baseURL}/v1`, query }
|
||||||
|
}
|
||||||
|
|
||||||
export const configure = (input: Config) => {
|
export const configure = (input: Config) => {
|
||||||
const configuredResponsesRoute = configuredRoute(responsesRoute, input)
|
|
||||||
const configuredChatRoute = configuredRoute(chatRoute, input)
|
|
||||||
const modelDefaults = defaults(input)
|
const modelDefaults = defaults(input)
|
||||||
|
|
||||||
const responses = (modelID: string | ModelID) =>
|
const responses = (modelID: string | ModelID) =>
|
||||||
configuredResponsesRoute
|
configuredRoute(responsesRoute, input, modelID)
|
||||||
.with(withOpenAIOptions(modelID, modelDefaults))
|
.with(withOpenAIOptions(modelID, modelDefaults))
|
||||||
.model<OpenAIProviderOptionsInput>({ id: modelID })
|
.model<OpenAIProviderOptionsInput>({ id: modelID })
|
||||||
|
|
||||||
const chat = (modelID: string | ModelID) =>
|
const chat = (modelID: string | ModelID) =>
|
||||||
configuredChatRoute
|
configuredRoute(chatRoute, input, modelID)
|
||||||
.with(withOpenAIOptions(modelID, modelDefaults))
|
.with(withOpenAIOptions(modelID, modelDefaults))
|
||||||
.model<OpenAIProviderOptionsInput>({ id: modelID })
|
.model<OpenAIProviderOptionsInput>({ id: modelID })
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
model: (modelID: string | ModelID) => (input.useCompletionUrls === true ? chat(modelID) : responses(modelID)),
|
model: responses,
|
||||||
responses,
|
responses,
|
||||||
chat,
|
chat,
|
||||||
configure,
|
configure,
|
||||||
@@ -131,6 +129,7 @@ const config = (settings: Settings): Config => {
|
|||||||
limits: settings.limits,
|
limits: settings.limits,
|
||||||
providerOptions: settings.providerOptions,
|
providerOptions: settings.providerOptions,
|
||||||
queryParams: settings.queryParams === undefined ? undefined : { ...settings.queryParams },
|
queryParams: settings.queryParams === undefined ? undefined : { ...settings.queryParams },
|
||||||
|
useDeploymentBasedUrls: settings.useDeploymentBasedUrls,
|
||||||
}
|
}
|
||||||
if (settings.baseURL !== undefined) return { ...common, baseURL: settings.baseURL }
|
if (settings.baseURL !== undefined) return { ...common, baseURL: settings.baseURL }
|
||||||
if (settings.resourceName !== undefined) return { ...common, resourceName: settings.resourceName }
|
if (settings.resourceName !== undefined) return { ...common, resourceName: settings.resourceName }
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ export type AnthropicThinkingInput = AnthropicMessages.ThinkingInput
|
|||||||
|
|
||||||
const VERSION = "vertex-2023-10-16" as const
|
const VERSION = "vertex-2023-10-16" as const
|
||||||
|
|
||||||
// models.dev uses this provider id even though the API contract is Anthropic Messages.
|
export const id = ProviderID.make("google-vertex")
|
||||||
export const id = ProviderID.make("google-vertex-anthropic")
|
|
||||||
|
|
||||||
export type Config = RouteDefaultsInput &
|
export type Config = RouteDefaultsInput &
|
||||||
GoogleVertexShared.OAuthOptions & {
|
GoogleVertexShared.OAuthOptions & {
|
||||||
|
|||||||
@@ -29,45 +29,14 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/AI
|
|||||||
const transportError = (
|
const transportError = (
|
||||||
method: string,
|
method: string,
|
||||||
message: string,
|
message: string,
|
||||||
input: {
|
input: { readonly url?: string; readonly kind?: string } = {},
|
||||||
readonly url?: string
|
|
||||||
readonly kind?: string
|
|
||||||
readonly phase?: TransportReason["phase"]
|
|
||||||
readonly delivery?: TransportReason["delivery"]
|
|
||||||
} = {},
|
|
||||||
) =>
|
) =>
|
||||||
new AIError({
|
new AIError({
|
||||||
module: "WebSocketExecutor",
|
module: "WebSocketExecutor",
|
||||||
method,
|
method,
|
||||||
reason: new TransportReason({
|
reason: new TransportReason({ message, url: input.url, kind: input.kind }),
|
||||||
message,
|
|
||||||
url: input.url,
|
|
||||||
kind: input.kind,
|
|
||||||
phase: input.phase,
|
|
||||||
delivery: input.delivery,
|
|
||||||
}),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const annotateTransportError = (
|
|
||||||
error: AIError,
|
|
||||||
input: { readonly phase: TransportReason["phase"]; readonly delivery: TransportReason["delivery"] },
|
|
||||||
) =>
|
|
||||||
error.reason._tag === "Transport"
|
|
||||||
? new AIError({
|
|
||||||
module: error.module,
|
|
||||||
method: error.method,
|
|
||||||
reason: new TransportReason({
|
|
||||||
message: error.reason.message,
|
|
||||||
kind: error.reason.kind,
|
|
||||||
url: error.reason.url,
|
|
||||||
http: error.reason.http,
|
|
||||||
phase: input.phase,
|
|
||||||
delivery: input.delivery,
|
|
||||||
recovery: error.reason.recovery,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
: error
|
|
||||||
|
|
||||||
const eventMessage = (event: Event) => {
|
const eventMessage = (event: Event) => {
|
||||||
if ("message" in event && typeof event.message === "string") return event.message
|
if ("message" in event && typeof event.message === "string") return event.message
|
||||||
return event.type
|
return event.type
|
||||||
@@ -87,8 +56,6 @@ const waitOpen = (ws: globalThis.WebSocket, input: WebSocketRequest) => {
|
|||||||
transportError("open", `WebSocket closed before opening (state ${ws.readyState})`, {
|
transportError("open", `WebSocket closed before opening (state ${ws.readyState})`, {
|
||||||
url: input.url,
|
url: input.url,
|
||||||
kind: "open",
|
kind: "open",
|
||||||
phase: "connect",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -112,12 +79,7 @@ const waitOpen = (ws: globalThis.WebSocket, input: WebSocketRequest) => {
|
|||||||
cleanup()
|
cleanup()
|
||||||
resume(
|
resume(
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
transportError("open", `Failed to open WebSocket: ${eventMessage(event)}`, {
|
transportError("open", `Failed to open WebSocket: ${eventMessage(event)}`, { url: input.url, kind: "open" }),
|
||||||
url: input.url,
|
|
||||||
kind: "open",
|
|
||||||
phase: "connect",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -128,8 +90,6 @@ const waitOpen = (ws: globalThis.WebSocket, input: WebSocketRequest) => {
|
|||||||
transportError("open", `WebSocket closed before opening with code ${event.code}`, {
|
transportError("open", `WebSocket closed before opening with code ${event.code}`, {
|
||||||
url: input.url,
|
url: input.url,
|
||||||
kind: "open",
|
kind: "open",
|
||||||
phase: "connect",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -159,8 +119,6 @@ const webSocketUrl = (value: string) =>
|
|||||||
transportError("prepare", error instanceof Error ? error.message : "Invalid WebSocket URL", {
|
transportError("prepare", error instanceof Error ? error.message : "Invalid WebSocket URL", {
|
||||||
url: value,
|
url: value,
|
||||||
kind: "websocket",
|
kind: "websocket",
|
||||||
phase: "prepare",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -172,8 +130,6 @@ export const open = (input: WebSocketRequest) =>
|
|||||||
transportError("open", error instanceof Error ? error.message : "Failed to construct WebSocket", {
|
transportError("open", error instanceof Error ? error.message : "Failed to construct WebSocket", {
|
||||||
url: input.url,
|
url: input.url,
|
||||||
kind: "open",
|
kind: "open",
|
||||||
phase: "connect",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
}),
|
||||||
}).pipe(Effect.flatMap((ws) => fromWebSocket(ws, input)))
|
}).pipe(Effect.flatMap((ws) => fromWebSocket(ws, input)))
|
||||||
|
|
||||||
@@ -194,11 +150,7 @@ export const fromWebSocket = (
|
|||||||
Queue.failCauseUnsafe(
|
Queue.failCauseUnsafe(
|
||||||
messages,
|
messages,
|
||||||
Cause.fail(
|
Cause.fail(
|
||||||
transportError("message", "Unsupported WebSocket message payload", {
|
transportError("message", "Unsupported WebSocket message payload", { url: input.url, kind: "message" }),
|
||||||
url: input.url,
|
|
||||||
kind: "message",
|
|
||||||
phase: "receive",
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -206,23 +158,16 @@ export const fromWebSocket = (
|
|||||||
Queue.failCauseUnsafe(
|
Queue.failCauseUnsafe(
|
||||||
messages,
|
messages,
|
||||||
Cause.fail(
|
Cause.fail(
|
||||||
transportError("message", `WebSocket error: ${eventMessage(event)}`, {
|
transportError("message", `WebSocket error: ${eventMessage(event)}`, { url: input.url, kind: "message" }),
|
||||||
url: input.url,
|
|
||||||
kind: "message",
|
|
||||||
phase: "receive",
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
const onClose = (event: CloseEvent) => {
|
const onClose = (event: CloseEvent) => {
|
||||||
|
if (event.code === 1000 || event.code === 1005) return Queue.endUnsafe(messages)
|
||||||
Queue.failCauseUnsafe(
|
Queue.failCauseUnsafe(
|
||||||
messages,
|
messages,
|
||||||
Cause.fail(
|
Cause.fail(
|
||||||
transportError("message", `WebSocket closed with code ${event.code}`, {
|
transportError("message", `WebSocket closed with code ${event.code}`, { url: input.url, kind: "close" }),
|
||||||
url: input.url,
|
|
||||||
kind: "close",
|
|
||||||
phase: "close",
|
|
||||||
}),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -244,8 +189,6 @@ export const fromWebSocket = (
|
|||||||
transportError("sendText", error instanceof Error ? error.message : "Failed to send WebSocket message", {
|
transportError("sendText", error instanceof Error ? error.message : "Failed to send WebSocket message", {
|
||||||
url: input.url,
|
url: input.url,
|
||||||
kind: "write",
|
kind: "write",
|
||||||
phase: "send",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
messages: Stream.fromQueue(messages),
|
messages: Stream.fromQueue(messages),
|
||||||
@@ -301,8 +244,6 @@ export const json = <Body, Message>(input: JsonInput<Body, Message>): JsonTransp
|
|||||||
transportError("json", "WebSocket JSON transport requires WebSocketExecutor.Service", {
|
transportError("json", "WebSocket JSON transport requires WebSocketExecutor.Service", {
|
||||||
url: prepared.url,
|
url: prepared.url,
|
||||||
kind: "websocket",
|
kind: "websocket",
|
||||||
phase: "prepare",
|
|
||||||
delivery: "not-sent",
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -310,27 +251,11 @@ export const json = <Body, Message>(input: JsonInput<Body, Message>): JsonTransp
|
|||||||
return Stream.unwrap(
|
return Stream.unwrap(
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const connection = yield* Effect.acquireRelease(
|
const connection = yield* Effect.acquireRelease(
|
||||||
webSocket
|
webSocket.open({ url: prepared.url, headers: prepared.headers }),
|
||||||
.open({ url: prepared.url, headers: prepared.headers })
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((error) => annotateTransportError(error, { phase: "connect", delivery: "not-sent" })),
|
|
||||||
),
|
|
||||||
(connection) => connection.close,
|
(connection) => connection.close,
|
||||||
)
|
)
|
||||||
yield* connection.sendText(prepared.message)
|
yield* connection.sendText(prepared.message)
|
||||||
let observed = false
|
return connection.messages.pipe(Stream.map((message) => messageText(message, decoder)))
|
||||||
return connection.messages.pipe(
|
|
||||||
Stream.map((message) => {
|
|
||||||
observed = true
|
|
||||||
return messageText(message, decoder)
|
|
||||||
}),
|
|
||||||
Stream.mapError((error) =>
|
|
||||||
annotateTransportError(error, {
|
|
||||||
phase: error.reason._tag === "Transport" && error.reason.phase === "close" ? "close" : "receive",
|
|
||||||
delivery: observed ? "accepted" : "ambiguous",
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -98,13 +98,6 @@ export class TransportReason extends Schema.Class<TransportReason>("AI.Error.Tra
|
|||||||
kind: Schema.optional(Schema.String),
|
kind: Schema.optional(Schema.String),
|
||||||
url: Schema.optional(Schema.String),
|
url: Schema.optional(Schema.String),
|
||||||
http: Schema.optional(HttpContext),
|
http: Schema.optional(HttpContext),
|
||||||
phase: Schema.optional(
|
|
||||||
Schema.Literals(["prepare", "queue", "connect", "send", "receive", "decode", "complete", "fallback", "close"]),
|
|
||||||
),
|
|
||||||
delivery: Schema.optional(Schema.Literals(["not-sent", "rejected", "ambiguous", "accepted"])),
|
|
||||||
recovery: Schema.optional(
|
|
||||||
Schema.Literals(["retry-connect", "retry-full", "rotate-and-retry-full", "fallback-http", "fail"]),
|
|
||||||
),
|
|
||||||
}) {}
|
}) {}
|
||||||
|
|
||||||
export class InvalidProviderOutputReason extends Schema.Class<InvalidProviderOutputReason>(
|
export class InvalidProviderOutputReason extends Schema.Class<InvalidProviderOutputReason>(
|
||||||
|
|||||||
@@ -69,10 +69,10 @@ describe("provider error classification", () => {
|
|||||||
|
|
||||||
test("classifies V1 overloaded provider codes", () => {
|
test("classifies V1 overloaded provider codes", () => {
|
||||||
expect(
|
expect(
|
||||||
['{"code":"resource_exhausted"}', '{"code":"service_unavailable"}', '{"code":"slow_down"}'].map(
|
['{"code":"resource_exhausted"}', '{"code":"service_unavailable"}'].map(
|
||||||
(message) => classifyProviderFailure({ message })._tag,
|
(message) => classifyProviderFailure({ message })._tag,
|
||||||
),
|
),
|
||||||
).toEqual(["ProviderInternal", "ProviderInternal", "ProviderInternal"])
|
).toEqual(["ProviderInternal", "ProviderInternal"])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("classifies transient client statuses as provider internal", () => {
|
test("classifies transient client statuses as provider internal", () => {
|
||||||
|
|||||||
@@ -209,6 +209,27 @@ describe("provider package entrypoints", () => {
|
|||||||
expect(chat.route.id).toBe("azure-openai-chat")
|
expect(chat.route.id).toBe("azure-openai-chat")
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("constructs Azure deployment URLs and preserves custom gateway URLs", async () => {
|
||||||
|
const Azure = await import("@opencode-ai/ai/providers/azure")
|
||||||
|
const deployment = Azure.model("custom-deployment", {
|
||||||
|
apiKey: "fixture",
|
||||||
|
resourceName: "opencode-test",
|
||||||
|
apiVersion: "2025-01-01-preview",
|
||||||
|
useDeploymentBasedUrls: true,
|
||||||
|
})
|
||||||
|
const gateway = Azure.model("gateway-model", {
|
||||||
|
apiKey: "fixture",
|
||||||
|
baseURL: "https://gateway.example/azure/",
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(deployment.route.endpoint).toMatchObject({
|
||||||
|
baseURL: "https://opencode-test.openai.azure.com/openai/deployments/custom-deployment",
|
||||||
|
query: { "api-version": "2025-01-01-preview" },
|
||||||
|
})
|
||||||
|
expect(gateway.route.endpoint.baseURL).toBe("https://gateway.example/azure")
|
||||||
|
expect(gateway.route.endpoint.query).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
test("maps Google package settings onto the Gemini model", async () => {
|
test("maps Google package settings onto the Gemini model", async () => {
|
||||||
const Google = await import("@opencode-ai/ai/providers/google")
|
const Google = await import("@opencode-ai/ai/providers/google")
|
||||||
const selected = Google.model("gemini-2.5-flash", {
|
const selected = Google.model("gemini-2.5-flash", {
|
||||||
|
|||||||
@@ -56,13 +56,14 @@ describe("Google Vertex providers", () => {
|
|||||||
|
|
||||||
it.effect("projects Anthropic Messages onto the Vertex raw-predict API", () =>
|
it.effect("projects Anthropic Messages onto the Vertex raw-predict API", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
|
const model = GoogleVertexMessages.configure({
|
||||||
|
accessToken: "vertex-token",
|
||||||
|
location: "eu",
|
||||||
|
project: "vertex-project",
|
||||||
|
}).model("claude-sonnet-4-6")
|
||||||
const response = yield* LLMClient.generate(
|
const response = yield* LLMClient.generate(
|
||||||
LLM.request({
|
LLM.request({
|
||||||
model: GoogleVertexMessages.configure({
|
model,
|
||||||
accessToken: "vertex-token",
|
|
||||||
location: "eu",
|
|
||||||
project: "vertex-project",
|
|
||||||
}).model("claude-sonnet-4-6"),
|
|
||||||
prompt: "Say hello.",
|
prompt: "Say hello.",
|
||||||
}),
|
}),
|
||||||
).pipe(
|
).pipe(
|
||||||
@@ -97,6 +98,7 @@ describe("Google Vertex providers", () => {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
expect(model.provider).toBe("google-vertex")
|
||||||
expect(response.text).toBe("Hello.")
|
expect(response.text).toBe("Hello.")
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { compileRequest } from "../../src/route/client"
|
|||||||
import * as OpenAICompatible from "../../src/providers/openai-compatible"
|
import * as OpenAICompatible from "../../src/providers/openai-compatible"
|
||||||
import * as OpenAICompatibleChat from "../../src/protocols/openai-compatible-chat"
|
import * as OpenAICompatibleChat from "../../src/protocols/openai-compatible-chat"
|
||||||
import { it } from "../lib/effect"
|
import { it } from "../lib/effect"
|
||||||
import { dynamicResponse } from "../lib/http"
|
import { dynamicResponse, fixedResponse } from "../lib/http"
|
||||||
import { sseEvents } from "../lib/sse"
|
import { sseEvents } from "../lib/sse"
|
||||||
|
|
||||||
const Json = Schema.fromJsonString(Schema.Unknown)
|
const Json = Schema.fromJsonString(Schema.Unknown)
|
||||||
@@ -253,4 +253,106 @@ describe("OpenAI-compatible Chat route", () => {
|
|||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("accepts nullable usage and preserves provider fields", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
deltaChunk({ content: "Hello" }),
|
||||||
|
deltaChunk({}, "stop"),
|
||||||
|
usageChunk({
|
||||||
|
prompt_tokens: null,
|
||||||
|
completion_tokens: null,
|
||||||
|
total_tokens: null,
|
||||||
|
prompt_tokens_details: { cached_tokens: null, vendor_cache_tokens: 3 },
|
||||||
|
completion_tokens_details: {
|
||||||
|
reasoning_tokens: null,
|
||||||
|
accepted_prediction_tokens: null,
|
||||||
|
rejected_prediction_tokens: null,
|
||||||
|
},
|
||||||
|
cost: "0.001",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.usage).toMatchObject({
|
||||||
|
inputTokens: undefined,
|
||||||
|
outputTokens: undefined,
|
||||||
|
totalTokens: undefined,
|
||||||
|
providerMetadata: {
|
||||||
|
openai: {
|
||||||
|
prompt_tokens: null,
|
||||||
|
completion_tokens: null,
|
||||||
|
total_tokens: null,
|
||||||
|
prompt_tokens_details: { cached_tokens: null, vendor_cache_tokens: 3 },
|
||||||
|
cost: "0.001",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("assembles indexless parallel tool calls across sparse chunks", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const response = yield* LLMClient.generate(
|
||||||
|
LLMRequest.update(request, {
|
||||||
|
tools: [ToolDefinition.make({ name: "weather", description: "Get weather", inputSchema: { type: "object" } })],
|
||||||
|
}),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
deltaChunk({
|
||||||
|
tool_calls: [
|
||||||
|
{ id: "call_paris", function: { name: "weather", arguments: '{"city":"' } },
|
||||||
|
{ index: null, id: "call_london", function: { name: "weather", arguments: '{"city":"' } },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
deltaChunk({ tool_calls: [{ function: { arguments: 'London"}' } }] }),
|
||||||
|
deltaChunk({ tool_calls: [{ id: "call_paris", function: { arguments: 'Paris"}' } }] }),
|
||||||
|
deltaChunk({}, "tool_calls"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.toolCalls).toMatchObject([
|
||||||
|
{ id: "call_paris", name: "weather", input: { city: "Paris" } },
|
||||||
|
{ id: "call_london", name: "weather", input: { city: "London" } },
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("treats an empty finish reason as terminal", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(fixedResponse(sseEvents(deltaChunk({ content: "Hello" }), deltaChunk({}, "")))),
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(response.finishReason).toEqual({ normalized: "unknown", raw: "" })
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("rejects content after a terminal chunk", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const error = yield* LLMClient.generate(request).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
fixedResponse(
|
||||||
|
sseEvents(
|
||||||
|
deltaChunk({ content: "Hello" }),
|
||||||
|
deltaChunk({}, "stop"),
|
||||||
|
deltaChunk({ tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: "{}" } }] }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.flip,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(error.message).toContain("OpenAI Chat received content after the finish reason")
|
||||||
|
}),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
ToolCallPart,
|
ToolCallPart,
|
||||||
ToolDefinition,
|
ToolDefinition,
|
||||||
ToolResultPart,
|
ToolResultPart,
|
||||||
TransportReason,
|
|
||||||
Usage,
|
Usage,
|
||||||
} from "../../src"
|
} from "../../src"
|
||||||
import { Auth, LLMClient, RequestExecutor, WebSocketExecutor } from "../../src/route"
|
import { Auth, LLMClient, RequestExecutor, WebSocketExecutor } from "../../src/route"
|
||||||
@@ -289,114 +288,6 @@ describe("OpenAI Responses route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
it.effect("terminates WebSocket control events without waiting for the socket to close", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const events = [
|
|
||||||
{ type: "error", error: { code: "slow_down", message: "Try later" } },
|
|
||||||
{
|
|
||||||
type: "error",
|
|
||||||
status_code: 429,
|
|
||||||
message: "Rate limited",
|
|
||||||
headers: { "retry-after": 1, "x-request-id": "request", cached: false, invalid: [] },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "response.failed",
|
|
||||||
response: { error: { code: "server_error", message: "Unavailable" } },
|
|
||||||
},
|
|
||||||
{ type: "error", status: "not-a-status", message: "Malformed status" },
|
|
||||||
]
|
|
||||||
|
|
||||||
const errors = yield* Effect.forEach(events, (event) =>
|
|
||||||
LLMClient.generate(
|
|
||||||
LLM.request({
|
|
||||||
model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).responsesWebSocket(
|
|
||||||
"gpt-4.1-mini",
|
|
||||||
),
|
|
||||||
prompt: "Say hello.",
|
|
||||||
}),
|
|
||||||
).pipe(
|
|
||||||
Effect.provide(
|
|
||||||
LLMClient.layer.pipe(
|
|
||||||
Layer.provide(
|
|
||||||
Layer.mergeAll(
|
|
||||||
Layer.succeed(
|
|
||||||
RequestExecutor.Service,
|
|
||||||
RequestExecutor.Service.of({ execute: () => Effect.die("unexpected HTTP request") }),
|
|
||||||
),
|
|
||||||
Layer.succeed(
|
|
||||||
WebSocketExecutor.Service,
|
|
||||||
WebSocketExecutor.Service.of({
|
|
||||||
open: () =>
|
|
||||||
Effect.succeed({
|
|
||||||
sendText: () => Effect.void,
|
|
||||||
messages: Stream.make(ProviderShared.encodeJson(event)).pipe(Stream.concat(Stream.never)),
|
|
||||||
close: Effect.void,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Effect.flip,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(errors.map((error) => error.reason._tag)).toEqual([
|
|
||||||
"ProviderInternal",
|
|
||||||
"RateLimit",
|
|
||||||
"ProviderInternal",
|
|
||||||
"UnknownProvider",
|
|
||||||
])
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
it.effect("marks post-send WebSocket failures with delivery state", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const failure = new AIError({
|
|
||||||
module: "test",
|
|
||||||
method: "receive",
|
|
||||||
reason: new TransportReason({ message: "socket closed", phase: "close" }),
|
|
||||||
})
|
|
||||||
const streams = [
|
|
||||||
Stream.fail(failure),
|
|
||||||
Stream.make(ProviderShared.encodeJson({ type: "response.created" })).pipe(Stream.concat(Stream.fail(failure))),
|
|
||||||
]
|
|
||||||
const deps = Layer.mergeAll(
|
|
||||||
Layer.succeed(
|
|
||||||
RequestExecutor.Service,
|
|
||||||
RequestExecutor.Service.of({ execute: () => Effect.die("unexpected HTTP request") }),
|
|
||||||
),
|
|
||||||
Layer.succeed(
|
|
||||||
WebSocketExecutor.Service,
|
|
||||||
WebSocketExecutor.Service.of({
|
|
||||||
open: () =>
|
|
||||||
Effect.succeed({
|
|
||||||
sendText: () => Effect.void,
|
|
||||||
messages: streams.shift() ?? Stream.die("unexpected WebSocket open"),
|
|
||||||
close: Effect.void,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
const model = OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).responsesWebSocket(
|
|
||||||
"gpt-4.1-mini",
|
|
||||||
)
|
|
||||||
|
|
||||||
const errors = yield* Effect.forEach(["first", "second"], (prompt) =>
|
|
||||||
LLMClient.generate(LLM.request({ model, prompt })).pipe(
|
|
||||||
Effect.provide(LLMClient.layer.pipe(Layer.provide(deps))),
|
|
||||||
Effect.flip,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(errors.map((error) => error.reason)).toEqual([
|
|
||||||
expect.objectContaining({ _tag: "Transport", phase: "close", delivery: "ambiguous" }),
|
|
||||||
expect.objectContaining({ _tag: "Transport", phase: "close", delivery: "accepted" }),
|
|
||||||
])
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
it.effect("fails immediately when WebSocket is already closed", () =>
|
it.effect("fails immediately when WebSocket is already closed", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const error = yield* WebSocketExecutor.fromWebSocket(
|
const error = yield* WebSocketExecutor.fromWebSocket(
|
||||||
@@ -406,7 +297,6 @@ describe("OpenAI Responses route", () => {
|
|||||||
).pipe(Effect.flip)
|
).pipe(Effect.flip)
|
||||||
|
|
||||||
expect(error.message).toContain("closed before opening")
|
expect(error.message).toContain("closed before opening")
|
||||||
expect(error.reason).toMatchObject({ _tag: "Transport", phase: "connect", delivery: "not-sent" })
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
LanguageModel,
|
LanguageModel,
|
||||||
ModelID,
|
ModelID,
|
||||||
ProviderID,
|
ProviderID,
|
||||||
TransportReason,
|
|
||||||
Usage,
|
Usage,
|
||||||
} from "../src/schema"
|
} from "../src/schema"
|
||||||
import { ProviderShared } from "../src/protocols/shared"
|
import { ProviderShared } from "../src/protocols/shared"
|
||||||
@@ -109,21 +108,3 @@ test("AI errors expose the shared runtime tag", async () => {
|
|||||||
await Effect.runPromise(Effect.fail(error).pipe(Effect.catchTag("AI.Error", () => Effect.succeed("caught")))),
|
await Effect.runPromise(Effect.fail(error).pipe(Effect.catchTag("AI.Error", () => Effect.succeed("caught")))),
|
||||||
).toBe("caught")
|
).toBe("caught")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("transport errors serialize execution facts", () => {
|
|
||||||
const reason = new TransportReason({
|
|
||||||
message: "connection closed",
|
|
||||||
phase: "receive",
|
|
||||||
delivery: "ambiguous",
|
|
||||||
recovery: "fail",
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(Schema.encodeSync(TransportReason)(reason)).toEqual({
|
|
||||||
_tag: "Transport",
|
|
||||||
message: "connection closed",
|
|
||||||
phase: "receive",
|
|
||||||
delivery: "ambiguous",
|
|
||||||
recovery: "fail",
|
|
||||||
})
|
|
||||||
expect(Schema.decodeUnknownSync(TransportReason)(Schema.encodeSync(TransportReason)(reason))).toEqual(reason)
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,220 +0,0 @@
|
|||||||
# V1 API Migration Checklist
|
|
||||||
|
|
||||||
The app is currently hybrid. In this document, V1 refers to the legacy unprefixed server APIs used by `@opencode-ai/sdk/v2`, despite the SDK package name.
|
|
||||||
|
|
||||||
## Events
|
|
||||||
|
|
||||||
- [x] Replace `GET /global/event` with `GET /api/event`.
|
|
||||||
- `src/context/server-sdk.tsx`
|
|
||||||
- [x] Reduce current granular session and message events into the existing app projections.
|
|
||||||
- `src/context/server-session-v2-reducer.ts`
|
|
||||||
- `src/context/server-session.ts`
|
|
||||||
- [ ] Remove transitional session event dependencies: `session.created`, `session.updated`, `session.diff`, `session.status`, `session.idle`, and `session.error`.
|
|
||||||
- `src/context/global-sync/event-reducer.ts`
|
|
||||||
- `src/context/server-session.ts`
|
|
||||||
- `src/context/notification.tsx`
|
|
||||||
- `src/pages/session/usage-exceeded-dialogs.tsx`
|
|
||||||
- [ ] Remove legacy message event compatibility: `message.updated`, `message.removed`, `message.part.updated`, `message.part.removed`, and `message.part.delta`.
|
|
||||||
- `src/context/global-sync/event-reducer.ts`
|
|
||||||
- `src/context/server-session.ts`
|
|
||||||
- [x] Adapt current permission and question events to the existing request model.
|
|
||||||
- `src/context/global-sync/event-reducer.ts`
|
|
||||||
- `src/context/permission.tsx`
|
|
||||||
- [x] Consume current file watcher events.
|
|
||||||
- `src/context/file.tsx`
|
|
||||||
- [x] Consume current VCS events.
|
|
||||||
- `src/context/global-sync/event-reducer.ts`
|
|
||||||
- `src/pages/session.tsx`
|
|
||||||
- [x] Consume current `pty.exited` events.
|
|
||||||
- `src/context/terminal.tsx`
|
|
||||||
- [ ] Migrate LSP and reference events.
|
|
||||||
- `src/context/global-sync/event-reducer.ts`
|
|
||||||
|
|
||||||
## Sessions
|
|
||||||
|
|
||||||
- [x] Replace `GET /session/status` with one server-scoped `GET /api/session/active` snapshot plus V2 execution events.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [x] Migrate session listing from `GET /session`.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- `src/context/directory-sync.ts`
|
|
||||||
- `src/pages/layout.tsx`
|
|
||||||
- [x] Migrate the remaining direct session read from `GET /session/:sessionID`.
|
|
||||||
- `src/components/titlebar.tsx`
|
|
||||||
- [x] Migrate session updates from `PATCH /session/:sessionID`.
|
|
||||||
- `src/context/directory-sync.ts`
|
|
||||||
- `src/context/layout.tsx`
|
|
||||||
- `src/pages/home.tsx`
|
|
||||||
- `src/pages/layout.tsx`
|
|
||||||
- `src/pages/session/timeline/message-timeline.tsx`
|
|
||||||
- `src/components/titlebar-tab-nav.tsx`
|
|
||||||
- Renames use `POST /api/session/:sessionID/rename`; archival uses `POST /api/session/:sessionID/archive`.
|
|
||||||
- [x] Migrate session deletion from `DELETE /session/:sessionID`.
|
|
||||||
- `src/pages/session/timeline/message-timeline.tsx`
|
|
||||||
- [x] Remove session diff loading from `GET /session/:sessionID/diff`.
|
|
||||||
- Historical Session diffs remain unavailable until the current API defines their snapshot semantics.
|
|
||||||
- [x] Migrate abort from `POST /session/:sessionID/abort`.
|
|
||||||
- `src/components/prompt-input/submit.ts`
|
|
||||||
- `src/pages/session/use-session-commands.tsx`
|
|
||||||
- `src/pages/session.tsx`
|
|
||||||
- [x] Migrate revert and unrevert from `POST /session/:sessionID/revert` and `POST /session/:sessionID/unrevert`.
|
|
||||||
- `src/pages/session/use-session-commands.tsx`
|
|
||||||
- `src/pages/session.tsx`
|
|
||||||
- [x] Replace `POST /session/:sessionID/summarize` with the current compact API.
|
|
||||||
- `src/pages/session/use-session-commands.tsx`
|
|
||||||
- [x] Migrate slash commands from `POST /session/:sessionID/command`.
|
|
||||||
- `src/components/prompt-input/submit.ts`
|
|
||||||
- [x] Migrate shell execution from `POST /session/:sessionID/shell`.
|
|
||||||
- `src/components/prompt-input/submit.ts`
|
|
||||||
- [x] Migrate session fork from `POST /session/:sessionID/fork`.
|
|
||||||
- `src/components/dialog-fork.tsx`
|
|
||||||
- [ ] Migrate sharing from `POST /session/:sessionID/share` and `DELETE /session/:sessionID/share`.
|
|
||||||
- `src/pages/session/use-session-commands.tsx`
|
|
||||||
- `src/pages/session/timeline/message-timeline.tsx`
|
|
||||||
- Blocked: the current API has no sharing contract or implementation.
|
|
||||||
|
|
||||||
## Session Compatibility Fallbacks
|
|
||||||
|
|
||||||
These calls are retained as fallback adapters. The current production path supplies the current session and message APIs.
|
|
||||||
|
|
||||||
- [ ] Remove fallback `GET /session/:sessionID` after compatibility support is unnecessary.
|
|
||||||
- `src/context/server-session.ts`
|
|
||||||
- [ ] Remove fallback `GET /session/:sessionID/message` after compatibility support is unnecessary.
|
|
||||||
- `src/context/server-session.ts`
|
|
||||||
- [ ] Remove fallback `GET /session/:sessionID/message/:messageID` after compatibility support is unnecessary.
|
|
||||||
- `src/context/server-session.ts`
|
|
||||||
|
|
||||||
## Filesystem
|
|
||||||
|
|
||||||
- [ ] Migrate file listing from `GET /file`.
|
|
||||||
- `src/context/file.tsx`
|
|
||||||
- [ ] Migrate file reads from `GET /file/content`.
|
|
||||||
- `src/context/file.tsx`
|
|
||||||
- `src/pages/session/review-tab.tsx`
|
|
||||||
- `src/pages/session/v2/review-panel-v2.tsx`
|
|
||||||
- [x] Migrate path discovery from `GET /path` to `GET /api/path`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- `src/components/dialog-select-directory.tsx`
|
|
||||||
- `src/components/dialog-select-directory-v2.tsx`
|
|
||||||
|
|
||||||
## Projects And Worktrees
|
|
||||||
|
|
||||||
- [x] Migrate project listing from `GET /project` to `GET /api/project`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- [x] Migrate the current project lookup from `GET /project/current` to `GET /api/project/current`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- [ ] Migrate Git initialization from `POST /project/git/init`.
|
|
||||||
- `src/pages/session.tsx`
|
|
||||||
- [x] Migrate project updates from `PATCH /project/:projectID` to `PATCH /api/project/:projectID`.
|
|
||||||
- `src/context/layout.tsx`
|
|
||||||
- `src/components/edit-project.ts`
|
|
||||||
- `src/pages/layout.tsx`
|
|
||||||
- [ ] Migrate experimental worktree listing, creation, removal, and reset from `/experimental/worktree`.
|
|
||||||
- `src/pages/layout.tsx`
|
|
||||||
- `src/components/prompt-input/submit.ts`
|
|
||||||
- Listing now uses `GET /api/project/:projectID/directories`; create, removal, and reset remain.
|
|
||||||
- [ ] Migrate instance disposal from `POST /instance/dispose`.
|
|
||||||
- `src/pages/layout.tsx`
|
|
||||||
|
|
||||||
## VCS
|
|
||||||
|
|
||||||
- [x] Migrate repository information from `GET /vcs` to `GET /api/vcs`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- [x] Migrate diffs from `GET /vcs/diff` to `GET /api/vcs/diff`.
|
|
||||||
- `src/pages/session.tsx`
|
|
||||||
- [x] Migrate status from `GET /vcs/status` to `GET /api/vcs/status`.
|
|
||||||
- `src/pages/layout.tsx`
|
|
||||||
|
|
||||||
## Configuration And Authentication
|
|
||||||
|
|
||||||
- [ ] Migrate global configuration reads from `GET /global/config`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- [ ] Migrate directory configuration reads from `GET /config`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- [ ] Migrate global configuration updates from `PATCH /global/config`.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [x] Migrate provider authentication method discovery from `GET /provider/auth` to `GET /api/integration/:integrationID`.
|
|
||||||
- `src/components/dialog-connect-provider.tsx`
|
|
||||||
- [x] Migrate built-in provider OAuth authorization and callbacks to `/api/integration/:integrationID/connect/oauth/*`.
|
|
||||||
- `src/components/dialog-connect-provider.tsx`
|
|
||||||
- [ ] Migrate remaining credentials from `PUT /auth/:providerID` and `DELETE /auth/:providerID`.
|
|
||||||
- Built-in provider key connections now use `POST /api/integration/:integrationID/connect/key`.
|
|
||||||
- `src/components/dialog-connect-provider.tsx`
|
|
||||||
- `src/components/dialog-custom-provider.tsx`
|
|
||||||
- `src/components/settings-providers.tsx`
|
|
||||||
- `src/components/settings-v2/providers.tsx`
|
|
||||||
- [ ] Migrate global disposal from `POST /global/dispose`.
|
|
||||||
- `src/components/dialog-connect-provider.tsx`
|
|
||||||
- `src/components/settings-providers.tsx`
|
|
||||||
- `src/components/settings-v2/providers.tsx`
|
|
||||||
|
|
||||||
## Permissions And Questions
|
|
||||||
|
|
||||||
- [x] Migrate permission listing from `GET /permission` to `GET /api/permission/request`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- `src/context/permission.tsx`
|
|
||||||
- [x] Migrate permission responses from `/session/:sessionID/permissions/:permissionID`.
|
|
||||||
- `src/context/permission.tsx`
|
|
||||||
- `src/pages/session/composer/session-composer-state.ts`
|
|
||||||
- [x] Migrate question listing from `GET /question` to `GET /api/question/request`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- [x] Migrate question replies and rejections from `/question/:requestID/*` to `/api/session/:sessionID/question/:requestID/*`.
|
|
||||||
- `src/pages/session/composer/session-question-dock.tsx`
|
|
||||||
|
|
||||||
## Commands, MCP, LSP, And References
|
|
||||||
|
|
||||||
- [x] Migrate command listing from `GET /command` to `GET /api/command`.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [x] Migrate MCP listing, connection, and disconnection from `/mcp` to `/api/mcp`.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [ ] Replace legacy MCP authentication with the Integration OAuth workflow.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [x] Migrate experimental resource listing from `GET /experimental/resource` to `GET /api/mcp/resource`.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [ ] Migrate LSP status from `GET /lsp`.
|
|
||||||
- `src/context/server-sync.tsx`
|
|
||||||
- [x] Move `GET /api/reference` off the legacy generated SDK transport.
|
|
||||||
- `src/context/global-sync/bootstrap.ts`
|
|
||||||
|
|
||||||
## Search
|
|
||||||
|
|
||||||
- [x] Migrate global session search from `GET /experimental/session` to `GET /api/session`.
|
|
||||||
- `src/components/command-palette.ts`
|
|
||||||
- `src/components/dialog-command-palette-v2.tsx`
|
|
||||||
|
|
||||||
## PTY And Terminal
|
|
||||||
|
|
||||||
- [x] Migrate PTY creation, reads, updates, and deletion from `/pty` to `/api/pty`.
|
|
||||||
- `src/context/terminal.tsx`
|
|
||||||
- `src/components/terminal.tsx`
|
|
||||||
- [x] Migrate shell listing from `GET /pty/shells` to `GET /api/pty/shells`.
|
|
||||||
- `src/components/settings-general.tsx`
|
|
||||||
- `src/components/settings-v2/general.tsx`
|
|
||||||
- [x] Migrate connection tokens from `POST /pty/:ptyID/connect-token` to `POST /api/pty/:ptyID/connect-token`.
|
|
||||||
- `src/components/terminal.tsx`
|
|
||||||
- [x] Migrate the direct WebSocket connection from `/pty/:ptyID/connect` to `/api/pty/:ptyID/connect`.
|
|
||||||
- `src/components/terminal.tsx`
|
|
||||||
|
|
||||||
## Legacy Types And Adapters
|
|
||||||
|
|
||||||
These are not V1 network requests, but they keep the UI coupled to V1 data contracts.
|
|
||||||
|
|
||||||
- [ ] Replace the current-session-to-legacy-session adapter.
|
|
||||||
- `src/utils/session.ts`
|
|
||||||
- [ ] Replace the current-message-to-legacy-message-and-part adapter.
|
|
||||||
- `src/utils/session-message.ts`
|
|
||||||
- [ ] Replace current agent, provider, and model adapters to legacy SDK structures.
|
|
||||||
- `src/context/global-sync/utils.ts`
|
|
||||||
- [ ] Replace legacy `Session`, `Message`, `Part`, `PermissionRequest`, `QuestionRequest`, `Project`, `FileNode`, `FileDiffInfo`, and `Event` types throughout app state and rendering.
|
|
||||||
- [ ] Remove the `@opencode-ai/sdk` runtime dependency after all legacy calls and types are gone.
|
|
||||||
- `package.json`
|
|
||||||
|
|
||||||
## Test Infrastructure
|
|
||||||
|
|
||||||
- [ ] Replace V1 endpoint mocks with current API mocks.
|
|
||||||
- `e2e/utils/mock-server.ts`
|
|
||||||
- [x] Replace `/global/event` and `/event` interception with current event transport handling.
|
|
||||||
- `e2e/utils/sse-transport.ts`
|
|
||||||
- [ ] Replace `SessionV1` and legacy SDK fixtures in timeline performance tests.
|
|
||||||
- `e2e/performance/timeline-stability/fixture.ts`
|
|
||||||
- [ ] Remove remaining legacy SDK type fixtures from unit and browser tests.
|
|
||||||
@@ -45,10 +45,6 @@ describe("timeline fixture validation", () => {
|
|||||||
expect(first.payload.id).toMatch(/^evt_timeline_\d{4}$/)
|
expect(first.payload.id).toMatch(/^evt_timeline_\d{4}$/)
|
||||||
expect(Number(second.payload.id.slice(-4))).toBe(Number(first.payload.id.slice(-4)) + 1)
|
expect(Number(second.payload.id.slice(-4))).toBe(Number(first.payload.id.slice(-4)) + 1)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("uses the projected tool ID as its call ID", () => {
|
|
||||||
expect(toolPart("call_1", "read", "running", {})).toMatchObject({ id: "call_1", callID: "call_1" })
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if (false) {
|
if (false) {
|
||||||
|
|||||||
@@ -2,15 +2,8 @@ import { base64Encode } from "@opencode-ai/core/util/encode"
|
|||||||
import { Event } from "@opencode-ai/schema/event"
|
import { Event } from "@opencode-ai/schema/event"
|
||||||
import { SessionStatusEvent } from "@opencode-ai/schema/session-status-event"
|
import { SessionStatusEvent } from "@opencode-ai/schema/session-status-event"
|
||||||
import { SessionV1 } from "@opencode-ai/schema/session-v1"
|
import { SessionV1 } from "@opencode-ai/schema/session-v1"
|
||||||
import type {
|
import type { SessionInfo, SessionStatus } from "@opencode-ai/client/promise"
|
||||||
AssistantMessage,
|
import type { AssistantMessage, Message, Part, ToolPart, ToolState, UserMessage } from "../../../src/types"
|
||||||
Message,
|
|
||||||
Part,
|
|
||||||
ToolPart,
|
|
||||||
ToolState,
|
|
||||||
UserMessage,
|
|
||||||
} from "../../../src/types"
|
|
||||||
import type { SessionV1Info, SessionStatus } from "@opencode-ai/client/promise"
|
|
||||||
import { expect, type Page } from "@playwright/test"
|
import { expect, type Page } from "@playwright/test"
|
||||||
import { Schema } from "effect"
|
import { Schema } from "effect"
|
||||||
import { mockOpenCodeServer } from "../../utils/mock-server"
|
import { mockOpenCodeServer } from "../../utils/mock-server"
|
||||||
@@ -25,7 +18,7 @@ export const assistantID = "msg_1001_timeline_assistant"
|
|||||||
export const title = "Timeline visual stability"
|
export const title = "Timeline visual stability"
|
||||||
export const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
|
export const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
|
||||||
|
|
||||||
type Session = SessionV1Info
|
type Session = SessionInfo
|
||||||
type GlobalEvent = {
|
type GlobalEvent = {
|
||||||
directory: string
|
directory: string
|
||||||
project?: string
|
project?: string
|
||||||
@@ -537,11 +530,11 @@ export function project() {
|
|||||||
export function session(input: Partial<Session> = {}): Session {
|
export function session(input: Partial<Session> = {}): Session {
|
||||||
return {
|
return {
|
||||||
id: sessionID,
|
id: sessionID,
|
||||||
slug: "timeline-stability",
|
|
||||||
projectID,
|
projectID,
|
||||||
directory,
|
location: { directory },
|
||||||
title,
|
title,
|
||||||
version: "dev",
|
cost: 0,
|
||||||
|
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||||
time: { created: 1700000000000, updated: 1700000000000 },
|
time: { created: 1700000000000, updated: 1700000000000 },
|
||||||
...input,
|
...input,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -177,7 +177,8 @@ test("shows all and expands historical diff summary without overlap", async ({ p
|
|||||||
const firstUser = userMessage(undefined, {
|
const firstUser = userMessage(undefined, {
|
||||||
summary: {
|
summary: {
|
||||||
diffs: Array.from({ length: 12 }, (_, index) => ({
|
diffs: Array.from({ length: 12 }, (_, index) => ({
|
||||||
file: `src/diff-${index}.ts`,
|
file: `src/diff-${index}.ts`,
|
||||||
|
status: "modified",
|
||||||
additions: 1,
|
additions: 1,
|
||||||
deletions: 1,
|
deletions: 1,
|
||||||
patch: `@@ -1 +1 @@\n-export const value = ${index}\n+export const value = ${index + 1}`,
|
patch: `@@ -1 +1 @@\n-export const value = ${index}\n+export const value = ${index + 1}`,
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ const projectID = "proj_context_resize_regression"
|
|||||||
const sessionID = "ses_context_resize_regression"
|
const sessionID = "ses_context_resize_regression"
|
||||||
const title = "Context resize regression"
|
const title = "Context resize regression"
|
||||||
const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
|
const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
|
||||||
const contextIDs = ["prt_0100_read", "prt_0101_glob", "prt_0102_grep", "prt_0103_list"]
|
const contextIDs = ["ctx_0100_read", "ctx_0101_glob", "ctx_0102_grep", "ctx_0103_list"]
|
||||||
const followingTextID = "prt_0104_text"
|
const followingTextID = `${id("msg_assistant", 10)}:text:0`
|
||||||
|
|
||||||
type Message = {
|
type Message = {
|
||||||
info: Record<string, unknown> & { id: string; role: "user" | "assistant" }
|
info: Record<string, unknown> & { id: string; role: "user" | "assistant" }
|
||||||
@@ -295,7 +295,7 @@ function contextTool(
|
|||||||
sessionID,
|
sessionID,
|
||||||
messageID,
|
messageID,
|
||||||
type: "tool",
|
type: "tool",
|
||||||
callID: `call_${partID}`,
|
callID: partID,
|
||||||
tool,
|
tool,
|
||||||
state: {
|
state: {
|
||||||
status,
|
status,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type EventPayload = {
|
|||||||
|
|
||||||
test.use({ viewport: { width: 1440, height: 900 }, reducedMotion: "no-preference" })
|
test.use({ viewport: { width: 1440, height: 900 }, reducedMotion: "no-preference" })
|
||||||
|
|
||||||
test("animates todo lifecycle without replaying it across session tabs", async ({ page }) => {
|
test("animates todo opening without replaying it across session tabs", async ({ page }) => {
|
||||||
test.setTimeout(90_000)
|
test.setTimeout(90_000)
|
||||||
const events: EventPayload[] = []
|
const events: EventPayload[] = []
|
||||||
const todos: Record<string, typeof activeTodos> = { [sourceID]: [], [otherID]: [] }
|
const todos: Record<string, typeof activeTodos> = { [sourceID]: [], [otherID]: [] }
|
||||||
@@ -86,28 +86,8 @@ test("animates todo lifecycle without replaying it across session tabs", async (
|
|||||||
await switchSession(page, otherID, otherTitle)
|
await switchSession(page, otherID, otherTitle)
|
||||||
await expect(dock).toHaveCount(0)
|
await expect(dock).toHaveCount(0)
|
||||||
|
|
||||||
const returningOpen = sampleDock(page, 700)
|
|
||||||
await switchSession(page, sourceID, sourceTitle)
|
|
||||||
const openSamples = (await returningOpen).filter((sample) => sample.present)
|
|
||||||
expect(openSamples.length).toBeGreaterThan(0)
|
|
||||||
expect(openSamples[0]!.opacity).toBeGreaterThan(0.98)
|
|
||||||
expect(openSamples[0]!.height).toBeGreaterThan(70)
|
|
||||||
await expect(dock.locator('[data-state="in_progress"]')).toHaveCount(1)
|
|
||||||
|
|
||||||
const completedTodos = activeTodos.map((todo) => ({ ...todo, status: "completed" }))
|
|
||||||
const closing = sampleDock(page, 1_000)
|
|
||||||
todos[sourceID] = completedTodos
|
|
||||||
events.push(todoEvent(sourceID, completedTodos))
|
|
||||||
await expect(dock).toHaveCount(0)
|
|
||||||
expect((await closing).some((sample) => sample.opacity > 0.05 && sample.opacity < 0.95)).toBe(true)
|
|
||||||
todos[sourceID] = []
|
|
||||||
events.push(todoEvent(sourceID, []))
|
|
||||||
|
|
||||||
await switchSession(page, otherID, otherTitle)
|
|
||||||
const returningEmpty = sampleDock(page, 700)
|
|
||||||
await switchSession(page, sourceID, sourceTitle)
|
await switchSession(page, sourceID, sourceTitle)
|
||||||
await expect(dock).toHaveCount(0)
|
await expect(dock).toHaveCount(0)
|
||||||
expect((await returningEmpty).every((sample) => !sample.present)).toBe(true)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
function session(id: string, title: string, created: number) {
|
function session(id: string, title: string, created: number) {
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ test("keeps the terminal session alive when switching session tabs in a workspac
|
|||||||
const connection = new URL(connections[0]!)
|
const connection = new URL(connections[0]!)
|
||||||
expect(connection.pathname).toBe(`/api/pty/${ptyID}/connect`)
|
expect(connection.pathname).toBe(`/api/pty/${ptyID}/connect`)
|
||||||
expect(connection.searchParams.get("location[directory]")).toBe(directory)
|
expect(connection.searchParams.get("location[directory]")).toBe(directory)
|
||||||
expect(connection.searchParams.get("ticket")).toBe("e2e-ticket")
|
expect(connection.searchParams.get("ticket")).toBeNull()
|
||||||
await writeProbe(page)
|
await writeProbe(page)
|
||||||
|
|
||||||
await switchTab(page, titleB)
|
await switchTab(page, titleB)
|
||||||
|
|||||||
@@ -80,9 +80,8 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (path === "/global/health")
|
if (path === "/global/health")
|
||||||
return config.protocol === "v2" ? json(route, {}) : json(route, { healthy: true })
|
return config.protocol === "v2" ? json(route, {}, undefined, 404) : json(route, { healthy: true })
|
||||||
if (path === "/api/health" && config.protocol === "v2")
|
if (path === "/api/health") return json(route, { healthy: true, version: "2.0.0", pid: 1 })
|
||||||
return json(route, { healthy: true, version: "2.0.0", pid: 1 })
|
|
||||||
if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: true })
|
if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: true })
|
||||||
if (path === "/provider") return json(route, providerConfig(config))
|
if (path === "/provider") return json(route, providerConfig(config))
|
||||||
if (path === "/provider/auth") return json(route, config.integrationMethods ?? {})
|
if (path === "/provider/auth") return json(route, config.integrationMethods ?? {})
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { Page } from "@playwright/test"
|
|||||||
export type SseConnectionRecord = {
|
export type SseConnectionRecord = {
|
||||||
id: number
|
id: number
|
||||||
url: string
|
url: string
|
||||||
path: "/global/event" | "/event" | "/api/event"
|
path: "/api/event"
|
||||||
headers: Record<string, string>
|
headers: Record<string, string>
|
||||||
openedAt: number
|
openedAt: number
|
||||||
endedAt?: number
|
endedAt?: number
|
||||||
@@ -174,10 +174,7 @@ export async function installSseTransport<T>(
|
|||||||
const fetch = (input: RequestInfo | URL, init?: RequestInit) => {
|
const fetch = (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
const request = new Request(input, init)
|
const request = new Request(input, init)
|
||||||
const url = new URL(request.url)
|
const url = new URL(request.url)
|
||||||
if (
|
if (url.origin !== server || url.pathname !== "/api/event")
|
||||||
url.origin !== server ||
|
|
||||||
(url.pathname !== "/global/event" && url.pathname !== "/event" && url.pathname !== "/api/event")
|
|
||||||
)
|
|
||||||
return originalFetch(request)
|
return originalFetch(request)
|
||||||
|
|
||||||
const id = ++nextConnectionID
|
const id = ++nextConnectionID
|
||||||
@@ -193,18 +190,9 @@ export async function installSseTransport<T>(
|
|||||||
record.controller = controller
|
record.controller = controller
|
||||||
connections.push(record)
|
connections.push(record)
|
||||||
if (retry !== undefined) controller.enqueue(encoder.encode(`retry: ${retry}\n\n`))
|
if (retry !== undefined) controller.enqueue(encoder.encode(`retry: ${retry}\n\n`))
|
||||||
if (url.pathname === "/api/event")
|
controller.enqueue(
|
||||||
controller.enqueue(
|
encoder.encode(frame({ id: `evt_mock_connected_${id}`, type: "server.connected", data: {} })),
|
||||||
encoder.encode(frame({ id: `evt_mock_connected_${id}`, type: "server.connected", data: {} })),
|
)
|
||||||
)
|
|
||||||
if (url.pathname === "/global/event")
|
|
||||||
controller.enqueue(
|
|
||||||
encoder.encode(
|
|
||||||
frame({
|
|
||||||
payload: { id: `evt_mock_connected_${id}`, type: "server.connected", properties: {} },
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
request.signal.addEventListener(
|
request.signal.addEventListener(
|
||||||
"abort",
|
"abort",
|
||||||
() => {
|
() => {
|
||||||
|
|||||||
@@ -40,6 +40,7 @@
|
|||||||
"@types/luxon": "catalog:",
|
"@types/luxon": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"@typescript/native-preview": "catalog:",
|
"@typescript/native-preview": "catalog:",
|
||||||
|
"happy-dom": "20.11.1",
|
||||||
"tw-animate-css": "1.4.0",
|
"tw-animate-css": "1.4.0",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vite": "catalog:",
|
"vite": "catalog:",
|
||||||
@@ -56,7 +57,6 @@
|
|||||||
"@opencode-ai/client": "workspace:*",
|
"@opencode-ai/client": "workspace:*",
|
||||||
"@opencode-ai/core": "workspace:*",
|
"@opencode-ai/core": "workspace:*",
|
||||||
"@opencode-ai/schema": "workspace:*",
|
"@opencode-ai/schema": "workspace:*",
|
||||||
"@opencode-ai/sdk": "file:vendor/opencode-ai-sdk-1.18.8-dev.tgz",
|
|
||||||
"@opencode-ai/session-ui": "workspace:*",
|
"@opencode-ai/session-ui": "workspace:*",
|
||||||
"@opencode-ai/ui": "workspace:*",
|
"@opencode-ai/ui": "workspace:*",
|
||||||
"@opencode-ai/util": "workspace:*",
|
"@opencode-ai/util": "workspace:*",
|
||||||
|
|||||||
@@ -155,7 +155,7 @@ function LegacyTargetSessionRedirect() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const directory = current()?.session.directory
|
const directory = current()?.session.location.directory
|
||||||
if (!directory) return
|
if (!directory) return
|
||||||
navigate(legacySessionHref(directory, params.id), { replace: true })
|
navigate(legacySessionHref(directory, params.id), { replace: true })
|
||||||
})
|
})
|
||||||
@@ -238,26 +238,6 @@ function UiI18nBridge(props: ParentProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function LayoutCompatibility(props: ParentProps) {
|
function LayoutCompatibility(props: ParentProps) {
|
||||||
const global = useGlobal()
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const server = useServer()
|
|
||||||
const settings = useSettings()
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
if (settings.general.newLayoutDesigns()) return
|
|
||||||
const current = server.current
|
|
||||||
if (!current) return
|
|
||||||
const protocol = global.ensureServerCtx(current).sdk.protocolKind()
|
|
||||||
if (protocol !== "v2") return
|
|
||||||
const next = global.servers.list().find((s) => {
|
|
||||||
if (ServerConnection.key(s) === ServerConnection.key(current)) return false
|
|
||||||
return global.ensureServerCtx(s).sdk.protocolKind() !== "v2"
|
|
||||||
})
|
|
||||||
if (!next) return
|
|
||||||
navigate("/")
|
|
||||||
queueMicrotask(() => server.setActive(ServerConnection.key(next)))
|
|
||||||
})
|
|
||||||
|
|
||||||
return <>{props.children}</>
|
return <>{props.children}</>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 23 KiB |
@@ -14,7 +14,6 @@ import { useTabs } from "@/context/tabs"
|
|||||||
import { displayName, projectForSession } from "@/pages/layout/helpers"
|
import { displayName, projectForSession } from "@/pages/layout/helpers"
|
||||||
import { createSessionTabs } from "@/pages/session/helpers"
|
import { createSessionTabs } from "@/pages/session/helpers"
|
||||||
import { useSessionLayout } from "@/pages/session/session-layout"
|
import { useSessionLayout } from "@/pages/session/session-layout"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
|
|
||||||
export type CommandPaletteEntry = {
|
export type CommandPaletteEntry = {
|
||||||
id: string
|
id: string
|
||||||
@@ -146,7 +145,7 @@ export function createCommandPaletteModel(props: { filesOnly?: () => boolean; on
|
|||||||
server: ServerConnection.key(serverSDK.server),
|
server: ServerConnection.key(serverSDK.server),
|
||||||
opened: serverCtx.projects.list,
|
opened: serverCtx.projects.list,
|
||||||
stored: () => serverCtx.sync.data.project,
|
stored: () => serverCtx.sync.data.project,
|
||||||
load: (search, signal) => serverSDK.currentApi.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
load: (search, signal) => serverSDK.api.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
||||||
untitled: () => language.t("command.session.new"),
|
untitled: () => language.t("command.session.new"),
|
||||||
category: () => language.t("command.category.session"),
|
category: () => language.t("command.category.session"),
|
||||||
})
|
})
|
||||||
@@ -257,7 +256,6 @@ export function createServerSessionEntries(props: {
|
|||||||
.load(search, current.signal)
|
.load(search, current.signal)
|
||||||
.then((result) =>
|
.then((result) =>
|
||||||
result.data
|
result.data
|
||||||
.map(normalizeSessionInfo)
|
|
||||||
.filter((session) => !session.time.archived)
|
.filter((session) => !session.time.archived)
|
||||||
.map((session) => {
|
.map((session) => {
|
||||||
const project =
|
const project =
|
||||||
@@ -266,9 +264,9 @@ export function createServerSessionEntries(props: {
|
|||||||
id: `session:${props.server}:${session.id}`,
|
id: `session:${props.server}:${session.id}`,
|
||||||
type: "session" as const,
|
type: "session" as const,
|
||||||
title: session.title || props.untitled(),
|
title: session.title || props.untitled(),
|
||||||
description: project ? displayName(project) : getFilename(session.directory),
|
description: project ? displayName(project) : getFilename(session.location.directory),
|
||||||
category: props.category(),
|
category: props.category(),
|
||||||
directory: session.directory,
|
directory: session.location.directory,
|
||||||
sessionID: session.id,
|
sessionID: session.id,
|
||||||
server: props.server,
|
server: props.server,
|
||||||
project,
|
project,
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export function DialogHomeCommandPaletteV2(props: {
|
|||||||
server: ServerConnection.key(props.server),
|
server: ServerConnection.key(props.server),
|
||||||
opened: serverCtx.projects.list,
|
opened: serverCtx.projects.list,
|
||||||
stored: () => serverCtx.sync.data.project,
|
stored: () => serverCtx.sync.data.project,
|
||||||
load: (search, signal) => serverCtx.sdk.currentApi.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
load: (search, signal) => serverCtx.sdk.api.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
||||||
untitled: () => language.t("command.session.new"),
|
untitled: () => language.t("command.session.new"),
|
||||||
category: () => language.t("command.category.session"),
|
category: () => language.t("command.category.session"),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -418,7 +418,7 @@ function ProviderConnection(props: {
|
|||||||
() => ({ provider: props.provider, directory: directory() }),
|
() => ({ provider: props.provider, directory: directory() }),
|
||||||
(input) =>
|
(input) =>
|
||||||
serverSDK()
|
serverSDK()
|
||||||
.currentApi.integration.get({
|
.api.integration.get({
|
||||||
integrationID: input.provider,
|
integrationID: input.provider,
|
||||||
location: input.directory ? { directory: input.directory } : undefined,
|
location: input.directory ? { directory: input.directory } : undefined,
|
||||||
})
|
})
|
||||||
@@ -547,7 +547,7 @@ function ProviderConnection(props: {
|
|||||||
}
|
}
|
||||||
dispatch({ type: "auth.pending" })
|
dispatch({ type: "auth.pending" })
|
||||||
await serverSDK()
|
await serverSDK()
|
||||||
.currentApi.integration.oauth.connect({
|
.api.integration.oauth.connect({
|
||||||
integrationID: props.provider,
|
integrationID: props.provider,
|
||||||
methodID: method.id,
|
methodID: method.id,
|
||||||
inputs: inputs ?? {},
|
inputs: inputs ?? {},
|
||||||
@@ -816,7 +816,7 @@ function ProviderConnection(props: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setFormStore("error", undefined)
|
setFormStore("error", undefined)
|
||||||
await serverSDK().currentApi.integration.connect.key({
|
await serverSDK().api.integration.connect.key({
|
||||||
integrationID: props.provider,
|
integrationID: props.provider,
|
||||||
location: location(),
|
location: location(),
|
||||||
key: apiKey,
|
key: apiKey,
|
||||||
@@ -947,7 +947,7 @@ function ProviderConnection(props: {
|
|||||||
|
|
||||||
setFormStore("error", undefined)
|
setFormStore("error", undefined)
|
||||||
const result = await serverSDK()
|
const result = await serverSDK()
|
||||||
.currentApi.integration.oauth.complete({
|
.api.integration.oauth.complete({
|
||||||
integrationID: props.provider,
|
integrationID: props.provider,
|
||||||
attemptID: store.authorization!.attemptID,
|
attemptID: store.authorization!.attemptID,
|
||||||
location: location(),
|
location: location(),
|
||||||
@@ -1044,7 +1044,7 @@ function ProviderConnection(props: {
|
|||||||
const authorization = store.authorization
|
const authorization = store.authorization
|
||||||
if (!authorization || !alive.value) return
|
if (!authorization || !alive.value) return
|
||||||
const result = await serverSDK()
|
const result = await serverSDK()
|
||||||
.currentApi.integration.oauth.status({
|
.api.integration.oauth.status({
|
||||||
integrationID: props.provider,
|
integrationID: props.provider,
|
||||||
attemptID: authorization.attemptID,
|
attemptID: authorization.attemptID,
|
||||||
location: location(),
|
location: location(),
|
||||||
|
|||||||
@@ -130,26 +130,9 @@ export function CustomProviderForm(props: { autofocus?: boolean } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const saveMutation = useMutation(() => ({
|
const saveMutation = useMutation(() => ({
|
||||||
mutationFn: async (result: NonNullable<ReturnType<typeof validate>>) => {
|
mutationFn: async (result: NonNullable<ReturnType<typeof validate>>): Promise<typeof result> => {
|
||||||
if ((await serverSDK().protocol) !== "v1") throw new Error("Custom providers are unavailable on this server")
|
// TODO: Restore custom providers when V2 exposes config and arbitrary credential APIs.
|
||||||
const disabledProviders = serverSync().data.config.disabled_providers ?? []
|
throw new Error(`Custom provider ${result.providerID} is unavailable`)
|
||||||
const nextDisabled = disabledProviders.filter((id) => id !== result.providerID)
|
|
||||||
|
|
||||||
if (result.key) {
|
|
||||||
await serverSDK().legacy.auth.set({
|
|
||||||
providerID: result.providerID,
|
|
||||||
auth: {
|
|
||||||
type: "api",
|
|
||||||
key: result.key,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
await serverSync().updateConfig({
|
|
||||||
provider: { [result.providerID]: result.config },
|
|
||||||
disabled_providers: nextDisabled,
|
|
||||||
})
|
|
||||||
return result
|
|
||||||
},
|
},
|
||||||
onSuccess: (result) => {
|
onSuccess: (result) => {
|
||||||
dialog.close()
|
dialog.close()
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ export function DialogEditProjectV2(props: { project: LocalProject; server: Serv
|
|||||||
<ButtonV2 type="button" variant="neutral" disabled={model.save.isPending} onClick={model.close}>
|
<ButtonV2 type="button" variant="neutral" disabled={model.save.isPending} onClick={model.close}>
|
||||||
{language.t("common.cancel")}
|
{language.t("common.cancel")}
|
||||||
</ButtonV2>
|
</ButtonV2>
|
||||||
<ButtonV2 type="submit" variant="contrast" disabled={model.save.isPending}>
|
<ButtonV2 type="submit" variant="contrast" disabled={!model.supported || model.save.isPending}>
|
||||||
{model.save.isPending ? language.t("common.saving") : language.t("common.save")}
|
{model.save.isPending ? language.t("common.saving") : language.t("common.save")}
|
||||||
</ButtonV2>
|
</ButtonV2>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ export function DialogEditProject(props: { project: LocalProject; server: Server
|
|||||||
<Button type="button" variant="ghost" size="large" onClick={model.close}>
|
<Button type="button" variant="ghost" size="large" onClick={model.close}>
|
||||||
{language.t("common.cancel")}
|
{language.t("common.cancel")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="submit" variant="primary" size="large" disabled={model.save.isPending}>
|
<Button type="submit" variant="primary" size="large" disabled={!model.supported || model.save.isPending}>
|
||||||
{model.save.isPending ? language.t("common.saving") : language.t("common.save")}
|
{model.save.isPending ? language.t("common.saving") : language.t("common.save")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ export const DialogFork: Component = () => {
|
|||||||
const dir = base64Encode(sdk().directory)
|
const dir = base64Encode(sdk().directory)
|
||||||
|
|
||||||
sdk()
|
sdk()
|
||||||
.currentApi.session.fork({ sessionID, boundary: { type: "before", messageID: item.id } })
|
.api.session.fork({ sessionID, boundary: { type: "before", messageID: item.id } })
|
||||||
.then((forked) => {
|
.then((forked) => {
|
||||||
dialog.close()
|
dialog.close()
|
||||||
prompt.set(restored, undefined, { dir, id: forked.id })
|
prompt.set(restored, undefined, { dir, id: forked.id })
|
||||||
|
|||||||
@@ -66,23 +66,21 @@ export function DialogSelectDirectoryV2(props: DialogSelectDirectoryV2Props) {
|
|||||||
let pathArea: HTMLDivElement | undefined
|
let pathArea: HTMLDivElement | undefined
|
||||||
let navigation = 0
|
let navigation = 0
|
||||||
|
|
||||||
const missingBase = createMemo(() => !(sync.data.path.home || sync.data.path.directory))
|
|
||||||
const [fallbackPath] = createResource(
|
const [fallbackPath] = createResource(
|
||||||
() => (missingBase() ? true : undefined),
|
() => (!(sync.data.path.home || sync.data.path.directory) ? true : undefined),
|
||||||
async (): Promise<Path | undefined> => {
|
() =>
|
||||||
if ((await sdk.protocol) === "v1")
|
sdk.api.location
|
||||||
return sdk.legacy.path.get().catch(() => undefined)
|
|
||||||
return sdk.api.location
|
|
||||||
.get()
|
.get()
|
||||||
.then((location) => ({
|
.then(
|
||||||
state: "",
|
(location): Path => ({
|
||||||
config: "",
|
state: "",
|
||||||
worktree: location.project.directory,
|
config: "",
|
||||||
directory: location.directory,
|
worktree: location.project.directory,
|
||||||
home: "",
|
directory: location.directory,
|
||||||
}))
|
home: "",
|
||||||
.catch(() => undefined)
|
}),
|
||||||
},
|
)
|
||||||
|
.catch(() => undefined),
|
||||||
{ initialValue: undefined },
|
{ initialValue: undefined },
|
||||||
)
|
)
|
||||||
const home = createMemo(() => sync.data.path.home || fallbackPath()?.home || "")
|
const home = createMemo(() => sync.data.path.home || fallbackPath()?.home || "")
|
||||||
@@ -104,7 +102,7 @@ export function DialogSelectDirectoryV2(props: DialogSelectDirectoryV2Props) {
|
|||||||
if (!policy.includeFiles) return { query: value, items: directories.slice(0, 5) }
|
if (!policy.includeFiles) return { query: value, items: directories.slice(0, 5) }
|
||||||
const base = pickerRoot(cleaned) || root() || start()
|
const base = pickerRoot(cleaned) || root() || start()
|
||||||
if (!base) return { query: value, items: directories.slice(0, 5) }
|
if (!base) return { query: value, items: directories.slice(0, 5) }
|
||||||
const files = await sdk.currentApi.file
|
const files = await sdk.api.file
|
||||||
.find({
|
.find({
|
||||||
location: { directory: base },
|
location: { directory: base },
|
||||||
query: pickerFileSearchQuery(base, value, home()),
|
query: pickerFileSearchQuery(base, value, home()),
|
||||||
@@ -134,7 +132,7 @@ export function DialogSelectDirectoryV2(props: DialogSelectDirectoryV2Props) {
|
|||||||
existing ??
|
existing ??
|
||||||
loads.schedule(`${generation}:${key}`, eager ? "background" : "user", () => {
|
loads.schedule(`${generation}:${key}`, eager ? "background" : "user", () => {
|
||||||
if (!activeTreeNavigation(generation, navigation)) return Promise.resolve(undefined)
|
if (!activeTreeNavigation(generation, navigation)) return Promise.resolve(undefined)
|
||||||
return sdk.currentApi.file
|
return sdk.api.file
|
||||||
.list({ location: { directory: absolute } })
|
.list({ location: { directory: absolute } })
|
||||||
.then((result) =>
|
.then((result) =>
|
||||||
result.data.map((entry) => ({
|
result.data.map((entry) => ({
|
||||||
|
|||||||
@@ -57,23 +57,21 @@ export function DialogSelectDirectory(props: DialogSelectDirectoryProps) {
|
|||||||
const [filter, setFilter] = createSignal("")
|
const [filter, setFilter] = createSignal("")
|
||||||
let list: ListRef | undefined
|
let list: ListRef | undefined
|
||||||
|
|
||||||
const missingBase = createMemo(() => !(sync.data.path.home || sync.data.path.directory))
|
|
||||||
const [fallbackPath] = createResource(
|
const [fallbackPath] = createResource(
|
||||||
() => (missingBase() ? true : undefined),
|
() => (!(sync.data.path.home || sync.data.path.directory) ? true : undefined),
|
||||||
async (): Promise<Path | undefined> => {
|
() =>
|
||||||
if ((await sdk.protocol) === "v1")
|
sdk.api.location
|
||||||
return sdk.legacy.path.get().catch(() => undefined)
|
|
||||||
return sdk.api.location
|
|
||||||
.get()
|
.get()
|
||||||
.then((location) => ({
|
.then(
|
||||||
state: "",
|
(location): Path => ({
|
||||||
config: "",
|
state: "",
|
||||||
worktree: location.project.directory,
|
config: "",
|
||||||
directory: location.directory,
|
worktree: location.project.directory,
|
||||||
home: "",
|
directory: location.directory,
|
||||||
}))
|
home: "",
|
||||||
.catch(() => undefined)
|
}),
|
||||||
},
|
)
|
||||||
|
.catch(() => undefined),
|
||||||
{ initialValue: undefined },
|
{ initialValue: undefined },
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import { useGlobal } from "@/context/global"
|
|||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { usePlatform } from "@/context/platform"
|
import { usePlatform } from "@/context/platform"
|
||||||
import { normalizeServerUrl, ServerConnection, useServer } from "@/context/server"
|
import { normalizeServerUrl, ServerConnection, useServer } from "@/context/server"
|
||||||
import { detectServerProtocol } from "@/utils/server-protocol"
|
|
||||||
import { type ServerHealth, useCheckServerHealth } from "@/utils/server-health"
|
import { type ServerHealth, useCheckServerHealth } from "@/utils/server-health"
|
||||||
import { useSettings } from "@/context/settings"
|
import { useSettings } from "@/context/settings"
|
||||||
import { useTabs } from "@/context/tabs"
|
import { useTabs } from "@/context/tabs"
|
||||||
@@ -264,13 +263,6 @@ export function useServerManagementController(options: { onSelect?: () => void;
|
|||||||
setStore("addServer", { error: language.t("dialog.server.add.error") })
|
setStore("addServer", { error: language.t("dialog.server.add.error") })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (
|
|
||||||
!settings.general.newLayoutDesigns() &&
|
|
||||||
(await detectServerProtocol(conn.http, platform.fetch ?? globalThis.fetch)) === "v2"
|
|
||||||
) {
|
|
||||||
setStore("addServer", { error: language.t("dialog.server.add.error") })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
resetAdd()
|
resetAdd()
|
||||||
if (options.navigateOnAdd === false) {
|
if (options.navigateOnAdd === false) {
|
||||||
@@ -315,13 +307,6 @@ export function useServerManagementController(options: { onSelect?: () => void;
|
|||||||
setStore("editServer", { error: language.t("dialog.server.add.error") })
|
setStore("editServer", { error: language.t("dialog.server.add.error") })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (
|
|
||||||
!settings.general.newLayoutDesigns() &&
|
|
||||||
(await detectServerProtocol(conn.http, platform.fetch ?? globalThis.fetch)) === "v2"
|
|
||||||
) {
|
|
||||||
setStore("editServer", { error: language.t("dialog.server.add.error") })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (normalized === input.original.http.url) {
|
if (normalized === input.original.http.url) {
|
||||||
server.add(conn)
|
server.add(conn)
|
||||||
} else {
|
} else {
|
||||||
@@ -360,9 +345,7 @@ export function useServerManagementController(options: { onSelect?: () => void;
|
|||||||
|
|
||||||
const sortedItems = createMemo(() => {
|
const sortedItems = createMemo(() => {
|
||||||
const raw = items()
|
const raw = items()
|
||||||
const list = settings.general.newLayoutDesigns()
|
const list = raw
|
||||||
? raw
|
|
||||||
: raw.filter((x) => global.ensureServerCtx(x).sdk.protocolKind() !== "v2")
|
|
||||||
if (!list.length) return list
|
if (!list.length) return list
|
||||||
const active = current()
|
const active = current()
|
||||||
const order = new Map(list.map((url, index) => [url, index] as const))
|
const order = new Map(list.map((url, index) => [url, index] as const))
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ test("scopes file autocomplete to the current browser root", () => {
|
|||||||
test("resolves directory autocomplete from the current browser root", async () => {
|
test("resolves directory autocomplete from the current browser root", async () => {
|
||||||
const directories: string[] = []
|
const directories: string[] = []
|
||||||
const sdk = {
|
const sdk = {
|
||||||
currentApi: {
|
api: {
|
||||||
file: {
|
file: {
|
||||||
find: (input: { location?: { directory?: string } }) => {
|
find: (input: { location?: { directory?: string } }) => {
|
||||||
directories.push(input.location?.directory ?? "")
|
directories.push(input.location?.directory ?? "")
|
||||||
@@ -155,7 +155,7 @@ test("resolves directory autocomplete from the current browser root", async () =
|
|||||||
test("searches from an absolute root without a default base", async () => {
|
test("searches from an absolute root without a default base", async () => {
|
||||||
const directories: string[] = []
|
const directories: string[] = []
|
||||||
const sdk = {
|
const sdk = {
|
||||||
currentApi: {
|
api: {
|
||||||
file: {
|
file: {
|
||||||
list: (input: { location?: { directory?: string } }) => {
|
list: (input: { location?: { directory?: string } }) => {
|
||||||
directories.push(input.location?.directory ?? "")
|
directories.push(input.location?.directory ?? "")
|
||||||
|
|||||||
@@ -342,7 +342,7 @@ export function createDirectorySearch(args: { sdk: ServerSDK; base: () => string
|
|||||||
const key = trimPickerPath(directory)
|
const key = trimPickerPath(directory)
|
||||||
const existing = cache.get(key)
|
const existing = cache.get(key)
|
||||||
if (existing) return existing
|
if (existing) return existing
|
||||||
const request = args.sdk.currentApi.file
|
const request = args.sdk.api.file
|
||||||
.list({ location: { directory: key } })
|
.list({ location: { directory: key } })
|
||||||
.then((result) => result.data)
|
.then((result) => result.data)
|
||||||
.catch(() => [])
|
.catch(() => [])
|
||||||
@@ -374,7 +374,7 @@ export function createDirectorySearch(args: { sdk: ServerSDK; base: () => string
|
|||||||
const pathInput = raw.startsWith("~") || !!pickerRoot(raw) || raw.includes("/")
|
const pathInput = raw.startsWith("~") || !!pickerRoot(raw) || raw.includes("/")
|
||||||
const query = normalizePickerDrive(input.path)
|
const query = normalizePickerDrive(input.path)
|
||||||
if (!pathInput) {
|
if (!pathInput) {
|
||||||
const results = await args.sdk.currentApi.file
|
const results = await args.sdk.api.file
|
||||||
.find({ location: { directory: input.directory }, query, type: "directory", limit: 50 })
|
.find({ location: { directory: input.directory }, query, type: "directory", limit: 50 })
|
||||||
.then((result) => result.data.map((entry) => entry.path))
|
.then((result) => result.data.map((entry) => entry.path))
|
||||||
.catch(() => [])
|
.catch(() => [])
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { type LocalProject } from "@/context/layout"
|
|||||||
import { ServerConnection } from "@/context/server"
|
import { ServerConnection } from "@/context/server"
|
||||||
|
|
||||||
export function createEditProjectModel(props: { project: LocalProject; server: ServerConnection.Any }) {
|
export function createEditProjectModel(props: { project: LocalProject; server: ServerConnection.Any }) {
|
||||||
|
const supported = !props.project.id || props.project.id === "global"
|
||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const global = useGlobal()
|
const global = useGlobal()
|
||||||
const serverCtx = createMemo(() => global.ensureServerCtx(props.server))
|
const serverCtx = createMemo(() => global.ensureServerCtx(props.server))
|
||||||
@@ -71,23 +72,9 @@ export function createEditProjectModel(props: { project: LocalProject; server: S
|
|||||||
const start = store.startup.trim()
|
const start = store.startup.trim()
|
||||||
|
|
||||||
if (props.project.id && props.project.id !== "global") {
|
if (props.project.id && props.project.id !== "global") {
|
||||||
if ((await serverCtx().sdk.protocol) !== "v1") return
|
// TODO: Restore project edits when the V2 client exposes a project update API.
|
||||||
const project = await serverCtx()
|
// await serverCtx().sdk.api.project.update({ projectID: props.project.id, name, icon, commands })
|
||||||
.sdk.legacy.project.update({
|
throw new Error(`Project ${props.project.id} cannot be updated`)
|
||||||
projectID: props.project.id,
|
|
||||||
directory: props.project.worktree,
|
|
||||||
name,
|
|
||||||
icon: { color: store.color || "", override: store.iconOverride || "" },
|
|
||||||
commands: { start },
|
|
||||||
})
|
|
||||||
.then((result) => result.data)
|
|
||||||
if (!project) return
|
|
||||||
serverCtx().sync.set("project", (items) =>
|
|
||||||
items.map((item) => (item.id === project.id ? normalizeProjectInfo(project) : item)),
|
|
||||||
)
|
|
||||||
serverCtx().sync.project.icon(props.project.worktree, store.iconOverride || undefined)
|
|
||||||
dialog.close()
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
serverCtx().sync.project.meta(props.project.worktree, {
|
serverCtx().sync.project.meta(props.project.worktree, {
|
||||||
@@ -101,7 +88,7 @@ export function createEditProjectModel(props: { project: LocalProject; server: S
|
|||||||
|
|
||||||
function submit(event: SubmitEvent) {
|
function submit(event: SubmitEvent) {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
if (save.isPending) return
|
if (!supported || save.isPending) return
|
||||||
save.mutate()
|
save.mutate()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,6 +98,7 @@ export function createEditProjectModel(props: { project: LocalProject; server: S
|
|||||||
folderName,
|
folderName,
|
||||||
defaultName,
|
defaultName,
|
||||||
save,
|
save,
|
||||||
|
supported,
|
||||||
submit,
|
submit,
|
||||||
drop,
|
drop,
|
||||||
dragOver,
|
dragOver,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { ButtonV2 } from "@opencode-ai/ui/v2/button-v2"
|
|||||||
import { Icon } from "@opencode-ai/ui/v2/icon"
|
import { Icon } from "@opencode-ai/ui/v2/icon"
|
||||||
import { KeybindV2 } from "@opencode-ai/ui/v2/keybind-v2"
|
import { KeybindV2 } from "@opencode-ai/ui/v2/keybind-v2"
|
||||||
import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
|
import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
|
||||||
import type { ReferenceInfo } from "@/types"
|
import type { ReferenceInfo } from "@opencode-ai/client/promise"
|
||||||
import { createEffect, createMemo, on, Show } from "solid-js"
|
import { createEffect, createMemo, on, Show } from "solid-js"
|
||||||
import { ModelSelectorPopoverV2 } from "@/components/dialog-select-model"
|
import { ModelSelectorPopoverV2 } from "@/components/dialog-select-model"
|
||||||
import { DialogSelectModelUnpaidV2 } from "@/components/dialog-select-model-unpaid-v2"
|
import { DialogSelectModelUnpaidV2 } from "@/components/dialog-select-model-unpaid-v2"
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ import { promptDesignPlaceholder, promptPlaceholder } from "./prompt-input/place
|
|||||||
import { createPromptInputTransientState } from "./prompt-input/transient-state"
|
import { createPromptInputTransientState } from "./prompt-input/transient-state"
|
||||||
import { showToast } from "@/utils/toast"
|
import { showToast } from "@/utils/toast"
|
||||||
import { ImagePreview } from "@opencode-ai/ui/image-preview"
|
import { ImagePreview } from "@opencode-ai/ui/image-preview"
|
||||||
import type { ReferenceInfo } from "@/types"
|
import type { ReferenceInfo } from "@opencode-ai/client/promise"
|
||||||
|
|
||||||
export { createPromptInputHistory }
|
export { createPromptInputHistory }
|
||||||
export type { PromptInputControls, PromptInputHistory, PromptInputProps, PromptInputState, PromptInputSubmission }
|
export type { PromptInputControls, PromptInputHistory, PromptInputProps, PromptInputState, PromptInputSubmission }
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
import { getFilename } from "@opencode-ai/core/util/path"
|
import { getFilename } from "@opencode-ai/core/util/path"
|
||||||
import type { AgentPartInput, FilePartInput, Part, TextPartInput } from "@/types"
|
import type { AgentPart as MessageAgentPart, FilePart, Part, TextPart } from "@/types"
|
||||||
import type { FileSelection } from "@/context/file"
|
import type { FileSelection } from "@/context/file"
|
||||||
import { encodeFilePath } from "@/context/file/path"
|
import { encodeFilePath } from "@/context/file/path"
|
||||||
import type { AgentPart, FileAttachmentPart, ImageAttachmentPart, Prompt } from "@/context/prompt"
|
import type { AgentPart, FileAttachmentPart, ImageAttachmentPart, Prompt } from "@/context/prompt"
|
||||||
import { Identifier } from "@/utils/id"
|
import { Identifier } from "@/utils/id"
|
||||||
import { createCommentMetadata, formatCommentNote } from "@/utils/comment-note"
|
import { createCommentMetadata, formatCommentNote } from "@/utils/comment-note"
|
||||||
|
|
||||||
type PromptRequestPart = (TextPartInput | FilePartInput | AgentPartInput) & { id: string }
|
type PromptRequestPart =
|
||||||
|
| (Omit<TextPart, "id" | "sessionID" | "messageID"> & { id: string })
|
||||||
|
| (Omit<FilePart, "id" | "sessionID" | "messageID"> & { id: string })
|
||||||
|
| (Omit<MessageAgentPart, "id" | "sessionID" | "messageID"> & { id: string })
|
||||||
|
|
||||||
type ContextFile = {
|
type ContextFile = {
|
||||||
key: string
|
key: string
|
||||||
|
|||||||
@@ -31,6 +31,12 @@ const promotedDrafts: Array<{ draftID: string; server: string; sessionId: string
|
|||||||
const sentPrompts: string[] = []
|
const sentPrompts: string[] = []
|
||||||
const promptInputs: unknown[] = []
|
const promptInputs: unknown[] = []
|
||||||
const sentCommands: unknown[] = []
|
const sentCommands: unknown[] = []
|
||||||
|
const switchedAgents: Array<{ sessionID: string; agent: string }> = []
|
||||||
|
const switchedModels: Array<{
|
||||||
|
sessionID: string
|
||||||
|
model: { id: string; providerID: string; variant?: string }
|
||||||
|
}> = []
|
||||||
|
const sessionRequestOrder: string[] = []
|
||||||
const commands: Array<{ name: string }> = []
|
const commands: Array<{ name: string }> = []
|
||||||
let serverSessionSyncs = 0
|
let serverSessionSyncs = 0
|
||||||
|
|
||||||
@@ -93,10 +99,22 @@ const clientFor = (directory: string) => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
prompt: async (input: unknown) => {
|
prompt: async (input: unknown) => {
|
||||||
|
sessionRequestOrder.push("prompt")
|
||||||
sentPrompts.push(directory)
|
sentPrompts.push(directory)
|
||||||
promptInputs.push(input)
|
promptInputs.push(input)
|
||||||
return { data: undefined }
|
return { data: undefined }
|
||||||
},
|
},
|
||||||
|
switchAgent: async (input: { sessionID: string; agent: string }) => {
|
||||||
|
sessionRequestOrder.push("agent")
|
||||||
|
switchedAgents.push(input)
|
||||||
|
},
|
||||||
|
switchModel: async (input: {
|
||||||
|
sessionID: string
|
||||||
|
model: { id: string; providerID: string; variant?: string }
|
||||||
|
}) => {
|
||||||
|
sessionRequestOrder.push("model")
|
||||||
|
switchedModels.push(input)
|
||||||
|
},
|
||||||
command: async (input: unknown) => {
|
command: async (input: unknown) => {
|
||||||
sentCommands.push(input)
|
sentCommands.push(input)
|
||||||
},
|
},
|
||||||
@@ -125,13 +143,6 @@ beforeAll(async () => {
|
|||||||
useSearchParams: () => [search, () => undefined],
|
useSearchParams: () => [search, () => undefined],
|
||||||
}))
|
}))
|
||||||
|
|
||||||
mock.module("@opencode-ai/sdk/v2/client", () => ({
|
|
||||||
createOpencodeClient: (input: { directory: string }) => {
|
|
||||||
createdClients.push(input.directory)
|
|
||||||
return clientFor(input.directory)
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
mock.module("@opencode-ai/ui/toast", () => ({
|
mock.module("@opencode-ai/ui/toast", () => ({
|
||||||
Toast: { Region: () => null },
|
Toast: { Region: () => null },
|
||||||
showToast: () => 0,
|
showToast: () => 0,
|
||||||
@@ -197,13 +208,8 @@ beforeAll(async () => {
|
|||||||
const sdk = {
|
const sdk = {
|
||||||
scope: "local",
|
scope: "local",
|
||||||
directory: "/repo/main",
|
directory: "/repo/main",
|
||||||
client: rootClient,
|
|
||||||
api: rootClient.api,
|
api: rootClient.api,
|
||||||
currentApi: rootClient.api,
|
|
||||||
url: "http://localhost:4096",
|
url: "http://localhost:4096",
|
||||||
createClient(opts: any) {
|
|
||||||
return clientFor(opts.directory)
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
return () => sdk
|
return () => sdk
|
||||||
},
|
},
|
||||||
@@ -291,6 +297,9 @@ beforeEach(() => {
|
|||||||
sentPrompts.length = 0
|
sentPrompts.length = 0
|
||||||
promptInputs.length = 0
|
promptInputs.length = 0
|
||||||
sentCommands.length = 0
|
sentCommands.length = 0
|
||||||
|
switchedAgents.length = 0
|
||||||
|
switchedModels.length = 0
|
||||||
|
sessionRequestOrder.length = 0
|
||||||
commands.length = 0
|
commands.length = 0
|
||||||
promptValue = [{ type: "text", content: "ls", start: 0, end: 2 }]
|
promptValue = [{ type: "text", content: "ls", start: 0, end: 2 }]
|
||||||
params = {}
|
params = {}
|
||||||
@@ -448,13 +457,17 @@ describe("prompt submit worktree selection", () => {
|
|||||||
expect(promotedDrafts).toEqual([{ draftID: "draft-1", server: "project-server", sessionId: "session-1" }])
|
expect(promotedDrafts).toEqual([{ draftID: "draft-1", server: "project-server", sessionId: "session-1" }])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("includes the selected variant on optimistic prompts", async () => {
|
test("switches the selected agent and model before prompting", async () => {
|
||||||
params = { id: "session-1" }
|
params = { id: "session-1" }
|
||||||
variant = "high"
|
variant = "high"
|
||||||
|
|
||||||
const submit = createPromptSubmit({
|
const submit = createPromptSubmit({
|
||||||
prompt,
|
prompt,
|
||||||
info: () => ({ id: "session-1" }),
|
info: () => ({
|
||||||
|
id: "session-1",
|
||||||
|
agent: "old-agent",
|
||||||
|
model: { id: "old-model", providerID: "old-provider" },
|
||||||
|
}),
|
||||||
imageAttachments: () => [],
|
imageAttachments: () => [],
|
||||||
commentCount: () => 0,
|
commentCount: () => 0,
|
||||||
autoAccept: () => false,
|
autoAccept: () => false,
|
||||||
@@ -483,6 +496,14 @@ describe("prompt submit worktree selection", () => {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
expect(sentPrompts).toEqual(["/repo/main"])
|
expect(sentPrompts).toEqual(["/repo/main"])
|
||||||
|
expect(switchedAgents).toEqual([{ sessionID: "session-1", agent: "agent" }])
|
||||||
|
expect(switchedModels).toEqual([
|
||||||
|
{
|
||||||
|
sessionID: "session-1",
|
||||||
|
model: { id: "model", providerID: "provider", variant: "high" },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(sessionRequestOrder).toEqual(["agent", "model", "prompt"])
|
||||||
expect(promptInputs[0]).toMatchObject({
|
expect(promptInputs[0]).toMatchObject({
|
||||||
sessionID: "session-1",
|
sessionID: "session-1",
|
||||||
text: "ls",
|
text: "ls",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Message, Session } from "@/types"
|
import type { Message } from "@/types"
|
||||||
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { showToast } from "@/utils/toast"
|
import { showToast } from "@/utils/toast"
|
||||||
import { base64Encode } from "@opencode-ai/core/util/encode"
|
import { base64Encode } from "@opencode-ai/core/util/encode"
|
||||||
import { Binary } from "@opencode-ai/core/util/binary"
|
import { Binary } from "@opencode-ai/core/util/binary"
|
||||||
@@ -15,14 +16,13 @@ import { useSDK, type DirectorySDK } from "@/context/sdk"
|
|||||||
import { useSync, type DirectorySync } from "@/context/sync"
|
import { useSync, type DirectorySync } from "@/context/sync"
|
||||||
import { Identifier } from "@/utils/id"
|
import { Identifier } from "@/utils/id"
|
||||||
import { Worktree as WorktreeState } from "@/utils/worktree"
|
import { Worktree as WorktreeState } from "@/utils/worktree"
|
||||||
|
import { getDirectory } from "@opencode-ai/core/util/path"
|
||||||
import { buildRequestParts } from "./build-request-parts"
|
import { buildRequestParts } from "./build-request-parts"
|
||||||
import { setCursorPosition } from "./editor-dom"
|
import { setCursorPosition } from "./editor-dom"
|
||||||
import { formatServerError } from "@/utils/server-errors"
|
import { formatServerError } from "@/utils/server-errors"
|
||||||
import { ScopedKey } from "@/utils/server-scope"
|
import { ScopedKey } from "@/utils/server-scope"
|
||||||
import { createPromptSubmissionState } from "./submission-state"
|
import { createPromptSubmissionState } from "./submission-state"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
import { Event } from "@opencode-ai/schema/event"
|
import { Event } from "@opencode-ai/schema/event"
|
||||||
import { getDirectory } from "@opencode-ai/core/util/path"
|
|
||||||
|
|
||||||
type PendingPrompt = {
|
type PendingPrompt = {
|
||||||
abort: AbortController
|
abort: AbortController
|
||||||
@@ -42,9 +42,10 @@ export type FollowupDraft = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type FollowupSendInput = {
|
type FollowupSendInput = {
|
||||||
api: DirectorySDK["currentApi"]["session"]
|
api: DirectorySDK["api"]["session"]
|
||||||
serverSync: ServerSync
|
serverSync: ServerSync
|
||||||
sync: DirectorySync
|
sync: DirectorySync
|
||||||
|
session: Accessor<{ agent?: string; model?: { id: string; providerID: string; variant?: string } } | undefined>
|
||||||
draft: FollowupDraft
|
draft: FollowupDraft
|
||||||
messageID?: string
|
messageID?: string
|
||||||
optimisticBusy?: boolean
|
optimisticBusy?: boolean
|
||||||
@@ -157,6 +158,25 @@ export async function sendFollowupDraft(input: FollowupSendInput) {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const session = input.session()
|
||||||
|
if (session?.agent !== input.draft.agent) {
|
||||||
|
await input.api.switchAgent({ sessionID: input.draft.sessionID, agent: input.draft.agent })
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
session?.model?.providerID !== input.draft.model.providerID ||
|
||||||
|
session.model.id !== input.draft.model.modelID ||
|
||||||
|
(session.model.variant ?? "default") !== (input.draft.variant ?? "default")
|
||||||
|
) {
|
||||||
|
await input.api.switchModel({
|
||||||
|
sessionID: input.draft.sessionID,
|
||||||
|
model: {
|
||||||
|
id: input.draft.model.modelID,
|
||||||
|
providerID: input.draft.model.providerID,
|
||||||
|
variant: input.draft.variant,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
await input.api.prompt({
|
await input.api.prompt({
|
||||||
sessionID: input.draft.sessionID,
|
sessionID: input.draft.sessionID,
|
||||||
id: messageID,
|
id: messageID,
|
||||||
@@ -197,7 +217,9 @@ export async function sendFollowupDraft(input: FollowupSendInput) {
|
|||||||
|
|
||||||
type PromptSubmitInput = {
|
type PromptSubmitInput = {
|
||||||
prompt: ReturnType<typeof usePrompt>
|
prompt: ReturnType<typeof usePrompt>
|
||||||
info: Accessor<{ id: string } | undefined>
|
info: Accessor<
|
||||||
|
{ id: string; agent?: string; model?: { id: string; providerID: string; variant?: string } } | undefined
|
||||||
|
>
|
||||||
imageAttachments: Accessor<ImageAttachmentPart[]>
|
imageAttachments: Accessor<ImageAttachmentPart[]>
|
||||||
commentCount: Accessor<number>
|
commentCount: Accessor<number>
|
||||||
autoAccept: Accessor<boolean>
|
autoAccept: Accessor<boolean>
|
||||||
@@ -261,7 +283,7 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
return Promise.resolve()
|
return Promise.resolve()
|
||||||
}
|
}
|
||||||
return sdk()
|
return sdk()
|
||||||
.currentApi.session.interrupt({ sessionID })
|
.api.session.interrupt({ sessionID })
|
||||||
.catch(() => {})
|
.catch(() => {})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,10 +310,10 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const seed = (dir: string, info: Session) => {
|
const seed = (dir: string, info: SessionInfo) => {
|
||||||
serverSync().session.remember(info)
|
serverSync().session.remember(info)
|
||||||
const [, setStore] = serverSync().child(dir)
|
const [, setStore] = serverSync().child(dir)
|
||||||
setStore("session", (list: Session[]) => {
|
setStore("session", (list: SessionInfo[]) => {
|
||||||
const result = Binary.search(list, info.id, (item) => item.id)
|
const result = Binary.search(list, info.id, (item) => item.id)
|
||||||
const next = [...list]
|
const next = [...list]
|
||||||
if (result.found) {
|
if (result.found) {
|
||||||
@@ -345,11 +367,10 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
const worktreeSelection = input.newSessionWorktree?.() || "main"
|
const worktreeSelection = input.newSessionWorktree?.() || "main"
|
||||||
|
|
||||||
let sessionDirectory = projectDirectory
|
let sessionDirectory = projectDirectory
|
||||||
|
|
||||||
if (isNewSession) {
|
if (isNewSession) {
|
||||||
if (worktreeSelection === "create") {
|
if (worktreeSelection === "create") {
|
||||||
const createdWorktree = await sdk()
|
const createdWorktree = await sdk()
|
||||||
.currentApi.projectCopy.create({
|
.api.projectCopy.create({
|
||||||
projectID: sync().data.project,
|
projectID: sync().data.project,
|
||||||
strategy: "git_worktree",
|
strategy: "git_worktree",
|
||||||
directory: getDirectory(projectDirectory),
|
directory: getDirectory(projectDirectory),
|
||||||
@@ -362,7 +383,6 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
})
|
})
|
||||||
return undefined
|
return undefined
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!createdWorktree) return
|
if (!createdWorktree) return
|
||||||
WorktreeState.pending(sdk().scope, createdWorktree.directory)
|
WorktreeState.pending(sdk().scope, createdWorktree.directory)
|
||||||
sessionDirectory = createdWorktree.directory
|
sessionDirectory = createdWorktree.directory
|
||||||
@@ -382,12 +402,11 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
let session = input.info()
|
let session = input.info()
|
||||||
if (!session && isNewSession) {
|
if (!session && isNewSession) {
|
||||||
const created = await sdk()
|
const created = await sdk()
|
||||||
.currentApi.session.create({
|
.api.session.create({
|
||||||
agent: currentAgent.name,
|
agent: currentAgent.name,
|
||||||
model: { id: currentModel.id, providerID: currentModel.provider.id, variant },
|
model: { id: currentModel.id, providerID: currentModel.provider.id, variant },
|
||||||
location: { directory: sessionDirectory },
|
location: { directory: sessionDirectory },
|
||||||
})
|
})
|
||||||
.then(normalizeSessionInfo)
|
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
showToast({
|
showToast({
|
||||||
title: language.t("prompt.toast.sessionCreateFailed.title"),
|
title: language.t("prompt.toast.sessionCreateFailed.title"),
|
||||||
@@ -473,7 +492,7 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
clearInput()
|
clearInput()
|
||||||
const eventID = Event.ID.create()
|
const eventID = Event.ID.create()
|
||||||
sdk()
|
sdk()
|
||||||
.currentApi.session.shell({
|
.api.session.shell({
|
||||||
sessionID: session.id,
|
sessionID: session.id,
|
||||||
id: eventID,
|
id: eventID,
|
||||||
command: text,
|
command: text,
|
||||||
@@ -497,7 +516,7 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
const messageID = Identifier.ascending("message")
|
const messageID = Identifier.ascending("message")
|
||||||
serverSync().session.set("session_status", session.id, { type: "busy" })
|
serverSync().session.set("session_status", session.id, { type: "busy" })
|
||||||
sdk()
|
sdk()
|
||||||
.currentApi.session.command({
|
.api.session.command({
|
||||||
sessionID: session.id,
|
sessionID: session.id,
|
||||||
id: messageID,
|
id: messageID,
|
||||||
command: commandName,
|
command: commandName,
|
||||||
@@ -594,9 +613,10 @@ export function createPromptSubmit(input: PromptSubmitInput) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void sendFollowupDraft({
|
void sendFollowupDraft({
|
||||||
api: sdk().currentApi.session,
|
api: sdk().api.session,
|
||||||
sync: sync(),
|
sync: sync(),
|
||||||
serverSync: serverSync(),
|
serverSync: serverSync(),
|
||||||
|
session: () => input.info() ?? session,
|
||||||
draft,
|
draft,
|
||||||
messageID,
|
messageID,
|
||||||
optimisticBusy: sessionDirectory === projectDirectory,
|
optimisticBusy: sessionDirectory === projectDirectory,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { useLanguage } from "@/context/language"
|
|||||||
import { usePermission } from "@/context/permission"
|
import { usePermission } from "@/context/permission"
|
||||||
import { usePlatform, type DisplayBackend } from "@/context/platform"
|
import { usePlatform, type DisplayBackend } from "@/context/platform"
|
||||||
import { useServerSync } from "@/context/server-sync"
|
import { useServerSync } from "@/context/server-sync"
|
||||||
import { useServerProtocol, useServerSDK } from "@/context/server-sdk"
|
import { useServerSDK } from "@/context/server-sdk"
|
||||||
import { useUpdaterAction } from "./updater-action"
|
import { useUpdaterAction } from "./updater-action"
|
||||||
import {
|
import {
|
||||||
monoDefault,
|
monoDefault,
|
||||||
@@ -125,11 +125,12 @@ export const SettingsGeneral: Component = () => {
|
|||||||
|
|
||||||
const serverSync = useServerSync()
|
const serverSync = useServerSync()
|
||||||
const serverSdk = useServerSDK()
|
const serverSdk = useServerSDK()
|
||||||
const protocol = useServerProtocol()
|
|
||||||
|
|
||||||
const [shells] = createResource(
|
const [shells] = createResource(
|
||||||
() => (protocol() === "v1" ? serverSdk() : undefined),
|
async () => {
|
||||||
(sdk) => sdk.legacy.pty.shells().catch(() => [] as ShellOption[]),
|
// TODO: Restore executable shell discovery; V2 shell.list only lists shell processes.
|
||||||
|
return [] as ShellOption[]
|
||||||
|
},
|
||||||
{ initialValue: [] as ShellOption[] },
|
{ initialValue: [] as ShellOption[] },
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -320,13 +321,13 @@ export const SettingsGeneral: Component = () => {
|
|||||||
</div>
|
</div>
|
||||||
</SettingsRow>
|
</SettingsRow>
|
||||||
|
|
||||||
<Show when={protocol() === "v1"}>
|
<SettingsRow
|
||||||
<SettingsRow
|
title={language.t("settings.general.row.shell.title")}
|
||||||
title={language.t("settings.general.row.shell.title")}
|
description={language.t("settings.general.row.shell.description")}
|
||||||
description={language.t("settings.general.row.shell.description")}
|
>
|
||||||
>
|
|
||||||
<Select
|
<Select
|
||||||
data-action="settings-shell"
|
data-action="settings-shell"
|
||||||
|
disabled
|
||||||
options={shellOptions()}
|
options={shellOptions()}
|
||||||
current={shellOptions().find((o) => o.value === currentShell()) ?? autoOption}
|
current={shellOptions().find((o) => o.value === currentShell()) ?? autoOption}
|
||||||
value={(o) => o.id}
|
value={(o) => o.id}
|
||||||
@@ -334,15 +335,15 @@ export const SettingsGeneral: Component = () => {
|
|||||||
onSelect={(option) => {
|
onSelect={(option) => {
|
||||||
if (!option) return
|
if (!option) return
|
||||||
if (option.value === currentShell()) return
|
if (option.value === currentShell()) return
|
||||||
serverSync().updateConfig({ shell: option.value })
|
// TODO: Restore config writes when the V2 client exposes a config API.
|
||||||
|
// void serverSync().updateConfig({ shell: option.value })
|
||||||
}}
|
}}
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
size="small"
|
size="small"
|
||||||
triggerVariant="settings"
|
triggerVariant="settings"
|
||||||
triggerStyle={{ "min-width": "180px" }}
|
triggerStyle={{ "min-width": "180px" }}
|
||||||
/>
|
/>
|
||||||
</SettingsRow>
|
</SettingsRow>
|
||||||
</Show>
|
|
||||||
|
|
||||||
<SettingsRow
|
<SettingsRow
|
||||||
title={language.t("settings.general.row.reasoningSummaries.title")}
|
title={language.t("settings.general.row.reasoningSummaries.title")}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { showToast } from "@/utils/toast"
|
|||||||
import { popularProviders, useProviders } from "@/hooks/use-providers"
|
import { popularProviders, useProviders } from "@/hooks/use-providers"
|
||||||
import { createMemo, type Component, For, Show } from "solid-js"
|
import { createMemo, type Component, For, Show } from "solid-js"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { useServerProtocol, useServerSDK } from "@/context/server-sdk"
|
import { useServerSDK } from "@/context/server-sdk"
|
||||||
import { useServerSync } from "@/context/server-sync"
|
import { useServerSync } from "@/context/server-sync"
|
||||||
import { DialogConnectProvider, useProviderConnectController } from "./dialog-connect-provider"
|
import { DialogConnectProvider, useProviderConnectController } from "./dialog-connect-provider"
|
||||||
import { DialogCustomProvider } from "./dialog-custom-provider"
|
import { DialogCustomProvider } from "./dialog-custom-provider"
|
||||||
@@ -39,7 +39,6 @@ const SettingsProvidersContent: Component<{ onBack?: () => void }> = (props) =>
|
|||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const serverSDK = useServerSDK()
|
const serverSDK = useServerSDK()
|
||||||
const protocol = useServerProtocol()
|
|
||||||
const serverSync = useServerSync()
|
const serverSync = useServerSync()
|
||||||
const providers = useProviders(() => undefined)
|
const providers = useProviders(() => undefined)
|
||||||
const providerConnect = useProviderConnectController({ onBack: props.onBack })
|
const providerConnect = useProviderConnectController({ onBack: props.onBack })
|
||||||
@@ -84,8 +83,7 @@ const SettingsProvidersContent: Component<{ onBack?: () => void }> = (props) =>
|
|||||||
return language.t("settings.providers.tag.other")
|
return language.t("settings.providers.tag.other")
|
||||||
}
|
}
|
||||||
|
|
||||||
const canDisconnect = (item: ProviderItem) =>
|
const canDisconnect = (item: ProviderItem) => source(item) !== "env" && !isConfigCustom(item.id)
|
||||||
source(item) !== "env" && (protocol() === "v1" || !isConfigCustom(item.id))
|
|
||||||
|
|
||||||
const note = (id: string) => PROVIDER_NOTES.find((item) => item.match(id))?.key
|
const note = (id: string) => PROVIDER_NOTES.find((item) => item.match(id))?.key
|
||||||
|
|
||||||
@@ -98,7 +96,7 @@ const SettingsProvidersContent: Component<{ onBack?: () => void }> = (props) =>
|
|||||||
}
|
}
|
||||||
|
|
||||||
const disableProvider = async (providerID: string, name: string) => {
|
const disableProvider = async (providerID: string, name: string) => {
|
||||||
if (protocol() !== "v1") return
|
return
|
||||||
const before = serverSync().data.config.disabled_providers ?? []
|
const before = serverSync().data.config.disabled_providers ?? []
|
||||||
const next = before.includes(providerID) ? before : [...before, providerID]
|
const next = before.includes(providerID) ? before : [...before, providerID]
|
||||||
serverSync().set("config", "disabled_providers", next)
|
serverSync().set("config", "disabled_providers", next)
|
||||||
@@ -121,18 +119,13 @@ const SettingsProvidersContent: Component<{ onBack?: () => void }> = (props) =>
|
|||||||
}
|
}
|
||||||
|
|
||||||
const disconnect = async (providerID: string, name: string) => {
|
const disconnect = async (providerID: string, name: string) => {
|
||||||
if (isConfigCustom(providerID)) {
|
|
||||||
await serverSDK().legacy.auth.remove({ providerID }).catch(() => undefined)
|
|
||||||
await disableProvider(providerID, name)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await serverSDK()
|
await serverSDK()
|
||||||
.currentApi.integration.get({ integrationID: providerID })
|
.api.integration.get({ integrationID: providerID })
|
||||||
.then(async (integration) => {
|
.then(async (integration) => {
|
||||||
const credentials = integration.data?.connections.filter((item) => item.type === "credential") ?? []
|
const credentials = integration.data?.connections.filter((item) => item.type === "credential") ?? []
|
||||||
if (credentials.length === 0) throw new Error(`No removable credentials found for ${name}`)
|
if (credentials.length === 0) throw new Error(`No removable credentials found for ${name}`)
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
credentials.map((credential) => serverSDK().currentApi.credential.remove({ credentialID: credential.id })),
|
credentials.map((credential) => serverSDK().api.credential.remove({ credentialID: credential.id })),
|
||||||
)
|
)
|
||||||
showToast({
|
showToast({
|
||||||
variant: "success",
|
variant: "success",
|
||||||
@@ -223,7 +216,7 @@ const SettingsProvidersContent: Component<{ onBack?: () => void }> = (props) =>
|
|||||||
)}
|
)}
|
||||||
</For>
|
</For>
|
||||||
|
|
||||||
<Show when={protocol() === "v1"}>
|
<Show when={false}>
|
||||||
<div
|
<div
|
||||||
class="flex items-center justify-between gap-4 min-h-16 border-b border-border-weak-base last:border-none flex-wrap py-3"
|
class="flex items-center justify-between gap-4 min-h-16 border-b border-border-weak-base last:border-none flex-wrap py-3"
|
||||||
data-component="custom-provider-section"
|
data-component="custom-provider-section"
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export const DialogSettings: Component<{
|
|||||||
const draft = tabs.store.find((item) => item.type === "draft" && item.draftID === route.draftID)
|
const draft = tabs.store.find((item) => item.type === "draft" && item.draftID === route.draftID)
|
||||||
return draft?.type === "draft" ? draft.directory : undefined
|
return draft?.type === "draft" ? draft.directory : undefined
|
||||||
}
|
}
|
||||||
if (route.type === "session") return serverSync().session.get(route.sessionId)?.directory
|
if (route.type === "session") return serverSync().session.get(route.sessionId)?.location.directory
|
||||||
return undefined
|
return undefined
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import { useLanguage } from "@/context/language"
|
|||||||
import { usePermission } from "@/context/permission"
|
import { usePermission } from "@/context/permission"
|
||||||
import { usePlatform } from "@/context/platform"
|
import { usePlatform } from "@/context/platform"
|
||||||
import { useServerSync } from "@/context/server-sync"
|
import { useServerSync } from "@/context/server-sync"
|
||||||
import { useServerProtocol, useServerSDK } from "@/context/server-sdk"
|
|
||||||
import { useUpdaterAction } from "../updater-action"
|
import { useUpdaterAction } from "../updater-action"
|
||||||
import {
|
import {
|
||||||
monoDefault,
|
monoDefault,
|
||||||
@@ -91,15 +90,13 @@ export const SettingsGeneralV2: Component<{
|
|||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const settings = useSettings()
|
const settings = useSettings()
|
||||||
const serverSync = useServerSync()
|
const serverSync = useServerSync()
|
||||||
const serverSdk = useServerSDK()
|
|
||||||
const protocol = useServerProtocol()
|
|
||||||
const mobile = createMediaQuery("(max-width: 767px)")
|
const mobile = createMediaQuery("(max-width: 767px)")
|
||||||
|
|
||||||
const updater = useUpdaterAction()
|
const updater = useUpdaterAction()
|
||||||
|
|
||||||
const dir = createMemo(() => {
|
const dir = createMemo(() => {
|
||||||
if (!props.sessionID) return undefined
|
if (!props.sessionID) return undefined
|
||||||
return serverSync().session.lineage.peek(props.sessionID)?.session.directory
|
return serverSync().session.lineage.peek(props.sessionID)?.session.location.directory
|
||||||
})
|
})
|
||||||
const accepting = createMemo(() => {
|
const accepting = createMemo(() => {
|
||||||
const value = dir()
|
const value = dir()
|
||||||
@@ -123,8 +120,11 @@ export const SettingsGeneralV2: Component<{
|
|||||||
const themeOptions = createMemo<ThemeOption[]>(() => theme.ids().map((id) => ({ id, name: theme.name(id) })))
|
const themeOptions = createMemo<ThemeOption[]>(() => theme.ids().map((id) => ({ id, name: theme.name(id) })))
|
||||||
|
|
||||||
const [shells] = createResource(
|
const [shells] = createResource(
|
||||||
() => (protocol() === "v1" ? serverSdk() : undefined),
|
async () => {
|
||||||
(sdk) => sdk.legacy.pty.shells().catch(() => [] as ShellOption[]),
|
// TODO: Restore executable shell discovery when the V2 client exposes it.
|
||||||
|
// return (await sdk.api.pty.shells()).data
|
||||||
|
return [] as ShellOption[]
|
||||||
|
},
|
||||||
{ initialValue: [] as ShellOption[] },
|
{ initialValue: [] as ShellOption[] },
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -279,11 +279,10 @@ export const SettingsGeneralV2: Component<{
|
|||||||
</div>
|
</div>
|
||||||
</SettingsRowV2>
|
</SettingsRowV2>
|
||||||
|
|
||||||
<Show when={protocol() === "v1"}>
|
<SettingsRowV2
|
||||||
<SettingsRowV2
|
title={language.t("settings.general.row.shell.title")}
|
||||||
title={language.t("settings.general.row.shell.title")}
|
description={language.t("settings.general.row.shell.description")}
|
||||||
description={language.t("settings.general.row.shell.description")}
|
>
|
||||||
>
|
|
||||||
<SelectV2
|
<SelectV2
|
||||||
appearance="inline"
|
appearance="inline"
|
||||||
data-action="settings-shell"
|
data-action="settings-shell"
|
||||||
@@ -299,8 +298,7 @@ export const SettingsGeneralV2: Component<{
|
|||||||
serverSync().updateConfig({ shell: option.value })
|
serverSync().updateConfig({ shell: option.value })
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</SettingsRowV2>
|
</SettingsRowV2>
|
||||||
</Show>
|
|
||||||
|
|
||||||
<SettingsRowV2
|
<SettingsRowV2
|
||||||
title={language.t("settings.general.row.reasoningSummaries.title")}
|
title={language.t("settings.general.row.reasoningSummaries.title")}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { showToast } from "@/utils/toast"
|
|||||||
import { popularProviders, useProviders } from "@/hooks/use-providers"
|
import { popularProviders, useProviders } from "@/hooks/use-providers"
|
||||||
import { createMemo, type Accessor, type Component, For, Show } from "solid-js"
|
import { createMemo, type Accessor, type Component, For, Show } from "solid-js"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { useServerProtocol, useServerSDK } from "@/context/server-sdk"
|
import { useServerSDK } from "@/context/server-sdk"
|
||||||
import { useServerSync } from "@/context/server-sync"
|
import { useServerSync } from "@/context/server-sync"
|
||||||
import { DialogConnectProvider, useProviderConnectController } from "../dialog-connect-provider"
|
import { DialogConnectProvider, useProviderConnectController } from "../dialog-connect-provider"
|
||||||
import { DialogCustomProvider } from "../dialog-custom-provider"
|
import { DialogCustomProvider } from "../dialog-custom-provider"
|
||||||
@@ -36,7 +36,6 @@ export const SettingsProvidersV2: Component<{
|
|||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const serverSdk = useServerSDK()
|
const serverSdk = useServerSDK()
|
||||||
const protocol = useServerProtocol()
|
|
||||||
const serverSync = useServerSync()
|
const serverSync = useServerSync()
|
||||||
const providers = useProviders(props.directory)
|
const providers = useProviders(props.directory)
|
||||||
const providerConnect = useProviderConnectController({ onBack: props.onBack })
|
const providerConnect = useProviderConnectController({ onBack: props.onBack })
|
||||||
@@ -81,8 +80,7 @@ export const SettingsProvidersV2: Component<{
|
|||||||
return language.t("settings.providers.tag.other")
|
return language.t("settings.providers.tag.other")
|
||||||
}
|
}
|
||||||
|
|
||||||
const canDisconnect = (item: ProviderItem) =>
|
const canDisconnect = (item: ProviderItem) => source(item) !== "env" && !isConfigCustom(item.id)
|
||||||
source(item) !== "env" && (protocol() === "v1" || !isConfigCustom(item.id))
|
|
||||||
|
|
||||||
const note = (id: string) => PROVIDER_NOTES.find((item) => item.match(id))?.key
|
const note = (id: string) => PROVIDER_NOTES.find((item) => item.match(id))?.key
|
||||||
|
|
||||||
@@ -95,7 +93,7 @@ export const SettingsProvidersV2: Component<{
|
|||||||
}
|
}
|
||||||
|
|
||||||
const disableProvider = async (providerID: string, name: string) => {
|
const disableProvider = async (providerID: string, name: string) => {
|
||||||
if (protocol() !== "v1") return
|
return
|
||||||
const before = serverSync().data.config.disabled_providers ?? []
|
const before = serverSync().data.config.disabled_providers ?? []
|
||||||
const next = before.includes(providerID) ? before : [...before, providerID]
|
const next = before.includes(providerID) ? before : [...before, providerID]
|
||||||
serverSync().set("config", "disabled_providers", next)
|
serverSync().set("config", "disabled_providers", next)
|
||||||
@@ -118,20 +116,15 @@ export const SettingsProvidersV2: Component<{
|
|||||||
}
|
}
|
||||||
|
|
||||||
const disconnect = async (providerID: string, name: string) => {
|
const disconnect = async (providerID: string, name: string) => {
|
||||||
if (isConfigCustom(providerID)) {
|
|
||||||
await serverSdk().legacy.auth.remove({ providerID }).catch(() => undefined)
|
|
||||||
await disableProvider(providerID, name)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const location = props.directory() ? { directory: props.directory() } : undefined
|
const location = props.directory() ? { directory: props.directory() } : undefined
|
||||||
await serverSdk()
|
await serverSdk()
|
||||||
.currentApi.integration.get({ integrationID: providerID, location })
|
.api.integration.get({ integrationID: providerID, location })
|
||||||
.then(async (integration) => {
|
.then(async (integration) => {
|
||||||
const credentials = integration.data?.connections.filter((item) => item.type === "credential") ?? []
|
const credentials = integration.data?.connections.filter((item) => item.type === "credential") ?? []
|
||||||
if (credentials.length === 0) throw new Error(`No removable credentials found for ${name}`)
|
if (credentials.length === 0) throw new Error(`No removable credentials found for ${name}`)
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
credentials.map((credential) =>
|
credentials.map((credential) =>
|
||||||
serverSdk().currentApi.credential.remove({ credentialID: credential.id, location }),
|
serverSdk().api.credential.remove({ credentialID: credential.id, location }),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
showToast({
|
showToast({
|
||||||
@@ -229,7 +222,7 @@ export const SettingsProvidersV2: Component<{
|
|||||||
)}
|
)}
|
||||||
</For>
|
</For>
|
||||||
|
|
||||||
<Show when={protocol() === "v1"}>
|
<Show when={false}>
|
||||||
<div class="settings-v2-provider-row" data-component="custom-provider-section">
|
<div class="settings-v2-provider-row" data-component="custom-provider-section">
|
||||||
<div class="settings-v2-provider-lead">
|
<div class="settings-v2-provider-lead">
|
||||||
<ProviderIcon
|
<ProviderIcon
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { Switch } from "@opencode-ai/ui/switch"
|
|||||||
import { Tabs } from "@opencode-ai/ui/tabs"
|
import { Tabs } from "@opencode-ai/ui/tabs"
|
||||||
import { showToast } from "@/utils/toast"
|
import { showToast } from "@/utils/toast"
|
||||||
import { useNavigate } from "@solidjs/router"
|
import { useNavigate } from "@solidjs/router"
|
||||||
import { type Accessor, createEffect, createMemo, For, type JSXElement, onCleanup, Show } from "solid-js"
|
import { type Accessor, createEffect, createMemo, createResource, For, type JSXElement, onCleanup, Show } from "solid-js"
|
||||||
import { createStore } from "solid-js/store"
|
import { createStore } from "solid-js/store"
|
||||||
import { ServerHealthIndicator, ServerRow } from "@/components/server/server-row"
|
import { ServerHealthIndicator, ServerRow } from "@/components/server/server-row"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
@@ -16,7 +16,7 @@ import { type ServerHealth } from "@/utils/server-health"
|
|||||||
import { useGlobal } from "@/context/global"
|
import { useGlobal } from "@/context/global"
|
||||||
import { useSettings } from "@/context/settings"
|
import { useSettings } from "@/context/settings"
|
||||||
import { useMcpToggle } from "@/context/mcp"
|
import { useMcpToggle } from "@/context/mcp"
|
||||||
import { useServerProtocol } from "@/context/server-sdk"
|
import { useSDK } from "@/context/sdk"
|
||||||
|
|
||||||
const pluginEmptyMessage = (value: string, file: string): JSXElement => {
|
const pluginEmptyMessage = (value: string, file: string): JSXElement => {
|
||||||
const parts = value.split(file)
|
const parts = value.split(file)
|
||||||
@@ -251,6 +251,7 @@ function ServerStatusList(props: { state: ServerStatusState }) {
|
|||||||
|
|
||||||
export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
||||||
const sync = useSync()
|
const sync = useSync()
|
||||||
|
const sdk = useSDK()
|
||||||
const global = useGlobal()
|
const global = useGlobal()
|
||||||
const server = useServer()
|
const server = useServer()
|
||||||
const platform = usePlatform()
|
const platform = usePlatform()
|
||||||
@@ -258,7 +259,6 @@ export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const settings = useSettings()
|
const settings = useSettings()
|
||||||
const protocol = useServerProtocol()
|
|
||||||
|
|
||||||
const fail = (err: unknown) => {
|
const fail = (err: unknown) => {
|
||||||
showToast({
|
showToast({
|
||||||
@@ -279,9 +279,7 @@ export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|||||||
dialogRun += 1
|
dialogRun += 1
|
||||||
})
|
})
|
||||||
const sortedServers = createMemo(() => {
|
const sortedServers = createMemo(() => {
|
||||||
const list = settings.general.newLayoutDesigns()
|
const list = global.servers.list()
|
||||||
? global.servers.list()
|
|
||||||
: global.servers.list().filter((x) => global.ensureServerCtx(x).sdk.protocolKind() !== "v2")
|
|
||||||
return listServersByHealth(list, server.key, global.servers.health)
|
return listServersByHealth(list, server.key, global.servers.health)
|
||||||
})
|
})
|
||||||
const toggleMcp = useMcpToggle()
|
const toggleMcp = useMcpToggle()
|
||||||
@@ -291,9 +289,11 @@ export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|||||||
const mcpConnected = createMemo(() => mcpNames().filter((name) => mcpStatus(name) === "connected").length)
|
const mcpConnected = createMemo(() => mcpNames().filter((name) => mcpStatus(name) === "connected").length)
|
||||||
const lspItems = createMemo(() => sync().data.lsp ?? [])
|
const lspItems = createMemo(() => sync().data.lsp ?? [])
|
||||||
const lspCount = createMemo(() => lspItems().length)
|
const lspCount = createMemo(() => lspItems().length)
|
||||||
const plugins = createMemo(() =>
|
const [pluginList] = createResource(
|
||||||
(sync().data.config.plugin ?? []).map((item) => (typeof item === "string" ? item : item[0])),
|
() => (props.shown() ? sdk().directory : undefined),
|
||||||
|
(directory) => sdk().api.plugin.list({ location: { directory } }).then((result) => result.data),
|
||||||
)
|
)
|
||||||
|
const plugins = createMemo(() => (pluginList.latest ?? []).map((item) => item.id))
|
||||||
const pluginCount = createMemo(() => plugins().length)
|
const pluginCount = createMemo(() => plugins().length)
|
||||||
const pluginEmpty = createMemo(() => pluginEmptyMessage(language.t("dialog.plugins.empty"), "opencode.json"))
|
const pluginEmpty = createMemo(() => pluginEmptyMessage(language.t("dialog.plugins.empty"), "opencode.json"))
|
||||||
|
|
||||||
@@ -318,13 +318,11 @@ export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|||||||
{mcpConnected() > 0 ? `${mcpConnected()} ` : ""}
|
{mcpConnected() > 0 ? `${mcpConnected()} ` : ""}
|
||||||
{language.t("status.popover.tab.mcp")}
|
{language.t("status.popover.tab.mcp")}
|
||||||
</Tabs.Trigger>
|
</Tabs.Trigger>
|
||||||
<Show when={protocol() === "v1"}>
|
<Tabs.Trigger value="lsp" data-slot="tab" class="text-12-regular">
|
||||||
<Tabs.Trigger value="lsp" data-slot="tab" class="text-12-regular">
|
{lspCount() > 0 ? `${lspCount()} ` : ""}
|
||||||
{lspCount() > 0 ? `${lspCount()} ` : ""}
|
{language.t("status.popover.tab.lsp")}
|
||||||
{language.t("status.popover.tab.lsp")}
|
</Tabs.Trigger>
|
||||||
</Tabs.Trigger>
|
<Show when={true}>
|
||||||
</Show>
|
|
||||||
<Show when={protocol() === "v1"}>
|
|
||||||
<Tabs.Trigger value="plugins" data-slot="tab" class="text-12-regular">
|
<Tabs.Trigger value="plugins" data-slot="tab" class="text-12-regular">
|
||||||
{pluginCount() > 0 ? `${pluginCount()} ` : ""}
|
{pluginCount() > 0 ? `${pluginCount()} ` : ""}
|
||||||
{language.t("status.popover.tab.plugins")}
|
{language.t("status.popover.tab.plugins")}
|
||||||
@@ -461,8 +459,7 @@ export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|||||||
</div>
|
</div>
|
||||||
</Tabs.Content>
|
</Tabs.Content>
|
||||||
|
|
||||||
<Show when={protocol() === "v1"}>
|
<Tabs.Content value="lsp">
|
||||||
<Tabs.Content value="lsp">
|
|
||||||
<div class="flex flex-col px-2 pb-2">
|
<div class="flex flex-col px-2 pb-2">
|
||||||
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
||||||
<Show
|
<Show
|
||||||
@@ -488,10 +485,9 @@ export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Tabs.Content>
|
</Tabs.Content>
|
||||||
</Show>
|
|
||||||
|
|
||||||
<Show when={protocol() === "v1"}>
|
<Show when={true}>
|
||||||
<Tabs.Content value="plugins">
|
<Tabs.Content value="plugins">
|
||||||
<div class="flex flex-col px-2 pb-2">
|
<div class="flex flex-col px-2 pb-2">
|
||||||
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
||||||
|
|||||||
@@ -11,13 +11,11 @@ import { matchKeybind, parseKeybind } from "@/context/command"
|
|||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { usePlatform } from "@/context/platform"
|
import { usePlatform } from "@/context/platform"
|
||||||
import { useSDK } from "@/context/sdk"
|
import { useSDK } from "@/context/sdk"
|
||||||
import { useServerSDK } from "@/context/server-sdk"
|
|
||||||
import { terminalFontFamily, useSettings } from "@/context/settings"
|
import { terminalFontFamily, useSettings } from "@/context/settings"
|
||||||
import type { LocalPTY } from "@/context/terminal"
|
import type { LocalPTY } from "@/context/terminal"
|
||||||
import { disposeIfDisposable, getHoveredLinkText, setOptionIfSupported } from "@/utils/runtime-adapters"
|
import { disposeIfDisposable, getHoveredLinkText, setOptionIfSupported } from "@/utils/runtime-adapters"
|
||||||
import { terminalWriter } from "@/utils/terminal-writer"
|
import { terminalWriter } from "@/utils/terminal-writer"
|
||||||
import { terminalWebSocketURL } from "@/utils/terminal-websocket-url"
|
import { terminalWebSocketURL } from "@/utils/terminal-websocket-url"
|
||||||
import { authTokenFromCredentials } from "@/utils/server"
|
|
||||||
|
|
||||||
const TOGGLE_TERMINAL_ID = "terminal.toggle"
|
const TOGGLE_TERMINAL_ID = "terminal.toggle"
|
||||||
const DEFAULT_TOGGLE_TERMINAL_KEYBIND = "ctrl+`"
|
const DEFAULT_TOGGLE_TERMINAL_KEYBIND = "ctrl+`"
|
||||||
@@ -176,13 +174,8 @@ export const Terminal = (props: TerminalProps) => {
|
|||||||
const settings = useSettings()
|
const settings = useSettings()
|
||||||
const theme = useTheme()
|
const theme = useTheme()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
// Terminal captures its connection for the PTY lifetime, so callers must key it per server/session.
|
|
||||||
const connection = useServerSDK()().server
|
|
||||||
const directory = sdk().directory
|
const directory = sdk().directory
|
||||||
const url = sdk().url
|
const url = sdk().url
|
||||||
const auth = connection.http
|
|
||||||
const username = auth?.username ?? "opencode"
|
|
||||||
const password = auth?.password ?? ""
|
|
||||||
let container!: HTMLDivElement
|
let container!: HTMLDivElement
|
||||||
const [local, others] = splitProps(props, [
|
const [local, others] = splitProps(props, [
|
||||||
"pty",
|
"pty",
|
||||||
@@ -241,7 +234,7 @@ export const Terminal = (props: TerminalProps) => {
|
|||||||
|
|
||||||
const pushSize = async (cols: number, rows: number) => {
|
const pushSize = async (cols: number, rows: number) => {
|
||||||
return sdk()
|
return sdk()
|
||||||
.currentApi.pty.update({
|
.api.pty.update({
|
||||||
ptyID: id,
|
ptyID: id,
|
||||||
location: { directory },
|
location: { directory },
|
||||||
size: { cols, rows },
|
size: { cols, rows },
|
||||||
@@ -523,7 +516,7 @@ export const Terminal = (props: TerminalProps) => {
|
|||||||
|
|
||||||
const gone = async () => {
|
const gone = async () => {
|
||||||
return sdk()
|
return sdk()
|
||||||
.currentApi.pty.get({ ptyID: id, location: { directory } })
|
.api.pty.get({ ptyID: id, location: { directory } })
|
||||||
.then((result) => result.data.status === "exited")
|
.then((result) => result.data.status === "exited")
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
if (err && typeof err === "object" && "_tag" in err && err._tag === "PtyNotFoundError") return true
|
if (err && typeof err === "object" && "_tag" in err && err._tag === "PtyNotFoundError") return true
|
||||||
@@ -533,23 +526,8 @@ export const Terminal = (props: TerminalProps) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const connectToken = async () => {
|
const connectToken = async () => {
|
||||||
const endpoint = new URL(`/api/pty/${encodeURIComponent(id)}/connect-token`, url)
|
// TODO: Add PTY tickets when the V2 client exposes a connect-token API.
|
||||||
endpoint.searchParams.set("location[directory]", directory)
|
return undefined
|
||||||
const response = await (platform.fetch ?? globalThis.fetch)(endpoint, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"x-opencode-ticket": "1",
|
|
||||||
...(password
|
|
||||||
? { Authorization: `Basic ${authTokenFromCredentials({ username, password })}` }
|
|
||||||
: undefined),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if (response.status === 403)
|
|
||||||
throw new Error("PTY connect ticket rejected by origin or CSRF checks. Check the server CORS config.")
|
|
||||||
if (!response.ok) throw new Error(`PTY connect ticket failed with ${response.status}`)
|
|
||||||
const result = (await response.json()) as { data?: { ticket?: string } }
|
|
||||||
if (!result.data?.ticket) throw new Error("PTY connect ticket response did not include a ticket")
|
|
||||||
return result.data.ticket
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const retry = (err: unknown) => {
|
const retry = (err: unknown) => {
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ import { createResizeObserver } from "@solid-primitives/resize-observer"
|
|||||||
import { createMutation } from "@tanstack/solid-query"
|
import { createMutation } from "@tanstack/solid-query"
|
||||||
import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
|
import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
|
||||||
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
|
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
|
||||||
import { displayLabel } from "@opencode-ai/util/session-title-fallback"
|
|
||||||
import { useGlobal } from "@/context/global"
|
import { useGlobal } from "@/context/global"
|
||||||
import { ServerConnection, serverName } from "@/context/server"
|
import { ServerConnection, serverName } from "@/context/server"
|
||||||
import { displayName, projectForSession } from "@/pages/layout/helpers"
|
import { displayName, projectForSession } from "@/pages/layout/helpers"
|
||||||
import { SessionTabAvatar } from "@/pages/layout/session-tab-avatar"
|
import { SessionTabAvatar } from "@/pages/layout/session-tab-avatar"
|
||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
|
import { sessionLabel } from "@/utils/session-title"
|
||||||
import { canOpenTabRename, forwardTabRef } from "./titlebar-tab-gesture"
|
import { canOpenTabRename, forwardTabRef } from "./titlebar-tab-gesture"
|
||||||
import { TabPreviewPopover } from "./titlebar-tab-popover"
|
import { TabPreviewPopover } from "./titlebar-tab-popover"
|
||||||
import "./titlebar-tab-nav.css"
|
import "./titlebar-tab-nav.css"
|
||||||
@@ -21,7 +21,7 @@ export function TabNavItem(props: {
|
|||||||
ref?: Ref<HTMLDivElement>
|
ref?: Ref<HTMLDivElement>
|
||||||
href: string
|
href: string
|
||||||
server: ServerConnection.Key
|
server: ServerConnection.Key
|
||||||
session: () => Session | undefined
|
session: () => SessionInfo | undefined
|
||||||
fallbackTitle?: string
|
fallbackTitle?: string
|
||||||
onRename: (title: string) => Promise<void>
|
onRename: (title: string) => Promise<void>
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
@@ -57,19 +57,19 @@ export function TabNavItem(props: {
|
|||||||
})
|
})
|
||||||
const title = createMemo(() => {
|
const title = createMemo(() => {
|
||||||
const session = props.session()
|
const session = props.session()
|
||||||
return session ? displayLabel(session) : props.fallbackTitle
|
return session ? sessionLabel(session) : props.fallbackTitle
|
||||||
})
|
})
|
||||||
|
|
||||||
const projectName = createMemo(() => {
|
const projectName = createMemo(() => {
|
||||||
const session = props.session()
|
const session = props.session()
|
||||||
if (!session) return
|
if (!session) return
|
||||||
return displayName(project() ?? { worktree: session.directory })
|
return displayName(project() ?? { worktree: session.location.directory })
|
||||||
})
|
})
|
||||||
const previewPath = createMemo(() => {
|
const previewPath = createMemo(() => {
|
||||||
const session = props.session()
|
const session = props.session()
|
||||||
if (!session) return
|
if (!session) return
|
||||||
const home = serverCtx()?.sync.data.path.home
|
const home = serverCtx()?.sync.data.path.home
|
||||||
return home ? session.directory.replace(home, "~") : session.directory
|
return home ? session.location.directory.replace(home, "~") : session.location.directory
|
||||||
})
|
})
|
||||||
// Only label the server when multiple servers are connected.
|
// Only label the server when multiple servers are connected.
|
||||||
const serverLabel = createMemo(() => {
|
const serverLabel = createMemo(() => {
|
||||||
@@ -235,7 +235,7 @@ export function TabNavItem(props: {
|
|||||||
{(session) => (
|
{(session) => (
|
||||||
<SessionTabAvatar
|
<SessionTabAvatar
|
||||||
project={project()}
|
project={project()}
|
||||||
directory={session().directory}
|
directory={session().location.directory}
|
||||||
sessionId={session().id}
|
sessionId={session().id}
|
||||||
server={props.server}
|
server={props.server}
|
||||||
/>
|
/>
|
||||||
@@ -306,7 +306,7 @@ export function TabNavItem(props: {
|
|||||||
}}
|
}}
|
||||||
data={{
|
data={{
|
||||||
projectName: projectName(),
|
projectName: projectName(),
|
||||||
title: title(),
|
title: props.session()?.title,
|
||||||
path: previewPath(),
|
path: previewPath(),
|
||||||
serverName: serverLabel(),
|
serverName: serverLabel(),
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import { base64Encode } from "@opencode-ai/core/util/encode"
|
|||||||
import { showToast } from "@/utils/toast"
|
import { showToast } from "@/utils/toast"
|
||||||
import { canStartTabDrag, isTabCloseTarget } from "./titlebar-tab-gesture"
|
import { canStartTabDrag, isTabCloseTarget } from "./titlebar-tab-gesture"
|
||||||
import { adjacentTabKey, mergeVisibleTabOrder } from "./titlebar-tab-order"
|
import { adjacentTabKey, mergeVisibleTabOrder } from "./titlebar-tab-order"
|
||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
|
|
||||||
function SessionTabSlot(props: {
|
function SessionTabSlot(props: {
|
||||||
tab: SessionTab
|
tab: SessionTab
|
||||||
@@ -27,7 +27,7 @@ function SessionTabSlot(props: {
|
|||||||
index: () => number
|
index: () => number
|
||||||
active: () => boolean
|
active: () => boolean
|
||||||
forceTruncate: boolean
|
forceTruncate: boolean
|
||||||
session: () => Session | undefined
|
session: () => SessionInfo | undefined
|
||||||
fallbackTitle?: string
|
fallbackTitle?: string
|
||||||
onRename: (title: string) => Promise<void>
|
onRename: (title: string) => Promise<void>
|
||||||
onNavigate: (element: HTMLDivElement) => void
|
onNavigate: (element: HTMLDivElement) => void
|
||||||
@@ -105,7 +105,7 @@ function SessionTabEntry(props: {
|
|||||||
|
|
||||||
ctx.sync.session.remember({ ...value, title })
|
ctx.sync.session.remember({ ...value, title })
|
||||||
try {
|
try {
|
||||||
await ctx.sdk.currentApi.session.rename({ sessionID: value.id, title })
|
await ctx.sdk.api.session.rename({ sessionID: value.id, title })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const current = session()
|
const current = session()
|
||||||
const currentCtx = props.serverCtx()
|
const currentCtx = props.serverCtx()
|
||||||
@@ -127,7 +127,7 @@ function SessionTabEntry(props: {
|
|||||||
createRoot((dispose) => {
|
createRoot((dispose) => {
|
||||||
try {
|
try {
|
||||||
void ctx.sync
|
void ctx.sync
|
||||||
.ensureDirSyncContext(value.directory)
|
.ensureDirSyncContext(value.location.directory)
|
||||||
.session.sync(value.id)
|
.session.sync(value.id)
|
||||||
.catch(() => {})
|
.catch(() => {})
|
||||||
.finally(dispose)
|
.finally(dispose)
|
||||||
@@ -144,7 +144,7 @@ function SessionTabEntry(props: {
|
|||||||
const current = sdk()
|
const current = sdk()
|
||||||
if (!current) return
|
if (!current) return
|
||||||
createTabPromptState(tabs, props.tab, current.scope, {
|
createTabPromptState(tabs, props.tab, current.scope, {
|
||||||
dir: base64Encode(value.directory),
|
dir: base64Encode(value.location.directory),
|
||||||
id: value.id,
|
id: value.id,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ import { tabKey, useTabs } from "@/context/tabs"
|
|||||||
import type { PromptSession } from "@/context/prompt"
|
import type { PromptSession } from "@/context/prompt"
|
||||||
import "./titlebar.css"
|
import "./titlebar.css"
|
||||||
import { newTabTooltipKeybind } from "./command-tooltip-keybind"
|
import { newTabTooltipKeybind } from "./command-tooltip-keybind"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
|
|
||||||
const legacyTitlebarHeight = 40
|
const legacyTitlebarHeight = 40
|
||||||
const v2TitlebarHeight = 36
|
const v2TitlebarHeight = 36
|
||||||
@@ -192,9 +191,8 @@ export function Titlebar(props: { update?: TitlebarUpdate; debugTools?: { visibl
|
|||||||
return conn ? { route, sdk: global.ensureServerCtx(conn).sdk } : undefined
|
return conn ? { route, sdk: global.ensureServerCtx(conn).sdk } : undefined
|
||||||
},
|
},
|
||||||
({ route, sdk }) =>
|
({ route, sdk }) =>
|
||||||
sdk.currentApi.session
|
sdk.api.session
|
||||||
.get({ sessionID: route.sessionId })
|
.get({ sessionID: route.sessionId })
|
||||||
.then(normalizeSessionInfo)
|
|
||||||
.catch(() => {}),
|
.catch(() => {}),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -256,7 +254,7 @@ export function Titlebar(props: { update?: TitlebarUpdate; debugTools?: { visibl
|
|||||||
sessionId: activeSession.id,
|
sessionId: activeSession.id,
|
||||||
}
|
}
|
||||||
const model = tabs.stateValue<PromptSession>(sessionTab, "prompt")?.model.current()
|
const model = tabs.stateValue<PromptSession>(sessionTab, "prompt")?.model.current()
|
||||||
tabs.newDraft({ server: sessionTab.server, directory: activeSession.directory }, "", model)
|
tabs.newDraft({ server: sessionTab.server, directory: activeSession.location.directory }, "", model)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -248,11 +248,6 @@ export function formatKeybind(config: string, t?: (key: KeyLabel) => string): st
|
|||||||
return IS_MAC ? parts.join("") : parts.join("+")
|
return IS_MAC ? parts.join("") : parts.join("+")
|
||||||
}
|
}
|
||||||
|
|
||||||
// KeybindV2 takes an array instead of a string
|
|
||||||
export function formatKeybindKeys(config: string, t?: (key: KeyLabel) => string): string[] {
|
|
||||||
return formatKeybindParts(config, t)
|
|
||||||
}
|
|
||||||
|
|
||||||
function isEditableTarget(target: EventTarget | null) {
|
function isEditableTarget(target: EventTarget | null) {
|
||||||
if (!(target instanceof HTMLElement)) return false
|
if (!(target instanceof HTMLElement)) return false
|
||||||
if (target.isContentEditable) return true
|
if (target.isContentEditable) return true
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { Binary } from "@opencode-ai/core/util/binary"
|
import { Binary } from "@opencode-ai/core/util/binary"
|
||||||
import type { Message, Part, Session } from "@/types"
|
import type { Message, Part } from "@/types"
|
||||||
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { createMemo } from "solid-js"
|
import { createMemo } from "solid-js"
|
||||||
import { produce, reconcile, type SetStoreFunction } from "solid-js/store"
|
import { produce, reconcile, type SetStoreFunction } from "solid-js/store"
|
||||||
import type { createServerSdkContext } from "./server-sdk"
|
import type { createServerSdkContext } from "./server-sdk"
|
||||||
import type { createServerSyncContextInner } from "./server-sync"
|
import type { createServerSyncContextInner } from "./server-sync"
|
||||||
import type { State } from "./global-sync/types"
|
import type { State } from "./global-sync/types"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
|
|
||||||
const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
|
const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
|
||||||
const sessionFields = new Set([
|
const sessionFields = new Set([
|
||||||
@@ -26,7 +26,6 @@ export const createDirSyncContext = (
|
|||||||
serverSync: ReturnType<typeof createServerSyncContextInner>,
|
serverSync: ReturnType<typeof createServerSyncContextInner>,
|
||||||
serverSDK: ReturnType<typeof createServerSdkContext>,
|
serverSDK: ReturnType<typeof createServerSdkContext>,
|
||||||
) => {
|
) => {
|
||||||
const client = serverSDK.createClient({ directory, throwOnError: true })
|
|
||||||
const current = createMemo(() => serverSync.child(directory, { mcp: true }))
|
const current = createMemo(() => serverSync.child(directory, { mcp: true }))
|
||||||
const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
|
const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
|
||||||
const data = new Proxy({} as State, {
|
const data = new Proxy({} as State, {
|
||||||
@@ -47,7 +46,7 @@ export const createDirSyncContext = (
|
|||||||
|
|
||||||
const index = (sessionID: string) => {
|
const index = (sessionID: string) => {
|
||||||
const session = serverSync.session.get(sessionID)
|
const session = serverSync.session.get(sessionID)
|
||||||
if (!session || session.directory !== directory) return
|
if (!session || session.location.directory !== directory) return
|
||||||
const [store, setStore] = current()
|
const [store, setStore] = current()
|
||||||
const result = Binary.search(store.session, session.id, (item) => item.id)
|
const result = Binary.search(store.session, session.id, (item) => item.id)
|
||||||
if (result.found) {
|
if (result.found) {
|
||||||
@@ -75,13 +74,13 @@ export const createDirSyncContext = (
|
|||||||
if (match.found) return serverSync.data.project[match.index]
|
if (match.found) return serverSync.data.project[match.index]
|
||||||
},
|
},
|
||||||
session: {
|
session: {
|
||||||
remember(session: Session) {
|
remember(session: SessionInfo) {
|
||||||
serverSync.session.remember(session)
|
serverSync.session.remember(session)
|
||||||
index(session.id)
|
index(session.id)
|
||||||
},
|
},
|
||||||
get(sessionID: string) {
|
get(sessionID: string) {
|
||||||
const session = serverSync.session.get(sessionID)
|
const session = serverSync.session.get(sessionID)
|
||||||
if (session?.directory === directory) return session
|
if (session?.location.directory === directory) return session
|
||||||
},
|
},
|
||||||
optimistic: {
|
optimistic: {
|
||||||
add(input: { directory?: string; sessionID: string; message: Message; parts: Part[] }) {
|
add(input: { directory?: string; sessionID: string; message: Message; parts: Part[] }) {
|
||||||
@@ -124,9 +123,8 @@ export const createDirSyncContext = (
|
|||||||
fetch: async (count = 10) => {
|
fetch: async (count = 10) => {
|
||||||
const [store, setStore] = current()
|
const [store, setStore] = current()
|
||||||
setStore("limit", (value) => value + count)
|
setStore("limit", (value) => value + count)
|
||||||
const response = await serverSDK.currentApi.session.list({ directory, limit: store.limit, order: "desc" })
|
const response = await serverSDK.api.session.list({ directory, limit: store.limit, order: "desc" })
|
||||||
const sessions = response.data
|
const sessions = response.data
|
||||||
.map(normalizeSessionInfo)
|
|
||||||
.sort((a, b) => cmp(a.id, b.id))
|
.sort((a, b) => cmp(a.id, b.id))
|
||||||
.slice(0, store.limit)
|
.slice(0, store.limit)
|
||||||
sessions.forEach(serverSync.session.remember)
|
sessions.forEach(serverSync.session.remember)
|
||||||
@@ -134,14 +132,8 @@ export const createDirSyncContext = (
|
|||||||
},
|
},
|
||||||
more: createMemo(() => current()[0].session.length >= current()[0].limit),
|
more: createMemo(() => current()[0].session.length >= current()[0].limit),
|
||||||
archive: async (sessionID: string) => {
|
archive: async (sessionID: string) => {
|
||||||
await serverSDK.legacy.session.archive(sessionID, directory)
|
// TODO: Restore archiving when the V2 client exposes a session archive API.
|
||||||
current()[1](
|
void sessionID
|
||||||
"session",
|
|
||||||
produce((draft) => {
|
|
||||||
const match = Binary.search(draft, sessionID, (session) => session.id)
|
|
||||||
if (match.found) draft.splice(match.index, 1)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
mcp: {
|
mcp: {
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
|||||||
normalizeDir: path.normalizeDir,
|
normalizeDir: path.normalizeDir,
|
||||||
list: (dir) =>
|
list: (dir) =>
|
||||||
sdk()
|
sdk()
|
||||||
.currentApi.file.list({ path: dir, location: { directory: scope() } })
|
.api.file.list({ path: dir, location: { directory: scope() } })
|
||||||
.then((x) =>
|
.then((x) =>
|
||||||
x.data.map((entry) => ({
|
x.data.map((entry) => ({
|
||||||
...entry,
|
...entry,
|
||||||
@@ -188,7 +188,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
|||||||
setLoading(file)
|
setLoading(file)
|
||||||
|
|
||||||
const promise = sdk()
|
const promise = sdk()
|
||||||
.currentApi.file.read({ path: file, location: { directory } })
|
.api.file.read({ path: file, location: { directory } })
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
if (scope() !== directory) return
|
if (scope() !== directory) return
|
||||||
const content = { type: "text" as const, content: new TextDecoder().decode(data) }
|
const content = { type: "text" as const, content: new TextDecoder().decode(data) }
|
||||||
@@ -212,7 +212,7 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
|||||||
|
|
||||||
const search = (query: string, dirs: "true" | "false", options?: { limit?: number; signal?: AbortSignal }) =>
|
const search = (query: string, dirs: "true" | "false", options?: { limit?: number; signal?: AbortSignal }) =>
|
||||||
serverSDK()
|
serverSDK()
|
||||||
.currentApi.file.find(
|
.api.file.find(
|
||||||
{
|
{
|
||||||
location: { directory: sdk().directory },
|
location: { directory: sdk().directory },
|
||||||
query,
|
query,
|
||||||
@@ -286,13 +286,6 @@ export const { use: useFile, provider: FileProvider } = createSimpleContext({
|
|||||||
children: tree.children,
|
children: tree.children,
|
||||||
expand: tree.expandDir,
|
expand: tree.expandDir,
|
||||||
collapse: tree.collapseDir,
|
collapse: tree.collapseDir,
|
||||||
toggle(input: string) {
|
|
||||||
if (tree.dirState(input)?.expanded) {
|
|
||||||
tree.collapseDir(input)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
tree.expandDir(input)
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
get,
|
get,
|
||||||
load,
|
load,
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import { createStore } from "solid-js/store"
|
|
||||||
import { QueryClient } from "@tanstack/solid-query"
|
import { QueryClient } from "@tanstack/solid-query"
|
||||||
import type { Config, Project } from "@/types"
|
|
||||||
import type { LegacyCapabilities } from "@/utils/server-compat"
|
|
||||||
import type { AgentApi, CatalogApi, CommandApi, ReferenceApi } from "@opencode-ai/client/promise"
|
import type { AgentApi, CatalogApi, CommandApi, ReferenceApi } from "@opencode-ai/client/promise"
|
||||||
import type { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
import type { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
||||||
import {
|
import {
|
||||||
bootstrapDirectory,
|
|
||||||
loadAgentsQuery,
|
loadAgentsQuery,
|
||||||
loadCommands,
|
loadCommands,
|
||||||
loadPathQuery,
|
loadPathQuery,
|
||||||
@@ -14,139 +10,19 @@ import {
|
|||||||
loadProvidersQuery,
|
loadProvidersQuery,
|
||||||
loadReferencesQuery,
|
loadReferencesQuery,
|
||||||
} from "./bootstrap"
|
} from "./bootstrap"
|
||||||
import type { State, VcsCache } from "./types"
|
|
||||||
import { ServerScope } from "@/utils/server-scope"
|
import { ServerScope } from "@/utils/server-scope"
|
||||||
import type { ServerApi } from "@/utils/server"
|
import type { ServerApi } from "@/utils/server"
|
||||||
|
|
||||||
type ProjectApi = ServerApi["project"]
|
type ProjectApi = ServerApi["project"]
|
||||||
|
|
||||||
const provider = { all: new Map(), connected: [], default: {} } satisfies NormalizedProviderListResponse
|
|
||||||
const api = {
|
|
||||||
agent: { list: async () => ({ location: {}, data: [] }) },
|
|
||||||
provider: { list: async () => ({ location: {}, data: [] }) },
|
|
||||||
model: {
|
|
||||||
list: async () => ({ location: {}, data: [] }),
|
|
||||||
default: async () => ({ location: {}, data: null }),
|
|
||||||
},
|
|
||||||
permission: { request: { list: async () => ({ location: {}, data: [] }) } },
|
|
||||||
project: {
|
|
||||||
list: async () => [],
|
|
||||||
current: async () => ({ id: "project", directory: "/project" }),
|
|
||||||
},
|
|
||||||
question: { request: { list: async () => ({ location: {}, data: [] }) } },
|
|
||||||
reference: { list: async () => ({ location: {}, data: [] }) },
|
|
||||||
vcs: { get: async () => ({ location: {}, data: {} }) },
|
|
||||||
} as unknown as ServerApi
|
|
||||||
|
|
||||||
function directoryState() {
|
|
||||||
return createStore<State>({
|
|
||||||
status: "loading",
|
|
||||||
agent: [],
|
|
||||||
command: [],
|
|
||||||
reference: [],
|
|
||||||
project: "",
|
|
||||||
projectMeta: undefined,
|
|
||||||
icon: undefined,
|
|
||||||
provider_ready: true,
|
|
||||||
provider,
|
|
||||||
config: {},
|
|
||||||
path: { state: "", config: "", worktree: "/project", directory: "/project", home: "/home" },
|
|
||||||
session: [],
|
|
||||||
sessionTotal: 0,
|
|
||||||
session_status: {},
|
|
||||||
session_working(id: string) {
|
|
||||||
return this.session_status[id]?.type !== "idle"
|
|
||||||
},
|
|
||||||
session_diff: {},
|
|
||||||
todo: {},
|
|
||||||
permission: {},
|
|
||||||
question: {},
|
|
||||||
mcp_ready: true,
|
|
||||||
mcp: {},
|
|
||||||
mcp_resource: {},
|
|
||||||
lsp_ready: true,
|
|
||||||
lsp: [],
|
|
||||||
vcs: undefined,
|
|
||||||
limit: 5,
|
|
||||||
message: {},
|
|
||||||
session_message: {},
|
|
||||||
part: {},
|
|
||||||
part_text_accum_delta: {},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("bootstrapDirectory", () => {
|
|
||||||
test("uses current MCP endpoints while retaining unsupported v1 directory reads", async () => {
|
|
||||||
const mcpReads: string[] = []
|
|
||||||
const [store, setStore] = directoryState()
|
|
||||||
const currentApi = {
|
|
||||||
...api,
|
|
||||||
command: {
|
|
||||||
list: async () => {
|
|
||||||
mcpReads.push("command")
|
|
||||||
return { location: {}, data: [] }
|
|
||||||
},
|
|
||||||
},
|
|
||||||
mcp: {
|
|
||||||
list: async () => {
|
|
||||||
mcpReads.push("status")
|
|
||||||
return { location: {}, data: [] }
|
|
||||||
},
|
|
||||||
resource: {
|
|
||||||
catalog: async () => {
|
|
||||||
mcpReads.push("resource")
|
|
||||||
return { location: {}, data: { resources: [], templates: [] } }
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as unknown as ServerApi
|
|
||||||
|
|
||||||
await bootstrapDirectory({
|
|
||||||
directory: "/project",
|
|
||||||
scope: ServerScope.local,
|
|
||||||
mcp: true,
|
|
||||||
global: {
|
|
||||||
config: {} satisfies Config,
|
|
||||||
path: { state: "", config: "", worktree: "/project", directory: "/project", home: "/home" },
|
|
||||||
project: [{ id: "project", worktree: "/project" } as Project],
|
|
||||||
provider,
|
|
||||||
},
|
|
||||||
legacy: { config: { directory: async () => ({}) } } as unknown as LegacyCapabilities,
|
|
||||||
api: currentApi,
|
|
||||||
store,
|
|
||||||
setStore,
|
|
||||||
vcsCache: { setStore() {} } as unknown as VcsCache,
|
|
||||||
loadSessions() {},
|
|
||||||
translate: (key) => key,
|
|
||||||
queryClient: new QueryClient(),
|
|
||||||
protocol: Promise.resolve("v1"),
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(store.status).toBe("partial")
|
|
||||||
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 80))
|
|
||||||
|
|
||||||
expect(store.status).toBe("complete")
|
|
||||||
expect(mcpReads.sort()).toEqual(["command", "resource", "status"])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("query keys", () => {
|
describe("query keys", () => {
|
||||||
test("partitions identical directories by server scope", () => {
|
test("partitions identical directories by server scope", () => {
|
||||||
const location = {} as Parameters<typeof loadPathQuery>[2]
|
|
||||||
const api = {} as CatalogApi
|
const api = {} as CatalogApi
|
||||||
|
const location = {} as ServerApi["location"]
|
||||||
const remote = "https://debian.example" as typeof ServerScope.local
|
const remote = "https://debian.example" as typeof ServerScope.local
|
||||||
|
|
||||||
expect([...loadPathQuery(ServerScope.local, "/repo", location).queryKey]).toEqual([
|
expect([...loadPathQuery(ServerScope.local, "/repo", location).queryKey]).toEqual(["local", "/repo", "path"])
|
||||||
"local",
|
expect([...loadPathQuery(remote, "/repo", location).queryKey]).toEqual(["https://debian.example", "/repo", "path"])
|
||||||
"/repo",
|
|
||||||
"path",
|
|
||||||
])
|
|
||||||
expect([...loadPathQuery(remote, "/repo", location).queryKey]).toEqual([
|
|
||||||
"https://debian.example",
|
|
||||||
"/repo",
|
|
||||||
"path",
|
|
||||||
])
|
|
||||||
expect([...loadProvidersQuery(remote, null, api).queryKey]).toEqual(["https://debian.example", null, "providers"])
|
expect([...loadProvidersQuery(remote, null, api).queryKey]).toEqual(["https://debian.example", null, "providers"])
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -181,6 +57,21 @@ describe("query keys", () => {
|
|||||||
expect(result.connected).toEqual(["openai"])
|
expect(result.connected).toEqual(["openai"])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("loads current location metadata", async () => {
|
||||||
|
const calls: unknown[] = []
|
||||||
|
const api = {
|
||||||
|
get: async (input: unknown) => {
|
||||||
|
calls.push(input)
|
||||||
|
return { directory: "/repo/subpath", project: { id: "project", directory: "/repo" } }
|
||||||
|
},
|
||||||
|
} as ServerApi["location"]
|
||||||
|
|
||||||
|
const result = await new QueryClient().fetchQuery(loadPathQuery(ServerScope.local, "/repo/subpath", api))
|
||||||
|
|
||||||
|
expect(calls).toEqual([{ location: { directory: "/repo/subpath" } }])
|
||||||
|
expect(result).toMatchObject({ directory: "/repo/subpath", worktree: "/repo" })
|
||||||
|
})
|
||||||
|
|
||||||
test("loads agents from the current location-scoped endpoint", async () => {
|
test("loads agents from the current location-scoped endpoint", async () => {
|
||||||
const calls: unknown[] = []
|
const calls: unknown[] = []
|
||||||
const api = {
|
const api = {
|
||||||
|
|||||||
@@ -1,14 +1,9 @@
|
|||||||
import type {
|
import type {
|
||||||
Config,
|
Config,
|
||||||
Path,
|
Path,
|
||||||
PermissionRequest,
|
|
||||||
Project,
|
Project,
|
||||||
ProviderAuthResponse,
|
ProviderAuthResponse,
|
||||||
QuestionRequest,
|
|
||||||
ReferenceInfo,
|
|
||||||
Session,
|
|
||||||
} from "@/types"
|
} from "@/types"
|
||||||
import type { LegacyCapabilities } from "@/utils/server-compat"
|
|
||||||
import type {
|
import type {
|
||||||
AgentListInput,
|
AgentListInput,
|
||||||
AgentListOutput,
|
AgentListOutput,
|
||||||
@@ -18,12 +13,16 @@ import type {
|
|||||||
CommandListOutput,
|
CommandListOutput,
|
||||||
LocationGetInput,
|
LocationGetInput,
|
||||||
LocationGetOutput,
|
LocationGetOutput,
|
||||||
|
PermissionRequest,
|
||||||
ProjectCurrentInput,
|
ProjectCurrentInput,
|
||||||
ProjectCurrentOutput,
|
ProjectCurrentOutput,
|
||||||
ProjectListOutput,
|
ProjectListOutput,
|
||||||
ReferenceListInput,
|
ReferenceListInput,
|
||||||
ReferenceListOutput,
|
ReferenceListOutput,
|
||||||
|
ReferenceInfo,
|
||||||
|
QuestionRequest,
|
||||||
SessionApi,
|
SessionApi,
|
||||||
|
SessionInfo,
|
||||||
} from "@opencode-ai/client/promise"
|
} from "@opencode-ai/client/promise"
|
||||||
import { showToast } from "@/utils/toast"
|
import { showToast } from "@/utils/toast"
|
||||||
import { getFilename } from "@opencode-ai/core/util/path"
|
import { getFilename } from "@opencode-ai/core/util/path"
|
||||||
@@ -35,7 +34,6 @@ import type { ServerSession } from "../server-session"
|
|||||||
import {
|
import {
|
||||||
cmp,
|
cmp,
|
||||||
normalizeAgentList,
|
normalizeAgentList,
|
||||||
normalizePermissionRequest,
|
|
||||||
normalizeProjectInfo,
|
normalizeProjectInfo,
|
||||||
normalizeProviderList,
|
normalizeProviderList,
|
||||||
} from "./utils"
|
} from "./utils"
|
||||||
@@ -44,8 +42,6 @@ import { QueryClient, queryOptions } from "@tanstack/solid-query"
|
|||||||
import { loadMcpQuery, loadMcpResourcesQuery } from "../server-sync"
|
import { loadMcpQuery, loadMcpResourcesQuery } from "../server-sync"
|
||||||
import { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
import { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
||||||
import { ScopedKey, type ServerScope } from "@/utils/server-scope"
|
import { ScopedKey, type ServerScope } from "@/utils/server-scope"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
import type { ServerProtocol } from "@/utils/server-protocol"
|
|
||||||
import type { ServerApi } from "@/utils/server"
|
import type { ServerApi } from "@/utils/server"
|
||||||
|
|
||||||
type GlobalStore = {
|
type GlobalStore = {
|
||||||
@@ -107,11 +103,11 @@ function showErrors(input: {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export const loadGlobalConfigQuery = (scope: ServerScope, legacy: LegacyCapabilities, enabled = true) =>
|
export const loadGlobalConfigQuery = (scope: ServerScope) =>
|
||||||
queryOptions({
|
queryOptions({
|
||||||
queryKey: [scope, "config"],
|
queryKey: [scope, "config"],
|
||||||
queryFn: () => retry(() => legacy.config.global()),
|
// TODO: Restore config loading when the V2 client exposes a config API.
|
||||||
enabled,
|
queryFn: async (): Promise<Config> => ({}),
|
||||||
})
|
})
|
||||||
|
|
||||||
type ProjectApi = {
|
type ProjectApi = {
|
||||||
@@ -142,9 +138,7 @@ export const loadProjectsQuery = (scope: ServerScope, api: ProjectApi) =>
|
|||||||
})
|
})
|
||||||
|
|
||||||
export async function bootstrapGlobal(input: {
|
export async function bootstrapGlobal(input: {
|
||||||
legacy: LegacyCapabilities
|
|
||||||
serverAPI: CatalogApi & { readonly location: LocationApi; readonly project: ProjectApi }
|
serverAPI: CatalogApi & { readonly location: LocationApi; readonly project: ProjectApi }
|
||||||
protocol?: Promise<ServerProtocol>
|
|
||||||
scope: ServerScope
|
scope: ServerScope
|
||||||
requestFailedTitle: string
|
requestFailedTitle: string
|
||||||
translate: (key: string, vars?: Record<string, string | number>) => string
|
translate: (key: string, vars?: Record<string, string | number>) => string
|
||||||
@@ -152,22 +146,18 @@ export async function bootstrapGlobal(input: {
|
|||||||
setGlobalStore: SetStoreFunction<GlobalStore>
|
setGlobalStore: SetStoreFunction<GlobalStore>
|
||||||
queryClient: QueryClient
|
queryClient: QueryClient
|
||||||
}) {
|
}) {
|
||||||
const protocol = await input.protocol
|
|
||||||
const slow = [
|
const slow = [
|
||||||
protocol === "v1" && (() => input.queryClient.fetchQuery(loadGlobalConfigQuery(input.scope, input.legacy))),
|
() => input.queryClient.fetchQuery(loadGlobalConfigQuery(input.scope)),
|
||||||
() =>
|
() =>
|
||||||
input.queryClient.fetchQuery(
|
input.queryClient.fetchQuery(
|
||||||
loadProvidersQuery(input.scope, null, input.serverAPI),
|
loadProvidersQuery(input.scope, null, input.serverAPI),
|
||||||
),
|
),
|
||||||
() =>
|
() => input.queryClient.fetchQuery(loadPathQuery(input.scope, null, input.serverAPI.location)),
|
||||||
input.queryClient.fetchQuery(
|
|
||||||
loadPathQuery(input.scope, null, input.serverAPI.location),
|
|
||||||
),
|
|
||||||
() =>
|
() =>
|
||||||
input.queryClient
|
input.queryClient
|
||||||
.fetchQuery(loadProjectsQuery(input.scope, input.serverAPI.project))
|
.fetchQuery(loadProjectsQuery(input.scope, input.serverAPI.project))
|
||||||
.then((data) => input.setGlobalStore("project", data)),
|
.then((data) => input.setGlobalStore("project", data)),
|
||||||
].filter(Boolean) as Array<() => Promise<unknown>>
|
]
|
||||||
await runAll(slow)
|
await runAll(slow)
|
||||||
// showErrors({
|
// showErrors({
|
||||||
// errors: errors(),
|
// errors: errors(),
|
||||||
@@ -191,7 +181,7 @@ function projectID(directory: string, projects: Project[]) {
|
|||||||
return projects.find((project) => project.worktree === directory || project.sandboxes?.includes(directory))?.id
|
return projects.find((project) => project.worktree === directory || project.sandboxes?.includes(directory))?.id
|
||||||
}
|
}
|
||||||
|
|
||||||
function mergeSession(setStore: SetStoreFunction<State>, session: Session) {
|
function mergeSession(setStore: SetStoreFunction<State>, session: SessionInfo) {
|
||||||
setStore("session", (list) => {
|
setStore("session", (list) => {
|
||||||
const next = list.slice()
|
const next = list.slice()
|
||||||
const idx = next.findIndex((item) => item.id >= session.id)
|
const idx = next.findIndex((item) => item.id >= session.id)
|
||||||
@@ -216,9 +206,7 @@ function warmSessions(input: {
|
|||||||
if (ids.length === 0) return Promise.resolve()
|
if (ids.length === 0) return Promise.resolve()
|
||||||
return Promise.all(
|
return Promise.all(
|
||||||
ids.map((sessionID) =>
|
ids.map((sessionID) =>
|
||||||
retry(() => input.api.get({ sessionID })).then((session) =>
|
retry(() => input.api.get({ sessionID })).then((session) => mergeSession(input.setStore, session)),
|
||||||
mergeSession(input.setStore, normalizeSessionInfo(session)),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
).then(() => undefined)
|
).then(() => undefined)
|
||||||
}
|
}
|
||||||
@@ -279,7 +267,7 @@ export const loadPathQuery = (
|
|||||||
queryOptions<Path>({
|
queryOptions<Path>({
|
||||||
queryKey: [scope, directory, "path"],
|
queryKey: [scope, directory, "path"],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
retry(() => api.get(directory ? { location: { directory } } : undefined)).then((location) => ({
|
api.get(directory ? { location: { directory } } : undefined).then((location) => ({
|
||||||
state: "",
|
state: "",
|
||||||
config: "",
|
config: "",
|
||||||
worktree: location.project.directory,
|
worktree: location.project.directory,
|
||||||
@@ -304,7 +292,6 @@ export async function bootstrapDirectory(input: {
|
|||||||
directory: string
|
directory: string
|
||||||
scope: ServerScope
|
scope: ServerScope
|
||||||
mcp: boolean
|
mcp: boolean
|
||||||
legacy: LegacyCapabilities
|
|
||||||
api: CatalogApi & {
|
api: CatalogApi & {
|
||||||
readonly agent: AgentListApi
|
readonly agent: AgentListApi
|
||||||
readonly command: CommandListApi
|
readonly command: CommandListApi
|
||||||
@@ -330,7 +317,6 @@ export async function bootstrapDirectory(input: {
|
|||||||
}
|
}
|
||||||
queryClient: QueryClient
|
queryClient: QueryClient
|
||||||
session?: ServerSession
|
session?: ServerSession
|
||||||
protocol?: Promise<ServerProtocol>
|
|
||||||
}) {
|
}) {
|
||||||
const loading = input.store.status !== "complete"
|
const loading = input.store.status !== "complete"
|
||||||
const seededProject = projectID(input.directory, input.global.project)
|
const seededProject = projectID(input.directory, input.global.project)
|
||||||
@@ -352,13 +338,6 @@ export async function bootstrapDirectory(input: {
|
|||||||
input.queryClient
|
input.queryClient
|
||||||
.ensureQueryData(loadAgentsQuery(input.scope, input.directory, input.api.agent))
|
.ensureQueryData(loadAgentsQuery(input.scope, input.directory, input.api.agent))
|
||||||
.then((data) => input.setStore("agent", data)),
|
.then((data) => input.setStore("agent", data)),
|
||||||
(await input.protocol) === "v1" &&
|
|
||||||
(() =>
|
|
||||||
retry(() =>
|
|
||||||
input.legacy.config
|
|
||||||
.directory(input.directory)
|
|
||||||
.then((config) => input.setStore("config", reconcile(config, { merge: false }))),
|
|
||||||
)),
|
|
||||||
!seededProject &&
|
!seededProject &&
|
||||||
(() =>
|
(() =>
|
||||||
retry(() => input.api.project.current({ location: { directory: input.directory } })).then((project) =>
|
retry(() => input.api.project.current({ location: { directory: input.directory } })).then((project) =>
|
||||||
@@ -367,9 +346,7 @@ export async function bootstrapDirectory(input: {
|
|||||||
!seededPath &&
|
!seededPath &&
|
||||||
(() =>
|
(() =>
|
||||||
input.queryClient
|
input.queryClient
|
||||||
.ensureQueryData(
|
.ensureQueryData(loadPathQuery(input.scope, input.directory, input.api.location))
|
||||||
loadPathQuery(input.scope, input.directory, input.api.location),
|
|
||||||
)
|
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
const next = projectID(data.directory ?? input.directory, input.global.project)
|
const next = projectID(data.directory ?? input.directory, input.global.project)
|
||||||
if (next) input.setStore("project", next)
|
if (next) input.setStore("project", next)
|
||||||
@@ -387,7 +364,7 @@ export async function bootstrapDirectory(input: {
|
|||||||
retry(() =>
|
retry(() =>
|
||||||
input.api.permission.request
|
input.api.permission.request
|
||||||
.list({ location: { directory: input.directory } })
|
.list({ location: { directory: input.directory } })
|
||||||
.then((result) => result.data.map(normalizePermissionRequest))
|
.then((result) => result.data)
|
||||||
.then((permissions) => {
|
.then((permissions) => {
|
||||||
const ids = permissions.map((permission) => permission.sessionID)
|
const ids = permissions.map((permission) => permission.sessionID)
|
||||||
const grouped = groupBySession(
|
const grouped = groupBySession(
|
||||||
@@ -401,7 +378,7 @@ export async function bootstrapDirectory(input: {
|
|||||||
const current = input.session?.data.permission ?? input.store.permission
|
const current = input.session?.data.permission ?? input.store.permission
|
||||||
for (const sessionID of Object.keys(current)) {
|
for (const sessionID of Object.keys(current)) {
|
||||||
if (grouped[sessionID]) continue
|
if (grouped[sessionID]) continue
|
||||||
if (input.session?.get(sessionID)?.directory !== input.directory) continue
|
if (input.session?.get(sessionID)?.location.directory !== input.directory) continue
|
||||||
if (input.session) input.session.set("permission", sessionID, [])
|
if (input.session) input.session.set("permission", sessionID, [])
|
||||||
if (!input.session) input.setStore("permission", sessionID, [])
|
if (!input.session) input.setStore("permission", sessionID, [])
|
||||||
}
|
}
|
||||||
@@ -435,7 +412,7 @@ export async function bootstrapDirectory(input: {
|
|||||||
const current = input.session?.data.question ?? input.store.question
|
const current = input.session?.data.question ?? input.store.question
|
||||||
for (const sessionID of Object.keys(current)) {
|
for (const sessionID of Object.keys(current)) {
|
||||||
if (grouped[sessionID]) continue
|
if (grouped[sessionID]) continue
|
||||||
if (input.session?.get(sessionID)?.directory !== input.directory) continue
|
if (input.session?.get(sessionID)?.location.directory !== input.directory) continue
|
||||||
if (input.session) input.session.set("question", sessionID, [])
|
if (input.session) input.session.set("question", sessionID, [])
|
||||||
if (!input.session) input.setStore("question", sessionID, [])
|
if (!input.session) input.setStore("question", sessionID, [])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -191,10 +191,7 @@ export function createChildStoreManager(input: {
|
|||||||
const pathQuery = useQuery(() => ({ ...input.queryOptions.path(key), enabled: instanceQueriesEnabled() }))
|
const pathQuery = useQuery(() => ({ ...input.queryOptions.path(key), enabled: instanceQueriesEnabled() }))
|
||||||
const mcpQuery = useQuery(() => ({ ...input.queryOptions.mcp(key), enabled: mcpEnabled() }))
|
const mcpQuery = useQuery(() => ({ ...input.queryOptions.mcp(key), enabled: mcpEnabled() }))
|
||||||
const mcpResourceQuery = useQuery(() => ({ ...input.queryOptions.mcpResources(key), enabled: mcpEnabled() }))
|
const mcpResourceQuery = useQuery(() => ({ ...input.queryOptions.mcpResources(key), enabled: mcpEnabled() }))
|
||||||
const lspQuery = useQuery(() => {
|
const lspQuery = useQuery(() => ({ ...input.queryOptions.lsp(key), enabled: instanceQueriesEnabled() }))
|
||||||
const options = input.queryOptions.lsp(key)
|
|
||||||
return { ...options, enabled: options.enabled !== false && instanceQueriesEnabled() }
|
|
||||||
})
|
|
||||||
const providerQuery = useQuery(() => ({
|
const providerQuery = useQuery(() => ({
|
||||||
...input.queryOptions.providers(key),
|
...input.queryOptions.providers(key),
|
||||||
enabled: instanceQueriesEnabled(),
|
enabled: instanceQueriesEnabled(),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { Message, Part, PermissionRequest, Project, QuestionRequest, Session } from "@/types"
|
import type { Message, Part, Project } from "@/types"
|
||||||
|
import type { PermissionRequest, QuestionRequest, SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { createStore } from "solid-js/store"
|
import { createStore } from "solid-js/store"
|
||||||
import type { State } from "./types"
|
import type { State } from "./types"
|
||||||
import { applyDirectoryEvent, applyGlobalEvent, cleanupDroppedSessionCaches } from "./event-reducer"
|
import { applyDirectoryEvent, applyGlobalEvent, cleanupDroppedSessionCaches } from "./event-reducer"
|
||||||
@@ -13,7 +14,7 @@ const rootSession = (input: { id: string; parentID?: string; archived?: number }
|
|||||||
updated: 1,
|
updated: 1,
|
||||||
archived: input.archived,
|
archived: input.archived,
|
||||||
},
|
},
|
||||||
}) as Session
|
}) as SessionInfo
|
||||||
|
|
||||||
const userMessage = (id: string, sessionID: string) =>
|
const userMessage = (id: string, sessionID: string) =>
|
||||||
({
|
({
|
||||||
@@ -38,10 +39,10 @@ const permissionRequest = (id: string, sessionID: string, title = id) =>
|
|||||||
({
|
({
|
||||||
id,
|
id,
|
||||||
sessionID,
|
sessionID,
|
||||||
permission: title,
|
action: title,
|
||||||
patterns: ["*"],
|
resources: ["*"],
|
||||||
metadata: {},
|
metadata: {},
|
||||||
always: [],
|
save: [],
|
||||||
}) as PermissionRequest
|
}) as PermissionRequest
|
||||||
|
|
||||||
const questionRequest = (id: string, sessionID: string, title = id) =>
|
const questionRequest = (id: string, sessionID: string, title = id) =>
|
||||||
@@ -512,7 +513,7 @@ describe("applyDirectoryEvent", () => {
|
|||||||
directory: "/tmp",
|
directory: "/tmp",
|
||||||
loadLsp() {},
|
loadLsp() {},
|
||||||
})
|
})
|
||||||
expect(store.permission[sessionID]?.find((x) => x.id === "perm_2")?.permission).toBe("updated")
|
expect(store.permission[sessionID]?.find((x) => x.id === "perm_2")?.action).toBe("updated")
|
||||||
|
|
||||||
applyDirectoryEvent({
|
applyDirectoryEvent({
|
||||||
event: { type: "permission.replied", properties: { sessionID, requestID: "perm_2" } },
|
event: { type: "permission.replied", properties: { sessionID, requestID: "perm_2" } },
|
||||||
|
|||||||
@@ -3,14 +3,10 @@ import { produce, reconcile, type SetStoreFunction, type Store } from "solid-js/
|
|||||||
import type {
|
import type {
|
||||||
Message,
|
Message,
|
||||||
Part,
|
Part,
|
||||||
PermissionRequest,
|
|
||||||
Project,
|
Project,
|
||||||
QuestionRequest,
|
|
||||||
Session,
|
|
||||||
SessionStatus,
|
|
||||||
Todo,
|
Todo,
|
||||||
} from "@/types"
|
} from "@/types"
|
||||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
import type { FileDiffInfo, PermissionRequest, QuestionRequest, SessionInfo, SessionStatus } from "@opencode-ai/client/promise"
|
||||||
import type { State, VcsCache } from "./types"
|
import type { State, VcsCache } from "./types"
|
||||||
import { trimSessions } from "./session-trim"
|
import { trimSessions } from "./session-trim"
|
||||||
import { dropSessionCaches } from "./session-cache"
|
import { dropSessionCaches } from "./session-cache"
|
||||||
@@ -79,7 +75,7 @@ function cleanupSessionCaches(
|
|||||||
export function cleanupDroppedSessionCaches(
|
export function cleanupDroppedSessionCaches(
|
||||||
store: Store<State>,
|
store: Store<State>,
|
||||||
setStore: SetStoreFunction<State>,
|
setStore: SetStoreFunction<State>,
|
||||||
next: Session[],
|
next: SessionInfo[],
|
||||||
setSessionTodo?: (sessionID: string, todos: Todo[] | undefined) => void,
|
setSessionTodo?: (sessionID: string, todos: Todo[] | undefined) => void,
|
||||||
) {
|
) {
|
||||||
const keep = new Set(next.map((item) => item.id))
|
const keep = new Set(next.map((item) => item.id))
|
||||||
@@ -128,7 +124,7 @@ export function applyDirectoryEvent(input: {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
case "session.created": {
|
case "session.created": {
|
||||||
const info = (event.properties as { info: Session }).info
|
const info = (event.properties as { info: SessionInfo }).info
|
||||||
const result = Binary.search(input.store.session, info.id, (s) => s.id)
|
const result = Binary.search(input.store.session, info.id, (s) => s.id)
|
||||||
if (result.found) {
|
if (result.found) {
|
||||||
input.setStore("session", result.index, reconcile(info))
|
input.setStore("session", result.index, reconcile(info))
|
||||||
@@ -143,7 +139,7 @@ export function applyDirectoryEvent(input: {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
case "session.updated": {
|
case "session.updated": {
|
||||||
const info = (event.properties as { info: Session }).info
|
const info = (event.properties as { info: SessionInfo }).info
|
||||||
const result = Binary.search(input.store.session, info.id, (s) => s.id)
|
const result = Binary.search(input.store.session, info.id, (s) => s.id)
|
||||||
if (info.time.archived) {
|
if (info.time.archived) {
|
||||||
if (!result.found) break
|
if (!result.found) break
|
||||||
@@ -171,7 +167,7 @@ export function applyDirectoryEvent(input: {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
case "session.deleted": {
|
case "session.deleted": {
|
||||||
const properties = event.properties as { sessionID?: string; info?: Session }
|
const properties = event.properties as { sessionID?: string; info?: SessionInfo }
|
||||||
const sessionID = properties.info?.id ?? properties.sessionID
|
const sessionID = properties.info?.id ?? properties.sessionID
|
||||||
if (!sessionID) break
|
if (!sessionID) break
|
||||||
const result = Binary.search(input.store.session, sessionID, (s) => s.id)
|
const result = Binary.search(input.store.session, sessionID, (s) => s.id)
|
||||||
@@ -201,7 +197,7 @@ export function applyDirectoryEvent(input: {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
case "session.usage.updated": {
|
case "session.usage.updated": {
|
||||||
const properties = event.properties as Pick<Session, "cost" | "tokens"> & { sessionID: string }
|
const properties = event.properties as Pick<SessionInfo, "cost" | "tokens"> & { sessionID: string }
|
||||||
const result = Binary.search(input.store.session, properties.sessionID, (session) => session.id)
|
const result = Binary.search(input.store.session, properties.sessionID, (session) => session.id)
|
||||||
if (!result.found) break
|
if (!result.found) break
|
||||||
input.setStore("session", result.index, (session) => ({
|
input.setStore("session", result.index, (session) => ({
|
||||||
@@ -237,9 +233,8 @@ export function applyDirectoryEvent(input: {
|
|||||||
input.setStore("session", result.index, (session) => ({
|
input.setStore("session", result.index, (session) => ({
|
||||||
...session,
|
...session,
|
||||||
projectID: properties.projectID ?? session.projectID,
|
projectID: properties.projectID ?? session.projectID,
|
||||||
workspaceID: properties.location.workspaceID,
|
location: properties.location,
|
||||||
directory: properties.location.directory,
|
subpath: properties.subpath,
|
||||||
path: properties.subpath,
|
|
||||||
time: { ...session.time, updated: Date.now() },
|
time: { ...session.time, updated: Date.now() },
|
||||||
}))
|
}))
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { SessionV2Info } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import {
|
import {
|
||||||
applyHomeSessionEvent,
|
applyHomeSessionEvent,
|
||||||
appendHomeSessionEvent,
|
appendHomeSessionEvent,
|
||||||
@@ -33,7 +33,7 @@ describe("Home V2 session index", () => {
|
|||||||
const calls: unknown[] = []
|
const calls: unknown[] = []
|
||||||
const result = await loadHomeSessionIndex(async (input) => {
|
const result = await loadHomeSessionIndex(async (input) => {
|
||||||
calls.push(input)
|
calls.push(input)
|
||||||
return { data: { data: [session({ id: "root" })], cursor: {} } }
|
return { data: [session({ id: "root" })], cursor: {} }
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(result.sessions).toHaveLength(1)
|
expect(result.sessions).toHaveLength(1)
|
||||||
@@ -48,15 +48,11 @@ describe("Home V2 session index", () => {
|
|||||||
calls.push({ input, signal: options.signal })
|
calls.push({ input, signal: options.signal })
|
||||||
if (!("cursor" in input)) {
|
if (!("cursor" in input)) {
|
||||||
return {
|
return {
|
||||||
data: {
|
data: Array.from({ length: HOME_V2_SESSION_PAGE_LIMIT }, (_, index) => session({ id: `page-1-${index}` })),
|
||||||
data: Array.from({ length: HOME_V2_SESSION_PAGE_LIMIT }, (_, index) =>
|
cursor: { next: "next-page" },
|
||||||
session({ id: `page-1-${index}` }),
|
|
||||||
),
|
|
||||||
cursor: { next: "next-page" },
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { data: { data: [session({ id: "page-2" })], cursor: {} } }
|
return { data: [session({ id: "page-2" })], cursor: {} }
|
||||||
},
|
},
|
||||||
0,
|
0,
|
||||||
controller.signal,
|
controller.signal,
|
||||||
@@ -76,7 +72,7 @@ describe("Home V2 session index", () => {
|
|||||||
const activeNull = {
|
const activeNull = {
|
||||||
...session({ id: "active-null", updated: 20 }),
|
...session({ id: "active-null", updated: 20 }),
|
||||||
time: { created: 1, updated: 20, archived: null },
|
time: { created: 1, updated: 20, archived: null },
|
||||||
} as unknown as SessionV2Info
|
} as unknown as SessionInfo
|
||||||
const result = parseHomeSessionIndex([
|
const result = parseHomeSessionIndex([
|
||||||
session({ id: "root", updated: 30 }),
|
session({ id: "root", updated: 30 }),
|
||||||
activeNull,
|
activeNull,
|
||||||
@@ -85,11 +81,9 @@ describe("Home V2 session index", () => {
|
|||||||
])
|
])
|
||||||
|
|
||||||
expect(result).toEqual([
|
expect(result).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
id: "root",
|
id: "root",
|
||||||
slug: "root",
|
location: { directory: "/project" },
|
||||||
version: "",
|
|
||||||
directory: "/project",
|
|
||||||
projectID: "project",
|
projectID: "project",
|
||||||
title: "root",
|
title: "root",
|
||||||
time: { created: 1, updated: 30 },
|
time: { created: 1, updated: 30 },
|
||||||
@@ -105,17 +99,17 @@ describe("Home V2 session index", () => {
|
|||||||
const now = 10 * 60 * 60 * 1000
|
const now = 10 * 60 * 60 * 1000
|
||||||
const sessions = Array.from({ length: 80 }, (_, index) => ({
|
const sessions = Array.from({ length: 80 }, (_, index) => ({
|
||||||
...parseHomeSessionIndex([session({ id: `session-${index}`, updated: index + 1 })])[0],
|
...parseHomeSessionIndex([session({ id: `session-${index}`, updated: index + 1 })])[0],
|
||||||
directory: index % 2 === 0 ? "/one" : "/two",
|
location: { directory: index % 2 === 0 ? "/one" : "/two" },
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const retained = retainHomeSessions(sessions, 10, now)
|
const retained = retainHomeSessions(sessions, 10, now)
|
||||||
expect(retained.filter((item) => item.directory === "/one")).toHaveLength(10)
|
expect(retained.filter((item) => item.location.directory === "/one")).toHaveLength(10)
|
||||||
expect(retained.filter((item) => item.directory === "/two")).toHaveLength(10)
|
expect(retained.filter((item) => item.location.directory === "/two")).toHaveLength(10)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("replays session events over the loaded index", () => {
|
test("replays session events over the loaded index", () => {
|
||||||
const initial = parseHomeSessionIndex([session({ id: "old" })])
|
const initial = parseHomeSessionIndex([session({ id: "old" })])
|
||||||
const created = { ...initial[0], id: "new", slug: "new", title: "new", time: { created: 2, updated: 2 } }
|
const created = { ...initial[0], id: "new", title: "new", time: { created: 2, updated: 2 } }
|
||||||
|
|
||||||
const afterCreate = applyHomeSessionEvent(initial, {
|
const afterCreate = applyHomeSessionEvent(initial, {
|
||||||
type: "session.created",
|
type: "session.created",
|
||||||
@@ -145,10 +139,8 @@ describe("Home V2 session index", () => {
|
|||||||
expect(homeSessionIndexSessions({ sessions: initial, eventSequence: 1 }, events)[0]?.title).toBe("current")
|
expect(homeSessionIndexSessions({ sessions: initial, eventSequence: 1 }, events)[0]?.title).toBe("current")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("refetches after reconnect, disposal, and session moves", () => {
|
test("refetches after reconnect", () => {
|
||||||
expect(homeSessionIndexRefresh("server.connected", false)).toEqual({ connected: true, refetch: false })
|
expect(homeSessionIndexRefresh("server.connected", false)).toEqual({ connected: true, refetch: false })
|
||||||
expect(homeSessionIndexRefresh("server.connected", true)).toEqual({ connected: true, refetch: true })
|
expect(homeSessionIndexRefresh("server.connected", true)).toEqual({ connected: true, refetch: true })
|
||||||
expect(homeSessionIndexRefresh("global.disposed", true).refetch).toBe(true)
|
|
||||||
expect(homeSessionIndexRefresh("session.next.moved", true).refetch).toBe(true)
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Event, Session, SessionV2Info, V2SessionListResponse } from "@/types"
|
import type { Event } from "@/types"
|
||||||
|
import type { SessionInfo, SessionsResponse } from "@opencode-ai/client/promise"
|
||||||
import type { QueryClient } from "@tanstack/solid-query"
|
import type { QueryClient } from "@tanstack/solid-query"
|
||||||
import { trimSessions } from "./session-trim"
|
import { trimSessions } from "./session-trim"
|
||||||
import { pathKey } from "@/utils/path-key"
|
import { pathKey } from "@/utils/path-key"
|
||||||
@@ -7,31 +8,29 @@ export const HOME_V2_SESSION_PAGE_LIMIT = 5_000
|
|||||||
|
|
||||||
export type HomeSessionEvent = {
|
export type HomeSessionEvent = {
|
||||||
type: "session.created" | "session.updated" | "session.deleted"
|
type: "session.created" | "session.updated" | "session.deleted"
|
||||||
properties: { sessionID: string; info: Session }
|
properties: { sessionID: string; info?: SessionInfo }
|
||||||
}
|
}
|
||||||
export type HomeSessionEvents = {
|
export type HomeSessionEvents = {
|
||||||
sequence: number
|
sequence: number
|
||||||
entries: Array<{ sequence: number; event: HomeSessionEvent }>
|
entries: Array<{ sequence: number; event: HomeSessionEvent }>
|
||||||
}
|
}
|
||||||
export type HomeSessionIndex = {
|
export type HomeSessionIndex = {
|
||||||
sessions: Session[]
|
sessions: SessionInfo[]
|
||||||
eventSequence: number
|
eventSequence: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const homeSessionIndexKey = (server: string) => ["home", "session-index", server] as const
|
export const homeSessionIndexKey = (server: string) => ["home", "session-index", server] as const
|
||||||
export const homeSessionEventsKey = (server: string) => ["home", "session-events", server] as const
|
export const homeSessionEventsKey = (server: string) => ["home", "session-events", server] as const
|
||||||
|
|
||||||
type HomeSessionPage = { data?: V2SessionListResponse }
|
|
||||||
|
|
||||||
export async function loadHomeSessionIndex(
|
export async function loadHomeSessionIndex(
|
||||||
list: (
|
list: (
|
||||||
input: { limit: number; order: "desc"; cursor?: string },
|
input: { limit: number; order: "desc"; cursor?: string },
|
||||||
options: { signal?: AbortSignal },
|
options: { signal?: AbortSignal },
|
||||||
) => Promise<HomeSessionPage>,
|
) => Promise<SessionsResponse>,
|
||||||
eventSequence = 0,
|
eventSequence = 0,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
) {
|
) {
|
||||||
const data: SessionV2Info[] = []
|
const data: SessionInfo[] = []
|
||||||
let cursor: string | undefined
|
let cursor: string | undefined
|
||||||
|
|
||||||
for (;;) {
|
for (;;) {
|
||||||
@@ -43,7 +42,7 @@ export async function loadHomeSessionIndex(
|
|||||||
},
|
},
|
||||||
{ signal },
|
{ signal },
|
||||||
)
|
)
|
||||||
const page = response.data!
|
const page = response
|
||||||
data.push(...page.data)
|
data.push(...page.data)
|
||||||
if (page.data.length < HOME_V2_SESSION_PAGE_LIMIT || !page.cursor.next)
|
if (page.data.length < HOME_V2_SESSION_PAGE_LIMIT || !page.cursor.next)
|
||||||
return { sessions: parseHomeSessionIndex(data), eventSequence }
|
return { sessions: parseHomeSessionIndex(data), eventSequence }
|
||||||
@@ -75,10 +74,7 @@ export function homeSessionIndexSessions(index: HomeSessionIndex | undefined, ev
|
|||||||
|
|
||||||
export function homeSessionIndexRefresh(event: Event["type"], connected: boolean) {
|
export function homeSessionIndexRefresh(event: Event["type"], connected: boolean) {
|
||||||
if (event === "server.connected") return { connected: true, refetch: connected }
|
if (event === "server.connected") return { connected: true, refetch: connected }
|
||||||
return {
|
return { connected, refetch: false }
|
||||||
connected,
|
|
||||||
refetch: event === "global.disposed" || event === "session.next.moved",
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createHomeSessionIndexCache(queryClient: QueryClient, server: string) {
|
export function createHomeSessionIndexCache(queryClient: QueryClient, server: string) {
|
||||||
@@ -129,23 +125,28 @@ export function createHomeSessionIndexCache(queryClient: QueryClient, server: st
|
|||||||
// current V2 API orders by creation time and cannot filter roots, archives, or
|
// current V2 API orders by creation time and cannot filter roots, archives, or
|
||||||
// multiple directories. A bounded page could omit an old session updated today.
|
// multiple directories. A bounded page could omit an old session updated today.
|
||||||
// Once released, use client.v2.project.list() and client.v2.session.list({
|
// Once released, use client.v2.project.list() and client.v2.session.list({
|
||||||
// parentID: null, order: "desc" }), then remove this adapter and its V1 fields.
|
// parentID: null, order: "desc" }) and replace this full-table scan.
|
||||||
export function parseHomeSessionIndex(sessions: SessionV2Info[]): Session[] {
|
export function parseHomeSessionIndex(sessions: SessionInfo[]): SessionInfo[] {
|
||||||
return sessions.flatMap((item) => {
|
return sessions.flatMap((item) => {
|
||||||
if (item.parentID || typeof item.time.archived === "number") return []
|
if (item.parentID || typeof item.time.archived === "number") return []
|
||||||
return [toLegacySummary(item)]
|
return [item]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function retainHomeSessions(sessions: Session[], limit: number, now: number) {
|
export function retainHomeSessions(sessions: SessionInfo[], limit: number, now: number) {
|
||||||
const grouped = Map.groupBy(sessions, (session) => pathKey(session.directory))
|
const grouped = Map.groupBy(sessions, (session) => pathKey(session.location.directory))
|
||||||
return [...grouped.values()].flatMap((items) => trimSessions(items, { limit, permission: {}, now }))
|
return [...grouped.values()].flatMap((items) => trimSessions(items, { limit, permission: {}, now }))
|
||||||
}
|
}
|
||||||
|
|
||||||
export function applyHomeSessionEvent(sessions: Session[], event: HomeSessionEvent) {
|
export function applyHomeSessionEvent(sessions: SessionInfo[], event: HomeSessionEvent) {
|
||||||
const info = event.properties.info
|
const info = event.properties.info
|
||||||
const index = sessions.findIndex((session) => session.id === info.id)
|
const index = sessions.findIndex((session) => session.id === (info?.id ?? event.properties.sessionID))
|
||||||
if (event.type === "session.deleted" || info.parentID || typeof info.time.archived === "number") {
|
if (event.type === "session.deleted") {
|
||||||
|
if (index === -1) return sessions
|
||||||
|
return sessions.toSpliced(index, 1)
|
||||||
|
}
|
||||||
|
if (!info) return sessions
|
||||||
|
if (info.parentID || typeof info.time.archived === "number") {
|
||||||
if (index === -1) return sessions
|
if (index === -1) return sessions
|
||||||
return sessions.toSpliced(index, 1)
|
return sessions.toSpliced(index, 1)
|
||||||
}
|
}
|
||||||
@@ -153,22 +154,3 @@ export function applyHomeSessionEvent(sessions: Session[], event: HomeSessionEve
|
|||||||
if (index === -1) return [...sessions, info]
|
if (index === -1) return [...sessions, info]
|
||||||
return sessions.with(index, info)
|
return sessions.with(index, info)
|
||||||
}
|
}
|
||||||
|
|
||||||
function toLegacySummary(session: SessionV2Info): Session {
|
|
||||||
return {
|
|
||||||
id: session.id,
|
|
||||||
slug: session.id,
|
|
||||||
projectID: session.projectID,
|
|
||||||
workspaceID: session.location.workspaceID,
|
|
||||||
directory: session.location.directory,
|
|
||||||
path: session.subpath,
|
|
||||||
parentID: session.parentID,
|
|
||||||
cost: session.cost,
|
|
||||||
tokens: session.tokens,
|
|
||||||
title: session.title,
|
|
||||||
agent: session.agent,
|
|
||||||
model: session.model,
|
|
||||||
version: "",
|
|
||||||
time: session.time,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { Message, Part, PermissionRequest, QuestionRequest, SessionStatus, Todo } from "@/types"
|
import type { Message, Part, Todo } from "@/types"
|
||||||
|
import type { PermissionRequest, QuestionRequest, SessionStatus } from "@opencode-ai/client/promise"
|
||||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
||||||
import { dropSessionCaches, pickSessionCacheEvictions } from "./session-cache"
|
import { dropSessionCaches, pickSessionCacheEvictions } from "./session-cache"
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Message, Part, PermissionRequest, QuestionRequest, SessionStatus, Todo } from "@/types"
|
import type { Message, Part, Todo } from "@/types"
|
||||||
|
import type { PermissionRequest, QuestionRequest, SessionStatus } from "@opencode-ai/client/promise"
|
||||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
||||||
import type { SessionMessageInfo } from "@opencode-ai/client/promise"
|
import type { SessionMessageInfo } from "@opencode-ai/client/promise"
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { SessionApi } from "@opencode-ai/client/promise"
|
import type { SessionApi } from "@opencode-ai/client/promise"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
|
|
||||||
export async function loadRootSessions(input: { api: Pick<SessionApi, "list">; directory: string; limit: number }) {
|
export async function loadRootSessions(input: { api: Pick<SessionApi, "list">; directory: string; limit: number }) {
|
||||||
const result = await input.api.list({
|
const result = await input.api.list({
|
||||||
@@ -9,7 +8,7 @@ export async function loadRootSessions(input: { api: Pick<SessionApi, "list">; d
|
|||||||
order: "desc",
|
order: "desc",
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
data: result.data.map(normalizeSessionInfo),
|
data: result.data,
|
||||||
limit: input.limit,
|
limit: input.limit,
|
||||||
limited: true,
|
limited: true,
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { PermissionRequest, Session } from "@/types"
|
import type { PermissionRequest, SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { trimSessions } from "./session-trim"
|
import { trimSessions } from "./session-trim"
|
||||||
|
|
||||||
const session = (input: { id: string; parentID?: string; created: number; updated?: number; archived?: number }) =>
|
const session = (input: { id: string; parentID?: string; created: number; updated?: number; archived?: number }) =>
|
||||||
@@ -11,7 +11,7 @@ const session = (input: { id: string; parentID?: string; created: number; update
|
|||||||
updated: input.updated,
|
updated: input.updated,
|
||||||
archived: input.archived,
|
archived: input.archived,
|
||||||
},
|
},
|
||||||
}) as Session
|
}) as SessionInfo
|
||||||
|
|
||||||
describe("trimSessions", () => {
|
describe("trimSessions", () => {
|
||||||
test("keeps base roots and recent roots beyond the limit", () => {
|
test("keeps base roots and recent roots beyond the limit", () => {
|
||||||
|
|||||||
@@ -1,21 +1,22 @@
|
|||||||
import type { PermissionRequest, Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
|
import type { PermissionRequest } from "@opencode-ai/client/promise"
|
||||||
import { cmp } from "./utils"
|
import { cmp } from "./utils"
|
||||||
import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "./types"
|
import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "./types"
|
||||||
|
|
||||||
export function sessionUpdatedAt(session: Session) {
|
export function sessionUpdatedAt(session: SessionInfo) {
|
||||||
return session.time.updated ?? session.time.created
|
return session.time.updated ?? session.time.created
|
||||||
}
|
}
|
||||||
|
|
||||||
export function compareSessionRecent(a: Session, b: Session) {
|
export function compareSessionRecent(a: SessionInfo, b: SessionInfo) {
|
||||||
const aUpdated = sessionUpdatedAt(a)
|
const aUpdated = sessionUpdatedAt(a)
|
||||||
const bUpdated = sessionUpdatedAt(b)
|
const bUpdated = sessionUpdatedAt(b)
|
||||||
if (aUpdated !== bUpdated) return bUpdated - aUpdated
|
if (aUpdated !== bUpdated) return bUpdated - aUpdated
|
||||||
return cmp(a.id, b.id)
|
return cmp(a.id, b.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function takeRecentSessions(sessions: Session[], limit: number, cutoff: number) {
|
export function takeRecentSessions(sessions: SessionInfo[], limit: number, cutoff: number) {
|
||||||
if (limit <= 0) return [] as Session[]
|
if (limit <= 0) return [] as SessionInfo[]
|
||||||
const selected: Session[] = []
|
const selected: SessionInfo[] = []
|
||||||
const seen = new Set<string>()
|
const seen = new Set<string>()
|
||||||
for (const session of sessions) {
|
for (const session of sessions) {
|
||||||
if (!session?.id) continue
|
if (!session?.id) continue
|
||||||
@@ -31,7 +32,7 @@ export function takeRecentSessions(sessions: Session[], limit: number, cutoff: n
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function trimSessions(
|
export function trimSessions(
|
||||||
input: Session[],
|
input: SessionInfo[],
|
||||||
options: { limit: number; permission: Record<string, PermissionRequest[]>; now?: number },
|
options: { limit: number; permission: Record<string, PermissionRequest[]>; now?: number },
|
||||||
) {
|
) {
|
||||||
const limit = Math.max(0, options.limit)
|
const limit = Math.max(0, options.limit)
|
||||||
|
|||||||
@@ -5,15 +5,17 @@ import type {
|
|||||||
Message,
|
Message,
|
||||||
Part,
|
Part,
|
||||||
Path,
|
Path,
|
||||||
PermissionRequest,
|
|
||||||
QuestionRequest,
|
|
||||||
ReferenceInfo,
|
|
||||||
Session,
|
|
||||||
SessionStatus,
|
|
||||||
Todo,
|
Todo,
|
||||||
VcsInfo,
|
VcsInfo,
|
||||||
} from "@/types"
|
} from "@/types"
|
||||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
import type {
|
||||||
|
FileDiffInfo,
|
||||||
|
PermissionRequest,
|
||||||
|
QuestionRequest,
|
||||||
|
ReferenceInfo,
|
||||||
|
SessionInfo,
|
||||||
|
SessionStatus,
|
||||||
|
} from "@opencode-ai/client/promise"
|
||||||
import { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
import { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
||||||
import type { CommandInfo, McpResource, McpServer, SessionMessageInfo } from "@opencode-ai/client/promise"
|
import type { CommandInfo, McpResource, McpServer, SessionMessageInfo } from "@opencode-ai/client/promise"
|
||||||
import type { Accessor } from "solid-js"
|
import type { Accessor } from "solid-js"
|
||||||
@@ -42,7 +44,7 @@ export type State = {
|
|||||||
provider: NormalizedProviderListResponse
|
provider: NormalizedProviderListResponse
|
||||||
config: Config
|
config: Config
|
||||||
path: Path
|
path: Path
|
||||||
session: Session[]
|
session: SessionInfo[]
|
||||||
sessionTotal: number
|
sessionTotal: number
|
||||||
session_status: {
|
session_status: {
|
||||||
[sessionID: string]: SessionStatus
|
[sessionID: string]: SessionStatus
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type {
|
|||||||
ModelListOutput,
|
ModelListOutput,
|
||||||
ProviderListOutput,
|
ProviderListOutput,
|
||||||
} from "@opencode-ai/client/promise"
|
} from "@opencode-ai/client/promise"
|
||||||
import { directoryKey, normalizeAgentList, normalizePermissionRequest, normalizeProviderList } from "./utils"
|
import { directoryKey, normalizeAgentList, normalizeProviderList } from "./utils"
|
||||||
|
|
||||||
describe("normalizeAgentList", () => {
|
describe("normalizeAgentList", () => {
|
||||||
test("adapts current agents to the app agent shape", () => {
|
test("adapts current agents to the app agent shape", () => {
|
||||||
@@ -43,30 +43,6 @@ describe("normalizeAgentList", () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("normalizePermissionRequest", () => {
|
|
||||||
test("adapts the current permission request to app state", () => {
|
|
||||||
expect(
|
|
||||||
normalizePermissionRequest({
|
|
||||||
id: "permission-1",
|
|
||||||
sessionID: "session-1",
|
|
||||||
action: "read",
|
|
||||||
resources: ["README.md"],
|
|
||||||
save: ["*.md"],
|
|
||||||
metadata: { path: "README.md" },
|
|
||||||
source: { type: "tool", messageID: "message-1", id: "call-1" },
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
id: "permission-1",
|
|
||||||
sessionID: "session-1",
|
|
||||||
permission: "read",
|
|
||||||
patterns: ["README.md"],
|
|
||||||
always: ["*.md"],
|
|
||||||
metadata: { path: "README.md" },
|
|
||||||
tool: { messageID: "message-1", callID: "call-1" },
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("normalizeProviderList", () => {
|
describe("normalizeProviderList", () => {
|
||||||
test("groups current models into the app provider catalog", () => {
|
test("groups current models into the app provider catalog", () => {
|
||||||
const result = normalizeProviderList(
|
const result = normalizeProviderList(
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ import type {
|
|||||||
AgentListOutput,
|
AgentListOutput,
|
||||||
ModelDefaultOutput,
|
ModelDefaultOutput,
|
||||||
ModelListOutput,
|
ModelListOutput,
|
||||||
PermissionRequest,
|
|
||||||
ProviderListOutput,
|
ProviderListOutput,
|
||||||
} from "@opencode-ai/client/promise"
|
} from "@opencode-ai/client/promise"
|
||||||
import type { Agent, Event, Project, Provider, ProviderListResponse } from "@/types"
|
import type { Agent, Project, Provider, ProviderListResponse } from "@/types"
|
||||||
import type { Project as CurrentProject } from "@opencode-ai/client/promise"
|
import type { Project as CurrentProject } from "@opencode-ai/client/promise"
|
||||||
import { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
import { NormalizedProviderListResponse } from "@opencode-ai/session-ui/context"
|
||||||
export { pathKey as directoryKey, type PathKey as DirectoryKey } from "@/utils/path-key"
|
export { pathKey as directoryKey, type PathKey as DirectoryKey } from "@/utils/path-key"
|
||||||
@@ -36,42 +35,13 @@ export function normalizeAgentList(input: AgentListOutput["data"] | Agent[]): Ag
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
type LegacyPermissionRequest = Extract<Event, { type: "permission.asked" }>["properties"]
|
|
||||||
|
|
||||||
export function normalizePermissionRequest(input: PermissionRequest | LegacyPermissionRequest): LegacyPermissionRequest {
|
|
||||||
if ("permission" in input) return input
|
|
||||||
return {
|
|
||||||
id: input.id,
|
|
||||||
sessionID: input.sessionID,
|
|
||||||
permission: input.action,
|
|
||||||
patterns: input.resources,
|
|
||||||
always: input.save ?? [],
|
|
||||||
metadata: input.metadata ?? {},
|
|
||||||
tool:
|
|
||||||
input.source?.type === "tool" ? { messageID: input.source.messageID, callID: input.source.id } : undefined,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeProviderList(
|
export function normalizeProviderList(
|
||||||
providers: ProviderListOutput["data"] | ProviderListResponse,
|
providers: ProviderListOutput["data"] | ProviderListResponse,
|
||||||
models?: ModelListOutput["data"],
|
models?: ModelListOutput["data"],
|
||||||
defaultModel?: ModelDefaultOutput["data"],
|
defaultModel?: ModelDefaultOutput["data"],
|
||||||
): NormalizedProviderListResponse {
|
): NormalizedProviderListResponse {
|
||||||
if (!Array.isArray(providers)) {
|
if (!Array.isArray(providers)) {
|
||||||
return {
|
return providers
|
||||||
...providers,
|
|
||||||
all: new Map(
|
|
||||||
providers.all.map((provider) => [
|
|
||||||
provider.id,
|
|
||||||
{
|
|
||||||
...provider,
|
|
||||||
models: Object.fromEntries(
|
|
||||||
Object.entries(provider.models).filter(([, model]) => model.status !== "deprecated"),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const all = new Map<string, Provider>()
|
const all = new Map<string, Provider>()
|
||||||
|
|
||||||
@@ -153,18 +123,6 @@ export function normalizeProviderList(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sanitizeProject(project: Project) {
|
|
||||||
if (!project.icon?.url && !project.icon?.override) return project
|
|
||||||
return {
|
|
||||||
...project,
|
|
||||||
icon: {
|
|
||||||
...project.icon,
|
|
||||||
url: undefined,
|
|
||||||
override: undefined,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeProjectInfo(project: Project | CurrentProject): Project {
|
export function normalizeProjectInfo(project: Project | CurrentProject): Project {
|
||||||
return {
|
return {
|
||||||
...project,
|
...project,
|
||||||
|
|||||||
@@ -340,7 +340,7 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
void removePersisted(target, platform)
|
void removePersisted(target, platform)
|
||||||
|
|
||||||
if (scope !== ServerScope.local) continue
|
if (scope !== ServerScope.local) continue
|
||||||
const legacyKey = `${dir}/${entry.legacy}${session ? "/" + session : ""}.${entry.version}`
|
const legacyKey = `${dir}/${entry["legacy"]}${session ? "/" + session : ""}.${entry.version}`
|
||||||
void removePersisted({ key: legacyKey }, platform)
|
void removePersisted({ key: legacyKey }, platform)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -572,17 +572,8 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
|
|
||||||
const projectID = project.id
|
const projectID = project.id
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const sdk = serverSdk()
|
// TODO: Restore project color updates when the V2 client exposes a project update API.
|
||||||
if ((await sdk.protocol) !== "v1") return
|
void projectID
|
||||||
return sdk.legacy.project
|
|
||||||
.update({ projectID, directory: worktree, icon: { color } })
|
|
||||||
.then((response) => response.data)
|
|
||||||
.then((result) => {
|
|
||||||
if (!result) return
|
|
||||||
serverSync().set("project", (items) =>
|
|
||||||
items.map((item) => (item.id === result.id ? normalizeProjectInfo(result) : item)),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})().catch(() => {
|
})().catch(() => {
|
||||||
if (colorRequested.get(worktree) === color) colorRequested.delete(worktree)
|
if (colorRequested.get(worktree) === color) colorRequested.delete(worktree)
|
||||||
})
|
})
|
||||||
@@ -753,9 +744,6 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
},
|
},
|
||||||
mobileSidebar: {
|
mobileSidebar: {
|
||||||
opened: createMemo(() => store.mobileSidebar?.opened ?? false),
|
opened: createMemo(() => store.mobileSidebar?.opened ?? false),
|
||||||
show() {
|
|
||||||
setStore("mobileSidebar", "opened", true)
|
|
||||||
},
|
|
||||||
hide() {
|
hide() {
|
||||||
setStore("mobileSidebar", "opened", false)
|
setStore("mobileSidebar", "opened", false)
|
||||||
},
|
},
|
||||||
@@ -961,33 +949,6 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
if (current.reviewOpen.includes(path)) return
|
if (current.reviewOpen.includes(path)) return
|
||||||
setStore("sessionView", session, "reviewOpen", current.reviewOpen.length, path)
|
setStore("sessionView", session, "reviewOpen", current.reviewOpen.length, path)
|
||||||
},
|
},
|
||||||
closePath(path: string) {
|
|
||||||
const session = key()
|
|
||||||
const current = store.sessionView[session]?.reviewOpen
|
|
||||||
if (!current) return
|
|
||||||
|
|
||||||
const index = current.indexOf(path)
|
|
||||||
if (index === -1) return
|
|
||||||
setStore(
|
|
||||||
"sessionView",
|
|
||||||
session,
|
|
||||||
"reviewOpen",
|
|
||||||
produce((draft) => {
|
|
||||||
if (!draft) return
|
|
||||||
draft.splice(index, 1)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
togglePath(path: string) {
|
|
||||||
const session = key()
|
|
||||||
const current = store.sessionView[session]?.reviewOpen
|
|
||||||
if (!current || !current.includes(path)) {
|
|
||||||
this.openPath(path)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
this.closePath(path)
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -360,7 +360,7 @@ function createServerNotificationState(input: {
|
|||||||
|
|
||||||
const handleSessionError = (
|
const handleSessionError = (
|
||||||
directory: string,
|
directory: string,
|
||||||
event: { properties: { sessionID?: string; error?: EventSessionError["properties"]["error"] } },
|
event: { properties: EventSessionError["properties"] },
|
||||||
time: number,
|
time: number,
|
||||||
) => {
|
) => {
|
||||||
const sessionID = event.properties.sessionID
|
const sessionID = event.properties.sessionID
|
||||||
@@ -372,7 +372,7 @@ function createServerNotificationState(input: {
|
|||||||
void playSoundById(settings.sounds.errors())
|
void playSoundById(settings.sounds.errors())
|
||||||
}
|
}
|
||||||
|
|
||||||
const error = "error" in event.properties ? event.properties.error : undefined
|
const error = event.properties.error
|
||||||
append({
|
append({
|
||||||
directory,
|
directory,
|
||||||
time,
|
time,
|
||||||
@@ -393,7 +393,7 @@ function createServerNotificationState(input: {
|
|||||||
|
|
||||||
const unsub = serverSDK().event.listen((e) => {
|
const unsub = serverSDK().event.listen((e) => {
|
||||||
const event = e.details
|
const event = e.details
|
||||||
if (event.type !== "session.idle" && event.type !== "session.error") return
|
if (event.type !== "session.idle" && event.type !== "session.execution.failed") return
|
||||||
|
|
||||||
const directory = e.name
|
const directory = e.name
|
||||||
const time = Date.now()
|
const time = Date.now()
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { PermissionRequest, Session } from "@/types"
|
import type { PermissionRequest, SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { base64Encode } from "@opencode-ai/core/util/encode"
|
import { base64Encode } from "@opencode-ai/core/util/encode"
|
||||||
import { autoRespondsPermission, isDirectoryAutoAccepting, sessionAutoAccept } from "./permission-auto-respond"
|
import { autoRespondsPermission, isDirectoryAutoAccepting, sessionAutoAccept } from "./permission-auto-respond"
|
||||||
|
|
||||||
@@ -7,7 +7,7 @@ const session = (input: { id: string; parentID?: string }) =>
|
|||||||
({
|
({
|
||||||
id: input.id,
|
id: input.id,
|
||||||
parentID: input.parentID,
|
parentID: input.parentID,
|
||||||
}) as Session
|
}) as SessionInfo
|
||||||
|
|
||||||
const permission = (sessionID: string) =>
|
const permission = (sessionID: string) =>
|
||||||
({
|
({
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createEffect, createMemo, createRoot, getOwner, onCleanup } from "solid-js"
|
import { createEffect, createMemo, createRoot, getOwner, onCleanup } from "solid-js"
|
||||||
import { createStore, produce } from "solid-js/store"
|
import { createStore, produce } from "solid-js/store"
|
||||||
import { createSimpleContext } from "@opencode-ai/ui/context"
|
import { createSimpleContext } from "@opencode-ai/ui/context"
|
||||||
import type { PermissionRequest } from "@/types"
|
import type { PermissionRequest } from "@opencode-ai/client/promise"
|
||||||
import { Persist, persisted } from "@/utils/persist"
|
import { Persist, persisted } from "@/utils/persist"
|
||||||
import type { ServerSDK } from "@/context/server-sdk"
|
import type { ServerSDK } from "@/context/server-sdk"
|
||||||
import type { ServerSync } from "./server-sync"
|
import type { ServerSync } from "./server-sync"
|
||||||
@@ -13,7 +13,6 @@ import { type DraftTab, useTabs } from "./tabs"
|
|||||||
import { useSettings } from "./settings"
|
import { useSettings } from "./settings"
|
||||||
import { requireServerKey } from "@/utils/session-route"
|
import { requireServerKey } from "@/utils/session-route"
|
||||||
import type { ServerScope } from "@/utils/server-scope"
|
import type { ServerScope } from "@/utils/server-scope"
|
||||||
import { normalizePermissionRequest } from "./global-sync/utils"
|
|
||||||
import {
|
import {
|
||||||
acceptKey,
|
acceptKey,
|
||||||
directoryAcceptKey,
|
directoryAcceptKey,
|
||||||
@@ -133,7 +132,7 @@ export const { use: usePermission, provider: PermissionProvider } = createSimple
|
|||||||
if (draft) return draft.directory
|
if (draft) return draft.directory
|
||||||
if (!params.id) return
|
if (!params.id) return
|
||||||
if (!global.servers.list().some((conn) => ServerConnection.key(conn) === activeServer())) return
|
if (!global.servers.list().some((conn) => ServerConnection.key(conn) === activeServer())) return
|
||||||
return selected().sync.session.lineage.peek(params.id)?.session.directory
|
return selected().sync.session.lineage.peek(params.id)?.session.location.directory
|
||||||
})
|
})
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
@@ -212,7 +211,6 @@ function createServerPermissionState(input: { sdk: ServerSDK; sync: ServerSync }
|
|||||||
)
|
)
|
||||||
|
|
||||||
function enableConfiguredDirectory(directory: string) {
|
function enableConfiguredDirectory(directory: string) {
|
||||||
if (input.sdk.protocolKind() !== "v1") return
|
|
||||||
if (meta.disposed || !ready()) return
|
if (meta.disposed || !ready()) return
|
||||||
const [childStore] = input.sync.child(directory)
|
const [childStore] = input.sync.child(directory)
|
||||||
if (childStore.config.permission !== "allow") return
|
if (childStore.config.permission !== "allow") return
|
||||||
@@ -250,7 +248,6 @@ function createServerPermissionState(input: { sdk: ServerSDK; sync: ServerSync }
|
|||||||
sessionID: request.sessionID,
|
sessionID: request.sessionID,
|
||||||
requestID: request.permissionID,
|
requestID: request.permissionID,
|
||||||
reply: request.response,
|
reply: request.response,
|
||||||
location: request.directory ? { directory: request.directory } : undefined,
|
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
responded.delete(request.permissionID)
|
responded.delete(request.permissionID)
|
||||||
@@ -258,9 +255,7 @@ function createServerPermissionState(input: { sdk: ServerSDK; sync: ServerSync }
|
|||||||
}
|
}
|
||||||
|
|
||||||
const list = async (directory: string) => {
|
const list = async (directory: string) => {
|
||||||
return input.sdk.api.permission.request
|
return input.sdk.api.permission.request.list({ location: { directory } }).then((result) => result.data)
|
||||||
.list({ location: { directory } })
|
|
||||||
.then((result) => result.data.map(normalizePermissionRequest))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function respondOnce(permission: PermissionRequest, directory?: string) {
|
function respondOnce(permission: PermissionRequest, directory?: string) {
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { createSimpleContext } from "@opencode-ai/ui/context"
|
import { createSimpleContext } from "@opencode-ai/ui/context"
|
||||||
import { type Accessor, createMemo } from "solid-js"
|
import { type Accessor, createMemo } from "solid-js"
|
||||||
import { type DirectorySDK, useServerSDK } from "./server-sdk"
|
import { type DirectorySDK, useServerSDK } from "./server-sdk"
|
||||||
|
export type { DirectorySDK } from "./server-sdk"
|
||||||
|
|
||||||
export type { DirectorySDK }
|
const context = createSimpleContext({
|
||||||
|
|
||||||
export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|
||||||
name: "SDK",
|
name: "SDK",
|
||||||
// Resolves the directory-scoped SDK reactively from the (possibly changing) server.
|
// Resolves the directory-scoped SDK reactively from the (possibly changing) server.
|
||||||
init: (props: { directory: string | Accessor<string> }) => {
|
init: (props: { directory: string | Accessor<string> }) => {
|
||||||
@@ -15,3 +14,6 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export const useSDK: () => Accessor<DirectorySDK> = context.use
|
||||||
|
export const SDKProvider = context.provider
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import { adaptServerEvent, coalesceServerEvents, enqueueServerEvent, resumeStreamAfterPageShow } from "./server-sdk"
|
|
||||||
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||||
import type { Event } from "@/types"
|
import { adaptServerEvent, coalesceServerEvents, enqueueServerEvent, resumeStreamAfterPageShow } from "./server-sdk"
|
||||||
|
|
||||||
describe("resumeStreamAfterPageShow", () => {
|
describe("resumeStreamAfterPageShow", () => {
|
||||||
test("restarts a stream only after a back-forward cache restore", () => {
|
test("restarts a stream only after a back-forward cache restore", () => {
|
||||||
@@ -16,7 +15,7 @@ describe("resumeStreamAfterPageShow", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe("adaptServerEvent", () => {
|
describe("adaptServerEvent", () => {
|
||||||
test("preserves V2 events while adapting permission requests for existing consumers", () => {
|
test("preserves current permission requests", () => {
|
||||||
const current = {
|
const current = {
|
||||||
id: "evt_1",
|
id: "evt_1",
|
||||||
created: 1,
|
created: 1,
|
||||||
@@ -31,55 +30,38 @@ describe("adaptServerEvent", () => {
|
|||||||
} as OpenCodeEvent
|
} as OpenCodeEvent
|
||||||
|
|
||||||
expect(adaptServerEvent(current)).toMatchObject({
|
expect(adaptServerEvent(current)).toMatchObject({
|
||||||
|
id: "evt_1",
|
||||||
type: "permission.asked",
|
type: "permission.asked",
|
||||||
properties: {
|
properties: {
|
||||||
id: "perm_1",
|
id: "perm_1",
|
||||||
sessionID: "ses_1",
|
sessionID: "ses_1",
|
||||||
permission: "read",
|
action: "read",
|
||||||
patterns: ["src/**"],
|
resources: ["src/**"],
|
||||||
tool: { messageID: "msg_1", callID: "call_1" },
|
source: { type: "tool", messageID: "msg_1", id: "call_1" },
|
||||||
},
|
},
|
||||||
current,
|
current,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("coalesceServerEvents", () => {
|
describe("current event buffering", () => {
|
||||||
const delta = (value: string, field = "text", partID = "part") => ({
|
const delta = (id: string, value: string, ordinal = 0) => ({
|
||||||
directory: "/repo",
|
directory: "/repo",
|
||||||
payload: {
|
payload: adaptServerEvent({
|
||||||
type: "message.part.delta",
|
id,
|
||||||
properties: { messageID: "msg", partID, field, delta: value },
|
created: 1,
|
||||||
} as Event,
|
type: "session.text.delta",
|
||||||
|
location: { directory: "/repo" },
|
||||||
|
data: { sessionID: "ses", assistantMessageID: "msg", ordinal, delta: value },
|
||||||
|
} as OpenCodeEvent),
|
||||||
})
|
})
|
||||||
|
|
||||||
test("merges adjacent deltas for the same field", () => {
|
test("merges adjacent text deltas for the same message and ordinal", () => {
|
||||||
const first = delta("hello ")
|
const result = coalesceServerEvents([delta("evt_1", "hello "), delta("evt_2", "world")])
|
||||||
const second = delta("world")
|
|
||||||
first.payload.id = "first"
|
|
||||||
second.payload.id = "second"
|
|
||||||
const result = coalesceServerEvents([first, second])
|
|
||||||
|
|
||||||
expect(result).toHaveLength(1)
|
|
||||||
expect(result[0]?.payload).toMatchObject({ id: "second", properties: { delta: "hello world" } })
|
|
||||||
})
|
|
||||||
|
|
||||||
test("merges adjacent current text deltas", () => {
|
|
||||||
const current = (id: string, value: string) =>
|
|
||||||
adaptServerEvent({
|
|
||||||
id,
|
|
||||||
created: 1,
|
|
||||||
type: "session.text.delta",
|
|
||||||
location: { directory: "/repo" },
|
|
||||||
data: { sessionID: "ses", assistantMessageID: "msg", ordinal: 0, delta: value },
|
|
||||||
} as OpenCodeEvent)
|
|
||||||
const result = coalesceServerEvents([
|
|
||||||
{ directory: "/repo", payload: current("evt_1", "hello ") },
|
|
||||||
{ directory: "/repo", payload: current("evt_2", "world") },
|
|
||||||
])
|
|
||||||
|
|
||||||
expect(result).toHaveLength(1)
|
expect(result).toHaveLength(1)
|
||||||
expect(result[0]?.payload.current).toMatchObject({ id: "evt_2", data: { delta: "hello world" } })
|
expect(result[0]?.payload.current).toMatchObject({ id: "evt_2", data: { delta: "hello world" } })
|
||||||
|
expect(result[0]?.payload.properties).toMatchObject({ delta: "hello world" })
|
||||||
})
|
})
|
||||||
|
|
||||||
test("coalesces current tool input deltas by tool ID", () => {
|
test("coalesces current tool input deltas by tool ID", () => {
|
||||||
@@ -102,127 +84,16 @@ describe("coalesceServerEvents", () => {
|
|||||||
expect(result[1]?.payload.current).toMatchObject({ id: "evt_3", data: { id: "call_2", delta: "[]" } })
|
expect(result[1]?.payload.current).toMatchObject({ id: "evt_3", data: { id: "call_2", delta: "[]" } })
|
||||||
})
|
})
|
||||||
|
|
||||||
test("preserves event boundaries and distinct fields", () => {
|
test("preserves boundaries between distinct delta streams", () => {
|
||||||
const status = {
|
const events = [delta("evt_1", "a"), delta("evt_2", "b", 1), delta("evt_3", "c")]
|
||||||
directory: "/repo",
|
|
||||||
payload: { type: "session.status", properties: { sessionID: "ses", status: { type: "idle" } } } as Event,
|
|
||||||
}
|
|
||||||
const result = coalesceServerEvents([delta("a"), delta("b", "metadata"), status, delta("c")])
|
|
||||||
|
|
||||||
expect(result.map((event) => event.payload.type)).toEqual([
|
expect(coalesceServerEvents(events).map((event) => event.payload.current?.id)).toEqual(["evt_1", "evt_2", "evt_3"])
|
||||||
"message.part.delta",
|
|
||||||
"message.part.delta",
|
|
||||||
"session.status",
|
|
||||||
"message.part.delta",
|
|
||||||
])
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("preserves event ID order across interleaved deltas", () => {
|
test("preserves current event order when enqueuing", () => {
|
||||||
const first = delta("a")
|
const events: Parameters<typeof enqueueServerEvent>[0] = []
|
||||||
const other = delta("b", "text", "other")
|
;[delta("evt_1", "a"), delta("evt_2", "b", 1)].forEach((event) => enqueueServerEvent(events, event))
|
||||||
const last = delta("c")
|
|
||||||
first.payload.id = "1"
|
|
||||||
other.payload.id = "2"
|
|
||||||
last.payload.id = "3"
|
|
||||||
|
|
||||||
const result = coalesceServerEvents([first, other, last])
|
expect(events.map((event) => event.payload.current?.id)).toEqual(["evt_1", "evt_2"])
|
||||||
|
|
||||||
expect(result.map((event) => event.payload.id)).toEqual(["1", "2", "3"])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("enqueueServerEvent", () => {
|
|
||||||
const partUpdated = (text: string) =>
|
|
||||||
({
|
|
||||||
type: "message.part.updated",
|
|
||||||
properties: {
|
|
||||||
sessionID: "session",
|
|
||||||
part: { id: "part", sessionID: "session", messageID: "message", type: "text", text },
|
|
||||||
},
|
|
||||||
}) as Event
|
|
||||||
|
|
||||||
test("preserves part updates across message remove and re-add barriers", () => {
|
|
||||||
const events: Array<{ directory: string; payload: Event }> = []
|
|
||||||
const enqueue = (payload: Event) => enqueueServerEvent(events, { directory: "/repo", payload })
|
|
||||||
|
|
||||||
enqueue(partUpdated("old"))
|
|
||||||
enqueue({ type: "message.removed", properties: { sessionID: "session", messageID: "message" } } as Event)
|
|
||||||
enqueue({
|
|
||||||
type: "message.updated",
|
|
||||||
properties: {
|
|
||||||
sessionID: "session",
|
|
||||||
info: {
|
|
||||||
id: "message",
|
|
||||||
sessionID: "session",
|
|
||||||
role: "user",
|
|
||||||
time: { created: 1 },
|
|
||||||
agent: "build",
|
|
||||||
model: { providerID: "provider", modelID: "model" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as Event)
|
|
||||||
enqueue(partUpdated("new"))
|
|
||||||
|
|
||||||
expect(events.map((event) => event.payload.type)).toEqual([
|
|
||||||
"message.part.updated",
|
|
||||||
"message.removed",
|
|
||||||
"message.updated",
|
|
||||||
"message.part.updated",
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("preserves deltas after a replacement snapshot", () => {
|
|
||||||
const events: Array<{ directory: string; payload: Event }> = []
|
|
||||||
const enqueue = (payload: Event) => enqueueServerEvent(events, { directory: "/repo", payload })
|
|
||||||
|
|
||||||
enqueue(partUpdated("a"))
|
|
||||||
enqueue(partUpdated("ab"))
|
|
||||||
enqueue({
|
|
||||||
type: "message.part.delta",
|
|
||||||
properties: { sessionID: "session", messageID: "message", partID: "part", field: "text", delta: "c" },
|
|
||||||
} as Event)
|
|
||||||
|
|
||||||
const result = coalesceServerEvents(events)
|
|
||||||
expect(result.map((event) => event.payload.type)).toEqual(["message.part.updated", "message.part.delta"])
|
|
||||||
expect(result[0]?.payload).toMatchObject({ properties: { part: { text: "ab" } } })
|
|
||||||
expect(result[1]?.payload).toMatchObject({ properties: { delta: "c" } })
|
|
||||||
})
|
|
||||||
|
|
||||||
test("preserves updates after session deletion", () => {
|
|
||||||
const events: Array<{ directory: string; payload: Event }> = []
|
|
||||||
const enqueue = (payload: Event) => enqueueServerEvent(events, { directory: "/repo", payload })
|
|
||||||
|
|
||||||
enqueue(partUpdated("old"))
|
|
||||||
enqueue({
|
|
||||||
type: "session.deleted",
|
|
||||||
properties: { sessionID: "session", info: { id: "session" } },
|
|
||||||
} as Event)
|
|
||||||
enqueue(partUpdated("new"))
|
|
||||||
|
|
||||||
expect(events.map((event) => event.payload.type)).toEqual([
|
|
||||||
"message.part.updated",
|
|
||||||
"session.deleted",
|
|
||||||
"message.part.updated",
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("does not coalesce edge-triggered session statuses", () => {
|
|
||||||
const events: Array<{ directory: string; payload: Event }> = []
|
|
||||||
const enqueue = (status: "retry" | "busy") =>
|
|
||||||
enqueueServerEvent(events, {
|
|
||||||
directory: "/repo",
|
|
||||||
payload: {
|
|
||||||
type: "session.status",
|
|
||||||
properties: {
|
|
||||||
sessionID: "session",
|
|
||||||
status: status === "retry" ? { type: "retry", attempt: 1, message: "retry", next: 1 } : { type: "busy" },
|
|
||||||
},
|
|
||||||
} as Event,
|
|
||||||
})
|
|
||||||
|
|
||||||
enqueue("retry")
|
|
||||||
enqueue("busy")
|
|
||||||
|
|
||||||
expect(events).toHaveLength(2)
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,24 +1,16 @@
|
|||||||
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||||
import type { Event, PermissionRequest } from "@/types"
|
import type { Event } from "@/types"
|
||||||
import { createSimpleContext } from "@opencode-ai/ui/context"
|
import { createSimpleContext } from "@opencode-ai/ui/context"
|
||||||
import { createGlobalEmitter } from "@solid-primitives/event-bus"
|
import { createGlobalEmitter } from "@solid-primitives/event-bus"
|
||||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||||
import { type Accessor, batch, createMemo, createResource, onCleanup, onMount } from "solid-js"
|
import { type Accessor, batch, createMemo, onCleanup, onMount } from "solid-js"
|
||||||
import { createApiForServer, createSdkForServer, type ServerApi } from "@/utils/server"
|
import { createApiForServer, type ServerApi } from "@/utils/server"
|
||||||
import { useLanguage } from "./language"
|
import { useLanguage } from "./language"
|
||||||
import { usePlatform } from "./platform"
|
import { usePlatform } from "./platform"
|
||||||
import { ServerConnection, useServer } from "./server"
|
import { ServerConnection, useServer } from "./server"
|
||||||
import { createRefCountMap } from "@/utils/refcount"
|
import { createRefCountMap } from "@/utils/refcount"
|
||||||
import { useGlobal } from "./global"
|
import { useGlobal } from "./global"
|
||||||
import { ServerScope } from "@/utils/server-scope"
|
import { ServerScope } from "@/utils/server-scope"
|
||||||
import { detectServerProtocol, type ServerProtocol } from "@/utils/server-protocol"
|
|
||||||
import {
|
|
||||||
createCompatibleApi,
|
|
||||||
createLegacyCapabilities,
|
|
||||||
type CompatibleApi,
|
|
||||||
type LegacyCapabilities,
|
|
||||||
} from "@/utils/server-compat"
|
|
||||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client"
|
|
||||||
|
|
||||||
const isAbortError = (error: unknown) =>
|
const isAbortError = (error: unknown) =>
|
||||||
error !== null && typeof error === "object" && "name" in error && error.name === "AbortError"
|
error !== null && typeof error === "object" && "name" in error && error.name === "AbortError"
|
||||||
@@ -32,44 +24,10 @@ type CurrentDelta = Extract<
|
|||||||
>
|
>
|
||||||
|
|
||||||
export function adaptServerEvent(event: OpenCodeEvent): ServerEvent {
|
export function adaptServerEvent(event: OpenCodeEvent): ServerEvent {
|
||||||
if (event.type === "permission.asked") {
|
|
||||||
return {
|
|
||||||
id: event.id,
|
|
||||||
type: "permission.asked",
|
|
||||||
properties: {
|
|
||||||
id: event.data.id,
|
|
||||||
sessionID: event.data.sessionID,
|
|
||||||
permission: event.data.action,
|
|
||||||
patterns: event.data.resources,
|
|
||||||
always: event.data.save ?? [],
|
|
||||||
metadata: event.data.metadata ?? {},
|
|
||||||
tool:
|
|
||||||
event.data.source?.type === "tool"
|
|
||||||
? { messageID: event.data.source.messageID, callID: event.data.source.id }
|
|
||||||
: undefined,
|
|
||||||
} satisfies PermissionRequest,
|
|
||||||
current: event,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { id: event.id, type: event.type, properties: event.data, current: event } as ServerEvent
|
return { id: event.id, type: event.type, properties: event.data, current: event } as ServerEvent
|
||||||
}
|
}
|
||||||
|
|
||||||
const coalescedKey = (event: QueuedServerEvent) => {
|
|
||||||
if (event.payload.type === "lsp.updated") return `lsp.updated:${event.directory}`
|
|
||||||
if (event.payload.type === "message.part.updated") {
|
|
||||||
const part = event.payload.properties.part
|
|
||||||
return `message.part.updated:${event.directory}:${part.messageID}:${part.id}`
|
|
||||||
}
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
export function enqueueServerEvent(queue: QueuedServerEvent[], event: QueuedServerEvent) {
|
export function enqueueServerEvent(queue: QueuedServerEvent[], event: QueuedServerEvent) {
|
||||||
const key = coalescedKey(event)
|
|
||||||
const previous = queue[queue.length - 1]
|
|
||||||
if (key && previous && coalescedKey(previous) === key) {
|
|
||||||
queue[queue.length - 1] = event
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
queue.push(event)
|
queue.push(event)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -105,33 +63,7 @@ export function coalesceServerEvents(events: QueuedServerEvent[]) {
|
|||||||
output.push(event)
|
output.push(event)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (event.payload.type !== "message.part.delta") {
|
output.push(event)
|
||||||
output.push(event)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const props = event.payload.properties
|
|
||||||
const previous = output[output.length - 1]
|
|
||||||
if (
|
|
||||||
!previous ||
|
|
||||||
previous.payload.type !== "message.part.delta" ||
|
|
||||||
previous.directory !== event.directory ||
|
|
||||||
previous.payload.properties.messageID !== props.messageID ||
|
|
||||||
previous.payload.properties.partID !== props.partID ||
|
|
||||||
previous.payload.properties.field !== props.field
|
|
||||||
) {
|
|
||||||
output.push({
|
|
||||||
directory: event.directory,
|
|
||||||
payload: { ...event.payload, properties: { ...props } },
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
output[output.length - 1] = {
|
|
||||||
directory: event.directory,
|
|
||||||
payload: {
|
|
||||||
...event.payload,
|
|
||||||
properties: { ...props, delta: previous.payload.properties.delta + props.delta },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
return output
|
return output
|
||||||
}
|
}
|
||||||
@@ -166,21 +98,13 @@ type ServerEventEmitter = ReturnType<typeof createGlobalEmitter<{ [key: string]:
|
|||||||
type ServerSDKBase = {
|
type ServerSDKBase = {
|
||||||
server: ServerConnection.Any
|
server: ServerConnection.Any
|
||||||
scope: ServerScope
|
scope: ServerScope
|
||||||
protocol: Promise<ServerProtocol>
|
|
||||||
protocolKind: Accessor<ServerProtocol | undefined>
|
|
||||||
url: string
|
url: string
|
||||||
client: ReturnType<typeof createSdkForServer>
|
api: ServerApi
|
||||||
api: CompatibleApi
|
|
||||||
legacy: LegacyCapabilities
|
|
||||||
currentApi: ServerApi
|
|
||||||
event: {
|
event: {
|
||||||
on: ServerEventEmitter["on"]
|
on: ServerEventEmitter["on"]
|
||||||
listen: ServerEventEmitter["listen"]
|
listen: ServerEventEmitter["listen"]
|
||||||
start: () => Promise<void> | undefined
|
start: () => Promise<void> | undefined
|
||||||
}
|
}
|
||||||
createClient: (
|
|
||||||
opts: Omit<Parameters<typeof createSdkForServer>[0], "server" | "fetch">,
|
|
||||||
) => ReturnType<typeof createSdkForServer>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerScope): ServerSDKBase {
|
function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerScope): ServerSDKBase {
|
||||||
@@ -199,11 +123,6 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
|
|||||||
})()
|
})()
|
||||||
|
|
||||||
const eventApi = createApiForServer({ server: server.http, fetch: eventFetch })
|
const eventApi = createApiForServer({ server: server.http, fetch: eventFetch })
|
||||||
const protocol = detectServerProtocol(server.http, platform.fetch ?? globalThis.fetch)
|
|
||||||
const [protocolKind] = createResource(
|
|
||||||
() => protocol,
|
|
||||||
(value) => value,
|
|
||||||
)
|
|
||||||
const emitter = createGlobalEmitter<{
|
const emitter = createGlobalEmitter<{
|
||||||
[key: string]: ServerEvent
|
[key: string]: ServerEvent
|
||||||
}>()
|
}>()
|
||||||
@@ -321,66 +240,23 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
|
|||||||
flush()
|
flush()
|
||||||
})
|
})
|
||||||
|
|
||||||
const sdk = createSdkForServer({
|
const api = createApiForServer({ server: server.http, fetch: platform.fetch })
|
||||||
server: server.http,
|
|
||||||
fetch: platform.fetch,
|
|
||||||
throwOnError: true,
|
|
||||||
})
|
|
||||||
const currentApi: ServerApi = createApiForServer({ server: server.http, fetch: platform.fetch })
|
|
||||||
const legacy = (directory?: string) =>
|
|
||||||
createSdkForServer({
|
|
||||||
server: server.http,
|
|
||||||
fetch: platform.fetch,
|
|
||||||
throwOnError: true,
|
|
||||||
directory,
|
|
||||||
})
|
|
||||||
const api = createCompatibleApi({ protocol, current: currentApi, legacy })
|
|
||||||
const capabilities = createLegacyCapabilities({ protocol, current: currentApi, legacy })
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
server,
|
server,
|
||||||
scope,
|
scope,
|
||||||
protocol,
|
|
||||||
protocolKind,
|
|
||||||
url: server.http.url,
|
url: server.http.url,
|
||||||
client: sdk,
|
|
||||||
api,
|
api,
|
||||||
legacy: capabilities,
|
|
||||||
currentApi,
|
|
||||||
event: {
|
event: {
|
||||||
on: emitter.on.bind(emitter),
|
on: emitter.on.bind(emitter),
|
||||||
listen: emitter.listen.bind(emitter),
|
listen: emitter.listen.bind(emitter),
|
||||||
start,
|
start,
|
||||||
},
|
},
|
||||||
createClient(opts: Omit<Parameters<typeof createSdkForServer>[0], "server" | "fetch">) {
|
|
||||||
return createSdkForServer({
|
|
||||||
server: server.http,
|
|
||||||
fetch: platform.fetch,
|
|
||||||
...opts,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type SDKEventMap = {
|
|
||||||
[key in Event["type"]]: Extract<ServerEvent, { type: key }>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type DirectorySDK = {
|
|
||||||
scope: ServerScope
|
|
||||||
protocol: Promise<ServerProtocol>
|
|
||||||
directory: string
|
|
||||||
client: OpencodeClient
|
|
||||||
currentApi: ServerApi
|
|
||||||
api: CompatibleApi
|
|
||||||
legacy: LegacyCapabilities
|
|
||||||
event: ReturnType<typeof createGlobalEmitter<SDKEventMap>>
|
|
||||||
readonly url: string
|
|
||||||
createClient: ServerSDKBase["createClient"]
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ServerSDK = ServerSDKBase & {
|
export type ServerSDK = ServerSDKBase & {
|
||||||
ensureDirSdkContext: (directory: string) => DirectorySDK
|
ensureDirSdkContext: (directory: string) => ReturnType<typeof createDirSdkContext>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createServerSdkContext(server: ServerConnection.Any, scope: ServerScope): ServerSDK {
|
export function createServerSdkContext(server: ServerConnection.Any, scope: ServerScope): ServerSDK {
|
||||||
@@ -407,17 +283,19 @@ export const { use: useServerSDK, provider: ServerSDKProvider } = createSimpleCo
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
export function useServerProtocol() {
|
type SDKEventMap = {
|
||||||
const serverSDK = useServerSDK()
|
[key in Event["type"]]: Extract<ServerEvent, { type: key }>
|
||||||
return createMemo(() => serverSDK().protocolKind())
|
}
|
||||||
|
|
||||||
|
export type DirectorySDK = {
|
||||||
|
scope: ServerScope
|
||||||
|
directory: string
|
||||||
|
api: ServerApi
|
||||||
|
event: ReturnType<typeof createGlobalEmitter<SDKEventMap>>
|
||||||
|
readonly url: string
|
||||||
}
|
}
|
||||||
|
|
||||||
function createDirSdkContext(directory: string, serverSDK: ServerSDKBase): DirectorySDK {
|
function createDirSdkContext(directory: string, serverSDK: ServerSDKBase): DirectorySDK {
|
||||||
const client = serverSDK.createClient({
|
|
||||||
directory,
|
|
||||||
throwOnError: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
const emitter = createGlobalEmitter<SDKEventMap>()
|
const emitter = createGlobalEmitter<SDKEventMap>()
|
||||||
|
|
||||||
const unsub = serverSDK.event.on(directory, (event) => {
|
const unsub = serverSDK.event.on(directory, (event) => {
|
||||||
@@ -427,28 +305,11 @@ function createDirSdkContext(directory: string, serverSDK: ServerSDKBase): Direc
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
scope: serverSDK.scope,
|
scope: serverSDK.scope,
|
||||||
protocol: serverSDK.protocol,
|
|
||||||
directory,
|
directory,
|
||||||
client,
|
api: serverSDK.api,
|
||||||
currentApi: serverSDK.currentApi,
|
|
||||||
api: createCompatibleApi({
|
|
||||||
protocol: serverSDK.protocol,
|
|
||||||
current: serverSDK.currentApi,
|
|
||||||
legacy: (next) => serverSDK.createClient({ directory: next ?? directory, throwOnError: true }),
|
|
||||||
directory,
|
|
||||||
}),
|
|
||||||
legacy: createLegacyCapabilities({
|
|
||||||
protocol: serverSDK.protocol,
|
|
||||||
current: serverSDK.currentApi,
|
|
||||||
legacy: (next) => serverSDK.createClient({ directory: next ?? directory, throwOnError: true }),
|
|
||||||
directory,
|
|
||||||
}),
|
|
||||||
event: emitter,
|
event: emitter,
|
||||||
get url() {
|
get url() {
|
||||||
return serverSDK.url
|
return serverSDK.url
|
||||||
},
|
},
|
||||||
createClient(opts: Parameters<typeof serverSDK.createClient>[0]) {
|
|
||||||
return serverSDK.createClient(opts)
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,26 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { retry } from "@opencode-ai/core/util/retry"
|
import type { retry } from "@opencode-ai/core/util/retry"
|
||||||
import type { OpenCodeEvent, SessionApi } from "@opencode-ai/client/promise"
|
import type {
|
||||||
import type { Message, Part, Session } from "@/types"
|
OpenCodeEvent,
|
||||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client"
|
SessionApi,
|
||||||
|
SessionInfo,
|
||||||
|
SessionMessageAssistant,
|
||||||
|
SessionMessageAssistantTool,
|
||||||
|
SessionMessageInfo,
|
||||||
|
} from "@opencode-ai/client/promise"
|
||||||
|
import type { Message, Part } from "@/types"
|
||||||
import { createServerSession } from "./server-session"
|
import { createServerSession } from "./server-session"
|
||||||
import type { ServerApi } from "@/utils/server"
|
import type { ServerApi } from "@/utils/server"
|
||||||
|
|
||||||
type MessageApi = ServerApi["message"]
|
type MessageApi = ServerApi["message"]
|
||||||
|
|
||||||
const session = (id: string, parentID?: string): Session => ({
|
const session = (id: string, parentID?: string): SessionInfo => ({
|
||||||
id,
|
id,
|
||||||
slug: id,
|
|
||||||
projectID: "project",
|
projectID: "project",
|
||||||
directory: "/repo",
|
location: { directory: "/repo" },
|
||||||
title: id,
|
title: id,
|
||||||
version: "1",
|
cost: 0,
|
||||||
|
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||||
parentID,
|
parentID,
|
||||||
time: { created: 1, updated: 1 },
|
time: { created: 1, updated: 1 },
|
||||||
})
|
})
|
||||||
@@ -22,19 +28,120 @@ const session = (id: string, parentID?: string): Session => ({
|
|||||||
type UserMessage = Extract<Message, { role: "user" }>
|
type UserMessage = Extract<Message, { role: "user" }>
|
||||||
type AssistantMessage = Extract<Message, { role: "assistant" }>
|
type AssistantMessage = Extract<Message, { role: "assistant" }>
|
||||||
type TextPart = Extract<Part, { type: "text" }>
|
type TextPart = Extract<Part, { type: "text" }>
|
||||||
|
type CurrentToolObject = Extract<SessionMessageAssistantTool["state"], { status: "running" }>["input"]
|
||||||
type MessageResponse = {
|
type MessageResponse = {
|
||||||
data: { info: Message; parts: Part[] }[]
|
data: { info: Message; parts: Part[] }[]
|
||||||
response: { headers: Headers }
|
response: { headers: Headers }
|
||||||
}
|
}
|
||||||
type SingleMessageResponse = { data: MessageResponse["data"][number] }
|
type SingleMessageResponse = { data: MessageResponse["data"][number] }
|
||||||
|
|
||||||
|
function sessionInfo(value: SessionInfo): SessionInfo {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentMessages(data: MessageResponse["data"]): SessionMessageInfo[] {
|
||||||
|
return data.flatMap((item): SessionMessageInfo[] => {
|
||||||
|
if (item.info.role === "user") {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: `${item.info.id}:agent`,
|
||||||
|
type: "agent-switched",
|
||||||
|
agent: item.info.agent,
|
||||||
|
time: item.info.time,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: `${item.info.id}:model`,
|
||||||
|
type: "model-switched",
|
||||||
|
model: {
|
||||||
|
id: item.info.model.modelID,
|
||||||
|
providerID: item.info.model.providerID,
|
||||||
|
variant: item.info.model.variant,
|
||||||
|
},
|
||||||
|
time: item.info.time,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: item.info.id,
|
||||||
|
type: "user",
|
||||||
|
text: item.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"),
|
||||||
|
time: item.info.time,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
return [{
|
||||||
|
id: item.info.id,
|
||||||
|
type: "assistant",
|
||||||
|
agent: item.info.agent,
|
||||||
|
model: { id: item.info.modelID, providerID: item.info.providerID, variant: item.info.variant },
|
||||||
|
content: item.parts.flatMap((part): SessionMessageAssistant["content"] => {
|
||||||
|
if (part.type === "text") return [{ type: "text", text: part.text }]
|
||||||
|
if (part.type === "reasoning")
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
type: "reasoning",
|
||||||
|
text: part.text,
|
||||||
|
time: part.time ? { created: part.time.start, completed: part.time.end } : undefined,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
if (part.type !== "tool") return []
|
||||||
|
const state: SessionMessageAssistantTool["state"] = (() => {
|
||||||
|
if (part.state.status === "pending") return { status: "streaming" as const, input: JSON.stringify(part.state.input) }
|
||||||
|
if (part.state.status === "running")
|
||||||
|
return {
|
||||||
|
status: "running" as const,
|
||||||
|
input: part.state.input as CurrentToolObject,
|
||||||
|
metadata: (part.state.metadata ?? {}) as CurrentToolObject,
|
||||||
|
}
|
||||||
|
if (part.state.status === "error")
|
||||||
|
return {
|
||||||
|
status: "error" as const,
|
||||||
|
input: part.state.input as CurrentToolObject,
|
||||||
|
error: { type: "tool_error", message: part.state.error },
|
||||||
|
metadata: part.state.metadata as CurrentToolObject | undefined,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: "completed" as const,
|
||||||
|
input: part.state.input as CurrentToolObject,
|
||||||
|
content: [{ type: "text" as const, text: part.state.output }],
|
||||||
|
metadata: part.state.metadata as CurrentToolObject,
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: part.id,
|
||||||
|
type: "tool" as const,
|
||||||
|
name: part.tool,
|
||||||
|
state,
|
||||||
|
time: {
|
||||||
|
created: part.state.status === "pending" ? item.info.time.created : part.state.time.start,
|
||||||
|
ran: part.state.status === "pending" ? undefined : part.state.time.start,
|
||||||
|
completed:
|
||||||
|
part.state.status === "completed" || part.state.status === "error" ? part.state.time.end : undefined,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
time: item.info.time,
|
||||||
|
cost: item.info.cost,
|
||||||
|
tokens: item.info.tokens,
|
||||||
|
finish: item.info.finish as "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown" | undefined,
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentPage(value: MessageResponse) {
|
||||||
|
return {
|
||||||
|
data: currentMessages(value.data).toReversed(),
|
||||||
|
cursor: { next: value.response.headers.get("x-next-cursor") ?? undefined },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const userMessage = (id: string, input: Partial<UserMessage> = {}): UserMessage => ({
|
const userMessage = (id: string, input: Partial<UserMessage> = {}): UserMessage => ({
|
||||||
id,
|
id,
|
||||||
sessionID: "child",
|
sessionID: "child",
|
||||||
role: "user",
|
role: "user",
|
||||||
time: { created: 1 },
|
time: { created: 1 },
|
||||||
agent: "build",
|
agent: "build",
|
||||||
model: { providerID: "provider", modelID: "model" },
|
model: { providerID: "provider", modelID: "model", variant: undefined },
|
||||||
...input,
|
...input,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -46,21 +153,24 @@ const assistantMessage = (id: string, parentID: string, input: Partial<Assistant
|
|||||||
parentID,
|
parentID,
|
||||||
modelID: "model",
|
modelID: "model",
|
||||||
providerID: "provider",
|
providerID: "provider",
|
||||||
|
variant: undefined,
|
||||||
mode: "build",
|
mode: "build",
|
||||||
agent: "build",
|
agent: "build",
|
||||||
path: { cwd: "/repo", root: "/repo" },
|
path: { cwd: "", root: "" },
|
||||||
cost: 0,
|
cost: 0,
|
||||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||||
|
error: undefined,
|
||||||
|
finish: undefined,
|
||||||
...input,
|
...input,
|
||||||
})
|
})
|
||||||
|
|
||||||
const textPart = (messageID: string, input: Partial<TextPart> = {}): TextPart => ({
|
const textPart = (messageID: string, input: Partial<TextPart> = {}): TextPart => ({
|
||||||
id: "part",
|
|
||||||
sessionID: "child",
|
sessionID: "child",
|
||||||
messageID,
|
messageID,
|
||||||
type: "text",
|
type: "text",
|
||||||
text: "text",
|
text: "text",
|
||||||
...input,
|
...input,
|
||||||
|
id: `${messageID}:text:${input.id === "pending" ? 1 : 0}`,
|
||||||
})
|
})
|
||||||
|
|
||||||
const response = (data: MessageResponse["data"] = [], cursor?: string): MessageResponse => ({
|
const response = (data: MessageResponse["data"] = [], cursor?: string): MessageResponse => ({
|
||||||
@@ -74,19 +184,27 @@ const deferredResponse = () => Promise.withResolvers<MessageResponse>()
|
|||||||
|
|
||||||
function messageClient(...responses: Array<MessageResponse | Promise<MessageResponse>>) {
|
function messageClient(...responses: Array<MessageResponse | Promise<MessageResponse>>) {
|
||||||
let index = 0
|
let index = 0
|
||||||
|
const pages = responses.map((value) =>
|
||||||
|
value instanceof Promise ? value.then(currentPage) : Promise.resolve(currentPage(value)),
|
||||||
|
)
|
||||||
const requests: unknown[] = []
|
const requests: unknown[] = []
|
||||||
const waiting = new Map<number, () => void>()
|
const waiting = new Map<number, () => void>()
|
||||||
const client = {
|
const client = {
|
||||||
session: {
|
session: {
|
||||||
get: async () => ({ data: session("child", "root") }),
|
get: async () => sessionInfo(session("child", "root")),
|
||||||
messages: (input: unknown) => {
|
message: async () => {
|
||||||
|
throw new Error("Unexpected single message request")
|
||||||
|
},
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
list: async (input: unknown) => {
|
||||||
requests.push(input)
|
requests.push(input)
|
||||||
waiting.get(requests.length)?.()
|
waiting.get(requests.length)?.()
|
||||||
waiting.delete(requests.length)
|
waiting.delete(requests.length)
|
||||||
return responses[index++]
|
return pages[index++]!
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
} as unknown as OpencodeClient
|
} as unknown as { session: SessionApi; message: MessageApi }
|
||||||
return Object.assign(client, {
|
return Object.assign(client, {
|
||||||
requests,
|
requests,
|
||||||
requested(count: number) {
|
requested(count: number) {
|
||||||
@@ -107,19 +225,22 @@ function rootMessageClient(
|
|||||||
const rootWaiting = new Map<number, () => void>()
|
const rootWaiting = new Map<number, () => void>()
|
||||||
const client = {
|
const client = {
|
||||||
session: {
|
session: {
|
||||||
get: async () => ({ data: session("child", "root") }),
|
get: async () => sessionInfo(session("child", "root")),
|
||||||
messages: (input: unknown) => {
|
message: async (input: unknown) => {
|
||||||
requests.push(input)
|
|
||||||
return pages[pageIndex++]
|
|
||||||
},
|
|
||||||
message: (input: unknown) => {
|
|
||||||
rootRequests.push(input)
|
rootRequests.push(input)
|
||||||
rootWaiting.get(rootRequests.length)?.()
|
rootWaiting.get(rootRequests.length)?.()
|
||||||
rootWaiting.delete(rootRequests.length)
|
rootWaiting.delete(rootRequests.length)
|
||||||
return roots[rootIndex++]
|
const value = await roots[rootIndex++]!
|
||||||
|
return currentMessages([value.data]).find((message) => message.id === value.data.info.id)!
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
} as unknown as OpencodeClient
|
message: {
|
||||||
|
list: async (input: unknown) => {
|
||||||
|
requests.push(input)
|
||||||
|
return currentPage(await pages[pageIndex++]!)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as unknown as { session: SessionApi; message: MessageApi }
|
||||||
return Object.assign(client, {
|
return Object.assign(client, {
|
||||||
requests,
|
requests,
|
||||||
rootRequests,
|
rootRequests,
|
||||||
@@ -141,7 +262,7 @@ const retryImmediately: typeof retry = async (task, options = {}) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setup(sessions: Record<string, Session>) {
|
function setup(sessions: Record<string, SessionInfo>) {
|
||||||
const get: unknown[] = []
|
const get: unknown[] = []
|
||||||
const messages: unknown[] = []
|
const messages: unknown[] = []
|
||||||
const client = {
|
const client = {
|
||||||
@@ -149,16 +270,19 @@ function setup(sessions: Record<string, Session>) {
|
|||||||
get: async (input: unknown) => {
|
get: async (input: unknown) => {
|
||||||
get.push(input)
|
get.push(input)
|
||||||
const id = (input as { sessionID: string }).sessionID
|
const id = (input as { sessionID: string }).sessionID
|
||||||
return { data: sessions[id] }
|
return sessionInfo(sessions[id]!)
|
||||||
},
|
},
|
||||||
messages: async (input: unknown) => {
|
message: async () => {
|
||||||
messages.push(input)
|
throw new Error("Unexpected single message request")
|
||||||
return response()
|
|
||||||
},
|
},
|
||||||
diff: async () => ({ data: [] }),
|
|
||||||
todo: async () => ({ data: [] }),
|
|
||||||
},
|
},
|
||||||
} as unknown as OpencodeClient
|
message: {
|
||||||
|
list: async (input: unknown) => {
|
||||||
|
messages.push(input)
|
||||||
|
return currentPage(response())
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as unknown as { session: SessionApi; message: MessageApi }
|
||||||
return { get, messages, store: createServerSession(client) }
|
return { get, messages, store: createServerSession(client) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +354,7 @@ describe("server session", () => {
|
|||||||
await ctx.store.sync("root")
|
await ctx.store.sync("root")
|
||||||
|
|
||||||
expect(ctx.get).toEqual([{ sessionID: "root" }])
|
expect(ctx.get).toEqual([{ sessionID: "root" }])
|
||||||
expect(ctx.messages).toEqual([{ sessionID: "root", limit: 20, before: undefined }])
|
expect(ctx.messages).toEqual([{ sessionID: "root", limit: 20, order: "desc" }])
|
||||||
expect(ctx.store.data.message.root).toEqual([])
|
expect(ctx.store.data.message.root).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -245,54 +369,19 @@ describe("server session", () => {
|
|||||||
content: [{ type: "text", text: "hi" }],
|
content: [{ type: "text", text: "hi" }],
|
||||||
time: { created: 2, completed: 3 },
|
time: { created: 2, completed: 3 },
|
||||||
}
|
}
|
||||||
const client = {
|
|
||||||
session: {
|
|
||||||
messages: () => {
|
|
||||||
throw new Error("legacy message endpoint called")
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as unknown as OpencodeClient
|
|
||||||
const messageApi = {
|
const messageApi = {
|
||||||
list: async (input: unknown) => {
|
list: async (input: unknown) => {
|
||||||
requests.push(input)
|
requests.push(input)
|
||||||
return { data: [assistant, user], cursor: { previous: null, next: null } }
|
return { data: [assistant, user], cursor: { previous: null, next: null } }
|
||||||
},
|
},
|
||||||
} as unknown as MessageApi
|
} as unknown as MessageApi
|
||||||
const store = createServerSession(client, {} as SessionApi, messageApi)
|
const store = createServerSession({} as SessionApi, messageApi)
|
||||||
store.remember(session("root"))
|
store.remember(session("root"))
|
||||||
|
|
||||||
await store.sync("root")
|
await store.sync("root")
|
||||||
|
|
||||||
expect(requests).toEqual([{ sessionID: "root", limit: 20, order: "desc" }])
|
expect(requests).toEqual([{ sessionID: "root", limit: 20, order: "desc" }])
|
||||||
expect(store.data.session_message.root.map((message) => message.id)).toEqual([user.id, assistant.id])
|
expect(store.data.session_message.root.map((message) => message.id)).toEqual([user.id, assistant.id])
|
||||||
expect(store.history.more("root")).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("replaces stale current projections on complete refreshes", async () => {
|
|
||||||
const first = { id: "msg_1", type: "user", text: "first", time: { created: 1 } } as const
|
|
||||||
const second = { id: "msg_2", type: "user", text: "second", time: { created: 2 } } as const
|
|
||||||
const pages = [
|
|
||||||
{ data: [first], cursor: { previous: null, next: null } },
|
|
||||||
{ data: [second], cursor: { previous: null, next: null } },
|
|
||||||
{ data: [], cursor: { previous: null, next: null } },
|
|
||||||
]
|
|
||||||
const messageApi = {
|
|
||||||
list: async () => pages.shift()!,
|
|
||||||
} as unknown as MessageApi
|
|
||||||
const sessionApi = { get: async () => session("root") } as unknown as SessionApi
|
|
||||||
const store = createServerSession({} as OpencodeClient, sessionApi, messageApi)
|
|
||||||
store.remember(session("root"))
|
|
||||||
|
|
||||||
await store.sync("root")
|
|
||||||
expect(store.data.session_message.root.map((message) => message.id)).toEqual([first.id])
|
|
||||||
|
|
||||||
await store.sync("root", { force: true })
|
|
||||||
expect(store.data.session_message.root.map((message) => message.id)).toEqual([second.id])
|
|
||||||
expect(store.data.message.root.map((message) => message.id)).toEqual([second.id])
|
|
||||||
|
|
||||||
await store.sync("root", { force: true })
|
|
||||||
expect(store.data.session_message.root).toEqual([])
|
|
||||||
expect(store.data.message.root).toEqual([])
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("extends a current page to include the user for split assistant turns", async () => {
|
test("extends a current page to include the user for split assistant turns", async () => {
|
||||||
@@ -321,7 +410,7 @@ describe("server session", () => {
|
|||||||
return pages.shift()!
|
return pages.shift()!
|
||||||
},
|
},
|
||||||
} as unknown as MessageApi
|
} as unknown as MessageApi
|
||||||
const store = createServerSession({} as OpencodeClient, {} as SessionApi, messageApi)
|
const store = createServerSession({} as SessionApi, messageApi)
|
||||||
store.remember(session("root"))
|
store.remember(session("root"))
|
||||||
|
|
||||||
await store.sync("root")
|
await store.sync("root")
|
||||||
@@ -337,50 +426,14 @@ describe("server session", () => {
|
|||||||
expect(assistants.map((item) => store.data.part[item.id]?.[0]?.type)).toEqual(["text", "text", "text"])
|
expect(assistants.map((item) => store.data.part[item.id]?.[0]?.type)).toEqual(["text", "text", "text"])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("indexes V1 messages for the current timeline projection", async () => {
|
// V2 messages are ordered projections and do not expose V1 assistant parent IDs.
|
||||||
const user = userMessage("message-1", { sessionID: "root" })
|
describe.skip("V1 assistant parent projections", () => {
|
||||||
const assistant = assistantMessage("message-2", user.id, { sessionID: "root" })
|
|
||||||
const client = messageClient(
|
|
||||||
response([
|
|
||||||
{ info: user, parts: [textPart(user.id, { sessionID: "root" })] },
|
|
||||||
{ info: assistant, parts: [textPart(assistant.id, { sessionID: "root" })] },
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
const messageApi = {
|
|
||||||
list: () => {
|
|
||||||
throw new Error("current message endpoint called")
|
|
||||||
},
|
|
||||||
} as unknown as MessageApi
|
|
||||||
const store = createServerSession(client, {} as SessionApi, messageApi, {
|
|
||||||
protocol: Promise.resolve("v1"),
|
|
||||||
})
|
|
||||||
store.remember(session("root"))
|
|
||||||
|
|
||||||
await store.sync("root")
|
|
||||||
|
|
||||||
expect(store.data.message.root.map((message) => message.id)).toEqual([user.id, assistant.id])
|
|
||||||
expect(store.data.session_message.root).toMatchObject([
|
|
||||||
{ id: user.id, type: "user", text: "text" },
|
|
||||||
{ id: assistant.id, type: "assistant" },
|
|
||||||
])
|
|
||||||
|
|
||||||
const next = userMessage("message-3", { sessionID: "root" })
|
|
||||||
store.apply({ type: "message.updated", properties: { info: next } })
|
|
||||||
expect(store.data.session_message.root.map((message) => message.id)).toEqual([user.id, assistant.id, next.id])
|
|
||||||
|
|
||||||
store.apply({ type: "message.removed", properties: { sessionID: "root", messageID: next.id } })
|
|
||||||
expect(store.data.session_message.root.map((message) => message.id)).toEqual([user.id, assistant.id])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("backfills an assistant-only initial page through its user root", async () => {
|
test("backfills an assistant-only initial page through its user root", async () => {
|
||||||
const user = userMessage("message-1")
|
const user = userMessage("message-1")
|
||||||
const assistants = [assistantMessage("message-2", user.id), assistantMessage("message-3", user.id)]
|
const assistants = [assistantMessage("message-2", user.id), assistantMessage("message-3", user.id)]
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[
|
[
|
||||||
response(
|
response(assistants.map((info) => ({ info, parts: [] }))),
|
||||||
assistants.map((info) => ({ info, parts: [] })),
|
|
||||||
"older",
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
[singleResponse(user)],
|
[singleResponse(user)],
|
||||||
)
|
)
|
||||||
@@ -388,16 +441,16 @@ describe("server session", () => {
|
|||||||
|
|
||||||
await store.sync("child")
|
await store.sync("child")
|
||||||
|
|
||||||
expect(client.requests).toEqual([{ sessionID: "child", limit: 20, before: undefined }])
|
expect(client.requests).toEqual([{ sessionID: "child", limit: 20, order: "desc" }])
|
||||||
expect(client.rootRequests).toEqual([{ sessionID: "child", messageID: user.id }])
|
expect(client.rootRequests).toEqual([{ sessionID: "child", messageID: user.id }])
|
||||||
expect(store.data.message.child).toEqual([user, ...assistants])
|
expect(store.data.message.child).toEqual([user, ...assistants])
|
||||||
expect(store.history.more("child")).toBe(true)
|
expect(store.history.more("child")).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("keeps assistant history when its deleted parent cannot be backfilled", async () => {
|
test("keeps assistant history when its deleted parent cannot be backfilled", async () => {
|
||||||
const missing = Promise.withResolvers<SingleMessageResponse>()
|
const missing = Promise.withResolvers<SingleMessageResponse>()
|
||||||
const assistant = assistantMessage("message-2", "message-missing")
|
const assistant = assistantMessage("message-2", "message-missing")
|
||||||
const client = rootMessageClient([response([{ info: assistant, parts: [] }], "older")], [missing.promise])
|
const client = rootMessageClient([response([{ info: assistant, parts: [] }])], [missing.promise])
|
||||||
const store = createServerSession(client)
|
const store = createServerSession(client)
|
||||||
const loading = store.sync("child")
|
const loading = store.sync("child")
|
||||||
await client.rootRequested(1)
|
await client.rootRequested(1)
|
||||||
@@ -407,7 +460,7 @@ describe("server session", () => {
|
|||||||
|
|
||||||
expect(client.rootRequests).toEqual([{ sessionID: "child", messageID: "message-missing" }])
|
expect(client.rootRequests).toEqual([{ sessionID: "child", messageID: "message-missing" }])
|
||||||
expect(store.data.message.child).toEqual([assistant])
|
expect(store.data.message.child).toEqual([assistant])
|
||||||
expect(store.history.more("child")).toBe(true)
|
expect(store.history.more("child")).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("drops a cached parent when a forced refresh confirms it was deleted", async () => {
|
test("drops a cached parent when a forced refresh confirms it was deleted", async () => {
|
||||||
@@ -421,7 +474,7 @@ describe("server session", () => {
|
|||||||
{ info: parent, parts: [part] },
|
{ info: parent, parts: [part] },
|
||||||
{ info: assistant, parts: [] },
|
{ info: assistant, parts: [] },
|
||||||
]),
|
]),
|
||||||
response([{ info: assistant, parts: [] }], "older"),
|
response([{ info: assistant, parts: [] }]),
|
||||||
],
|
],
|
||||||
[missing.promise],
|
[missing.promise],
|
||||||
)
|
)
|
||||||
@@ -443,10 +496,7 @@ describe("server session", () => {
|
|||||||
const assistants = [assistantMessage("message-2", user.id), assistantMessage("message-3", user.id)]
|
const assistants = [assistantMessage("message-2", user.id), assistantMessage("message-3", user.id)]
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[
|
[
|
||||||
response(
|
response(assistants.map((info) => ({ info, parts: [] }))),
|
||||||
assistants.map((info) => ({ info, parts: [] })),
|
|
||||||
"older",
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
[singleResponse(user)],
|
[singleResponse(user)],
|
||||||
)
|
)
|
||||||
@@ -468,10 +518,7 @@ describe("server session", () => {
|
|||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[
|
[
|
||||||
response([{ info: unrelated, parts: [] }]),
|
response([{ info: unrelated, parts: [] }]),
|
||||||
response(
|
response(assistants.map((info) => ({ info, parts: [] }))),
|
||||||
assistants.map((info) => ({ info, parts: [] })),
|
|
||||||
"older",
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
[singleResponse(user)],
|
[singleResponse(user)],
|
||||||
)
|
)
|
||||||
@@ -490,7 +537,7 @@ describe("server session", () => {
|
|||||||
const cached = userMessage("message-3", { time: { created: 3 } })
|
const cached = userMessage("message-3", { time: { created: 3 } })
|
||||||
const assistant = assistantMessage("message-4", user.id)
|
const assistant = assistantMessage("message-4", user.id)
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[response([{ info: cached, parts: [] }]), response([{ info: assistant, parts: [] }], "older")],
|
[response([{ info: cached, parts: [] }]), response([{ info: assistant, parts: [] }])],
|
||||||
[singleResponse(user)],
|
[singleResponse(user)],
|
||||||
)
|
)
|
||||||
const store = createServerSession(client)
|
const store = createServerSession(client)
|
||||||
@@ -508,7 +555,7 @@ describe("server session", () => {
|
|||||||
const freshPart = { ...stalePart, text: "fresh" }
|
const freshPart = { ...stalePart, text: "fresh" }
|
||||||
const assistant = assistantMessage("message-2", stale.id)
|
const assistant = assistantMessage("message-2", stale.id)
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[response([{ info: stale, parts: [stalePart] }]), response([{ info: assistant, parts: [] }], "older")],
|
[response([{ info: stale, parts: [stalePart] }]), response([{ info: assistant, parts: [] }])],
|
||||||
[singleResponse(fresh, [freshPart])],
|
[singleResponse(fresh, [freshPart])],
|
||||||
)
|
)
|
||||||
const store = createServerSession(client)
|
const store = createServerSession(client)
|
||||||
@@ -529,7 +576,7 @@ describe("server session", () => {
|
|||||||
const pending = textPart(stale.id, { id: "pending", text: "pending" })
|
const pending = textPart(stale.id, { id: "pending", text: "pending" })
|
||||||
const assistant = assistantMessage("message-2", stale.id)
|
const assistant = assistantMessage("message-2", stale.id)
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[response([{ info: stale, parts: [confirmed] }]), response([{ info: assistant, parts: [] }], "older")],
|
[response([{ info: stale, parts: [confirmed] }]), response([{ info: assistant, parts: [] }])],
|
||||||
[singleResponse(fresh, [refreshed])],
|
[singleResponse(fresh, [refreshed])],
|
||||||
)
|
)
|
||||||
const store = createServerSession(client)
|
const store = createServerSession(client)
|
||||||
@@ -552,7 +599,7 @@ describe("server session", () => {
|
|||||||
const loading = store.sync("child")
|
const loading = store.sync("child")
|
||||||
|
|
||||||
store.apply({ type: "message.updated", properties: { info: user } })
|
store.apply({ type: "message.updated", properties: { info: user } })
|
||||||
pending.resolve(response([{ info: assistant, parts: [] }], "older"))
|
pending.resolve(response([{ info: assistant, parts: [] }]))
|
||||||
await loading
|
await loading
|
||||||
|
|
||||||
expect(client.rootRequests).toEqual([])
|
expect(client.rootRequests).toEqual([])
|
||||||
@@ -568,7 +615,6 @@ describe("server session", () => {
|
|||||||
[
|
[
|
||||||
response(
|
response(
|
||||||
assistants.map((info) => ({ info, parts: [] })),
|
assistants.map((info) => ({ info, parts: [] })),
|
||||||
"older",
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
||||||
@@ -592,7 +638,7 @@ describe("server session", () => {
|
|||||||
const assistant = assistantMessage("message-2", user.id)
|
const assistant = assistantMessage("message-2", user.id)
|
||||||
const live = { ...assistant, cost: 1 }
|
const live = { ...assistant, cost: 1 }
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[response([{ info: assistant, parts: [] }], "older")],
|
[response([{ info: assistant, parts: [] }])],
|
||||||
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
||||||
)
|
)
|
||||||
const store = createServerSession(client, { retry: retryImmediately })
|
const store = createServerSession(client, { retry: retryImmediately })
|
||||||
@@ -612,7 +658,7 @@ describe("server session", () => {
|
|||||||
const assistant = assistantMessage("message-2", user.id)
|
const assistant = assistantMessage("message-2", user.id)
|
||||||
const live = userMessage("message-4", { time: { created: 4 } })
|
const live = userMessage("message-4", { time: { created: 4 } })
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[response([{ info: assistant, parts: [] }], "older")],
|
[response([{ info: assistant, parts: [] }])],
|
||||||
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
||||||
)
|
)
|
||||||
const store = createServerSession(client, { retry: retryImmediately })
|
const store = createServerSession(client, { retry: retryImmediately })
|
||||||
@@ -633,7 +679,7 @@ describe("server session", () => {
|
|||||||
const stale = textPart(assistant.id, { text: "stale" })
|
const stale = textPart(assistant.id, { text: "stale" })
|
||||||
const live = { ...stale, text: "live" }
|
const live = { ...stale, text: "live" }
|
||||||
const client = rootMessageClient(
|
const client = rootMessageClient(
|
||||||
[response([{ info: assistant, parts: [stale] }], "older")],
|
[response([{ info: assistant, parts: [stale] }])],
|
||||||
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
[failed.promise.then((result) => ({ data: result.data[0]! })), singleResponse(user)],
|
||||||
)
|
)
|
||||||
const store = createServerSession(client, { retry: retryImmediately })
|
const store = createServerSession(client, { retry: retryImmediately })
|
||||||
@@ -646,6 +692,7 @@ describe("server session", () => {
|
|||||||
|
|
||||||
expect(store.data.part[assistant.id]).toEqual([live])
|
expect(store.data.part[assistant.id]).toEqual([live])
|
||||||
})
|
})
|
||||||
|
})
|
||||||
|
|
||||||
test("merges live events into the initial page", async () => {
|
test("merges live events into the initial page", async () => {
|
||||||
const pending = deferredResponse()
|
const pending = deferredResponse()
|
||||||
@@ -1445,6 +1492,7 @@ describe("server session", () => {
|
|||||||
|
|
||||||
await store.history.loadMore("child")
|
await store.history.loadMore("child")
|
||||||
|
|
||||||
|
guard.active = false
|
||||||
expect(store.data.message.child).toEqual([older, latest])
|
expect(store.data.message.child).toEqual([older, latest])
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1629,7 +1677,7 @@ describe("server session", () => {
|
|||||||
ctx.store.apply({ type: "session.created", properties: { sessionID: "root", info: session("root") } })
|
ctx.store.apply({ type: "session.created", properties: { sessionID: "root", info: session("root") } })
|
||||||
ctx.store.apply({ type: "session.status", properties: { sessionID: "root", status: { type: "busy" } } })
|
ctx.store.apply({ type: "session.status", properties: { sessionID: "root", status: { type: "busy" } } })
|
||||||
|
|
||||||
expect(ctx.store.get("root")?.directory).toBe("/repo")
|
expect(ctx.store.get("root")?.location.directory).toBe("/repo")
|
||||||
expect(ctx.store.data.session_working("root")).toBe(true)
|
expect(ctx.store.data.session_working("root")).toBe(true)
|
||||||
expect(ctx.get).toEqual([])
|
expect(ctx.get).toEqual([])
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,23 +1,15 @@
|
|||||||
import { Binary } from "@opencode-ai/core/util/binary"
|
import { Binary } from "@opencode-ai/core/util/binary"
|
||||||
import { retry } from "@opencode-ai/core/util/retry"
|
import { retry } from "@opencode-ai/core/util/retry"
|
||||||
import type { OpenCodeEvent, SessionApi, SessionMessageInfo } from "@opencode-ai/client/promise"
|
import type { OpenCodeEvent, SessionApi, SessionInfo, SessionMessageInfo } from "@opencode-ai/client/promise"
|
||||||
import type {
|
import type {
|
||||||
Message,
|
Message,
|
||||||
Part,
|
Part,
|
||||||
PermissionRequest,
|
|
||||||
QuestionRequest,
|
|
||||||
Session,
|
|
||||||
SessionStatus,
|
|
||||||
Todo,
|
Todo,
|
||||||
} from "@/types"
|
} from "@/types"
|
||||||
import type { LegacyCapabilities } from "@/utils/server-compat"
|
import type { FileDiffInfo, PermissionRequest, QuestionRequest, SessionStatus } from "@opencode-ai/client/promise"
|
||||||
import type { FileDiffInfo } from "@opencode-ai/client/promise"
|
|
||||||
import { batch } from "solid-js"
|
import { batch } from "solid-js"
|
||||||
import { createStore, produce, reconcile } from "solid-js/store"
|
import { createStore, produce, reconcile } from "solid-js/store"
|
||||||
import { message as cleanMessage } from "@/utils/diffs"
|
|
||||||
import { sessionNotFoundError } from "@/utils/server-errors"
|
|
||||||
import { rootSession } from "@/utils/session-route"
|
import { rootSession } from "@/utils/session-route"
|
||||||
import { normalizeSessionInfo } from "@/utils/session"
|
|
||||||
import { normalizeSessionMessages } from "@/utils/session-message"
|
import { normalizeSessionMessages } from "@/utils/session-message"
|
||||||
import { dropSessionCaches, pickSessionCacheEvictions, SESSION_CACHE_LIMIT } from "./global-sync/session-cache"
|
import { dropSessionCaches, pickSessionCacheEvictions, SESSION_CACHE_LIMIT } from "./global-sync/session-cache"
|
||||||
import { createV2SessionReducer, type V2SessionReduction } from "./server-session-v2-reducer"
|
import { createV2SessionReducer, type V2SessionReduction } from "./server-session-v2-reducer"
|
||||||
@@ -33,6 +25,29 @@ const historyMessagePageSize = 200
|
|||||||
const sessionInfoLimit = 2_048
|
const sessionInfoLimit = 2_048
|
||||||
const emptyIDs: ReadonlySet<string> = new Set()
|
const emptyIDs: ReadonlySet<string> = new Set()
|
||||||
|
|
||||||
|
function projectMessageSource(message: Message): SessionMessageInfo[] {
|
||||||
|
if (message.role === "user") {
|
||||||
|
return [
|
||||||
|
{ id: `${message.id}:agent`, type: "agent-switched", agent: message.agent, time: message.time },
|
||||||
|
{
|
||||||
|
id: `${message.id}:model`,
|
||||||
|
type: "model-switched",
|
||||||
|
model: { id: message.model.modelID, providerID: message.model.providerID, variant: message.model.variant },
|
||||||
|
time: message.time,
|
||||||
|
},
|
||||||
|
{ id: message.id, type: "user", text: "", time: message.time },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
return [{
|
||||||
|
id: message.id,
|
||||||
|
type: "assistant",
|
||||||
|
agent: message.agent ?? message.mode,
|
||||||
|
model: { id: message.modelID, providerID: message.providerID, variant: message.variant },
|
||||||
|
content: [],
|
||||||
|
time: message.time,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
function needsOlderTurnRoot(source: readonly SessionMessageInfo[]) {
|
function needsOlderTurnRoot(source: readonly SessionMessageInfo[]) {
|
||||||
const boundary = source.find(
|
const boundary = source.find(
|
||||||
(message) =>
|
(message) =>
|
||||||
@@ -61,30 +76,6 @@ type MessagePage = {
|
|||||||
complete: boolean
|
complete: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
function legacyMessageSource(items: { info: Message; parts: Part[] }[]): SessionMessageInfo[] {
|
|
||||||
return items
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => cmp(a.info.id, b.info.id))
|
|
||||||
.map((item) => {
|
|
||||||
if (item.info.role === "user") {
|
|
||||||
return {
|
|
||||||
id: item.info.id,
|
|
||||||
type: "user" as const,
|
|
||||||
text: item.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"),
|
|
||||||
time: item.info.time,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id: item.info.id,
|
|
||||||
type: "assistant" as const,
|
|
||||||
agent: item.info.agent ?? item.info.mode,
|
|
||||||
model: { id: item.info.modelID, providerID: item.info.providerID, variant: item.info.variant },
|
|
||||||
content: [],
|
|
||||||
time: item.info.time,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Most markers describe the current HTTP attempt; deltaParts persists non-durable stream state across retries.
|
// Most markers describe the current HTTP attempt; deltaParts persists non-durable stream state across retries.
|
||||||
type MessageLoadState = {
|
type MessageLoadState = {
|
||||||
touchedMessages: Set<string>
|
touchedMessages: Set<string>
|
||||||
@@ -183,22 +174,20 @@ function reconcileFetched<T extends { id: string }>(
|
|||||||
return [...result.values()].sort((a, b) => cmp(a.id, b.id))
|
return [...result.values()].sort((a, b) => cmp(a.id, b.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServerSessionOptions = {
|
type ServerSessionOptions = { retry?: typeof retry }
|
||||||
retry?: typeof retry
|
type ServerSessionApis = { session: SessionApi; message: MessageApi }
|
||||||
protocol?: Promise<"v1" | "v2">
|
|
||||||
legacy?: LegacyCapabilities
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createServerSession(
|
export function createServerSession(
|
||||||
client: { session: Pick<LegacyCapabilities["session"], "get" | "messages" | "message"> },
|
api: SessionApi | ServerSessionApis,
|
||||||
sessionApiOrOptions?: SessionApi | ServerSessionOptions,
|
messageApiOrOptions?: MessageApi | ServerSessionOptions,
|
||||||
messageApi?: MessageApi,
|
|
||||||
currentOptions?: ServerSessionOptions,
|
currentOptions?: ServerSessionOptions,
|
||||||
) {
|
) {
|
||||||
const sessionApi = messageApi ? (sessionApiOrOptions as SessionApi) : undefined
|
const bundled = "session" in api
|
||||||
const options = messageApi ? currentOptions : (sessionApiOrOptions as ServerSessionOptions | undefined)
|
const sessionApi = bundled ? api.session : api
|
||||||
|
const messageApi = bundled ? api.message : (messageApiOrOptions as MessageApi)
|
||||||
|
const options = bundled ? (messageApiOrOptions as ServerSessionOptions | undefined) : currentOptions
|
||||||
const [data, setData] = createStore({
|
const [data, setData] = createStore({
|
||||||
info: {} as Record<string, Session | undefined>,
|
info: {} as Record<string, SessionInfo | undefined>,
|
||||||
session_status: {} as Record<string, SessionStatus>,
|
session_status: {} as Record<string, SessionStatus>,
|
||||||
session_diff: {} as Record<string, FileDiffInfo[]>,
|
session_diff: {} as Record<string, FileDiffInfo[]>,
|
||||||
todo: {} as Record<string, Todo[]>,
|
todo: {} as Record<string, Todo[]>,
|
||||||
@@ -212,7 +201,7 @@ export function createServerSession(
|
|||||||
return (this.session_status[id]?.type ?? "idle") !== "idle"
|
return (this.session_status[id]?.type ?? "idle") !== "idle"
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
const requests = new Map<string, Promise<Session>>()
|
const requests = new Map<string, Promise<SessionInfo>>()
|
||||||
const inflight = new Map<string, Promise<void>>()
|
const inflight = new Map<string, Promise<void>>()
|
||||||
const inflightTodo = new Map<string, Promise<void>>()
|
const inflightTodo = new Map<string, Promise<void>>()
|
||||||
const optimistic = new Map<string, Map<string, OptimisticItem>>()
|
const optimistic = new Map<string, Map<string, OptimisticItem>>()
|
||||||
@@ -251,17 +240,17 @@ export function createServerSession(
|
|||||||
at: {} as Record<string, number | undefined>,
|
at: {} as Record<string, number | undefined>,
|
||||||
})
|
})
|
||||||
|
|
||||||
const indexLegacyMessage = (message: Message) => {
|
const indexProjectedMessage = (message: Message) => {
|
||||||
const current = data.session_message[message.sessionID] ?? []
|
const current = data.session_message[message.sessionID] ?? []
|
||||||
if (current.some((item) => item.id === message.id)) return
|
if (current.some((item) => item.id === message.id)) return
|
||||||
setData(
|
setData(
|
||||||
"session_message",
|
"session_message",
|
||||||
message.sessionID,
|
message.sessionID,
|
||||||
reconcile([...current, ...legacyMessageSource([{ info: message, parts: [] }])]),
|
reconcile([...current, ...projectMessageSource(message)]),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const remember = (session: Session) => {
|
const remember = (session: SessionInfo) => {
|
||||||
setData("info", session.id, reconcile(session))
|
setData("info", session.id, reconcile(session))
|
||||||
infoSeen.delete(session.id)
|
infoSeen.delete(session.id)
|
||||||
infoSeen.add(session.id)
|
infoSeen.add(session.id)
|
||||||
@@ -311,12 +300,7 @@ export function createServerSession(
|
|||||||
const pending = requests.get(sessionID)
|
const pending = requests.get(sessionID)
|
||||||
if (pending) return pending
|
if (pending) return pending
|
||||||
const active = generation(sessionID)
|
const active = generation(sessionID)
|
||||||
const request = sessionApi
|
const request = sessionApi.get({ sessionID })
|
||||||
? sessionApi.get({ sessionID }).then(normalizeSessionInfo)
|
|
||||||
: client.session.get({ sessionID }).then((result) => {
|
|
||||||
if (!result.data) throw sessionNotFoundError(sessionID)
|
|
||||||
return result.data
|
|
||||||
})
|
|
||||||
const resolved = request.then((result) => {
|
const resolved = request.then((result) => {
|
||||||
if (generations.get(sessionID) !== active) return result
|
if (generations.get(sessionID) !== active) return result
|
||||||
return remember(result)
|
return remember(result)
|
||||||
@@ -542,72 +526,43 @@ export function createServerSession(
|
|||||||
)
|
)
|
||||||
|
|
||||||
const fetchMessages = async (sessionID: string, limit: number, before?: string, onAttempt?: () => void) => {
|
const fetchMessages = async (sessionID: string, limit: number, before?: string, onAttempt?: () => void) => {
|
||||||
if (messageApi && (await options?.protocol) !== "v1") {
|
const request = (cursor?: string) =>
|
||||||
const request = (cursor?: string) =>
|
(options?.retry ?? retry)(() => {
|
||||||
(options?.retry ?? retry)(() => {
|
onAttempt?.()
|
||||||
onAttempt?.()
|
return messageApi.list(cursor ? { sessionID, limit, cursor } : { sessionID, limit, order: "desc" })
|
||||||
return messageApi.list(cursor ? { sessionID, limit, cursor } : { sessionID, limit, order: "desc" })
|
})
|
||||||
})
|
const first = await request(before)
|
||||||
const first = await request(before)
|
const pages = [first]
|
||||||
const pages = [first]
|
while (pages.at(-1)?.cursor.next && needsOlderTurnRoot(pages.flatMap((page) => page.data).toReversed())) {
|
||||||
while (pages.at(-1)?.cursor.next && needsOlderTurnRoot(pages.flatMap((page) => page.data).toReversed())) {
|
const response = await request(pages.at(-1)!.cursor.next ?? undefined)
|
||||||
const response = await request(pages.at(-1)!.cursor.next ?? undefined)
|
pages.push(response)
|
||||||
pages.push(response)
|
if (!response.data.length) break
|
||||||
if (!response.data.length) break
|
|
||||||
}
|
|
||||||
const response = pages.at(-1)!
|
|
||||||
const source = pages.flatMap((page) => page.data).toReversed()
|
|
||||||
const normalized = normalizeSessionMessages(sessionID, source)
|
|
||||||
return {
|
|
||||||
session: normalized.messages.sort((a, b) => cmp(a.id, b.id)),
|
|
||||||
part: [...normalized.parts.entries()]
|
|
||||||
.map(([id, part]) => ({ id, part: part.sort((a, b) => cmp(a.id, b.id)) }))
|
|
||||||
.sort((a, b) => cmp(a.id, b.id)),
|
|
||||||
source,
|
|
||||||
sourceMode: before ? ("older" as const) : ("latest" as const),
|
|
||||||
projectSource: true,
|
|
||||||
cursor: response.cursor.next ?? undefined,
|
|
||||||
complete: !response.cursor.next,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const response = await (options?.retry ?? retry)(() => {
|
const response = pages.at(-1)!
|
||||||
onAttempt?.()
|
const source = pages.flatMap((page) => page.data).toReversed()
|
||||||
return client.session.messages({ sessionID, limit, before })
|
const normalized = normalizeSessionMessages(sessionID, source)
|
||||||
})
|
|
||||||
const items = (response.data ?? []).filter((item) => !!item?.info?.id)
|
|
||||||
return {
|
return {
|
||||||
session: items.map((item) => cleanMessage(item.info)).sort((a, b) => cmp(a.id, b.id)),
|
session: normalized.messages.sort((a, b) => cmp(a.id, b.id)),
|
||||||
part: items.map((item) => ({
|
part: [...normalized.parts.entries()]
|
||||||
id: item.info.id,
|
.map(([id, part]) => ({ id, part: part.sort((a, b) => cmp(a.id, b.id)) }))
|
||||||
part: item.parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id)),
|
.sort((a, b) => cmp(a.id, b.id)),
|
||||||
})),
|
source,
|
||||||
source: legacyMessageSource(items),
|
|
||||||
sourceMode: before ? ("older" as const) : ("latest" as const),
|
sourceMode: before ? ("older" as const) : ("latest" as const),
|
||||||
cursor: response.response.headers.get("x-next-cursor") ?? undefined,
|
projectSource: true,
|
||||||
complete: !response.response.headers.get("x-next-cursor"),
|
cursor: response.cursor.next ?? undefined,
|
||||||
|
complete: !response.cursor.next,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchMessage = async (sessionID: string, messageID: string, onAttempt?: () => void) => {
|
const fetchMessage = async (sessionID: string, messageID: string, onAttempt?: () => void) => {
|
||||||
if (sessionApi && (await options?.protocol) !== "v1") {
|
|
||||||
const response = await (options?.retry ?? retry)(() => {
|
|
||||||
onAttempt?.()
|
|
||||||
return sessionApi.message({ sessionID, messageID })
|
|
||||||
})
|
|
||||||
const normalized = normalizeSessionMessages(sessionID, [response])
|
|
||||||
const message = normalized.messages[0]
|
|
||||||
if (!message) throw new Error(`Message not found: ${messageID}`)
|
|
||||||
return { message, parts: normalized.parts.get(messageID) ?? [] }
|
|
||||||
}
|
|
||||||
const response = await (options?.retry ?? retry)(() => {
|
const response = await (options?.retry ?? retry)(() => {
|
||||||
onAttempt?.()
|
onAttempt?.()
|
||||||
return client.session.message({ sessionID, messageID })
|
return sessionApi.message({ sessionID, messageID })
|
||||||
})
|
})
|
||||||
if (!response.data?.info?.id) throw new Error(`Message not found: ${messageID}`)
|
const normalized = normalizeSessionMessages(sessionID, [response])
|
||||||
return {
|
const message = normalized.messages[0]
|
||||||
message: cleanMessage(response.data.info),
|
if (!message) throw new Error(`Message not found: ${messageID}`)
|
||||||
parts: response.data.parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id)),
|
return { message, parts: normalized.parts.get(messageID) ?? [] }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const replaceMessages = (sessionID: string, messages: Message[]) => {
|
const replaceMessages = (sessionID: string, messages: Message[]) => {
|
||||||
@@ -961,9 +916,8 @@ export function createServerSession(
|
|||||||
remember({
|
remember({
|
||||||
...info,
|
...info,
|
||||||
projectID: event.data.projectID ?? info.projectID,
|
projectID: event.data.projectID ?? info.projectID,
|
||||||
workspaceID: event.data.location.workspaceID,
|
location: event.data.location,
|
||||||
directory: event.data.location.directory,
|
subpath: event.data.subpath,
|
||||||
path: event.data.subpath,
|
|
||||||
time: { ...info.time, updated: event.created },
|
time: { ...info.time, updated: event.created },
|
||||||
})
|
})
|
||||||
if (event.type === "session.usage.updated" && info)
|
if (event.type === "session.usage.updated" && info)
|
||||||
@@ -1009,16 +963,17 @@ export function createServerSession(
|
|||||||
}
|
}
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case "session.created":
|
case "session.created":
|
||||||
remember((event.properties as { info: Session }).info)
|
if ((event.properties as { info?: SessionInfo }).info)
|
||||||
|
remember((event.properties as { info: SessionInfo }).info)
|
||||||
return
|
return
|
||||||
case "session.updated": {
|
case "session.updated": {
|
||||||
const info = (event.properties as { info: Session }).info
|
const info = (event.properties as { info: SessionInfo }).info
|
||||||
remember(info)
|
remember(info)
|
||||||
if (info.time.archived) evict([info.id])
|
if (info.time.archived) evict([info.id])
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
case "session.deleted": {
|
case "session.deleted": {
|
||||||
const properties = event.properties as { sessionID?: string; info?: Session }
|
const properties = event.properties as { sessionID?: string; info?: SessionInfo }
|
||||||
const sessionID = properties.info?.id ?? properties.sessionID
|
const sessionID = properties.info?.id ?? properties.sessionID
|
||||||
if (!sessionID) return
|
if (!sessionID) return
|
||||||
infoSeen.delete(sessionID)
|
infoSeen.delete(sessionID)
|
||||||
@@ -1040,8 +995,8 @@ export function createServerSession(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
case "message.updated": {
|
case "message.updated": {
|
||||||
const info = cleanMessage((event.properties as { info: Message }).info)
|
const info = (event.properties as { info: Message }).info
|
||||||
indexLegacyMessage(info)
|
indexProjectedMessage(info)
|
||||||
const load = messageLoads.get(info.sessionID)
|
const load = messageLoads.get(info.sessionID)
|
||||||
load?.touchedMessages.add(info.id)
|
load?.touchedMessages.add(info.id)
|
||||||
load?.removedMessages.delete(info.id)
|
load?.removedMessages.delete(info.id)
|
||||||
@@ -1392,19 +1347,8 @@ export function createServerSession(
|
|||||||
async todo(sessionID: string, request?: { force?: boolean }) {
|
async todo(sessionID: string, request?: { force?: boolean }) {
|
||||||
touch(sessionID)
|
touch(sessionID)
|
||||||
if (data.todo[sessionID] !== undefined && !request?.force) return
|
if (data.todo[sessionID] !== undefined && !request?.force) return
|
||||||
if ((await options?.protocol) === "v2") {
|
// TODO: Restore todos when the V2 client exposes a session todo API.
|
||||||
// TODO: Restore todos when the V2 API exposes a session todo snapshot.
|
setData("todo", sessionID, [])
|
||||||
setData("todo", sessionID, [])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return runInflight(inflightTodo, sessionID, () => {
|
|
||||||
const active = generation(sessionID)
|
|
||||||
if (!options?.legacy) return Promise.resolve()
|
|
||||||
return (options.retry ?? retry)(() => options.legacy!.session.todo(sessionID)).then((result) => {
|
|
||||||
if (generations.get(sessionID) !== active) return
|
|
||||||
setData("todo", sessionID, reconcile(result, { key: "id" }))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
history: {
|
history: {
|
||||||
more: (sessionID: string) =>
|
more: (sessionID: string) =>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client"
|
|
||||||
import type {
|
import type {
|
||||||
McpListInput,
|
McpListInput,
|
||||||
McpResourceCatalogInput,
|
McpResourceCatalogInput,
|
||||||
@@ -84,7 +83,7 @@ describe("active session query", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("does not overwrite statuses already written by events", () => {
|
test("does not overwrite statuses already written by events", () => {
|
||||||
const session = createServerSession({} as OpencodeClient)
|
const session = createServerSession({} as ServerApi["session"], {} as ServerApi["message"])
|
||||||
session.set("session_status", "ses_retry", { type: "retry", attempt: 2, message: "retrying", next: 10 })
|
session.set("session_status", "ses_retry", { type: "retry", attempt: 2, message: "retrying", next: 10 })
|
||||||
|
|
||||||
seedActiveSessionStatuses(session, {
|
seedActiveSessionStatuses(session, {
|
||||||
@@ -124,7 +123,7 @@ describe("pickDirectoriesToEvict", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe("loadRootSessions", () => {
|
describe("loadRootSessions", () => {
|
||||||
test("loads and normalizes a limited page of root sessions", async () => {
|
test("loads a limited page of root sessions", async () => {
|
||||||
const calls: SessionListInput[] = []
|
const calls: SessionListInput[] = []
|
||||||
|
|
||||||
const result = await loadRootSessions({
|
const result = await loadRootSessions({
|
||||||
@@ -138,9 +137,7 @@ describe("loadRootSessions", () => {
|
|||||||
limit: 10,
|
limit: 10,
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(result.data).toEqual([
|
expect(result.data).toEqual([expect.objectContaining({ id: "session-1", location: { directory: "dir" } })])
|
||||||
expect.objectContaining({ id: "session-1", directory: "dir", slug: "session-1", version: "" }),
|
|
||||||
])
|
|
||||||
expect(result.limited).toBe(true)
|
expect(result.limited).toBe(true)
|
||||||
expect(calls).toEqual([{ directory: "dir", parentID: null, limit: 10, order: "desc" }])
|
expect(calls).toEqual([{ directory: "dir", parentID: null, limit: 10, order: "desc" }])
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import type {
|
|||||||
Path,
|
Path,
|
||||||
Project,
|
Project,
|
||||||
ProviderAuthResponse,
|
ProviderAuthResponse,
|
||||||
SessionStatus,
|
|
||||||
} from "@/types"
|
} from "@/types"
|
||||||
import { showToast } from "@/utils/toast"
|
import { showToast } from "@/utils/toast"
|
||||||
import { getFilename } from "@opencode-ai/core/util/path"
|
import { getFilename } from "@opencode-ai/core/util/path"
|
||||||
@@ -55,11 +54,11 @@ import type {
|
|||||||
McpResourceCatalogOutput,
|
McpResourceCatalogOutput,
|
||||||
McpServer,
|
McpServer,
|
||||||
SessionActiveOutput,
|
SessionActiveOutput,
|
||||||
|
SessionStatus,
|
||||||
} from "@opencode-ai/client/promise"
|
} from "@opencode-ai/client/promise"
|
||||||
import { toggleMcp } from "./global-sync/mcp"
|
import { toggleMcp } from "./global-sync/mcp"
|
||||||
import { createServerSession, type ServerSession } from "./server-session"
|
import { createServerSession, type ServerSession } from "./server-session"
|
||||||
import { usePlatform } from "./platform"
|
import { usePlatform } from "./platform"
|
||||||
import type { LegacyCapabilities } from "@/utils/server-compat"
|
|
||||||
|
|
||||||
type GlobalStore = {
|
type GlobalStore = {
|
||||||
ready: boolean
|
ready: boolean
|
||||||
@@ -132,11 +131,11 @@ export const loadMcpResourcesQuery = (
|
|||||||
placeholderData: {},
|
placeholderData: {},
|
||||||
})
|
})
|
||||||
|
|
||||||
export const loadLspQuery = (scope: ServerScope, directory: string, legacy: LegacyCapabilities, enabled = true) =>
|
export const loadLspQuery = (scope: ServerScope, directory: string) =>
|
||||||
queryOptions({
|
queryOptions({
|
||||||
queryKey: [scope, directory, "lsp"] as const,
|
queryKey: [scope, directory, "lsp"] as const,
|
||||||
queryFn: () => legacy.lsp.status(directory),
|
// TODO: Restore LSP status when the V2 client exposes an LSP API.
|
||||||
enabled,
|
queryFn: async () => [],
|
||||||
})
|
})
|
||||||
|
|
||||||
export const loadActiveSessionsQuery = (
|
export const loadActiveSessionsQuery = (
|
||||||
@@ -168,19 +167,18 @@ export function seedActiveSessionStatuses(
|
|||||||
function makeQueryOptionsApi(
|
function makeQueryOptionsApi(
|
||||||
scope: ServerScope,
|
scope: ServerScope,
|
||||||
serverAPI: ServerApi,
|
serverAPI: ServerApi,
|
||||||
protocolKind: Accessor<"v1" | "v2" | undefined>,
|
|
||||||
legacy: LegacyCapabilities,
|
|
||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
globalConfig: () => loadGlobalConfigQuery(scope, legacy, protocolKind() === "v1"),
|
globalConfig: () => loadGlobalConfigQuery(scope),
|
||||||
projects: () => loadProjectsQuery(scope, serverAPI.project),
|
projects: () => loadProjectsQuery(scope, serverAPI.project),
|
||||||
providers: (directory: PathKey | null) => loadProvidersQuery(scope, directory, serverAPI),
|
providers: (directory: PathKey | null) =>
|
||||||
|
loadProvidersQuery(scope, directory, serverAPI),
|
||||||
path: (directory: PathKey | null) => loadPathQuery(scope, directory, serverAPI.location),
|
path: (directory: PathKey | null) => loadPathQuery(scope, directory, serverAPI.location),
|
||||||
agents: (directory: PathKey) => loadAgentsQuery(scope, directory, serverAPI.agent),
|
agents: (directory: PathKey) => loadAgentsQuery(scope, directory, serverAPI.agent),
|
||||||
references: (directory: PathKey) => loadReferencesQuery(scope, directory, serverAPI.reference),
|
references: (directory: PathKey) => loadReferencesQuery(scope, directory, serverAPI.reference),
|
||||||
mcp: (directory: PathKey) => loadMcpQuery(scope, directory, serverAPI.mcp),
|
mcp: (directory: PathKey) => loadMcpQuery(scope, directory, serverAPI.mcp),
|
||||||
mcpResources: (directory: PathKey) => loadMcpResourcesQuery(scope, directory, serverAPI.mcp),
|
mcpResources: (directory: PathKey) => loadMcpResourcesQuery(scope, directory, serverAPI.mcp),
|
||||||
lsp: (directory: PathKey) => loadLspQuery(scope, directory, legacy, protocolKind() === "v1"),
|
lsp: (directory: PathKey) => loadLspQuery(scope, directory),
|
||||||
sessions: (directory: PathKey) => ({ queryKey: [scope, directory, "loadSessions"] as const }),
|
sessions: (directory: PathKey) => ({ queryKey: [scope, directory, "loadSessions"] as const }),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -196,21 +194,8 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
const sessionLoads = new Map<string, Promise<void>>()
|
const sessionLoads = new Map<string, Promise<void>>()
|
||||||
const sessionMeta = new Map<string, { limit: number }>()
|
const sessionMeta = new Map<string, { limit: number }>()
|
||||||
|
|
||||||
const session = createServerSession(
|
const session = createServerSession(serverSDK.api.session, serverSDK.api.message)
|
||||||
{ session: serverSDK.legacy.session },
|
const queryOptionsApi = makeQueryOptionsApi(serverSDK.scope, serverSDK.api)
|
||||||
serverSDK.currentApi.session,
|
|
||||||
serverSDK.currentApi.message,
|
|
||||||
{
|
|
||||||
protocol: serverSDK.protocol,
|
|
||||||
legacy: serverSDK.legacy,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
const queryOptionsApi = makeQueryOptionsApi(
|
|
||||||
serverSDK.scope,
|
|
||||||
serverSDK.currentApi,
|
|
||||||
serverSDK.protocolKind,
|
|
||||||
serverSDK.legacy,
|
|
||||||
)
|
|
||||||
|
|
||||||
const [configQuery, providerQuery, pathQuery] = useQueries(() => ({
|
const [configQuery, providerQuery, pathQuery] = useQueries(() => ({
|
||||||
queries: [queryOptionsApi.globalConfig(), queryOptionsApi.providers(null), queryOptionsApi.path(null)],
|
queries: [queryOptionsApi.globalConfig(), queryOptionsApi.providers(null), queryOptionsApi.path(null)],
|
||||||
@@ -218,7 +203,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
const activeSessionsQuery = useQuery(() =>
|
const activeSessionsQuery = useQuery(() =>
|
||||||
loadActiveSessionsQuery(serverSDK.scope, {
|
loadActiveSessionsQuery(serverSDK.scope, {
|
||||||
active: async () => {
|
active: async () => {
|
||||||
const active = await serverSDK.currentApi.session.active()
|
const active = await serverSDK.api.session.active()
|
||||||
seedActiveSessionStatuses(session, active)
|
seedActiveSessionStatuses(session, active)
|
||||||
for (const sessionID of Object.keys(active)) {
|
for (const sessionID of Object.keys(active)) {
|
||||||
void session.resolve(sessionID).catch(() => undefined)
|
void session.resolve(sessionID).catch(() => undefined)
|
||||||
@@ -286,9 +271,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
queryKey: [serverSDK.scope, "bootstrap"],
|
queryKey: [serverSDK.scope, "bootstrap"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
await bootstrapGlobal({
|
await bootstrapGlobal({
|
||||||
legacy: serverSDK.legacy,
|
serverAPI: serverSDK.api,
|
||||||
serverAPI: serverSDK.currentApi,
|
|
||||||
protocol: serverSDK.protocol,
|
|
||||||
scope: serverSDK.scope,
|
scope: serverSDK.scope,
|
||||||
requestFailedTitle: language.t("common.requestFailed"),
|
requestFailedTitle: language.t("common.requestFailed"),
|
||||||
translate: language.t,
|
translate: language.t,
|
||||||
@@ -328,7 +311,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
void bootstrapInstance(directory)
|
void bootstrapInstance(directory)
|
||||||
},
|
},
|
||||||
onMcp: (directory, setStore) => {
|
onMcp: (directory, setStore) => {
|
||||||
void loadCommands(directory, serverSDK.currentApi.command)
|
void loadCommands(directory, serverSDK.api.command)
|
||||||
.then((commands) => setStore("command", commands))
|
.then((commands) => setStore("command", commands))
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
showToast({
|
showToast({
|
||||||
@@ -380,7 +363,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
.fetchQuery({
|
.fetchQuery({
|
||||||
...queryOptionsApi.sessions(key),
|
...queryOptionsApi.sessions(key),
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
loadRootSessions({ api: serverSDK.currentApi.session, directory, limit })
|
loadRootSessions({ api: serverSDK.api.session, directory, limit })
|
||||||
.then((x) => {
|
.then((x) => {
|
||||||
const nonArchived = (x.data ?? [])
|
const nonArchived = (x.data ?? [])
|
||||||
.filter((s) => !!s?.id)
|
.filter((s) => !!s?.id)
|
||||||
@@ -448,8 +431,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
project: globalStore.project,
|
project: globalStore.project,
|
||||||
provider: globalStore.provider,
|
provider: globalStore.provider,
|
||||||
},
|
},
|
||||||
legacy: serverSDK.legacy,
|
api: serverSDK.api,
|
||||||
api: serverSDK.currentApi,
|
|
||||||
store: child[0],
|
store: child[0],
|
||||||
setStore: child[1],
|
setStore: child[1],
|
||||||
vcsCache: cache,
|
vcsCache: cache,
|
||||||
@@ -457,7 +439,6 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
translate: language.t,
|
translate: language.t,
|
||||||
queryClient,
|
queryClient,
|
||||||
session,
|
session,
|
||||||
protocol: serverSDK.protocol,
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -470,7 +451,7 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const indexSession = (info: Parameters<typeof session.remember>[0]) => {
|
const indexSession = (info: Parameters<typeof session.remember>[0]) => {
|
||||||
const key = directoryKey(info.directory)
|
const key = directoryKey(info.location.directory)
|
||||||
const existing = children.children[key]
|
const existing = children.children[key]
|
||||||
if (!existing) return
|
if (!existing) return
|
||||||
applyDirectoryEvent({
|
applyDirectoryEvent({
|
||||||
@@ -495,8 +476,25 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
|
|
||||||
if (event.current) session.applyV2(event.current)
|
if (event.current) session.applyV2(event.current)
|
||||||
session.apply(event)
|
session.apply(event)
|
||||||
if (event.type === "session.created" || event.type === "session.updated" || event.type === "session.deleted") {
|
if (event.current?.type === "session.created")
|
||||||
homeSessions.apply(event)
|
void session
|
||||||
|
.resolve(event.current.data.sessionID, { force: true })
|
||||||
|
.then((info) => {
|
||||||
|
if (!session.get(info.id)) return
|
||||||
|
indexSession(info)
|
||||||
|
homeSessions.apply({
|
||||||
|
type: "session.created",
|
||||||
|
properties: { sessionID: info.id, info },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
if (event.current?.type === "session.deleted")
|
||||||
|
homeSessions.apply({
|
||||||
|
type: "session.deleted",
|
||||||
|
properties: { sessionID: event.current.data.sessionID },
|
||||||
|
})
|
||||||
|
if (event.type === "session.created" || event.type === "session.deleted") {
|
||||||
|
if ("info" in event.properties) homeSessions.apply(event as Parameters<typeof homeSessions.apply>[0])
|
||||||
}
|
}
|
||||||
homeSessions.refresh(event.type)
|
homeSessions.refresh(event.type)
|
||||||
if (eventType === "integration.connection.updated") void refreshProviders()
|
if (eventType === "integration.connection.updated") void refreshProviders()
|
||||||
@@ -568,7 +566,6 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
permission: session.data.permission,
|
permission: session.data.permission,
|
||||||
vcsCache: children.vcsCache.get(key),
|
vcsCache: children.vcsCache.get(key),
|
||||||
loadLsp: () => {
|
loadLsp: () => {
|
||||||
if (serverSDK.protocolKind() !== "v1") return
|
|
||||||
if (!children.active(key)) return
|
if (!children.active(key)) return
|
||||||
void queryClient.fetchQuery(queryOptionsApi.lsp(key))
|
void queryClient.fetchQuery(queryOptionsApi.lsp(key))
|
||||||
},
|
},
|
||||||
@@ -617,7 +614,11 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updateConfigMutation = useMutation(() => ({
|
const updateConfigMutation = useMutation(() => ({
|
||||||
mutationFn: (config: Config) => serverSDK.legacy.config.update(config),
|
mutationFn: async (config: Config) => {
|
||||||
|
// TODO: Restore config updates when the V2 client exposes a config API.
|
||||||
|
// await serverSDK.api.config.update({ config })
|
||||||
|
throw new Error(`Config updates are unavailable: ${Object.keys(config).length} fields were not saved`)
|
||||||
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
bootstrap.refetch()
|
bootstrap.refetch()
|
||||||
// Invalidate all provider queries so newly configured custom providers
|
// Invalidate all provider queries so newly configured custom providers
|
||||||
@@ -656,24 +657,24 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
await toggleMcp({
|
await toggleMcp({
|
||||||
status,
|
status,
|
||||||
connect: async () => {
|
connect: async () => {
|
||||||
await serverSDK.currentApi.mcp.connect({ server: name, location: { directory: key } })
|
await serverSDK.api.mcp.connect({ server: name, location: { directory: key } })
|
||||||
},
|
},
|
||||||
disconnect: async () => {
|
disconnect: async () => {
|
||||||
await serverSDK.currentApi.mcp.disconnect({ server: name, location: { directory: key } })
|
await serverSDK.api.mcp.disconnect({ server: name, location: { directory: key } })
|
||||||
},
|
},
|
||||||
authenticate: async () => {
|
authenticate: async () => {
|
||||||
const server = (await serverSDK.currentApi.mcp.list({ location: { directory: key } })).data.find(
|
const server = (await serverSDK.api.mcp.list({ location: { directory: key } })).data.find(
|
||||||
(item) => item.name === name,
|
(item) => item.name === name,
|
||||||
)
|
)
|
||||||
if (!server?.integrationID) throw new Error(`MCP server ${name} has no authentication integration`)
|
if (!server?.integrationID) throw new Error(`MCP server ${name} has no authentication integration`)
|
||||||
const integration = await serverSDK.currentApi.integration.get({
|
const integration = await serverSDK.api.integration.get({
|
||||||
integrationID: server.integrationID,
|
integrationID: server.integrationID,
|
||||||
location: { directory: key },
|
location: { directory: key },
|
||||||
})
|
})
|
||||||
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.prompts?.length)
|
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.prompts?.length)
|
||||||
if (!method || method.type !== "oauth")
|
if (!method || method.type !== "oauth")
|
||||||
throw new Error(`MCP server ${name} requires an interactive authentication form`)
|
throw new Error(`MCP server ${name} requires an interactive authentication form`)
|
||||||
const attempt = await serverSDK.currentApi.integration.oauth.connect({
|
const attempt = await serverSDK.api.integration.oauth.connect({
|
||||||
integrationID: server.integrationID,
|
integrationID: server.integrationID,
|
||||||
methodID: method.id,
|
methodID: method.id,
|
||||||
inputs: {},
|
inputs: {},
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { createSimpleContext } from "@opencode-ai/ui/context"
|
import { createSimpleContext } from "@opencode-ai/ui/context"
|
||||||
import { createStore, produce } from "solid-js/store"
|
import { createStore, produce } from "solid-js/store"
|
||||||
import { Persist, persisted, removePersisted, draftPersistedKeys } from "@/utils/persist"
|
import { Persist, persisted, removePersisted, draftPersistedKeys } from "@/utils/persist"
|
||||||
@@ -45,7 +45,7 @@ export const tabHref = (tab: Tab) =>
|
|||||||
|
|
||||||
export const tabKey = (tab: Tab) => (tab.type === "draft" ? `draft:${tab.draftID}` : `${tab.server}\n${tabHref(tab)}`)
|
export const tabKey = (tab: Tab) => (tab.type === "draft" ? `draft:${tab.draftID}` : `${tab.server}\n${tabHref(tab)}`)
|
||||||
|
|
||||||
export function sessionHasOpenTab(tabs: Tab[], server: ServerConnection.Key, session: Session) {
|
export function sessionHasOpenTab(tabs: Tab[], server: ServerConnection.Key, session: SessionInfo) {
|
||||||
return tabs.some((tab) => tab.type === "session" && tab.server === server && tab.sessionId === session.id)
|
return tabs.some((tab) => tab.type === "session" && tab.server === server && tab.sessionId === session.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,10 +349,11 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
|
|||||||
for (const key of removed) memory.remove(key)
|
for (const key of removed) memory.remove(key)
|
||||||
for (const key of removed) removeInfo(key)
|
for (const key of removed) removeInfo(key)
|
||||||
},
|
},
|
||||||
rememberSessionInfo(tab: SessionTab, session: Session) {
|
rememberSessionInfo(tab: SessionTab, session: SessionInfo) {
|
||||||
const key = tabKey(tab)
|
const key = tabKey(tab)
|
||||||
const next = { title: session.title, directory: session.directory }
|
const next = { title: session.title, directory: session.location.directory }
|
||||||
const current = info[key]
|
const current = info[key]
|
||||||
|
console.log({ tab, session, current })
|
||||||
if (current?.title === next.title && current.directory === next.directory) return
|
if (current?.title === next.title && current.directory === next.directory) return
|
||||||
setInfo(key, next)
|
setInfo(key, next)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -248,7 +248,7 @@ function createWorkspaceTerminalSession(
|
|||||||
setStore("all", index, (item) => ({ ...item, ...pty }))
|
setStore("all", index, (item) => ({ ...item, ...pty }))
|
||||||
}
|
}
|
||||||
const doUpdate = async () => {
|
const doUpdate = async () => {
|
||||||
await sdk.currentApi.pty.update({
|
await sdk.api.pty.update({
|
||||||
ptyID: pty.id,
|
ptyID: pty.id,
|
||||||
location,
|
location,
|
||||||
title: pty.title,
|
title: pty.title,
|
||||||
@@ -268,13 +268,10 @@ function createWorkspaceTerminalSession(
|
|||||||
const index = store.all.findIndex((x) => x.id === id)
|
const index = store.all.findIndex((x) => x.id === id)
|
||||||
const pty = store.all[index]
|
const pty = store.all[index]
|
||||||
if (!pty) return
|
if (!pty) return
|
||||||
const data = await sdk.currentApi.pty
|
const data = await sdk.api.pty.create({ location, title: pty.title }).then((result) => result.data).catch((error: unknown) => {
|
||||||
.create({ location, title: pty.title })
|
console.error("Failed to clone terminal", error)
|
||||||
.then((result) => result.data)
|
return undefined
|
||||||
.catch((error: unknown) => {
|
})
|
||||||
console.error("Failed to clone terminal", error)
|
|
||||||
return undefined
|
|
||||||
})
|
|
||||||
if (!data?.id) return
|
if (!data?.id) return
|
||||||
|
|
||||||
const active = store.active === pty.id
|
const active = store.active === pty.id
|
||||||
@@ -311,9 +308,7 @@ function createWorkspaceTerminalSession(
|
|||||||
const focusRequest = options?.focus ? requestFocus(undefined, true) : undefined
|
const focusRequest = options?.focus ? requestFocus(undefined, true) : undefined
|
||||||
|
|
||||||
const doCreate = async () => {
|
const doCreate = async () => {
|
||||||
return sdk.currentApi.pty
|
return sdk.api.pty.create({ location, title: defaultTitle(nextNumber) }).then((result) => result.data)
|
||||||
.create({ location, title: defaultTitle(nextNumber) })
|
|
||||||
.then((result) => result.data)
|
|
||||||
}
|
}
|
||||||
doCreate()
|
doCreate()
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
@@ -417,7 +412,7 @@ function createWorkspaceTerminalSession(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
await sdk.currentApi.pty.remove({ ptyID: id, location }).catch((error: unknown) => {
|
await sdk.api.pty.remove({ ptyID: id, location }).catch((error: unknown) => {
|
||||||
console.error("Failed to close terminal", error)
|
console.error("Failed to close terminal", error)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ test("archiving a Home session removes its open titlebar tab", async () => {
|
|||||||
|
|
||||||
await archiveHomeSession({
|
await archiveHomeSession({
|
||||||
server: remote,
|
server: remote,
|
||||||
session: { id: "ses_1", directory: "/workspace" },
|
session: { id: "ses_1", location: { directory: "/workspace" } },
|
||||||
archive: async () => undefined,
|
archive: async () => undefined,
|
||||||
remove: () => {
|
remove: () => {
|
||||||
removed = true
|
removed = true
|
||||||
@@ -36,7 +36,7 @@ test("reports archive failures without removing the session", async () => {
|
|||||||
|
|
||||||
await archiveHomeSession({
|
await archiveHomeSession({
|
||||||
server: remote,
|
server: remote,
|
||||||
session: { id: "ses_1", directory: "/workspace" },
|
session: { id: "ses_1", location: { directory: "/workspace" } },
|
||||||
archive: async () => Promise.reject(failure),
|
archive: async () => Promise.reject(failure),
|
||||||
remove: () => {
|
remove: () => {
|
||||||
removed = true
|
removed = true
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { notifySessionTabsRemoved } from "@/components/titlebar-session-events"
|
import { notifySessionTabsRemoved } from "@/components/titlebar-session-events"
|
||||||
import type { ServerConnection } from "@/context/server"
|
import type { ServerConnection } from "@/context/server"
|
||||||
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
|
|
||||||
type HomeSession = {
|
type HomeSession = Pick<SessionInfo, "id" | "location">
|
||||||
id: string
|
|
||||||
directory: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function archiveHomeSession(input: {
|
export async function archiveHomeSession(input: {
|
||||||
server: ServerConnection.Key
|
server: ServerConnection.Key
|
||||||
@@ -19,7 +17,7 @@ export async function archiveHomeSession(input: {
|
|||||||
input.remove()
|
input.remove()
|
||||||
notifySessionTabsRemoved({
|
notifySessionTabsRemoved({
|
||||||
server: input.server,
|
server: input.server,
|
||||||
directory: input.session.directory,
|
directory: input.session.location.directory,
|
||||||
sessionIDs: [input.session.id],
|
sessionIDs: [input.session.id],
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -109,7 +109,6 @@ export function createHomeProjectsController(home: HomeController) {
|
|||||||
home.server.context(conn).projects.move(worktree, index)
|
home.server.context(conn).projects.move(worktree, index)
|
||||||
},
|
},
|
||||||
canReveal: canRevealProject,
|
canReveal: canRevealProject,
|
||||||
canEdit: (conn: ServerConnection.Any) => home.server.context(conn).sdk.protocolKind() === "v1",
|
|
||||||
reveal: (conn: ServerConnection.Any, project: LocalProject) => {
|
reveal: (conn: ServerConnection.Any, project: LocalProject) => {
|
||||||
if (!platform.openPath || !canRevealProject(conn)) return
|
if (!platform.openPath || !canRevealProject(conn)) return
|
||||||
platform.openPath(project.worktree).catch((cause: unknown) =>
|
platform.openPath(project.worktree).catch((cause: unknown) =>
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ export type HomeProjectsViewProps = {
|
|||||||
canDefaultServer: Accessor<boolean>
|
canDefaultServer: Accessor<boolean>
|
||||||
defaultServerKey: Accessor<ServerConnection.Key | null | undefined>
|
defaultServerKey: Accessor<ServerConnection.Key | null | undefined>
|
||||||
canRevealProject: (server: ServerConnection.Any) => boolean
|
canRevealProject: (server: ServerConnection.Any) => boolean
|
||||||
canEditProject: (server: ServerConnection.Any) => boolean
|
|
||||||
unseenCount: (server: ServerConnection.Any, project: LocalProject) => number
|
unseenCount: (server: ServerConnection.Any, project: LocalProject) => number
|
||||||
onWheel: (event: WheelEvent) => void
|
onWheel: (event: WheelEvent) => void
|
||||||
onChooseProject: (server: ServerConnection.Any) => void
|
onChooseProject: (server: ServerConnection.Any) => void
|
||||||
@@ -549,11 +548,9 @@ function HomeProjectRow(
|
|||||||
<MenuV2.Item onSelect={() => props.onOpenProjectNewSession(props.server, props.project.worktree)}>
|
<MenuV2.Item onSelect={() => props.onOpenProjectNewSession(props.server, props.project.worktree)}>
|
||||||
{props.language.t("command.session.new")}
|
{props.language.t("command.session.new")}
|
||||||
</MenuV2.Item>
|
</MenuV2.Item>
|
||||||
<Show when={props.canEditProject(props.server)}>
|
<MenuV2.Item onSelect={() => props.onEditProject(props.server, props.project)}>
|
||||||
<MenuV2.Item onSelect={() => props.onEditProject(props.server, props.project)}>
|
{props.language.t("dialog.project.edit.title")}
|
||||||
{props.language.t("dialog.project.edit.title")}
|
</MenuV2.Item>
|
||||||
</MenuV2.Item>
|
|
||||||
</Show>
|
|
||||||
<Show when={props.canRevealProject(props.server)}>
|
<Show when={props.canRevealProject(props.server)}>
|
||||||
<MenuV2.Item onSelect={() => props.onRevealProject(props.server, props.project)}>
|
<MenuV2.Item onSelect={() => props.onRevealProject(props.server, props.project)}>
|
||||||
{props.language.t(
|
{props.language.t(
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ export function HomeProjects(props: { projects: HomeProjectsController; scroll:
|
|||||||
canDefaultServer={props.projects.server.canDefault}
|
canDefaultServer={props.projects.server.canDefault}
|
||||||
defaultServerKey={props.projects.server.defaultKey}
|
defaultServerKey={props.projects.server.defaultKey}
|
||||||
canRevealProject={props.projects.project.canReveal}
|
canRevealProject={props.projects.project.canReveal}
|
||||||
canEditProject={props.projects.project.canEdit}
|
|
||||||
unseenCount={props.projects.project.unseenCount}
|
unseenCount={props.projects.project.unseenCount}
|
||||||
onWheel={props.scroll.viewport.containWheel}
|
onWheel={props.scroll.viewport.containWheel}
|
||||||
onChooseProject={props.projects.project.choose}
|
onChooseProject={props.projects.project.choose}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import { useCommand } from "@/context/command"
|
|||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { serverName } from "@/context/server"
|
import { serverName } from "@/context/server"
|
||||||
import { displayName } from "@/pages/layout/helpers"
|
import { displayName } from "@/pages/layout/helpers"
|
||||||
|
import { sessionLabel } from "@/utils/session-title"
|
||||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||||
import { displayLabel } from "@opencode-ai/util/session-title-fallback"
|
|
||||||
import { createMemo, onCleanup } from "solid-js"
|
import { createMemo, onCleanup } from "solid-js"
|
||||||
import { createStore } from "solid-js/store"
|
import { createStore } from "solid-js/store"
|
||||||
import type { HomeController } from "./home-controller"
|
import type { HomeController } from "./home-controller"
|
||||||
@@ -24,7 +24,7 @@ export function createHomeSessionSearchController(home: HomeController, sessions
|
|||||||
if (!value) return []
|
if (!value) return []
|
||||||
return sessions.data
|
return sessions.data
|
||||||
.searchRecords()
|
.searchRecords()
|
||||||
.filter((record) => `${displayLabel(record.session)} ${record.projectName}`.toLowerCase().includes(value))
|
.filter((record) => `${sessionLabel(record.session)} ${record.projectName}`.toLowerCase().includes(value))
|
||||||
})
|
})
|
||||||
const active = createMemo(() => {
|
const active = createMemo(() => {
|
||||||
const records = results()
|
const records = results()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Session, V2SessionListResponse } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { preloadMarkdown } from "@opencode-ai/session-ui/markdown-cache"
|
import { preloadMarkdown } from "@opencode-ai/session-ui/markdown-cache"
|
||||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||||
import { useMarked } from "@opencode-ai/ui/context/marked"
|
import { useMarked } from "@opencode-ai/ui/context/marked"
|
||||||
@@ -26,7 +26,7 @@ import type { HomeController } from "./home-controller"
|
|||||||
|
|
||||||
const HOME_SESSION_LIMIT = 64
|
const HOME_SESSION_LIMIT = 64
|
||||||
export type HomeSessionRecord = {
|
export type HomeSessionRecord = {
|
||||||
session: Session
|
session: SessionInfo
|
||||||
project: LocalProject
|
project: LocalProject
|
||||||
projectName: string
|
projectName: string
|
||||||
}
|
}
|
||||||
@@ -69,10 +69,7 @@ export function createHomeSessionsController(home: HomeController) {
|
|||||||
const cache = homeSessions()
|
const cache = homeSessions()
|
||||||
const eventSequence = cache.eventSequence()
|
const eventSequence = cache.eventSequence()
|
||||||
const index = await loadHomeSessionIndex(
|
const index = await loadHomeSessionIndex(
|
||||||
(input, options) =>
|
(input, options) => ctx.sdk.api.session.list(input, options),
|
||||||
ctx.sdk.currentApi.session.list(input, options).then((data) => ({
|
|
||||||
data: data as unknown as V2SessionListResponse,
|
|
||||||
})),
|
|
||||||
eventSequence,
|
eventSequence,
|
||||||
signal,
|
signal,
|
||||||
)
|
)
|
||||||
@@ -182,10 +179,9 @@ export function createHomeSessionsController(home: HomeController) {
|
|||||||
showProjectName: () => !home.project.selected(),
|
showProjectName: () => !home.project.selected(),
|
||||||
server: () => home.selection.value().server,
|
server: () => home.selection.value().server,
|
||||||
canCreate: () => !!home.project.newSession(),
|
canCreate: () => !!home.project.newSession(),
|
||||||
canArchive: () => home.server.focusedContext()?.sdk.protocolKind() === "v1",
|
|
||||||
create: home.project.openNewSession,
|
create: home.project.openNewSession,
|
||||||
open: (session: Session, options?: OpenSessionOptions) => {
|
open: (session: SessionInfo, options?: OpenSessionOptions) => {
|
||||||
const directoryKey = pathKey(session.directory)
|
const directoryKey = pathKey(session.location.directory)
|
||||||
const project =
|
const project =
|
||||||
home.project
|
home.project
|
||||||
.list()
|
.list()
|
||||||
@@ -196,7 +192,7 @@ export function createHomeSessionsController(home: HomeController) {
|
|||||||
) ?? projectForSession(session, home.project.list(), projectByID())
|
) ?? projectForSession(session, home.project.list(), projectByID())
|
||||||
const conn = home.server.focused()
|
const conn = home.server.focused()
|
||||||
if (!conn) return
|
if (!conn) return
|
||||||
const directory = project?.worktree ?? session.directory
|
const directory = project?.worktree ?? session.location.directory
|
||||||
const ctx = home.server.focusedContext()
|
const ctx = home.server.focusedContext()
|
||||||
if (!ctx) return
|
if (!ctx) return
|
||||||
ctx.projects.open(directory)
|
ctx.projects.open(directory)
|
||||||
@@ -210,15 +206,16 @@ export function createHomeSessionsController(home: HomeController) {
|
|||||||
tabs.select(tab)
|
tabs.select(tab)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
archive: async (session: Session) => {
|
archive: async (session: SessionInfo) => {
|
||||||
const conn = home.server.focused()
|
const conn = home.server.focused()
|
||||||
const ctx = home.server.focusedContext()
|
const ctx = home.server.focusedContext()
|
||||||
if (!conn || !ctx) return
|
if (!conn || !ctx) return
|
||||||
const [, setStore] = ctx.sync.child(session.directory)
|
const [, setStore] = ctx.sync.child(session.location.directory)
|
||||||
await archiveHomeSession({
|
await archiveHomeSession({
|
||||||
server: ServerConnection.key(conn),
|
server: ServerConnection.key(conn),
|
||||||
session,
|
session,
|
||||||
archive: (sessionID) => ctx.sdk.legacy.session.archive(sessionID, session.directory),
|
// TODO: Restore archiving when the V2 client exposes a session archive API.
|
||||||
|
archive: async (_sessionID) => Promise.reject(new Error("Session archiving is unavailable")),
|
||||||
remove: () =>
|
remove: () =>
|
||||||
setStore(
|
setStore(
|
||||||
produce((draft) => {
|
produce((draft) => {
|
||||||
@@ -246,17 +243,17 @@ function directories(project: LocalProject) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildHomeSessionRecords(input: {
|
function buildHomeSessionRecords(input: {
|
||||||
sessions: () => Session[]
|
sessions: () => SessionInfo[]
|
||||||
projectDirectories: () => string[]
|
projectDirectories: () => string[]
|
||||||
projects: () => LocalProject[]
|
projects: () => LocalProject[]
|
||||||
projectByID: () => Map<string, LocalProject>
|
projectByID: () => Map<string, LocalProject>
|
||||||
}) {
|
}) {
|
||||||
const directories = new Set(input.projectDirectories().map(pathKey))
|
const directories = new Set(input.projectDirectories().map(pathKey))
|
||||||
const sessions = input.sessions().filter((session) => directories.has(pathKey(session.directory)))
|
const sessions = input.sessions().filter((session) => directories.has(pathKey(session.location.directory)))
|
||||||
return [...new Map(sessions.map((session) => [session.id, session] as const)).values()]
|
return [...new Map(sessions.map((session) => [session.id, session] as const)).values()]
|
||||||
.sort((a, b) => (b.time.updated ?? b.time.created) - (a.time.updated ?? a.time.created))
|
.sort((a, b) => (b.time.updated ?? b.time.created) - (a.time.updated ?? a.time.created))
|
||||||
.flatMap((session) => {
|
.flatMap((session) => {
|
||||||
const directory = pathKey(session.directory)
|
const directory = pathKey(session.location.directory)
|
||||||
const project =
|
const project =
|
||||||
input
|
input
|
||||||
.projects()
|
.projects()
|
||||||
@@ -270,7 +267,7 @@ function buildHomeSessionRecords(input: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function homeSessionSearchKey(record: HomeSessionRecord) {
|
export function homeSessionSearchKey(record: HomeSessionRecord) {
|
||||||
return `${pathKey(record.session.directory)}:${record.session.id}`
|
return `${pathKey(record.session.location.directory)}:${record.session.id}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function groupSessions(records: HomeSessionRecord[], language: ReturnType<typeof useLanguage>): HomeSessionGroup[] {
|
function groupSessions(records: HomeSessionRecord[], language: ReturnType<typeof useLanguage>): HomeSessionGroup[] {
|
||||||
@@ -307,7 +304,7 @@ export function HomeSessionStatusController(props: {
|
|||||||
}) {
|
}) {
|
||||||
const avatar = useSessionTabAvatarState(
|
const avatar = useSessionTabAvatarState(
|
||||||
props.server,
|
props.server,
|
||||||
() => props.record.session.directory,
|
() => props.record.session.location.directory,
|
||||||
() => props.record.session.id,
|
() => props.record.session.id,
|
||||||
)
|
)
|
||||||
return props.render({
|
return props.render({
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { type Accessor, createMemo, For, Show } from "solid-js"
|
import { type Accessor, createMemo, For, Show } from "solid-js"
|
||||||
import { Spinner } from "@opencode-ai/ui/spinner"
|
import { Spinner } from "@opencode-ai/ui/spinner"
|
||||||
import { ScrollView } from "@opencode-ai/ui/scroll-view"
|
import { ScrollView } from "@opencode-ai/ui/scroll-view"
|
||||||
@@ -6,10 +6,10 @@ import { ButtonV2 } from "@opencode-ai/ui/v2/button-v2"
|
|||||||
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
|
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
|
||||||
import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
|
import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
|
||||||
import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
|
import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
|
||||||
import { displayLabel } from "@opencode-ai/util/session-title-fallback"
|
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { ServerConnection } from "@/context/server"
|
import { ServerConnection } from "@/context/server"
|
||||||
import { SessionTabAvatarView } from "@/pages/layout/session-tab-avatar"
|
import { SessionTabAvatarView } from "@/pages/layout/session-tab-avatar"
|
||||||
|
import { sessionLabel } from "@/utils/session-title"
|
||||||
import { shouldOpenSessionInBackground } from "../home-session-open"
|
import { shouldOpenSessionInBackground } from "../home-session-open"
|
||||||
import {
|
import {
|
||||||
HomeSessionStatusController,
|
HomeSessionStatusController,
|
||||||
@@ -43,7 +43,6 @@ export type HomeSessionsViewProps = {
|
|||||||
showProjectName: Accessor<boolean>
|
showProjectName: Accessor<boolean>
|
||||||
server: Accessor<ServerConnection.Key>
|
server: Accessor<ServerConnection.Key>
|
||||||
canCreateSession: Accessor<boolean>
|
canCreateSession: Accessor<boolean>
|
||||||
canArchiveSession: Accessor<boolean>
|
|
||||||
searchValue: Accessor<string>
|
searchValue: Accessor<string>
|
||||||
searchPlaceholder: Accessor<string>
|
searchPlaceholder: Accessor<string>
|
||||||
searchOpen: Accessor<boolean>
|
searchOpen: Accessor<boolean>
|
||||||
@@ -54,8 +53,8 @@ export type HomeSessionsViewProps = {
|
|||||||
titleOpacity: (id: HomeSessionGroup["id"]) => number
|
titleOpacity: (id: HomeSessionGroup["id"]) => number
|
||||||
isOpenTab: (record: HomeSessionRecord) => boolean
|
isOpenTab: (record: HomeSessionRecord) => boolean
|
||||||
onCreateSession: () => void
|
onCreateSession: () => void
|
||||||
onOpenSession: (session: Session, options?: OpenSessionOptions) => void
|
onOpenSession: (session: SessionInfo, options?: OpenSessionOptions) => void
|
||||||
onArchiveSession: (session: Session) => Promise<void>
|
onArchiveSession: (session: SessionInfo) => Promise<void>
|
||||||
onSetHoverTarget: (element: HTMLElement) => void
|
onSetHoverTarget: (element: HTMLElement) => void
|
||||||
onSetThumbTrack: (element: HTMLDivElement) => void
|
onSetThumbTrack: (element: HTMLDivElement) => void
|
||||||
onSetContent: (element: HTMLDivElement) => void
|
onSetContent: (element: HTMLDivElement) => void
|
||||||
@@ -193,7 +192,7 @@ function HomeSessionLeading(props: {
|
|||||||
</Show>
|
</Show>
|
||||||
<SessionTabAvatarView
|
<SessionTabAvatarView
|
||||||
project={props.record.project}
|
project={props.record.project}
|
||||||
directory={props.record.session.directory}
|
directory={props.record.session.location.directory}
|
||||||
revealProjectOnHover={props.revealProjectOnHover}
|
revealProjectOnHover={props.revealProjectOnHover}
|
||||||
unread={props.unread}
|
unread={props.unread}
|
||||||
loading={props.loading}
|
loading={props.loading}
|
||||||
@@ -345,7 +344,7 @@ function HomeSessionSearchResultRow(
|
|||||||
selected: boolean
|
selected: boolean
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const title = createMemo(() => displayLabel(props.record.session))
|
const title = createMemo(() => sessionLabel(props.record.session))
|
||||||
const showProjectName = () => props.showProjectName() && props.record.projectName
|
const showProjectName = () => props.showProjectName() && props.record.projectName
|
||||||
const key = () => homeSessionSearchKey(props.record)
|
const key = () => homeSessionSearchKey(props.record)
|
||||||
|
|
||||||
@@ -416,7 +415,7 @@ function HomeSessionGroupHeader(props: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function HomeSessionRow(props: HomeSessionsViewProps & { record: HomeSessionRecord }) {
|
function HomeSessionRow(props: HomeSessionsViewProps & { record: HomeSessionRecord }) {
|
||||||
const title = createMemo(() => displayLabel(props.record.session))
|
const title = createMemo(() => sessionLabel(props.record.session))
|
||||||
const showProjectName = () => props.showProjectName() && props.record.projectName
|
const showProjectName = () => props.showProjectName() && props.record.projectName
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -461,8 +460,7 @@ function HomeSessionRow(props: HomeSessionsViewProps & { record: HomeSessionReco
|
|||||||
group-hover/session:opacity-100 focus-within:opacity-100
|
group-hover/session:opacity-100 focus-within:opacity-100
|
||||||
`}
|
`}
|
||||||
>
|
>
|
||||||
<Show when={props.canArchiveSession()}>
|
<TooltipV2 class="flex shrink-0 items-center" placement="bottom" value={props.language.t("common.archive")}>
|
||||||
<TooltipV2 class="flex shrink-0 items-center" placement="bottom" value={props.language.t("common.archive")}>
|
|
||||||
<IconButtonV2
|
<IconButtonV2
|
||||||
data-action="home-session-archive"
|
data-action="home-session-archive"
|
||||||
variant="ghost-muted"
|
variant="ghost-muted"
|
||||||
@@ -475,8 +473,7 @@ function HomeSessionRow(props: HomeSessionsViewProps & { record: HomeSessionReco
|
|||||||
void props.onArchiveSession(props.record.session)
|
void props.onArchiveSession(props.record.session)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</TooltipV2>
|
</TooltipV2>
|
||||||
</Show>
|
|
||||||
</div>
|
</div>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ export function HomeSessions(props: {
|
|||||||
showProjectName={props.sessions.session.showProjectName}
|
showProjectName={props.sessions.session.showProjectName}
|
||||||
server={props.sessions.session.server}
|
server={props.sessions.session.server}
|
||||||
canCreateSession={props.sessions.session.canCreate}
|
canCreateSession={props.sessions.session.canCreate}
|
||||||
canArchiveSession={props.sessions.session.canArchive}
|
|
||||||
searchValue={props.search.query.value}
|
searchValue={props.search.query.value}
|
||||||
searchPlaceholder={props.search.query.placeholder}
|
searchPlaceholder={props.search.query.placeholder}
|
||||||
searchOpen={props.search.query.open}
|
searchOpen={props.search.query.open}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import { Tooltip } from "@opencode-ai/ui/tooltip"
|
|||||||
import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu"
|
import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu"
|
||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
import { getDirectory, getFilename } from "@opencode-ai/core/util/path"
|
import { getDirectory, getFilename } from "@opencode-ai/core/util/path"
|
||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { usePlatform } from "@/context/platform"
|
import { usePlatform } from "@/context/platform"
|
||||||
import { useSettings } from "@/context/settings"
|
import { useSettings } from "@/context/settings"
|
||||||
import { createStore, produce, reconcile } from "solid-js/store"
|
import { createStore, produce, reconcile } from "solid-js/store"
|
||||||
@@ -390,22 +390,6 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unsub = serverSDK().event.listen((e) => {
|
const unsub = serverSDK().event.listen((e) => {
|
||||||
if (e.details?.type === "worktree.ready") {
|
|
||||||
setBusy(e.name, false)
|
|
||||||
WorktreeState.ready(serverSDK().scope, e.name)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (e.details?.type === "worktree.failed") {
|
|
||||||
setBusy(e.name, false)
|
|
||||||
WorktreeState.failed(
|
|
||||||
serverSDK().scope,
|
|
||||||
e.name,
|
|
||||||
e.details.properties?.message ?? language.t("common.requestFailed"),
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
e.details?.type === "question.replied" ||
|
e.details?.type === "question.replied" ||
|
||||||
e.details?.type === "question.rejected" ||
|
e.details?.type === "question.rejected" ||
|
||||||
@@ -619,9 +603,9 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
const currentSessions = createMemo(() => {
|
const currentSessions = createMemo(() => {
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
const dirs = visibleSessionDirs()
|
const dirs = visibleSessionDirs()
|
||||||
if (dirs.length === 0) return [] as Session[]
|
if (dirs.length === 0) return [] as SessionInfo[]
|
||||||
|
|
||||||
const result: Session[] = []
|
const result: SessionInfo[] = []
|
||||||
for (const dir of dirs) {
|
for (const dir of dirs) {
|
||||||
const [dirStore] = serverSync().child(dir, { bootstrap: true })
|
const [dirStore] = serverSync().child(dir, { bootstrap: true })
|
||||||
const dirSessions = sortedRootSessions(dirStore, now)
|
const dirSessions = sortedRootSessions(dirStore, now)
|
||||||
@@ -733,8 +717,8 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const prefetchSession = (session: Session, priority: "high" | "low" = "low") => {
|
const prefetchSession = (session: SessionInfo, priority: "high" | "low" = "low") => {
|
||||||
const directory = session.directory
|
const directory = session.location.directory
|
||||||
if (!directory) return
|
if (!directory) return
|
||||||
|
|
||||||
const cached = untrack(() => !serverSync().session.shouldPrefetch(session.id, prefetchChunk))
|
const cached = untrack(() => !serverSync().session.shouldPrefetch(session.id, prefetchChunk))
|
||||||
@@ -769,7 +753,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
pumpPrefetch(directory)
|
pumpPrefetch(directory)
|
||||||
}
|
}
|
||||||
|
|
||||||
const warm = (sessions: Session[], index: number) => {
|
const warm = (sessions: SessionInfo[], index: number) => {
|
||||||
for (let offset = 1; offset <= span; offset++) {
|
for (let offset = 1; offset <= span; offset++) {
|
||||||
const next = sessions[index + offset]
|
const next = sessions[index + offset]
|
||||||
if (next) prefetchSession(next, offset === 1 ? "high" : "low")
|
if (next) prefetchSession(next, offset === 1 ? "high" : "low")
|
||||||
@@ -871,13 +855,15 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function archiveSession(session: Session) {
|
async function archiveSession(session: SessionInfo) {
|
||||||
const [store, setStore] = serverSync().child(session.directory)
|
// TODO: Restore archiving when the V2 client exposes a session archive API.
|
||||||
|
void session
|
||||||
|
return
|
||||||
|
const [store, setStore] = serverSync().child(session.location.directory)
|
||||||
const sessions = store.session ?? []
|
const sessions = store.session ?? []
|
||||||
const index = sessions.findIndex((s) => s.id === session.id)
|
const index = sessions.findIndex((s) => s.id === session.id)
|
||||||
const nextSession = sessions[index + 1] ?? sessions[index - 1]
|
const nextSession = sessions[index + 1] ?? sessions[index - 1]
|
||||||
|
|
||||||
await serverSDK().legacy.session.archive(session.id, session.directory)
|
|
||||||
setStore(
|
setStore(
|
||||||
produce((draft) => {
|
produce((draft) => {
|
||||||
const match = Binary.search(draft.session, session.id, (s) => s.id)
|
const match = Binary.search(draft.session, session.id, (s) => s.id)
|
||||||
@@ -975,8 +961,8 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
title: language.t("command.session.archive"),
|
title: language.t("command.session.archive"),
|
||||||
category: language.t("command.category.session"),
|
category: language.t("command.category.session"),
|
||||||
keybind: "mod+shift+backspace",
|
keybind: "mod+shift+backspace",
|
||||||
hidden: serverSDK().protocolKind() !== "v1",
|
// TODO: Restore the command when the V2 client exposes session archive.
|
||||||
disabled: !params.dir || !params.id,
|
disabled: true,
|
||||||
onSelect: () => {
|
onSelect: () => {
|
||||||
const session = currentSessions().find((s) => s.id === params.id)
|
const session = currentSessions().find((s) => s.id === params.id)
|
||||||
if (session) void archiveSession(session)
|
if (session) void archiveSession(session)
|
||||||
@@ -1185,13 +1171,10 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
const refreshDirs = async (target?: string) => {
|
const refreshDirs = async (target?: string) => {
|
||||||
if (!target || target === root || canOpen(target)) return canOpen(target)
|
if (!target || target === root || canOpen(target)) return canOpen(target)
|
||||||
const listed = await Promise.resolve(
|
const listed = await Promise.resolve(
|
||||||
project?.id ?? serverSDK().currentApi.project.current({ location: { directory: root } }),
|
project?.id ?? serverSDK().api.project.current({ location: { directory: root } }),
|
||||||
)
|
)
|
||||||
.then((value) => (typeof value === "string" ? value : value.id))
|
.then((value) => (typeof value === "string" ? value : value.id))
|
||||||
.then(async (projectID) => {
|
.then((projectID) => serverSDK().api.project.directories({ projectID, location: { directory: root } }))
|
||||||
await serverSDK().currentApi.projectCopy.refresh({ projectID, location: { directory: root } })
|
|
||||||
return serverSDK().currentApi.project.directories({ projectID, location: { directory: root } })
|
|
||||||
})
|
|
||||||
.then((items) => items.map((item) => item.directory).filter((item) => pathKey(item) !== pathKey(root)))
|
.then((items) => items.map((item) => item.directory).filter((item) => pathKey(item) !== pathKey(root)))
|
||||||
.catch(() => [] as string[])
|
.catch(() => [] as string[])
|
||||||
dirs = effectiveWorkspaceOrder(root, [root, ...listed], store.workspaceOrder[root])
|
dirs = effectiveWorkspaceOrder(root, [root, ...listed], store.workspaceOrder[root])
|
||||||
@@ -1209,10 +1192,10 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
.sync(target.id)
|
.sync(target.id)
|
||||||
.then(() => sync.session.get(target.id))
|
.then(() => sync.session.get(target.id))
|
||||||
.catch(() => undefined)
|
.catch(() => undefined)
|
||||||
if (!resolved?.directory) return false
|
if (!resolved?.location.directory) return false
|
||||||
if (!canOpen(resolved.directory)) return false
|
if (!canOpen(resolved.location.directory)) return false
|
||||||
setStore("lastProjectSession", root, { directory: resolved.directory, id: resolved.id, at: Date.now() })
|
setStore("lastProjectSession", root, { directory: resolved.location.directory, id: resolved.id, at: Date.now() })
|
||||||
navigateWithSidebarReset(`/${base64Encode(resolved.directory)}/session/${resolved.id}`)
|
navigateWithSidebarReset(`/${base64Encode(resolved.location.directory)}/session/${resolved.id}`)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1228,7 +1211,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
dirs.map((item) => serverSync().child(item, { bootstrap: false })[0]),
|
dirs.map((item) => serverSync().child(item, { bootstrap: false })[0]),
|
||||||
Date.now(),
|
Date.now(),
|
||||||
)
|
)
|
||||||
if (latest && (await openSession(latest))) {
|
if (latest && (await openSession({ directory: latest.location.directory, id: latest.id }))) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1236,7 +1219,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
await Promise.all(
|
await Promise.all(
|
||||||
dirs.map(async (item) => ({
|
dirs.map(async (item) => ({
|
||||||
path: { directory: item },
|
path: { directory: item },
|
||||||
session: await listAllSessions(serverSDK().currentApi.session, {
|
session: await listAllSessions(serverSDK().api.session, {
|
||||||
directory: item,
|
directory: item,
|
||||||
parentID: null,
|
parentID: null,
|
||||||
order: "desc",
|
order: "desc",
|
||||||
@@ -1245,16 +1228,16 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
),
|
),
|
||||||
Date.now(),
|
Date.now(),
|
||||||
)
|
)
|
||||||
if (fetched && (await openSession(fetched))) {
|
if (fetched && (await openSession({ directory: fetched.location.directory, id: fetched.id }))) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
navigateWithSidebarReset(`/${base64Encode(root)}/session`)
|
navigateWithSidebarReset(`/${base64Encode(root)}/session`)
|
||||||
}
|
}
|
||||||
|
|
||||||
function navigateToSession(session: Session | undefined) {
|
function navigateToSession(session: SessionInfo | undefined) {
|
||||||
if (!session) return
|
if (!session) return
|
||||||
navigateWithSidebarReset(`/${base64Encode(session.directory)}/session/${session.id}`)
|
navigateWithSidebarReset(`/${base64Encode(session.location.directory)}/session/${session.id}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
function openProject(directory: string, navigate = true) {
|
function openProject(directory: string, navigate = true) {
|
||||||
@@ -1300,13 +1283,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
const name = next === getFilename(project.worktree) ? "" : next
|
const name = next === getFilename(project.worktree) ? "" : next
|
||||||
|
|
||||||
if (project.id && project.id !== "global") {
|
if (project.id && project.id !== "global") {
|
||||||
const result = await serverSDK().legacy.project
|
// TODO: Restore project renames when the V2 client exposes a project update API.
|
||||||
.update({ projectID: project.id, directory: project.worktree, name })
|
|
||||||
.then((response) => response.data)
|
|
||||||
if (!result) return
|
|
||||||
serverSync().set("project", (items) =>
|
|
||||||
items.map((item) => (item.id === result.id ? normalizeProjectInfo(result) : item)),
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1402,7 +1379,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
const projectID = serverSync().data.project.find((project) => project.worktree === root)?.id
|
const projectID = serverSync().data.project.find((project) => project.worktree === root)?.id
|
||||||
const result = projectID
|
const result = projectID
|
||||||
? await serverSDK()
|
? await serverSDK()
|
||||||
.currentApi.projectCopy.remove({ projectID, directory, force: false, location: { directory: root } })
|
.api.projectCopy.remove({ projectID, directory, force: false, location: { directory: root } })
|
||||||
.then(() => true)
|
.then(() => true)
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
showToast({
|
showToast({
|
||||||
@@ -1460,9 +1437,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
})
|
})
|
||||||
const dismiss = () => toaster.dismiss(progress)
|
const dismiss = () => toaster.dismiss(progress)
|
||||||
|
|
||||||
const sessions = await listAllSessions(serverSDK().currentApi.session, { directory, order: "desc" }).catch(
|
const sessions = await listAllSessions(serverSDK().api.session, { directory, order: "desc" }).catch(() => [])
|
||||||
() => [],
|
|
||||||
)
|
|
||||||
|
|
||||||
clearWorkspaceTerminals(
|
clearWorkspaceTerminals(
|
||||||
directory,
|
directory,
|
||||||
@@ -1470,16 +1445,8 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
platform,
|
platform,
|
||||||
serverSDK().scope,
|
serverSDK().scope,
|
||||||
)
|
)
|
||||||
const result = await serverSDK()
|
// TODO: Restore workspace reset and instance disposal when V2 exposes these operations.
|
||||||
.legacy.workspace.reset(root, directory)
|
const result = false
|
||||||
.then((x) => x.data)
|
|
||||||
.catch((err) => {
|
|
||||||
showToast({
|
|
||||||
title: language.t("workspace.reset.failed.title"),
|
|
||||||
description: errorMessage(err, language.t("common.requestFailed")),
|
|
||||||
})
|
|
||||||
return false
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!result) {
|
if (!result) {
|
||||||
setBusy(directory, false)
|
setBusy(directory, false)
|
||||||
@@ -1487,17 +1454,6 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((await serverSDK().protocol) === "v1")
|
|
||||||
await Promise.all(
|
|
||||||
sessions
|
|
||||||
.filter((session) => session.time.archived === undefined)
|
|
||||||
.map((session) =>
|
|
||||||
serverSDK()
|
|
||||||
.legacy.session.archive(session.id, session.directory)
|
|
||||||
.catch(() => undefined),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
setBusy(directory, false)
|
setBusy(directory, false)
|
||||||
dismiss()
|
dismiss()
|
||||||
|
|
||||||
@@ -1584,11 +1540,11 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
const [state, setState] = createStore({
|
const [state, setState] = createStore({
|
||||||
status: "loading" as "loading" | "ready" | "error",
|
status: "loading" as "loading" | "ready" | "error",
|
||||||
dirty: false,
|
dirty: false,
|
||||||
sessions: [] as Session[],
|
sessions: [] as SessionInfo[],
|
||||||
})
|
})
|
||||||
|
|
||||||
const refresh = async () => {
|
const refresh = async () => {
|
||||||
const sessions = await listAllSessions(serverSDK().currentApi.session, {
|
const sessions = await listAllSessions(serverSDK().api.session, {
|
||||||
directory: props.directory,
|
directory: props.directory,
|
||||||
order: "desc",
|
order: "desc",
|
||||||
}).catch(() => [])
|
}).catch(() => [])
|
||||||
@@ -1830,7 +1786,7 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
clearSidebarHoverState()
|
clearSidebarHoverState()
|
||||||
const created = project.id
|
const created = project.id
|
||||||
? await serverSDK()
|
? await serverSDK()
|
||||||
.currentApi.projectCopy.create({
|
.api.projectCopy.create({
|
||||||
projectID: project.id,
|
projectID: project.id,
|
||||||
strategy: "git_worktree",
|
strategy: "git_worktree",
|
||||||
directory: getDirectory(project.worktree),
|
directory: getDirectory(project.worktree),
|
||||||
@@ -1880,8 +1836,6 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
clearHoverProjectSoon,
|
clearHoverProjectSoon,
|
||||||
prefetchSession,
|
prefetchSession,
|
||||||
archiveSession,
|
archiveSession,
|
||||||
canArchive: () => serverSDK().protocolKind() === "v1",
|
|
||||||
canResetWorkspace: () => serverSDK().protocolKind() === "v1",
|
|
||||||
workspaceName,
|
workspaceName,
|
||||||
renameWorkspace,
|
renameWorkspace,
|
||||||
editorOpen,
|
editorOpen,
|
||||||
@@ -1918,7 +1872,6 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
openSidebar: () => layout.sidebar.open(),
|
openSidebar: () => layout.sidebar.open(),
|
||||||
closeProject,
|
closeProject,
|
||||||
showEditProjectDialog: (proj) => showEditProjectDialog(server.current!, proj),
|
showEditProjectDialog: (proj) => showEditProjectDialog(server.current!, proj),
|
||||||
canEditProject: () => serverSDK().protocolKind() === "v1",
|
|
||||||
toggleProjectWorkspaces,
|
toggleProjectWorkspaces,
|
||||||
workspacesEnabled: (project) => project.vcs === "git" && layout.sidebar.workspaces(project.worktree)(),
|
workspacesEnabled: (project) => project.vcs === "git" && layout.sidebar.workspaces(project.worktree)(),
|
||||||
workspaceIds,
|
workspaceIds,
|
||||||
@@ -1929,7 +1882,6 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
clearHoverProjectSoon,
|
clearHoverProjectSoon,
|
||||||
prefetchSession,
|
prefetchSession,
|
||||||
archiveSession,
|
archiveSession,
|
||||||
canArchive: () => serverSDK().protocolKind() === "v1",
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2021,13 +1973,15 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
<div class="group/project flex items-start justify-between gap-2 py-2 pl-2 pr-0">
|
<div class="group/project flex items-start justify-between gap-2 py-2 pl-2 pr-0">
|
||||||
<div class="flex flex-col min-w-0">
|
<div class="flex flex-col min-w-0">
|
||||||
<Show
|
<Show
|
||||||
when={serverSDK().protocolKind() === "v1" || !project.id || project.id === "global"}
|
when={!project.id || project.id === "global"}
|
||||||
fallback={<span class="text-14-medium text-text-strong truncate">{projectName()}</span>}
|
fallback={<span class="text-14-medium text-text-strong truncate">{projectName()}</span>}
|
||||||
>
|
>
|
||||||
<InlineEditor
|
<InlineEditor
|
||||||
id={`project:${projectId()}`}
|
id={`project:${projectId()}`}
|
||||||
value={projectName}
|
value={projectName}
|
||||||
onSave={(next) => void renameProject(project, next)}
|
onSave={(next) => {
|
||||||
|
void renameProject(project, next)
|
||||||
|
}}
|
||||||
class="text-14-medium text-text-strong truncate"
|
class="text-14-medium text-text-strong truncate"
|
||||||
displayClass="text-14-medium text-text-strong truncate"
|
displayClass="text-14-medium text-text-strong truncate"
|
||||||
stopPropagation
|
stopPropagation
|
||||||
@@ -2067,11 +2021,13 @@ export default function LegacyLayout(props: ParentProps) {
|
|||||||
/>
|
/>
|
||||||
<DropdownMenu.Portal>
|
<DropdownMenu.Portal>
|
||||||
<DropdownMenu.Content class="mt-1">
|
<DropdownMenu.Content class="mt-1">
|
||||||
<Show when={serverSDK().protocolKind() === "v1"}>
|
<DropdownMenu.Item
|
||||||
<DropdownMenu.Item onSelect={() => showEditProjectDialog(server.current!, project)}>
|
onSelect={() => {
|
||||||
<DropdownMenu.ItemLabel>{language.t("common.edit")}</DropdownMenu.ItemLabel>
|
showEditProjectDialog(server.current!, project)
|
||||||
</DropdownMenu.Item>
|
}}
|
||||||
</Show>
|
>
|
||||||
|
<DropdownMenu.ItemLabel>{language.t("common.edit")}</DropdownMenu.ItemLabel>
|
||||||
|
</DropdownMenu.Item>
|
||||||
<DropdownMenu.Item
|
<DropdownMenu.Item
|
||||||
data-action="project-workspaces-toggle"
|
data-action="project-workspaces-toggle"
|
||||||
data-project={slug()}
|
data-project={slug()}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
parseDeepLink,
|
parseDeepLink,
|
||||||
parseNewSessionDeepLink,
|
parseNewSessionDeepLink,
|
||||||
} from "./deep-links"
|
} from "./deep-links"
|
||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import {
|
import {
|
||||||
childSessionOnPath,
|
childSessionOnPath,
|
||||||
closeHomeProject,
|
closeHomeProject,
|
||||||
@@ -25,16 +25,18 @@ import { ServerConnection } from "@/context/server"
|
|||||||
|
|
||||||
const serverKey = ServerConnection.Key.make
|
const serverKey = ServerConnection.Key.make
|
||||||
|
|
||||||
const session = (input: Partial<Session> & Pick<Session, "id" | "directory">) =>
|
const session = (input: Partial<SessionInfo> & Pick<SessionInfo, "id"> & { directory: string }) =>
|
||||||
({
|
({
|
||||||
|
projectID: "project",
|
||||||
title: "",
|
title: "",
|
||||||
version: "v2",
|
cost: 0,
|
||||||
|
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||||
parentID: undefined,
|
parentID: undefined,
|
||||||
messageCount: 0,
|
|
||||||
permissions: { session: {}, share: {} },
|
|
||||||
time: { created: 0, updated: 0, archived: undefined },
|
time: { created: 0, updated: 0, archived: undefined },
|
||||||
...input,
|
...input,
|
||||||
}) as Session
|
location: { directory: input.directory },
|
||||||
|
directory: undefined,
|
||||||
|
}) as SessionInfo
|
||||||
|
|
||||||
describe("layout deep links", () => {
|
describe("layout deep links", () => {
|
||||||
test("parses open-project deep links", () => {
|
test("parses open-project deep links", () => {
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
import { getFilename } from "@opencode-ai/core/util/path"
|
import { getFilename } from "@opencode-ai/core/util/path"
|
||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { pathKey } from "@/utils/path-key"
|
import { pathKey } from "@/utils/path-key"
|
||||||
import type { ServerConnection } from "@/context/server"
|
import type { ServerConnection } from "@/context/server"
|
||||||
import type { HomeProjectSelection } from "@/context/layout"
|
import type { HomeProjectSelection } from "@/context/layout"
|
||||||
|
|
||||||
type SessionStore = {
|
type SessionStore = {
|
||||||
session?: Session[]
|
session?: SessionInfo[]
|
||||||
path: { directory: string }
|
path: { directory: string }
|
||||||
}
|
}
|
||||||
|
|
||||||
function sortSessions(now: number) {
|
function sortSessions(now: number) {
|
||||||
const oneMinuteAgo = now - 60 * 1000
|
const oneMinuteAgo = now - 60 * 1000
|
||||||
return (a: Session, b: Session) => {
|
return (a: SessionInfo, b: SessionInfo) => {
|
||||||
const aUpdated = a.time.updated ?? a.time.created
|
const aUpdated = a.time.updated ?? a.time.created
|
||||||
const bUpdated = b.time.updated ?? b.time.created
|
const bUpdated = b.time.updated ?? b.time.created
|
||||||
const aRecent = aUpdated > oneMinuteAgo
|
const aRecent = aUpdated > oneMinuteAgo
|
||||||
@@ -23,8 +23,8 @@ function sortSessions(now: number) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const isRootVisibleSession = (session: Session, directory: string) =>
|
const isRootVisibleSession = (session: SessionInfo, directory: string) =>
|
||||||
pathKey(session.directory) === pathKey(directory) && !session.parentID && !session.time?.archived
|
pathKey(session.location.directory) === pathKey(directory) && !session.parentID && !session.time.archived
|
||||||
|
|
||||||
export const roots = (store: SessionStore) =>
|
export const roots = (store: SessionStore) =>
|
||||||
(store.session ?? []).filter((session) => isRootVisibleSession(session, store.path.directory))
|
(store.session ?? []).filter((session) => isRootVisibleSession(session, store.path.directory))
|
||||||
@@ -41,7 +41,7 @@ export function hasProjectPermissions<T>(
|
|||||||
return Object.values(request ?? {}).some((list) => list?.some(include))
|
return Object.values(request ?? {}).some((list) => list?.some(include))
|
||||||
}
|
}
|
||||||
|
|
||||||
export const childSessionOnPath = (sessions: Session[] | undefined, rootID: string, activeID?: string) => {
|
export const childSessionOnPath = (sessions: SessionInfo[] | undefined, rootID: string, activeID?: string) => {
|
||||||
if (!activeID || activeID === rootID) return
|
if (!activeID || activeID === rootID) return
|
||||||
const map = new Map((sessions ?? []).map((session) => [session.id, session]))
|
const map = new Map((sessions ?? []).map((session) => [session.id, session]))
|
||||||
let id = activeID
|
let id = activeID
|
||||||
@@ -102,13 +102,13 @@ export function getProjectAvatarSource(id?: string, icon?: { color?: string; url
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function projectForSession<T extends { id?: string; worktree: string; sandboxes?: string[] }>(
|
export function projectForSession<T extends { id?: string; worktree: string; sandboxes?: string[] }>(
|
||||||
session: Session,
|
session: SessionInfo,
|
||||||
projects: T[],
|
projects: T[],
|
||||||
byID: Map<string, T> = new Map(projects.flatMap((project) => (project.id ? [[project.id, project] as const] : []))),
|
byID: Map<string, T> = new Map(projects.flatMap((project) => (project.id ? [[project.id, project] as const] : []))),
|
||||||
) {
|
) {
|
||||||
const direct = byID.get(session.projectID)
|
const direct = byID.get(session.projectID)
|
||||||
if (direct) return direct
|
if (direct) return direct
|
||||||
const directory = pathKey(session.directory)
|
const directory = pathKey(session.location.directory)
|
||||||
return projects.find(
|
return projects.find(
|
||||||
(project) =>
|
(project) =>
|
||||||
pathKey(project.worktree) === directory || project.sandboxes?.some((sandbox) => pathKey(sandbox) === directory),
|
pathKey(project.worktree) === directory || project.sandboxes?.some((sandbox) => pathKey(sandbox) === directory),
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import type { Session } from "@/types"
|
import type { SessionInfo } from "@opencode-ai/client/promise"
|
||||||
import { Avatar } from "@opencode-ai/ui/avatar"
|
import { Avatar } from "@opencode-ai/ui/avatar"
|
||||||
import { Icon } from "@opencode-ai/ui/icon"
|
import { Icon } from "@opencode-ai/ui/icon"
|
||||||
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
|
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
|
||||||
import { IconButton } from "@opencode-ai/ui/icon-button"
|
import { IconButton } from "@opencode-ai/ui/icon-button"
|
||||||
import { Spinner } from "@opencode-ai/ui/spinner"
|
import { Spinner } from "@opencode-ai/ui/spinner"
|
||||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||||
import { displayLabel } from "@opencode-ai/util/session-title-fallback"
|
|
||||||
import { getFilename } from "@opencode-ai/core/util/path"
|
import { getFilename } from "@opencode-ai/core/util/path"
|
||||||
import { A, useParams } from "@solidjs/router"
|
import { A, useParams } from "@solidjs/router"
|
||||||
import { type Accessor, createMemo, For, type JSX, Match, Show, Switch } from "solid-js"
|
import { type Accessor, createMemo, For, type JSX, Match, Show, Switch } from "solid-js"
|
||||||
@@ -15,6 +14,7 @@ import { getAvatarColors, type LocalProject, useLayout } from "@/context/layout"
|
|||||||
import { useNotification } from "@/context/notification"
|
import { useNotification } from "@/context/notification"
|
||||||
import { usePermission } from "@/context/permission"
|
import { usePermission } from "@/context/permission"
|
||||||
import { messageAgentColor } from "@/utils/agent"
|
import { messageAgentColor } from "@/utils/agent"
|
||||||
|
import { sessionLabel } from "@/utils/session-title"
|
||||||
import { sessionPermissionRequest } from "../session/composer/session-request-tree"
|
import { sessionPermissionRequest } from "../session/composer/session-request-tree"
|
||||||
import { childSessionOnPath, getProjectAvatarSource, hasProjectPermissions } from "./helpers"
|
import { childSessionOnPath, getProjectAvatarSource, hasProjectPermissions } from "./helpers"
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ export const ProjectIcon = (props: {
|
|||||||
const hasPermissions = createMemo(() =>
|
const hasPermissions = createMemo(() =>
|
||||||
dirs().some((directory) => {
|
dirs().some((directory) => {
|
||||||
return hasProjectPermissions(serverSync().session.data.permission, (item) => {
|
return hasProjectPermissions(serverSync().session.data.permission, (item) => {
|
||||||
if (serverSync().session.get(item.sessionID)?.directory !== directory) return false
|
if (serverSync().session.get(item.sessionID)?.location.directory !== directory) return false
|
||||||
return !permission.autoResponds(item, directory)
|
return !permission.autoResponds(item, directory)
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
@@ -74,9 +74,9 @@ export const ProjectIcon = (props: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type SessionItemProps = {
|
export type SessionItemProps = {
|
||||||
session: Session
|
session: SessionInfo
|
||||||
list: Session[]
|
list: SessionInfo[]
|
||||||
navList?: Accessor<Session[]>
|
navList?: Accessor<SessionInfo[]>
|
||||||
slug: string
|
slug: string
|
||||||
mobile?: boolean
|
mobile?: boolean
|
||||||
dense?: boolean
|
dense?: boolean
|
||||||
@@ -85,13 +85,12 @@ export type SessionItemProps = {
|
|||||||
level?: number
|
level?: number
|
||||||
sidebarExpanded: Accessor<boolean>
|
sidebarExpanded: Accessor<boolean>
|
||||||
clearHoverProjectSoon: () => void
|
clearHoverProjectSoon: () => void
|
||||||
prefetchSession: (session: Session, priority?: "high" | "low") => void
|
prefetchSession: (session: SessionInfo, priority?: "high" | "low") => void
|
||||||
archiveSession: (session: Session) => Promise<void>
|
archiveSession: (session: SessionInfo) => Promise<void>
|
||||||
canArchive: Accessor<boolean>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const SessionRow = (props: {
|
const SessionRow = (props: {
|
||||||
session: Session
|
session: SessionInfo
|
||||||
slug: string
|
slug: string
|
||||||
mobile?: boolean
|
mobile?: boolean
|
||||||
dense?: boolean
|
dense?: boolean
|
||||||
@@ -105,7 +104,7 @@ const SessionRow = (props: {
|
|||||||
warmPress: () => void
|
warmPress: () => void
|
||||||
warmFocus: () => void
|
warmFocus: () => void
|
||||||
}): JSX.Element => {
|
}): JSX.Element => {
|
||||||
const title = () => displayLabel(props.session)
|
const title = () => sessionLabel(props.session)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<A
|
<A
|
||||||
@@ -153,14 +152,14 @@ export const SessionItem = (props: SessionItemProps): JSX.Element => {
|
|||||||
const serverSync = useServerSync()
|
const serverSync = useServerSync()
|
||||||
const unseenCount = createMemo(() => notification.session.unseenCount(props.session.id))
|
const unseenCount = createMemo(() => notification.session.unseenCount(props.session.id))
|
||||||
const hasError = createMemo(() => notification.session.unseenHasError(props.session.id))
|
const hasError = createMemo(() => notification.session.unseenHasError(props.session.id))
|
||||||
const [sessionStore] = serverSync().child(props.session.directory)
|
const [sessionStore] = serverSync().child(props.session.location.directory)
|
||||||
const hasPermissions = createMemo(() => {
|
const hasPermissions = createMemo(() => {
|
||||||
return !!sessionPermissionRequest(
|
return !!sessionPermissionRequest(
|
||||||
sessionStore.session,
|
sessionStore.session,
|
||||||
serverSync().session.data.permission,
|
serverSync().session.data.permission,
|
||||||
props.session.id,
|
props.session.id,
|
||||||
(item) => {
|
(item) => {
|
||||||
return !permission.autoResponds(item, props.session.directory)
|
return !permission.autoResponds(item, props.session.location.directory)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -180,13 +179,17 @@ export const SessionItem = (props: SessionItemProps): JSX.Element => {
|
|||||||
|
|
||||||
const warm = (span: number, priority: "high" | "low") => {
|
const warm = (span: number, priority: "high" | "low") => {
|
||||||
const nav = props.navList?.()
|
const nav = props.navList?.()
|
||||||
const list = nav?.some((item) => item.id === props.session.id && item.directory === props.session.directory)
|
const list = nav?.some(
|
||||||
|
(item) => item.id === props.session.id && item.location.directory === props.session.location.directory,
|
||||||
|
)
|
||||||
? nav
|
? nav
|
||||||
: props.list
|
: props.list
|
||||||
|
|
||||||
props.prefetchSession(props.session, priority)
|
props.prefetchSession(props.session, priority)
|
||||||
|
|
||||||
const idx = list.findIndex((item) => item.id === props.session.id && item.directory === props.session.directory)
|
const idx = list.findIndex(
|
||||||
|
(item) => item.id === props.session.id && item.location.directory === props.session.location.directory,
|
||||||
|
)
|
||||||
if (idx === -1) return
|
if (idx === -1) return
|
||||||
|
|
||||||
for (let step = 1; step <= span; step++) {
|
for (let step = 1; step <= span; step++) {
|
||||||
@@ -230,7 +233,7 @@ export const SessionItem = (props: SessionItemProps): JSX.Element => {
|
|||||||
fallback={
|
fallback={
|
||||||
<Tooltip
|
<Tooltip
|
||||||
placement={props.mobile ? "bottom" : "right"}
|
placement={props.mobile ? "bottom" : "right"}
|
||||||
value={displayLabel(props.session)}
|
value={sessionLabel(props.session)}
|
||||||
gutter={10}
|
gutter={10}
|
||||||
class="min-w-0 w-full"
|
class="min-w-0 w-full"
|
||||||
>
|
>
|
||||||
@@ -242,7 +245,8 @@ export const SessionItem = (props: SessionItemProps): JSX.Element => {
|
|||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Show when={!props.level && props.canArchive()}>
|
{/* TODO: Restore the archive action when the V2 client exposes session archive. */}
|
||||||
|
<Show when={false}>
|
||||||
<div
|
<div
|
||||||
class="shrink-0 overflow-hidden transition-[width,opacity]"
|
class="shrink-0 overflow-hidden transition-[width,opacity]"
|
||||||
classList={{
|
classList={{
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ export type ProjectSidebarContext = {
|
|||||||
openSidebar: () => void
|
openSidebar: () => void
|
||||||
closeProject: (directory: string) => void
|
closeProject: (directory: string) => void
|
||||||
showEditProjectDialog: (project: LocalProject) => void
|
showEditProjectDialog: (project: LocalProject) => void
|
||||||
canEditProject: Accessor<boolean>
|
|
||||||
toggleProjectWorkspaces: (project: LocalProject) => void
|
toggleProjectWorkspaces: (project: LocalProject) => void
|
||||||
workspacesEnabled: (project: LocalProject) => boolean
|
workspacesEnabled: (project: LocalProject) => boolean
|
||||||
workspaceIds: (project: LocalProject) => string[]
|
workspaceIds: (project: LocalProject) => string[]
|
||||||
@@ -66,7 +65,6 @@ const ProjectTile = (props: {
|
|||||||
onProjectFocus: (worktree: string) => void
|
onProjectFocus: (worktree: string) => void
|
||||||
navigateToProject: (directory: string) => void
|
navigateToProject: (directory: string) => void
|
||||||
showEditProjectDialog: (project: LocalProject) => void
|
showEditProjectDialog: (project: LocalProject) => void
|
||||||
canEditProject: Accessor<boolean>
|
|
||||||
toggleProjectWorkspaces: (project: LocalProject) => void
|
toggleProjectWorkspaces: (project: LocalProject) => void
|
||||||
workspacesEnabled: (project: LocalProject) => boolean
|
workspacesEnabled: (project: LocalProject) => boolean
|
||||||
closeProject: (directory: string) => void
|
closeProject: (directory: string) => void
|
||||||
@@ -150,11 +148,9 @@ const ProjectTile = (props: {
|
|||||||
</ContextMenu.Trigger>
|
</ContextMenu.Trigger>
|
||||||
<ContextMenu.Portal>
|
<ContextMenu.Portal>
|
||||||
<ContextMenu.Content>
|
<ContextMenu.Content>
|
||||||
<Show when={props.canEditProject()}>
|
<ContextMenu.Item onSelect={() => props.showEditProjectDialog(props.project)}>
|
||||||
<ContextMenu.Item onSelect={() => props.showEditProjectDialog(props.project)}>
|
<ContextMenu.ItemLabel>{props.language.t("common.edit")}</ContextMenu.ItemLabel>
|
||||||
<ContextMenu.ItemLabel>{props.language.t("common.edit")}</ContextMenu.ItemLabel>
|
</ContextMenu.Item>
|
||||||
</ContextMenu.Item>
|
|
||||||
</Show>
|
|
||||||
<ContextMenu.Item
|
<ContextMenu.Item
|
||||||
data-action="project-workspaces-toggle"
|
data-action="project-workspaces-toggle"
|
||||||
data-project={base64Encode(props.project.worktree)}
|
data-project={base64Encode(props.project.worktree)}
|
||||||
@@ -309,7 +305,7 @@ export const SortableProject = (props: {
|
|||||||
const isWorking = createMemo(() =>
|
const isWorking = createMemo(() =>
|
||||||
dirs().some((directory) => {
|
dirs().some((directory) => {
|
||||||
return Object.keys(serverSync().session.data.session_status).some((id) => {
|
return Object.keys(serverSync().session.data.session_status).some((id) => {
|
||||||
if (serverSync().session.get(id)?.directory !== directory) return false
|
if (serverSync().session.get(id)?.location.directory !== directory) return false
|
||||||
return serverSync().session.data.session_working(id)
|
return serverSync().session.data.session_working(id)
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
@@ -335,7 +331,6 @@ export const SortableProject = (props: {
|
|||||||
onProjectFocus={props.ctx.onProjectFocus}
|
onProjectFocus={props.ctx.onProjectFocus}
|
||||||
navigateToProject={props.ctx.navigateToProject}
|
navigateToProject={props.ctx.navigateToProject}
|
||||||
showEditProjectDialog={props.ctx.showEditProjectDialog}
|
showEditProjectDialog={props.ctx.showEditProjectDialog}
|
||||||
canEditProject={props.ctx.canEditProject}
|
|
||||||
toggleProjectWorkspaces={props.ctx.toggleProjectWorkspaces}
|
toggleProjectWorkspaces={props.ctx.toggleProjectWorkspaces}
|
||||||
workspacesEnabled={props.ctx.workspacesEnabled}
|
workspacesEnabled={props.ctx.workspacesEnabled}
|
||||||
closeProject={props.ctx.closeProject}
|
closeProject={props.ctx.closeProject}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user