mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(app): drive quote comment, upload and @-mention search lifecycles through state machines (#62016)
This commit is contained in:
committed by
GitHub
Unverified
parent
e99b6c5ddd
commit
42be645ad7
@@ -115,6 +115,34 @@ test("a bare @ lists sessions, and a multi-word title matches while file search
|
||||
expect(prompts[1]?.text).toBe("@home now")
|
||||
})
|
||||
|
||||
test("closing the @ menu aborts its session search", async ({ page }) => {
|
||||
const view = await openSession(page, {
|
||||
name: "SessionMentionAbort",
|
||||
findFiles: () => [],
|
||||
sessions: [{ id: "ses_mention_abort_source", title: "Review the plan" }],
|
||||
seed: { tabs: ["ses_mention_abort_source"] },
|
||||
})
|
||||
|
||||
const suggestions = page.locator('[data-component="composer-suggestions"]')
|
||||
const search = await holdRoute(page, /\/api\/session\?.*search=auth(&|$)/)
|
||||
|
||||
try {
|
||||
await view.editor.pressSequentially("@auth")
|
||||
const request = await search.arrived
|
||||
|
||||
const failed = page.waitForEvent("requestfailed", {
|
||||
predicate: (candidate) => candidate === request,
|
||||
timeout: 10_000,
|
||||
})
|
||||
|
||||
await view.editor.press("Escape")
|
||||
await expect(suggestions).toBeHidden()
|
||||
expect((await failed).failure()?.errorText).toBe("net::ERR_ABORTED")
|
||||
} finally {
|
||||
search.release()
|
||||
}
|
||||
})
|
||||
|
||||
test("the free usage limit opens the Go dialog once, leaves a readable notice, and restores the prompt", async ({
|
||||
page,
|
||||
context,
|
||||
|
||||
@@ -2208,6 +2208,44 @@ test("a pending quote send hides mentions and keeps the comment read-only", asyn
|
||||
await expect.poll(() => sent).toEqual(["queue"])
|
||||
})
|
||||
|
||||
test("a double-clicked quote send sends once and keeps the popup open until it settles", async ({ page }) => {
|
||||
const sent: string[] = []
|
||||
|
||||
await setupTimeline(page, {
|
||||
messages: [userMessage(), assistantMessage([textPart("prt_quote_double", "Keep this quoted passage.")])],
|
||||
onPrompt: (input) => void sent.push(String(input.body.delivery)),
|
||||
})
|
||||
|
||||
const answer = page.locator(
|
||||
`[data-timeline-part-id="${renderedPartID("prt_quote_double")}"] [data-slot="text-part-body"]`,
|
||||
)
|
||||
|
||||
await expect(answer).toHaveText("Keep this quoted passage.")
|
||||
await selectQuoteText(answer)
|
||||
await page
|
||||
.getByRole("toolbar", { name: "Quote selection" })
|
||||
.getByRole("button", { name: "Quote", exact: true })
|
||||
.click()
|
||||
const popup = page.locator('[data-component="composer-quote-comment"]')
|
||||
|
||||
const chip = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]')
|
||||
|
||||
const modifier = await page.evaluate(() => (/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "Meta" : "Control"))
|
||||
|
||||
await popup.locator("textarea").fill("Only once")
|
||||
const admission = await holdRoute(page, new RegExp(`/api/session/${sessionID}/prompt(\\?|$)`), { method: "POST" })
|
||||
|
||||
await popup.locator('[data-slot="line-comment-v2-submit"]').dblclick({ modifiers: [modifier] })
|
||||
await admission.arrived
|
||||
// A click on the quote's chip while the send is in flight leaves the popup and its pending send alone.
|
||||
await chip.click()
|
||||
await expect(popup.locator('[data-component="loader-v2"]')).toBeVisible()
|
||||
admission.release()
|
||||
await expect(popup).toHaveCount(0)
|
||||
await expect.poll(() => sent.length).toBe(1)
|
||||
expect(admission.requests).toHaveLength(1)
|
||||
})
|
||||
|
||||
function selectQuoteText(target: Locator) {
|
||||
return target.evaluate((element) => {
|
||||
const range = document.createRange()
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { onCleanup, onMount } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { createBlobReference } from "@/runtime/persistence/drafts"
|
||||
import { uuid } from "@opencode/util/uuid"
|
||||
@@ -9,6 +8,8 @@ import type { AttachmentDestination } from "./destination"
|
||||
import { uploads } from "./uploads"
|
||||
|
||||
type PromptTarget = {
|
||||
/** The draft the prompt belongs to, which owns uploads started for it across composer remounts. */
|
||||
scope?: object
|
||||
current: () => ComposerPrompt
|
||||
cursor: () => number | undefined
|
||||
set: (prompt: ComposerPrompt, cursor?: number) => void
|
||||
@@ -55,8 +56,9 @@ export function createComposerAttachments(
|
||||
return { prompt, cursor: prompt.cursor() ?? cursorPosition(editor) }
|
||||
}
|
||||
|
||||
// Uploads this composer started; they finish (or fail) even if the composer unmounts.
|
||||
const [pending, setPending] = createStore<{ ids: string[] }>({ ids: [] })
|
||||
// A composer without a draft scope owns its uploads itself.
|
||||
const fallbackScope = {}
|
||||
const scopeOf = (prompt = input.capture()) => prompt.scope ?? fallbackScope
|
||||
|
||||
// Media the model reads natively travels inline with the prompt, so its bytes live in the draft
|
||||
// store. Everything else, including text, reaches the model as a path on the server that its
|
||||
@@ -125,19 +127,16 @@ export function createComposerAttachments(
|
||||
target: NonNullable<ReturnType<typeof capture>>,
|
||||
destination: AttachmentDestination,
|
||||
) => {
|
||||
const id = uuid()
|
||||
setPending("ids", (ids) => [...ids, id])
|
||||
|
||||
const path = await uploads
|
||||
.track({ id, filename: file.name, mime, size: file.size }, (report, signal) =>
|
||||
destination.upload(file, report, signal),
|
||||
.track(
|
||||
{ id: uuid(), scope: scopeOf(target.prompt), filename: file.name, mime, size: file.size },
|
||||
(report, signal) => destination.upload(file, report, signal),
|
||||
)
|
||||
.catch((error) => {
|
||||
input.onUploadError(error)
|
||||
|
||||
return undefined
|
||||
})
|
||||
.finally(() => setPending("ids", (ids) => ids.filter((item) => item !== id)))
|
||||
|
||||
if (path) addPath(target, { filename: file.name, mime, path })
|
||||
}
|
||||
@@ -251,10 +250,8 @@ export function createComposerAttachments(
|
||||
handlePaste,
|
||||
handleDrop,
|
||||
/** Uploads still in flight for this composer; sending waits for them. */
|
||||
pending: () => uploads.items().filter((item) => pending.ids.includes(item.id)),
|
||||
cancel(id: string) {
|
||||
uploads.items().find((item) => item.id === id)?.cancel()
|
||||
},
|
||||
pending: () => uploads.forScope(scopeOf()),
|
||||
cancel: (id: string) => uploads.cancel(id),
|
||||
pick(fallback: () => void, done: () => void) {
|
||||
if (!input.picker) {
|
||||
fallback()
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// An upload whose body stops advancing for this long is stuck on a dead connection; it fails instead of blocking sends.
|
||||
export const UPLOAD_STALL_TIMEOUT_MS = 60_000
|
||||
|
||||
/** The failure a stalled upload rejects with; it carries no message, so the toast shows the generic one. */
|
||||
export const UPLOAD_TIMED_OUT = Object.freeze({ reason: "timed-out" as const })
|
||||
|
||||
/** The draft an upload writes into, compared by identity; closing that draft cancels its uploads. */
|
||||
export type UploadScope = object
|
||||
|
||||
export type UploadEntry = {
|
||||
readonly id: string
|
||||
readonly attempt: number
|
||||
readonly scope: UploadScope
|
||||
readonly filename: string
|
||||
readonly mime: string
|
||||
readonly size: number
|
||||
readonly loaded: number
|
||||
/**
|
||||
* Only `sending` arms the stall timer. A `queued` request may wait behind the browser's per-host connection
|
||||
* limit before its first progress event, and a `sent` body waits on the server's answer; neither is a stall.
|
||||
*/
|
||||
readonly transfer: "queued" | "sending" | "sent"
|
||||
}
|
||||
|
||||
/**
|
||||
* Every upload in flight, process-wide: uploads outlive the composer view that started them.
|
||||
* - `idle`: nothing uploads.
|
||||
* - `uploading`: `entries` is never empty, in start order.
|
||||
*/
|
||||
export type UploadMachineState =
|
||||
| { readonly status: "idle"; readonly issued: number }
|
||||
| { readonly status: "uploading"; readonly issued: number; readonly entries: readonly UploadEntry[] }
|
||||
|
||||
export type UploadMachineEvent =
|
||||
| {
|
||||
readonly type: "upload.started"
|
||||
readonly id: string
|
||||
readonly scope: UploadScope
|
||||
readonly filename: string
|
||||
readonly mime: string
|
||||
readonly size: number
|
||||
}
|
||||
| { readonly type: "upload.progress"; readonly attempt: number; readonly loaded: number }
|
||||
| { readonly type: "upload.succeeded"; readonly attempt: number; readonly path: string }
|
||||
| { readonly type: "upload.failed"; readonly attempt: number; readonly error: unknown }
|
||||
| { readonly type: "upload.timed-out"; readonly attempt: number }
|
||||
| { readonly type: "upload.cancelled"; readonly id: string }
|
||||
| { readonly type: "scope.cancelled"; readonly scope: UploadScope }
|
||||
|
||||
export type UploadMachineEffect =
|
||||
| { readonly type: "upload.run"; readonly attempt: number }
|
||||
| { readonly type: "timer.reset"; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "timer.clear"; readonly attempt: number }
|
||||
| { readonly type: "upload.abort"; readonly attempt: number }
|
||||
| { readonly type: "upload.resolve"; readonly attempt: number; readonly path: string | undefined }
|
||||
| { readonly type: "upload.reject"; readonly attempt: number; readonly error: unknown }
|
||||
|
||||
export type UploadMachineTransition = {
|
||||
readonly state: UploadMachineState
|
||||
readonly effects: readonly UploadMachineEffect[]
|
||||
}
|
||||
|
||||
export const INITIAL_UPLOAD_MACHINE_STATE: UploadMachineState = Object.freeze({ status: "idle", issued: 0 })
|
||||
|
||||
const NO_EFFECTS: readonly UploadMachineEffect[] = Object.freeze([])
|
||||
|
||||
const NO_ENTRIES: readonly UploadEntry[] = Object.freeze([])
|
||||
|
||||
export function transitionUploads(state: UploadMachineState, event: UploadMachineEvent): UploadMachineTransition {
|
||||
if (event.type === "upload.started") {
|
||||
const entries = selectUploadEntries(state)
|
||||
|
||||
if (entries.some((entry) => entry.id === event.id)) return stay(state)
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "uploading",
|
||||
issued: attempt,
|
||||
entries: [
|
||||
...entries,
|
||||
{
|
||||
id: event.id,
|
||||
attempt,
|
||||
scope: event.scope,
|
||||
filename: event.filename,
|
||||
mime: event.mime,
|
||||
size: event.size,
|
||||
loaded: 0,
|
||||
transfer: "queued",
|
||||
},
|
||||
],
|
||||
},
|
||||
effects: [{ type: "upload.run", attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === "idle") return stay(state)
|
||||
|
||||
if (event.type === "scope.cancelled") {
|
||||
const cancelled = state.entries.filter((entry) => entry.scope === event.scope)
|
||||
|
||||
if (cancelled.length === 0) return stay(state)
|
||||
|
||||
return finish(
|
||||
state,
|
||||
state.entries.filter((entry) => entry.scope !== event.scope),
|
||||
cancelled.flatMap((entry) => cancel(entry.attempt)),
|
||||
)
|
||||
}
|
||||
|
||||
const entry = state.entries.find((item) =>
|
||||
event.type === "upload.cancelled" ? item.id === event.id : item.attempt === event.attempt,
|
||||
)
|
||||
|
||||
if (!entry) return stay(state)
|
||||
const rest = () => state.entries.filter((item) => item !== entry)
|
||||
|
||||
switch (event.type) {
|
||||
case "upload.progress": {
|
||||
const loaded = Math.min(Math.max(event.loaded, entry.loaded), entry.size)
|
||||
const transfer = loaded === entry.size ? "sent" : "sending"
|
||||
|
||||
if (loaded === entry.loaded && transfer === entry.transfer) return stay(state)
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
entries: state.entries.map((item) => (item === entry ? { ...entry, loaded, transfer } : item)),
|
||||
},
|
||||
effects:
|
||||
transfer === "sending"
|
||||
? [{ type: "timer.reset", attempt: entry.attempt, timeoutMs: UPLOAD_STALL_TIMEOUT_MS }]
|
||||
: entry.transfer === "sending"
|
||||
? [{ type: "timer.clear", attempt: entry.attempt }]
|
||||
: NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
case "upload.succeeded":
|
||||
return finish(state, rest(), [{ type: "upload.resolve", attempt: entry.attempt, path: event.path }])
|
||||
case "upload.failed":
|
||||
return finish(state, rest(), [{ type: "upload.reject", attempt: entry.attempt, error: event.error }])
|
||||
case "upload.timed-out":
|
||||
if (entry.transfer !== "sending") return stay(state)
|
||||
|
||||
return finish(state, rest(), [
|
||||
{ type: "upload.abort", attempt: entry.attempt },
|
||||
{ type: "upload.reject", attempt: entry.attempt, error: UPLOAD_TIMED_OUT },
|
||||
])
|
||||
case "upload.cancelled":
|
||||
return finish(state, rest(), cancel(entry.attempt))
|
||||
}
|
||||
}
|
||||
|
||||
export function selectUploadEntries(state: UploadMachineState) {
|
||||
return state.status === "uploading" ? state.entries : NO_ENTRIES
|
||||
}
|
||||
|
||||
export function uploadPercent(item: Pick<UploadEntry, "loaded" | "size">) {
|
||||
return item.size === 0 ? 100 : Math.floor((item.loaded / item.size) * 100)
|
||||
}
|
||||
|
||||
// A cancelled upload settles without its work: the work may wait where it cannot observe the abort.
|
||||
function cancel(attempt: number): UploadMachineEffect[] {
|
||||
return [
|
||||
{ type: "upload.abort", attempt },
|
||||
{ type: "upload.resolve", attempt, path: undefined },
|
||||
]
|
||||
}
|
||||
|
||||
function finish(
|
||||
state: Extract<UploadMachineState, { status: "uploading" }>,
|
||||
entries: readonly UploadEntry[],
|
||||
effects: readonly UploadMachineEffect[],
|
||||
): UploadMachineTransition {
|
||||
return {
|
||||
state: entries.length === 0 ? { status: "idle", issued: state.issued } : { ...state, entries },
|
||||
effects,
|
||||
}
|
||||
}
|
||||
|
||||
function stay(state: UploadMachineState): UploadMachineTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -1,14 +1,127 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { afterEach, describe, expect, jest, test } from "bun:test"
|
||||
import { uploads } from "./uploads"
|
||||
import {
|
||||
INITIAL_UPLOAD_MACHINE_STATE,
|
||||
UPLOAD_STALL_TIMEOUT_MS,
|
||||
UPLOAD_TIMED_OUT,
|
||||
transitionUploads,
|
||||
type UploadMachineEvent,
|
||||
type UploadMachineState,
|
||||
type UploadMachineTransition,
|
||||
type UploadScope,
|
||||
} from "./upload-machine"
|
||||
|
||||
test("cancelling an upload drops it even when its work never settles", async () => {
|
||||
const pending = uploads.track({ id: "stalled", filename: "image.png", mime: "image/png", size: 1024 }, () =>
|
||||
new Promise<string>(() => {}),
|
||||
)
|
||||
const scopeA = {}
|
||||
|
||||
expect(uploads.items().map((item) => item.id)).toEqual(["stalled"])
|
||||
uploads.items()[0]?.cancel()
|
||||
const scopeB = {}
|
||||
|
||||
expect(await pending).toBeUndefined()
|
||||
expect(uploads.items()).toEqual([])
|
||||
function start(id: string, scope: UploadScope): UploadMachineEvent {
|
||||
return { type: "upload.started", id, scope, filename: `${id}.bin`, mime: "application/octet-stream", size: 1024 }
|
||||
}
|
||||
|
||||
function replay(events: UploadMachineEvent[], state: UploadMachineState = INITIAL_UPLOAD_MACHINE_STATE) {
|
||||
const initial: UploadMachineTransition = { state, effects: [] }
|
||||
|
||||
return events.reduce((result, event) => transitionUploads(result.state, event), initial)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
describe("transitionUploads", () => {
|
||||
test("a queued upload has no stall timer until its first progress event, then only forward progress resets it", () => {
|
||||
const queued = replay([start("u1", scopeA)])
|
||||
|
||||
expect(queued.effects).toEqual([{ type: "upload.run", attempt: 1 }])
|
||||
expect(transitionUploads(queued.state, { type: "upload.timed-out", attempt: 1 }).state).toBe(queued.state)
|
||||
|
||||
const connected = replay([{ type: "upload.progress", attempt: 1, loaded: 0 }], queued.state)
|
||||
|
||||
expect(connected.state).toMatchObject({ entries: [{ id: "u1", loaded: 0, transfer: "sending" }] })
|
||||
expect(connected.effects).toEqual([{ type: "timer.reset", attempt: 1, timeoutMs: UPLOAD_STALL_TIMEOUT_MS }])
|
||||
|
||||
const progressed = replay([{ type: "upload.progress", attempt: 1, loaded: 512 }], connected.state)
|
||||
|
||||
expect(progressed.effects).toEqual([{ type: "timer.reset", attempt: 1, timeoutMs: UPLOAD_STALL_TIMEOUT_MS }])
|
||||
expect(transitionUploads(progressed.state, { type: "upload.progress", attempt: 1, loaded: 256 }).state).toBe(
|
||||
progressed.state,
|
||||
)
|
||||
|
||||
expect(transitionUploads(progressed.state, { type: "upload.timed-out", attempt: 1 })).toEqual({
|
||||
state: { status: "idle", issued: 1 },
|
||||
effects: [
|
||||
{ type: "upload.abort", attempt: 1 },
|
||||
{ type: "upload.reject", attempt: 1, error: UPLOAD_TIMED_OUT },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
test("a fully sent body waits for the server's answer without a stall timer", () => {
|
||||
const sending = replay([start("u1", scopeA), { type: "upload.progress", attempt: 1, loaded: 512 }])
|
||||
const sent = replay([{ type: "upload.progress", attempt: 1, loaded: 4096 }], sending.state)
|
||||
|
||||
expect(sent.state).toMatchObject({ entries: [{ id: "u1", loaded: 1024, transfer: "sent" }] })
|
||||
expect(sent.effects).toEqual([{ type: "timer.clear", attempt: 1 }])
|
||||
expect(transitionUploads(sent.state, { type: "upload.timed-out", attempt: 1 }).state).toBe(sent.state)
|
||||
expect(transitionUploads(sent.state, { type: "upload.succeeded", attempt: 1, path: "/tmp/u1.bin" })).toEqual({
|
||||
state: { status: "idle", issued: 1 },
|
||||
effects: [{ type: "upload.resolve", attempt: 1, path: "/tmp/u1.bin" }],
|
||||
})
|
||||
})
|
||||
|
||||
test("closing a draft cancels only that draft's uploads", () => {
|
||||
const result = replay([start("u1", scopeA), start("u2", scopeB), { type: "scope.cancelled", scope: scopeA }])
|
||||
|
||||
expect(result.state).toMatchObject({ status: "uploading", entries: [{ id: "u2", scope: scopeB }] })
|
||||
expect(result.effects).toEqual([
|
||||
{ type: "upload.abort", attempt: 1 },
|
||||
{ type: "upload.resolve", attempt: 1, path: undefined },
|
||||
])
|
||||
})
|
||||
|
||||
test("a result for an upload that was cancelled or already settled is ignored", () => {
|
||||
const cancelled = replay([start("u1", scopeA), { type: "upload.cancelled", id: "u1" }])
|
||||
|
||||
expect(cancelled.state).toEqual({ status: "idle", issued: 1 })
|
||||
expect(transitionUploads(cancelled.state, { type: "upload.failed", attempt: 1, error: new Error("x") }).state).toBe(
|
||||
cancelled.state,
|
||||
)
|
||||
expect(transitionUploads(cancelled.state, { type: "upload.cancelled", id: "u1" }).state).toBe(cancelled.state)
|
||||
})
|
||||
})
|
||||
|
||||
describe("uploads", () => {
|
||||
test("cancelling an upload drops it even when its work never settles", async () => {
|
||||
const pending = uploads.track(
|
||||
{ id: "stalled", scope: scopeA, filename: "image.png", mime: "image/png", size: 1024 },
|
||||
() => new Promise<string>(() => {}),
|
||||
)
|
||||
|
||||
expect(uploads.items().map((item) => item.id)).toEqual(["stalled"])
|
||||
uploads.items()[0]?.cancel()
|
||||
|
||||
expect(await pending).toBeUndefined()
|
||||
expect(uploads.items()).toEqual([])
|
||||
})
|
||||
|
||||
test("an upload whose body stops advancing fails after the stall timeout instead of blocking sends", async () => {
|
||||
jest.useFakeTimers()
|
||||
|
||||
const pending = uploads.track(
|
||||
{ id: "hung", scope: scopeB, filename: "big.zip", mime: "application/zip", size: 1024 },
|
||||
(report) => {
|
||||
report(100)
|
||||
|
||||
return new Promise<string>(() => {})
|
||||
},
|
||||
)
|
||||
|
||||
expect(uploads.forScope(scopeB).map((item) => item.id)).toEqual(["hung"])
|
||||
expect(uploads.forScope(scopeA)).toEqual([])
|
||||
jest.advanceTimersByTime(UPLOAD_STALL_TIMEOUT_MS)
|
||||
|
||||
await expect(pending).rejects.toBe(UPLOAD_TIMED_OUT)
|
||||
expect(uploads.forScope(scopeB)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import { createEffect, createRoot, For, on, onCleanup } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createEffect, createRoot, createSignal, For, on, onCleanup, untrack } from "solid-js"
|
||||
import { createStore, reconcile } from "solid-js/store"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { Toast, toaster } from "@opencode/ui/toast"
|
||||
import { abort } from "@opencode/util/abort"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import {
|
||||
INITIAL_UPLOAD_MACHINE_STATE,
|
||||
selectUploadEntries,
|
||||
transitionUploads,
|
||||
uploadPercent,
|
||||
type UploadEntry,
|
||||
type UploadScope,
|
||||
type UploadMachineEffect,
|
||||
type UploadMachineEvent,
|
||||
} from "./upload-machine"
|
||||
|
||||
export type Upload = {
|
||||
id: string
|
||||
@@ -13,39 +24,112 @@ export type Upload = {
|
||||
cancel: () => void
|
||||
}
|
||||
|
||||
// Uploads outlive the composer that started them, so one process-wide list feeds every chip
|
||||
type UploadWork = (report: (loaded: number) => void, signal: AbortSignal) => Promise<string>
|
||||
|
||||
// Uploads outlive the composer that started them, so one process-wide machine feeds every chip
|
||||
// and the single progress toast.
|
||||
const [state, setState] = createStore<{ items: Upload[] }>({ items: [] })
|
||||
const [machineState, setMachineState] = createSignal(INITIAL_UPLOAD_MACHINE_STATE)
|
||||
|
||||
export const uploads = {
|
||||
items: () => state.items,
|
||||
/** Runs `work` while the upload is listed. Resolves to undefined when the user cancels it. */
|
||||
async track<T>(
|
||||
input: Pick<Upload, "id" | "filename" | "mime" | "size">,
|
||||
work: (report: (loaded: number) => void, signal: AbortSignal) => Promise<T>,
|
||||
): Promise<T | undefined> {
|
||||
const controller = new AbortController()
|
||||
// Rows keep their identity while progress streams, so a cancel button under the pointer is not replaced.
|
||||
const [view, setView] = createStore<{ items: Upload[] }>({ items: [] })
|
||||
|
||||
// The work may wait where it cannot observe the signal, such as a request queued behind
|
||||
// others, so cancelling settles without it.
|
||||
const cancelled = new Promise<undefined>((resolve) =>
|
||||
controller.signal.addEventListener("abort", () => resolve(undefined), { once: true }),
|
||||
type Run = {
|
||||
work: UploadWork
|
||||
result: PromiseWithResolvers<string | undefined>
|
||||
controller: AbortController
|
||||
timer?: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
const runs = new Map<number, Run>()
|
||||
|
||||
// Handed from `track` to the `upload.run` effect its start causes in the same dispatch.
|
||||
let starting: { work: UploadWork; result: PromiseWithResolvers<string | undefined> } | undefined
|
||||
|
||||
function dispatch(event: UploadMachineEvent) {
|
||||
const previous = untrack(machineState)
|
||||
const next = transitionUploads(previous, event)
|
||||
|
||||
if (next.state !== previous) {
|
||||
setMachineState(next.state)
|
||||
setView("items", reconcile(selectUploadEntries(next.state).map(row), { key: "id" }))
|
||||
}
|
||||
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
function row(entry: UploadEntry): Upload {
|
||||
return {
|
||||
id: entry.id,
|
||||
filename: entry.filename,
|
||||
mime: entry.mime,
|
||||
size: entry.size,
|
||||
loaded: entry.loaded,
|
||||
cancel: () => dispatch({ type: "upload.cancelled", id: entry.id }),
|
||||
}
|
||||
}
|
||||
|
||||
function run(effect: UploadMachineEffect) {
|
||||
const attempt = effect.attempt
|
||||
|
||||
if (effect.type === "upload.run") {
|
||||
if (!starting) return
|
||||
const current: Run = { ...starting, controller: new AbortController() }
|
||||
starting = undefined
|
||||
runs.set(attempt, current)
|
||||
void Promise.try(() =>
|
||||
current.work((loaded) => dispatch({ type: "upload.progress", attempt, loaded }), current.controller.signal),
|
||||
).then(
|
||||
(path) => dispatch({ type: "upload.succeeded", attempt, path }),
|
||||
(error) => dispatch({ type: "upload.failed", attempt, error }),
|
||||
)
|
||||
|
||||
setState("items", (items) => [...items, { ...input, loaded: 0, cancel: () => controller.abort() }])
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
work((loaded) => setState("items", (item) => item.id === input.id, "loaded", loaded), controller.signal),
|
||||
cancelled,
|
||||
])
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return undefined
|
||||
throw error
|
||||
} finally {
|
||||
setState("items", (items) => items.filter((item) => item.id !== input.id))
|
||||
}
|
||||
const current = runs.get(attempt)
|
||||
|
||||
if (!current) return
|
||||
clearTimeout(current.timer)
|
||||
|
||||
if (effect.type === "timer.clear") return
|
||||
|
||||
if (effect.type === "timer.reset") {
|
||||
current.timer = setTimeout(() => dispatch({ type: "upload.timed-out", attempt }), effect.timeoutMs)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "upload.abort") return abort(current.controller)
|
||||
runs.delete(attempt)
|
||||
|
||||
if (effect.type === "upload.resolve") return current.result.resolve(effect.path)
|
||||
current.result.reject(effect.error)
|
||||
}
|
||||
|
||||
export const uploads = {
|
||||
items: () => view.items,
|
||||
/** Uploads in flight for one draft; they survive the composer view remounting. */
|
||||
forScope(scope: UploadScope) {
|
||||
const ids = selectUploadEntries(machineState()).flatMap((entry) => (entry.scope === scope ? [entry.id] : []))
|
||||
|
||||
return view.items.filter((item) => ids.includes(item.id))
|
||||
},
|
||||
/** Runs `work` while the upload is listed and resolves to its path, or to undefined when it is cancelled. */
|
||||
track(input: Pick<UploadEntry, "id" | "scope" | "filename" | "mime" | "size">, work: UploadWork) {
|
||||
const result = Promise.withResolvers<string | undefined>()
|
||||
starting = { work, result }
|
||||
dispatch({ type: "upload.started", ...input })
|
||||
|
||||
// A duplicate id starts nothing.
|
||||
if (starting) {
|
||||
starting = undefined
|
||||
result.resolve(undefined)
|
||||
}
|
||||
|
||||
return result.promise
|
||||
},
|
||||
cancel: (id: string) => dispatch({ type: "upload.cancelled", id }),
|
||||
cancelScope: (scope: UploadScope) => dispatch({ type: "scope.cancelled", scope }),
|
||||
}
|
||||
|
||||
// Sonner builds toast content outside the app's Solid tree: no context and no owner. This host
|
||||
@@ -53,34 +137,45 @@ export const uploads = {
|
||||
// root of its own so progress stays reactive.
|
||||
export function UploadToastHost() {
|
||||
const language = useLanguage()
|
||||
let active: { id: number; dispose: () => void } | undefined
|
||||
let toast: { id: number; dispose: () => void } | undefined
|
||||
|
||||
const dismiss = () => {
|
||||
if (!active) return
|
||||
toaster.dismiss(active.id)
|
||||
active.dispose()
|
||||
active = undefined
|
||||
if (!toast) return
|
||||
toaster.dismiss(toast.id)
|
||||
toast.dispose()
|
||||
toast = undefined
|
||||
}
|
||||
|
||||
createEffect(
|
||||
on(
|
||||
() => state.items.length > 0,
|
||||
() => view.items.length > 0,
|
||||
(uploading) => {
|
||||
if (!uploading) return dismiss()
|
||||
|
||||
if (active) return
|
||||
if (toast) return
|
||||
let root: (() => void) | undefined
|
||||
|
||||
const id = toaster.show(
|
||||
(props) =>
|
||||
createRoot((dispose) => {
|
||||
active = { id: props.toastId, dispose }
|
||||
(props) => {
|
||||
// Sonner renders the content again when the toast resizes; the previous root must not leak.
|
||||
root?.()
|
||||
|
||||
return createRoot((dispose) => {
|
||||
root = dispose
|
||||
|
||||
return <UploadToast toastId={props.toastId} language={language} />
|
||||
}),
|
||||
{ persistent: true, resize: () => state.items.length },
|
||||
})
|
||||
},
|
||||
{ persistent: true, resize: () => view.items.length },
|
||||
)
|
||||
|
||||
active ??= { id, dispose: () => {} }
|
||||
toast = {
|
||||
id,
|
||||
dispose: () => {
|
||||
root?.()
|
||||
root = undefined
|
||||
},
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -90,12 +185,10 @@ export function UploadToastHost() {
|
||||
}
|
||||
|
||||
function UploadToast(props: { toastId: number; language: ReturnType<typeof useLanguage> }) {
|
||||
const percent = (item: Upload) => (item.size === 0 ? 100 : Math.floor((item.loaded / item.size) * 100))
|
||||
|
||||
return (
|
||||
<Toast toastId={props.toastId}>
|
||||
<Toast.Content>
|
||||
<For each={state.items}>
|
||||
<For each={view.items}>
|
||||
{(item) => (
|
||||
<div data-component="upload-row">
|
||||
<div data-slot="upload-row-label">
|
||||
@@ -103,7 +196,7 @@ function UploadToast(props: { toastId: number; language: ReturnType<typeof useLa
|
||||
{item.filename}
|
||||
</span>
|
||||
<span data-slot="upload-row-percent">
|
||||
{props.language.t("prompt.toast.uploading.percent", { percent: percent(item) })}
|
||||
{props.language.t("prompt.toast.uploading.percent", { percent: uploadPercent(item) })}
|
||||
</span>
|
||||
</div>
|
||||
<div data-slot="upload-row-track">
|
||||
@@ -113,9 +206,9 @@ function UploadToast(props: { toastId: number; language: ReturnType<typeof useLa
|
||||
aria-label={item.filename}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={percent(item)}
|
||||
aria-valuenow={uploadPercent(item)}
|
||||
>
|
||||
<div data-slot="upload-progress-bar" style={{ width: `${percent(item)}%` }} />
|
||||
<div data-slot="upload-progress-bar" style={{ width: `${uploadPercent(item)}%` }} />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
transitionEditorSync,
|
||||
} from "./machine"
|
||||
import { QuoteCommentEditor } from "./quote-comment"
|
||||
import { selectQuoteCommentView, type QuoteCommentController } from "../quote-comment-machine"
|
||||
import "../attachments/attachments.css"
|
||||
import "./editor.css"
|
||||
import "@/shell/palette-menu.css"
|
||||
@@ -282,10 +283,8 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
onCommentClick={(comment) => props.controller.toggleContext(comment.key)}
|
||||
onCommentRemove={(comment) => props.controller.removeContext(comment.key)}
|
||||
onFileRemove={(file) => props.controller.removeContext(file.key)}
|
||||
editingQuote={props.controller.editingQuote()}
|
||||
quoteAnchor={props.controller.quoteAnchor()}
|
||||
quoteComment={props.controller.quoteComment}
|
||||
onQuoteFocus={props.controller.focusQuotePrompt}
|
||||
onEditQuote={props.controller.editQuote}
|
||||
onQuoteComment={(quote, comment) => props.controller.commentQuote(quote.key, comment)}
|
||||
quoteSubmit={view.submit.quote}
|
||||
searchPaths={props.controller.searchPaths}
|
||||
@@ -724,10 +723,8 @@ function ComposerAttachments(props: {
|
||||
onCommentClick?: (comment: ComposerComment) => void
|
||||
onCommentRemove?: (comment: ComposerComment) => void
|
||||
onFileRemove?: (file: Extract<ComposerComment, { type: "file" }>) => void
|
||||
editingQuote?: string
|
||||
quoteAnchor?: ReturnType<ComposerEditorModel["quoteAnchor"]>
|
||||
quoteComment: QuoteCommentController
|
||||
onQuoteFocus?: () => void
|
||||
onEditQuote?: (key?: string) => void
|
||||
onQuoteComment?: (quote: Extract<ComposerComment, { type: "quote" }>, comment: string) => void
|
||||
quoteSubmit?: ComposerEditorModel["view"]["submit"]["quote"]
|
||||
searchPaths?: (query: string) => Promise<string[]>
|
||||
@@ -739,15 +736,15 @@ function ComposerAttachments(props: {
|
||||
|
||||
// Plain functions, not inline conditionals: the tooltip reads these from event handlers, outside any owner.
|
||||
const quoteTitle = (comment: ComposerComment) => (comment.type === "quote" ? quoteTooltip(comment) : undefined)
|
||||
const quoteHint = (comment: ComposerComment) => comment.type === "quote" && props.editingQuote !== comment.key
|
||||
const quoteHint = (comment: ComposerComment) => comment.type === "quote" && props.quoteComment.key() !== comment.key
|
||||
|
||||
const commentActive = (comment: ComposerComment) =>
|
||||
comment.key === props.activeCommentID || comment.key === props.editingQuote
|
||||
comment.key === props.activeCommentID || comment.key === props.quoteComment.key()
|
||||
|
||||
const editing = createMemo(() =>
|
||||
props.comments?.find(
|
||||
(comment): comment is Extract<ComposerComment, { type: "quote" }> =>
|
||||
comment.type === "quote" && comment.key === props.editingQuote,
|
||||
comment.type === "quote" && comment.key === props.quoteComment.key(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -789,16 +786,13 @@ function ComposerAttachments(props: {
|
||||
active={commentActive(comment)}
|
||||
onClick={() => {
|
||||
if (comment.type !== "quote") return props.onCommentClick?.(comment)
|
||||
props.onEditQuote?.(props.editingQuote === comment.key ? undefined : comment.key)
|
||||
props.quoteComment.set(props.quoteComment.key() === comment.key ? undefined : comment.key)
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (props.editingQuote === comment.key) props.onEditQuote?.()
|
||||
props.onCommentRemove?.(comment)
|
||||
}}
|
||||
onClick={() => props.onCommentRemove?.(comment)}
|
||||
class="absolute -top-1 -end-1 size-4 rounded-full bg-v2-icon-icon-muted outline-solid outline-1 outline-v2-icon-icon-contrast flex items-center justify-center hover-reveal group-hover:opacity-100"
|
||||
aria-label={props.removeLabel}
|
||||
>
|
||||
@@ -922,24 +916,26 @@ function ComposerAttachments(props: {
|
||||
{(anchor) => (
|
||||
<QuoteCommentEditor
|
||||
anchor={anchor()}
|
||||
source={props.quoteAnchor}
|
||||
source={props.quoteComment.anchor()}
|
||||
text={current.text}
|
||||
comment={current.comment ?? ""}
|
||||
view={selectQuoteCommentView(props.quoteComment.state(), current.key, current.comment ?? "")}
|
||||
mention={(query) => props.searchPaths?.(query) ?? Promise.resolve([])}
|
||||
onInput={props.quoteComment.setDraft}
|
||||
send={
|
||||
props.quoteSubmit && {
|
||||
available: props.quoteSubmit.available(),
|
||||
delivery: props.quoteSubmit.delivery(),
|
||||
onSubmit: (comment) => props.quoteSubmit!.onSubmit(current.key, comment),
|
||||
onSubmit: (comment) => props.quoteComment.send(comment, props.quoteSubmit!.onSubmit),
|
||||
}
|
||||
}
|
||||
onSubmit={(comment) => {
|
||||
props.onQuoteComment?.(current, comment)
|
||||
props.onEditQuote?.()
|
||||
props.quoteComment.set()
|
||||
props.onQuoteFocus?.()
|
||||
}}
|
||||
onClose={(focus) => {
|
||||
props.onEditQuote?.()
|
||||
props.quoteComment.set()
|
||||
|
||||
if (focus) props.onQuoteFocus?.()
|
||||
}}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Predicate } from "effect"
|
||||
import { createEffect, createMemo, createSignal, on, onCleanup, type Accessor } from "solid-js"
|
||||
import { createStore, reconcile } from "solid-js/store"
|
||||
import { createEffect, createMemo, createSignal, on, onCleanup, untrack, type Accessor } from "solid-js"
|
||||
import { createStore, reconcile, unwrap } from "solid-js/store"
|
||||
import { useFilteredList } from "@opencode/ui/hooks"
|
||||
import { abort } from "@opencode/util/abort"
|
||||
import { createComposerAttachments, type ComposerAttachmentConfig } from "../attachments/attachments"
|
||||
@@ -25,7 +25,18 @@ import {
|
||||
import { clonePrompt, isAttachment, promptLength } from "../prompt-parts"
|
||||
import type { ComposerDelivery, ComposerQueue } from "../adapter"
|
||||
import { isCommentItem } from "../state"
|
||||
import type { ComposerQuoteAnchor } from "@opencode/plugin/gui"
|
||||
import { createQuoteCommentController, type QuoteCommentController } from "../quote-comment-machine"
|
||||
import {
|
||||
INITIAL_MENTION_SEARCH_STATE,
|
||||
isMentionFileStale,
|
||||
selectMentionFiles,
|
||||
selectMentionSessionsPending,
|
||||
transitionMentionSearch,
|
||||
type MentionSearchEffect,
|
||||
type MentionSearchEvent,
|
||||
} from "./mention-search-machine"
|
||||
|
||||
const MENTION_CONTEXT_CLOSED: MentionSearchEvent = Object.freeze({ type: "context.closed" })
|
||||
|
||||
export type ComposerSelectControl = {
|
||||
options: Accessor<ComposerOption[]>
|
||||
@@ -80,19 +91,15 @@ export function createComposerEditor(input: {
|
||||
searchContextFiles: (query: string, signal?: AbortSignal) => ComposerSuggestion[] | Promise<ComposerSuggestion[]>
|
||||
/** Reads reactively, so newly found sessions refresh the list without waiting on file search. */
|
||||
searchSessions?: (query: string) => ComposerSuggestion[]
|
||||
/** Whether the session search for this query has yet to settle; reads reactively. */
|
||||
sessionsPending?: (query: string) => boolean
|
||||
/** Loads sessions matching `word` into what `searchSessions` reads; settles once they are in. */
|
||||
requestSessionSearch?: (word: string, signal: AbortSignal) => Promise<void>
|
||||
openAttachment?: (attachment: ComposerAttachment, origin?: HTMLElement) => void
|
||||
/** An object URL for the image file at this path, which a path attachment references without its bytes. */
|
||||
readImage?: (path: string) => Promise<string | undefined>
|
||||
openContext?: (key: string) => void
|
||||
onContextRemove?: (item: ComposerComment) => void
|
||||
onQuoteComment?: (item: Extract<ComposerComment, { type: "quote" }>, comment: string) => void
|
||||
quoteComment?: {
|
||||
key: Accessor<string | undefined>
|
||||
anchor?: Accessor<ComposerQuoteAnchor | undefined>
|
||||
set: (key?: string) => void
|
||||
}
|
||||
quoteComment?: QuoteCommentController
|
||||
onEditor?: (element: HTMLElement) => void
|
||||
onSuggestionSelect?: (item: ComposerSuggestion) => (() => void) | void
|
||||
view: ComposerEditorView
|
||||
@@ -121,8 +128,7 @@ export function createComposerEditor(input: {
|
||||
|
||||
onCleanup(cancelFocus)
|
||||
const draft = createComposerEditorActions(input.store)
|
||||
const [localQuoteComment, setLocalQuoteComment] = createSignal<string>()
|
||||
const quoteComment = input.quoteComment ?? { key: localQuoteComment, set: setLocalQuoteComment }
|
||||
const quoteComment = input.quoteComment ?? createQuoteCommentController()
|
||||
const [state, setState] = input.state ?? createComposerEditorState(draft.state.mode)
|
||||
const [savedHistory, setSavedHistory] = createStore<{ entry?: ComposerHistoryEntry; cursor?: number }>({})
|
||||
const [cycle, setCycle] = createStore<{ index: number; entry?: ComposerHistoryEntry; cursor?: number }>({ index: -1 })
|
||||
@@ -148,6 +154,7 @@ export function createComposerEditor(input: {
|
||||
? createComposerAttachments({
|
||||
...input.attachments,
|
||||
capture: () => ({
|
||||
scope: unwrap(draft.state),
|
||||
current: () => draft.state.prompt,
|
||||
cursor: () => draft.state.cursor,
|
||||
set: (prompt, cursor) => draft.setPrompt(prompt, cursor),
|
||||
@@ -175,47 +182,74 @@ export function createComposerEditor(input: {
|
||||
)
|
||||
}
|
||||
|
||||
const [found, setFound] = createStore<{ query?: string; files: ComposerSuggestion[] }>({ files: [] })
|
||||
let fileQuery: string | undefined
|
||||
let fileAbort = new AbortController()
|
||||
onCleanup(() => abort(fileAbort))
|
||||
// Debounced and abortable: each keystroke or close replaces the pending searches instead of queueing behind them.
|
||||
const [mentionSearch, setMentionSearch] = createSignal(INITIAL_MENTION_SEARCH_STATE)
|
||||
const mentionRuns = new Map<number, { timer: ReturnType<typeof setTimeout>; controller?: AbortController }>()
|
||||
|
||||
// Debounced and abortable: each keystroke or close replaces the pending file search instead of queueing behind it.
|
||||
// The last results stay listed until the next ones arrive, so the menu keeps its rows and height while typing.
|
||||
const findFiles = (query?: string) => {
|
||||
if (query === fileQuery) return
|
||||
abort(fileAbort)
|
||||
const controller = new AbortController()
|
||||
fileQuery = query
|
||||
fileAbort = controller
|
||||
const dispatchMentionSearch = (event: MentionSearchEvent) => {
|
||||
const previous = untrack(mentionSearch)
|
||||
const next = transitionMentionSearch(previous, event)
|
||||
|
||||
if (query === undefined || !query.trim() || /\s/.test(query)) {
|
||||
if (found.files.length) setFound({ query: undefined, files: [] })
|
||||
if (next.state !== previous) setMentionSearch(next.state)
|
||||
next.effects.forEach(runMentionSearch)
|
||||
}
|
||||
|
||||
const runMentionSearch = (effect: MentionSearchEffect) => {
|
||||
const attempt = effect.attempt
|
||||
|
||||
if (effect.type === "file.debounce") {
|
||||
mentionRuns.set(attempt, {
|
||||
timer: setTimeout(() => dispatchMentionSearch({ type: "file.debounce.fired", attempt }), effect.delayMs),
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setTimeout(
|
||||
() =>
|
||||
void Promise.resolve(input.searchContextFiles(query, controller.signal)).then(
|
||||
(files) => !controller.signal.aborted && setFound({ query, files }),
|
||||
() => undefined,
|
||||
),
|
||||
150,
|
||||
)
|
||||
clearTimeout(mentionRuns.get(attempt)?.timer)
|
||||
|
||||
controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true })
|
||||
if (effect.type === "file.abort" || effect.type === "session.abort") {
|
||||
const controller = mentionRuns.get(attempt)?.controller
|
||||
mentionRuns.delete(attempt)
|
||||
|
||||
if (controller) abort(controller)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
|
||||
if (effect.type === "file.search") {
|
||||
mentionRuns.set(attempt, {
|
||||
controller,
|
||||
timer: setTimeout(() => dispatchMentionSearch({ type: "file.timed-out", attempt }), effect.timeoutMs),
|
||||
})
|
||||
void Promise.try(() => input.searchContextFiles(effect.query, controller.signal)).then(
|
||||
(items) => dispatchMentionSearch({ type: "file.resolved", attempt, items }),
|
||||
() => dispatchMentionSearch({ type: "file.failed", attempt }),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
mentionRuns.set(attempt, {
|
||||
controller,
|
||||
timer: setTimeout(() => dispatchMentionSearch({ type: "session.timed-out", attempt }), effect.timeoutMs),
|
||||
})
|
||||
// A failed search settles too: the titles already known still match locally.
|
||||
const settled = () => dispatchMentionSearch({ type: "session.settled", attempt })
|
||||
void Promise.try(() => input.requestSessionSearch?.(effect.word, controller.signal)).then(settled, settled)
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (state.popover.type !== "context") return untrack(() => dispatchMentionSearch(MENTION_CONTEXT_CLOSED))
|
||||
const query = state.popover.query
|
||||
untrack(() => dispatchMentionSearch({ type: "context.changed", query, hasSessions: !!input.requestSessionSearch }))
|
||||
})
|
||||
onCleanup(() => dispatchMentionSearch({ type: "disposed" }))
|
||||
|
||||
const contextList = useFilteredList<ComposerSuggestion>({
|
||||
items: (query) => {
|
||||
if (state.popover.type !== "context") {
|
||||
findFiles(undefined)
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
findFiles(query)
|
||||
if (state.popover.type !== "context") return []
|
||||
|
||||
const sessions = input.searchSessions?.(query) ?? []
|
||||
|
||||
@@ -227,7 +261,12 @@ export function createComposerEditor(input: {
|
||||
|
||||
const seen = new Set(recent.map((item) => item.id))
|
||||
|
||||
return [...fixed, ...sessions, ...recent, ...found.files.filter((item) => !seen.has(item.id))]
|
||||
return [
|
||||
...fixed,
|
||||
...sessions,
|
||||
...recent,
|
||||
...selectMentionFiles(mentionSearch()).filter((item) => !seen.has(item.id)),
|
||||
]
|
||||
},
|
||||
key: (item) => item.id,
|
||||
filterKeys: ["label"],
|
||||
@@ -274,7 +313,10 @@ export function createComposerEditor(input: {
|
||||
|
||||
// Files from the previous query stay listed while the next search runs, but the keyboard can't highlight or pick them.
|
||||
const stale = (item: ComposerSuggestion) =>
|
||||
state.popover.type === "context" && item.kind === "file" && !item.recent && found.query !== state.popover.query
|
||||
state.popover.type === "context" &&
|
||||
item.kind === "file" &&
|
||||
!item.recent &&
|
||||
isMentionFileStale(mentionSearch(), state.popover.query)
|
||||
|
||||
const selectable = () => suggestions().flatMap((item) => (stale(item) ? [] : [item.id]))
|
||||
|
||||
@@ -500,7 +542,7 @@ export function createComposerEditor(input: {
|
||||
createEffect(() => {
|
||||
if (state.popover.type !== "context" || !/\s/.test(state.popover.query)) return
|
||||
|
||||
if (input.sessionsPending?.(state.popover.query)) return
|
||||
if (selectMentionSessionsPending(mentionSearch(), state.popover.query, !!input.requestSessionSearch)) return
|
||||
|
||||
if (contextList.grouped.state === "ready" && contextList.flat().length === 0) dispatch({ type: "popover.close" })
|
||||
})
|
||||
@@ -612,9 +654,7 @@ export function createComposerEditor(input: {
|
||||
dispatch({ type: "context.active", id })
|
||||
input.openContext?.(id)
|
||||
},
|
||||
editingQuote: () => quoteComment.key(),
|
||||
quoteAnchor: () => input.quoteComment?.anchor?.(),
|
||||
editQuote: (key?: string) => quoteComment.set(key),
|
||||
quoteComment,
|
||||
focusQuotePrompt: () => restoreFocus(),
|
||||
commentQuote(id: string, comment: string) {
|
||||
const item = draft.state.context.items.find((entry) => entry.key === id)
|
||||
@@ -630,6 +670,7 @@ export function createComposerEditor(input: {
|
||||
|
||||
if (item) input.onContextRemove?.(item)
|
||||
draft.removeContext(id)
|
||||
quoteComment.retain(draft.state.context.items.map((entry) => entry.key))
|
||||
|
||||
if (state.activeContextID === id) dispatch({ type: "context.active", id })
|
||||
},
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { ComposerSuggestion } from "../types"
|
||||
import {
|
||||
INITIAL_MENTION_SEARCH_STATE,
|
||||
MENTION_FILE_DEBOUNCE_MS,
|
||||
MENTION_SEARCH_TIMEOUT_MS,
|
||||
isMentionFileStale,
|
||||
selectMentionFiles,
|
||||
selectMentionSessionsPending,
|
||||
transitionMentionSearch,
|
||||
type MentionSearchEvent,
|
||||
type MentionSearchState,
|
||||
type MentionSearchTransition,
|
||||
} from "./mention-search-machine"
|
||||
|
||||
const plan: ComposerSuggestion = { id: "file:re/plan.md", kind: "file", label: "re/plan.md", path: "re/plan.md" }
|
||||
|
||||
function replay(events: MentionSearchEvent[], state: MentionSearchState = INITIAL_MENTION_SEARCH_STATE) {
|
||||
const initial: MentionSearchTransition = { state, effects: [] }
|
||||
|
||||
return events.reduce((result, event) => transitionMentionSearch(result.state, event), initial)
|
||||
}
|
||||
|
||||
function changed(query: string, hasSessions = true): MentionSearchEvent {
|
||||
return { type: "context.changed", query, hasSessions }
|
||||
}
|
||||
|
||||
describe("transitionMentionSearch", () => {
|
||||
test("reopening @ on a word searched before waits for a fresh session search", () => {
|
||||
const reopened = replay([
|
||||
changed("auth"),
|
||||
{ type: "session.settled", attempt: 2 },
|
||||
{ type: "context.closed" },
|
||||
changed("auth "),
|
||||
])
|
||||
|
||||
expect(reopened.effects).toEqual([
|
||||
{ type: "session.search", attempt: 3, word: "auth", timeoutMs: MENTION_SEARCH_TIMEOUT_MS },
|
||||
])
|
||||
expect(selectMentionSessionsPending(reopened.state, "auth ", true)).toBe(true)
|
||||
expect(
|
||||
selectMentionSessionsPending(
|
||||
transitionMentionSearch(reopened.state, { type: "session.settled", attempt: 3 }).state,
|
||||
"auth ",
|
||||
true,
|
||||
),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
test("closing @ aborts its pending file and session searches", () => {
|
||||
const loading = replay([changed("re"), { type: "file.debounce.fired", attempt: 1 }])
|
||||
|
||||
expect(loading.effects).toEqual([
|
||||
{ type: "file.search", attempt: 1, query: "re", timeoutMs: MENTION_SEARCH_TIMEOUT_MS },
|
||||
])
|
||||
expect(transitionMentionSearch(loading.state, { type: "context.closed" })).toEqual({
|
||||
state: { status: "closed", issued: 2 },
|
||||
effects: [
|
||||
{ type: "file.abort", attempt: 1 },
|
||||
{ type: "session.abort", attempt: 2 },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
test("a failed or timed-out file search clears the previous query's rows", () => {
|
||||
const typed = replay([
|
||||
changed("re", false),
|
||||
{ type: "file.debounce.fired", attempt: 1 },
|
||||
{ type: "file.resolved", attempt: 1, items: [plan] },
|
||||
changed("rez", false),
|
||||
])
|
||||
|
||||
expect(typed.effects).toEqual([{ type: "file.debounce", attempt: 2, delayMs: MENTION_FILE_DEBOUNCE_MS }])
|
||||
expect(selectMentionFiles(typed.state)).toEqual([plan])
|
||||
expect(isMentionFileStale(typed.state, "rez")).toBe(true)
|
||||
|
||||
for (const type of ["file.failed", "file.timed-out"] as const) {
|
||||
const settled = replay(
|
||||
[
|
||||
{ type: "file.debounce.fired", attempt: 2 },
|
||||
{ type, attempt: 2 },
|
||||
],
|
||||
typed.state,
|
||||
)
|
||||
|
||||
expect(selectMentionFiles(settled.state)).toEqual([])
|
||||
expect(isMentionFileStale(settled.state, "rez")).toBe(false)
|
||||
expect(settled.effects).toEqual([{ type: "file.abort", attempt: 2 }])
|
||||
}
|
||||
})
|
||||
|
||||
test("refining a title keeps the in-flight session search and drops file search", () => {
|
||||
const first = replay([changed("auth")])
|
||||
const refined = transitionMentionSearch(first.state, changed("auth token"))
|
||||
|
||||
expect(refined.effects).toEqual([{ type: "file.abort", attempt: 1 }])
|
||||
expect(refined.state).toMatchObject({ files: { status: "idle" }, sessions: { status: "loading", attempt: 2 } })
|
||||
expect(transitionMentionSearch(refined.state, changed("auth token")).state).toBe(refined.state)
|
||||
})
|
||||
|
||||
test("ignores stale results and everything after dispose", () => {
|
||||
const first = replay([changed("re", false), changed("res", false)])
|
||||
|
||||
expect(transitionMentionSearch(first.state, { type: "file.debounce.fired", attempt: 1 }).state).toBe(first.state)
|
||||
|
||||
const disposed = transitionMentionSearch(first.state, { type: "disposed" })
|
||||
|
||||
expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "file.abort", attempt: 2 }] })
|
||||
expect(transitionMentionSearch(disposed.state, changed("re")).state).toBe(disposed.state)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { ComposerSuggestion } from "../types"
|
||||
|
||||
export const MENTION_FILE_DEBOUNCE_MS = 150
|
||||
|
||||
// A search that never answers settles as empty, so the menu cannot wait on it forever.
|
||||
export const MENTION_SEARCH_TIMEOUT_MS = 10_000
|
||||
|
||||
/**
|
||||
* The file search behind an open `@` menu. While the next query is `debouncing` or `loading`, the previous query's
|
||||
* rows stay listed (`settledQuery`, `items`) so the menu keeps its height, but they cannot be picked.
|
||||
*/
|
||||
export type MentionFileSearchState =
|
||||
| { readonly status: "idle" }
|
||||
| {
|
||||
readonly status: "debouncing" | "loading"
|
||||
readonly attempt: number
|
||||
readonly settledQuery: string | undefined
|
||||
readonly items: readonly ComposerSuggestion[]
|
||||
}
|
||||
/** A failed or timed-out search settles with no rows. */
|
||||
| { readonly status: "settled"; readonly settledQuery: string; readonly items: readonly ComposerSuggestion[] }
|
||||
|
||||
/** The server-side session search for the query's first word; titles then match the whole query locally. */
|
||||
export type MentionSessionSearchState =
|
||||
| { readonly status: "disabled" }
|
||||
| { readonly status: "loading"; readonly attempt: number; readonly word: string }
|
||||
| { readonly status: "settled"; readonly word: string }
|
||||
|
||||
/**
|
||||
* The searches an `@` menu runs while it is open.
|
||||
* - `closed`: no menu; closing aborts every search, so reopening on the same word searches again.
|
||||
* - `active`: the menu shows `query`.
|
||||
* - `disposed`: the composer unmounted; late results and timers are ignored.
|
||||
*/
|
||||
export type MentionSearchState =
|
||||
| { readonly status: "closed"; readonly issued: number }
|
||||
| {
|
||||
readonly status: "active"
|
||||
readonly issued: number
|
||||
readonly query: string
|
||||
readonly files: MentionFileSearchState
|
||||
readonly sessions: MentionSessionSearchState
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type MentionSearchEvent =
|
||||
| { readonly type: "context.changed"; readonly query: string; readonly hasSessions: boolean }
|
||||
| { readonly type: "context.closed" }
|
||||
| { readonly type: "file.debounce.fired"; readonly attempt: number }
|
||||
| { readonly type: "file.resolved"; readonly attempt: number; readonly items: readonly ComposerSuggestion[] }
|
||||
| { readonly type: "file.failed"; readonly attempt: number }
|
||||
| { readonly type: "file.timed-out"; readonly attempt: number }
|
||||
| { readonly type: "session.settled"; readonly attempt: number }
|
||||
| { readonly type: "session.timed-out"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
/** `file.abort` and `session.abort` also release a settled attempt's timer; aborting a settled request does nothing. */
|
||||
export type MentionSearchEffect =
|
||||
| { readonly type: "file.debounce"; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "file.search"; readonly attempt: number; readonly query: string; readonly timeoutMs: number }
|
||||
| { readonly type: "file.abort"; readonly attempt: number }
|
||||
| { readonly type: "session.search"; readonly attempt: number; readonly word: string; readonly timeoutMs: number }
|
||||
| { readonly type: "session.abort"; readonly attempt: number }
|
||||
|
||||
export type MentionSearchTransition = {
|
||||
readonly state: MentionSearchState
|
||||
readonly effects: readonly MentionSearchEffect[]
|
||||
}
|
||||
|
||||
export const INITIAL_MENTION_SEARCH_STATE: MentionSearchState = Object.freeze({ status: "closed", issued: 0 })
|
||||
|
||||
const DISPOSED: MentionSearchState = Object.freeze({ status: "disposed" })
|
||||
|
||||
const IDLE_FILES: MentionFileSearchState = Object.freeze({ status: "idle" })
|
||||
|
||||
const DISABLED_SESSIONS: MentionSessionSearchState = Object.freeze({ status: "disabled" })
|
||||
|
||||
const NO_EFFECTS: readonly MentionSearchEffect[] = Object.freeze([])
|
||||
|
||||
const NO_SUGGESTIONS: readonly ComposerSuggestion[] = Object.freeze([])
|
||||
|
||||
export function transitionMentionSearch(state: MentionSearchState, event: MentionSearchEvent): MentionSearchTransition {
|
||||
if (state.status === "disposed") return stay(state)
|
||||
|
||||
if (event.type === "disposed")
|
||||
return { state: DISPOSED, effects: state.status === "active" ? abortSearches(state) : NO_EFFECTS }
|
||||
|
||||
if (event.type === "context.changed") return change(state, event.query, event.hasSessions)
|
||||
|
||||
if (state.status === "closed") return stay(state)
|
||||
|
||||
if (event.type === "context.closed")
|
||||
return { state: { status: "closed", issued: state.issued }, effects: abortSearches(state) }
|
||||
|
||||
if (event.type === "session.settled" || event.type === "session.timed-out") {
|
||||
if (state.sessions.status !== "loading" || state.sessions.attempt !== event.attempt) return stay(state)
|
||||
|
||||
return {
|
||||
state: { ...state, sessions: { status: "settled", word: state.sessions.word } },
|
||||
effects: [{ type: "session.abort", attempt: event.attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
const files = state.files
|
||||
|
||||
if (event.type === "file.debounce.fired") {
|
||||
if (files.status !== "debouncing" || files.attempt !== event.attempt) return stay(state)
|
||||
|
||||
return {
|
||||
state: { ...state, files: { ...files, status: "loading" } },
|
||||
effects: [
|
||||
{ type: "file.search", attempt: event.attempt, query: state.query, timeoutMs: MENTION_SEARCH_TIMEOUT_MS },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (files.status !== "loading" || files.attempt !== event.attempt) return stay(state)
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
files: {
|
||||
status: "settled",
|
||||
settledQuery: state.query,
|
||||
items: event.type === "file.resolved" ? event.items : NO_SUGGESTIONS,
|
||||
},
|
||||
},
|
||||
effects: [{ type: "file.abort", attempt: event.attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
/** The file rows to list: the current query's, or the previous query's while the next search runs. */
|
||||
export function selectMentionFiles(state: MentionSearchState) {
|
||||
return state.status === "active" && state.files.status !== "idle" ? state.files.items : NO_SUGGESTIONS
|
||||
}
|
||||
|
||||
/** Whether listed file rows belong to an earlier query, so the keyboard cannot highlight or pick them. */
|
||||
export function isMentionFileStale(state: MentionSearchState, query: string) {
|
||||
return state.status !== "active" || state.files.status === "idle" || state.files.settledQuery !== query
|
||||
}
|
||||
|
||||
/** Whether the session search for this query has yet to settle, so the menu must not close as empty yet. */
|
||||
export function selectMentionSessionsPending(state: MentionSearchState, query: string, hasSessions: boolean) {
|
||||
if (!hasSessions || state.status === "disposed") return false
|
||||
|
||||
if (state.status === "closed") return true
|
||||
|
||||
if (state.sessions.status === "disabled") return false
|
||||
|
||||
if (state.sessions.word !== mentionSearchWord(query)) return true
|
||||
|
||||
return state.sessions.status === "loading"
|
||||
}
|
||||
|
||||
/** The server narrows sessions by the first word. */
|
||||
export function mentionSearchWord(query: string) {
|
||||
return query.toLowerCase().split(" ")[0] ?? ""
|
||||
}
|
||||
|
||||
function change(
|
||||
state: Exclude<MentionSearchState, { status: "disposed" }>,
|
||||
query: string,
|
||||
hasSessions: boolean,
|
||||
): MentionSearchTransition {
|
||||
const active = state.status === "active" ? state : undefined
|
||||
|
||||
if (active?.query === query && (active.sessions.status !== "disabled") === hasSessions) return stay(state)
|
||||
const effects: MentionSearchEffect[] = []
|
||||
const issued = { value: state.issued }
|
||||
const files = active?.query === query ? active.files : nextFiles(active?.files ?? IDLE_FILES, query, issued, effects)
|
||||
const previous = active?.sessions ?? DISABLED_SESSIONS
|
||||
const word = mentionSearchWord(query)
|
||||
|
||||
const keep = hasSessions && previous.status !== "disabled" && previous.word === word
|
||||
|
||||
if (!keep && previous.status === "loading") effects.push({ type: "session.abort", attempt: previous.attempt })
|
||||
|
||||
const sessions = keep ? previous : hasSessions ? startSessions(word, issued, effects) : DISABLED_SESSIONS
|
||||
|
||||
return { state: { status: "active", issued: issued.value, query, files, sessions }, effects }
|
||||
}
|
||||
|
||||
function nextFiles(
|
||||
previous: MentionFileSearchState,
|
||||
query: string,
|
||||
issued: { value: number },
|
||||
effects: MentionSearchEffect[],
|
||||
): MentionFileSearchState {
|
||||
if (previous.status === "debouncing" || previous.status === "loading")
|
||||
effects.push({ type: "file.abort", attempt: previous.attempt })
|
||||
|
||||
// Only paths are searched: an empty query lists recent files, and a space means prose or a session title.
|
||||
if (!query.trim() || /\s/.test(query)) return IDLE_FILES
|
||||
const attempt = ++issued.value
|
||||
effects.push({ type: "file.debounce", attempt, delayMs: MENTION_FILE_DEBOUNCE_MS })
|
||||
|
||||
return previous.status === "idle"
|
||||
? { status: "debouncing", attempt, settledQuery: undefined, items: NO_SUGGESTIONS }
|
||||
: { status: "debouncing", attempt, settledQuery: previous.settledQuery, items: previous.items }
|
||||
}
|
||||
|
||||
function startSessions(
|
||||
word: string,
|
||||
issued: { value: number },
|
||||
effects: MentionSearchEffect[],
|
||||
): MentionSessionSearchState {
|
||||
const attempt = ++issued.value
|
||||
effects.push({ type: "session.search", attempt, word, timeoutMs: MENTION_SEARCH_TIMEOUT_MS })
|
||||
|
||||
return { status: "loading", attempt, word }
|
||||
}
|
||||
|
||||
function abortSearches(state: Extract<MentionSearchState, { status: "active" }>) {
|
||||
const files: readonly MentionSearchEffect[] =
|
||||
state.files.status === "debouncing" || state.files.status === "loading"
|
||||
? [{ type: "file.abort", attempt: state.files.attempt }]
|
||||
: NO_EFFECTS
|
||||
|
||||
return state.sessions.status === "loading"
|
||||
? [...files, { type: "session.abort" as const, attempt: state.sessions.attempt }]
|
||||
: files
|
||||
}
|
||||
|
||||
function stay(state: MentionSearchState): MentionSearchTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { MenuScroll } from "@opencode/ui/menu-scroll"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { ComposerQuoteAnchor } from "@opencode/plugin/gui"
|
||||
import type { ComposerDelivery } from "../adapter"
|
||||
import type { QuoteCommentView } from "../quote-comment-machine"
|
||||
|
||||
const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
|
||||
|
||||
@@ -25,28 +26,28 @@ export function QuoteCommentEditor(props: {
|
||||
anchor: HTMLElement
|
||||
source?: ComposerQuoteAnchor
|
||||
text: string
|
||||
/** The saved comment. */
|
||||
comment: string
|
||||
view: QuoteCommentView
|
||||
mention: (query: string) => Promise<string[]>
|
||||
onInput: (draft: string) => void
|
||||
onSubmit: (comment: string) => void
|
||||
onClose: (focus?: boolean) => void
|
||||
send?: {
|
||||
available: boolean
|
||||
delivery: ComposerDelivery | undefined
|
||||
onSubmit: (comment: string) => Promise<boolean>
|
||||
onSubmit: (comment: string) => void
|
||||
}
|
||||
}) {
|
||||
const language = useLanguage()
|
||||
|
||||
const [state, setState] = createStore({
|
||||
draft: props.comment,
|
||||
rect: bounds(props.anchor),
|
||||
viewport: window.innerWidth,
|
||||
viewportHeight: window.innerHeight,
|
||||
revision: 0,
|
||||
height: 0,
|
||||
openingHeight: 0,
|
||||
sending: false,
|
||||
failed: false,
|
||||
})
|
||||
|
||||
const width = () => Math.min(WIDTH, state.viewport - GAP * 2)
|
||||
@@ -64,8 +65,6 @@ export function QuoteCommentEditor(props: {
|
||||
|
||||
let frame: number | undefined
|
||||
|
||||
let mounted = true
|
||||
|
||||
const schedule = () => {
|
||||
if (frame !== undefined) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
@@ -80,8 +79,6 @@ export function QuoteCommentEditor(props: {
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
mounted = false
|
||||
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
})
|
||||
|
||||
@@ -93,7 +90,7 @@ export function QuoteCommentEditor(props: {
|
||||
|
||||
if (target instanceof Node && (element?.contains(target) || props.anchor.contains(target))) return
|
||||
|
||||
if (!state.sending && state.draft.trim() === props.comment.trim()) props.onClose()
|
||||
if (props.view.canDismissOutside) props.onClose()
|
||||
})
|
||||
|
||||
const left = () => Math.min(Math.max(source()?.left ?? state.rect.left, GAP), state.viewport - width() - GAP)
|
||||
@@ -118,16 +115,7 @@ export function QuoteCommentEditor(props: {
|
||||
label: language.t(sendLabels[send.delivery ?? "send"]),
|
||||
keys: [IS_MAC ? "⌘" : language.t("common.key.ctrl"), "⏎"],
|
||||
disabled: !send.available,
|
||||
onSubmit: async (comment: string) => {
|
||||
setState({ sending: true, failed: false })
|
||||
|
||||
const sent = await send.onSubmit(comment)
|
||||
|
||||
if (!mounted) return
|
||||
setState({ sending: false, failed: !sent })
|
||||
|
||||
if (sent) props.onClose()
|
||||
},
|
||||
onSubmit: send.onSubmit,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -163,17 +151,17 @@ export function QuoteCommentEditor(props: {
|
||||
<LineCommentEditor
|
||||
variant="compact"
|
||||
style={{ "--line-comment-preview-lines": props.source ? 2 : 4 }}
|
||||
value={state.draft}
|
||||
onInput={(value) => setState("draft", value)}
|
||||
value={props.view.draft}
|
||||
onInput={props.onInput}
|
||||
onCancel={() => props.onClose(true)}
|
||||
onSubmit={props.onSubmit}
|
||||
submitting={state.sending}
|
||||
submitting={props.view.sending}
|
||||
alternateSubmit={alternateSubmit()}
|
||||
placeholder={language.t("session.quote.optionalCommentPlaceholder")}
|
||||
submitLabel={language.t(
|
||||
props.comment.trim()
|
||||
? "common.save"
|
||||
: state.draft.trim()
|
||||
: props.view.draft.trim()
|
||||
? "session.quote.addComment"
|
||||
: "session.quote.done",
|
||||
)}
|
||||
@@ -181,7 +169,7 @@ export function QuoteCommentEditor(props: {
|
||||
mention={{ items: props.mention }}
|
||||
selection={<span dir="auto">{props.text}</span>}
|
||||
/>
|
||||
<Show when={state.failed}>
|
||||
<Show when={props.view.failed}>
|
||||
<p
|
||||
role="alert"
|
||||
class="rounded-b-[8px] bg-v2-background-bg-layer-01 px-3 pb-3 text-[12px] leading-[var(--line-height-compact)] text-v2-text-text-base"
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ImagePreview } from "@opencode/ui/image-preview"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import type { ReferenceInfo } from "@opencode/client/promise"
|
||||
import type { Links, MountedSession } from "@opencode/plugin/gui"
|
||||
import { createComponent, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
|
||||
import { createComponent, createEffect, createMemo, on, onCleanup } from "solid-js"
|
||||
import { Predicate } from "effect"
|
||||
import type { ComposerSuggestion } from "./types"
|
||||
import { createComposerEditor, createComposerEditorState, type ComposerEditorModel } from "./editor/interaction"
|
||||
@@ -212,9 +212,6 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
|
||||
const skills = createMemo(() => data.location.skill.list({ directory: sdk().directory }) ?? [])
|
||||
|
||||
let sessionSearch: string | undefined
|
||||
const [sessionSearched, setSessionSearched] = createSignal<string>()
|
||||
|
||||
const sessions = createServerSessionEntries({
|
||||
server: server.key,
|
||||
known: createKnownServerSessions(() => server.ctx),
|
||||
@@ -371,25 +368,9 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
},
|
||||
commands,
|
||||
context,
|
||||
// The server narrows by the first word; the title match then needs the whole query.
|
||||
requestSessionSearch: (word, signal) => sessions.search(word, signal).then(() => undefined),
|
||||
searchSessions: (query) => {
|
||||
if (interaction[0].popover.type !== "context") {
|
||||
// Closing aborts the search, so reopening on the same query must fetch again.
|
||||
sessionSearch = undefined
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
// The server narrows by the first word; the title match then needs the whole query.
|
||||
const search = firstWord(query)
|
||||
|
||||
if (search !== sessionSearch) {
|
||||
sessionSearch = search
|
||||
void sessions.search(search).then(
|
||||
() => sessionSearch === search && setSessionSearched(search),
|
||||
() => sessionSearch === search && setSessionSearched(search),
|
||||
)
|
||||
}
|
||||
|
||||
const project = sdk().current?.project.id
|
||||
|
||||
const open = new Set(
|
||||
@@ -437,7 +418,6 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
|
||||
.slice(0, 5)
|
||||
.map((item) => item.suggestion)
|
||||
},
|
||||
sessionsPending: (query) => sessionSearched() !== firstWord(query),
|
||||
searchContextFiles: async (query, signal) =>
|
||||
(await files.searchFilesAndDirectories(query, { signal })).map((path) => ({
|
||||
id: `file:${path}`,
|
||||
@@ -663,7 +643,3 @@ function openComment(
|
||||
links.open({ href: item.path, origin: item.commentOrigin, exact: true, background: true, session })
|
||||
comments.open({ file: item.path, id: item.commentID })
|
||||
}
|
||||
|
||||
function firstWord(query: string) {
|
||||
return query.toLowerCase().split(" ")[0] ?? ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { afterEach, describe, expect, jest, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createMemoryComposerState } from "./state"
|
||||
import {
|
||||
INITIAL_QUOTE_COMMENT_STATE,
|
||||
QUOTE_SEND_TIMEOUT_MS,
|
||||
createQuoteCommentController,
|
||||
selectQuoteCommentKey,
|
||||
selectQuoteCommentView,
|
||||
transitionQuoteComment,
|
||||
type QuoteCommentEvent,
|
||||
type QuoteCommentState,
|
||||
type QuoteCommentTransition,
|
||||
} from "./quote-comment-machine"
|
||||
|
||||
const key = "quote:c=1"
|
||||
|
||||
function replay(events: QuoteCommentEvent[], state: QuoteCommentState = INITIAL_QUOTE_COMMENT_STATE) {
|
||||
const initial: QuoteCommentTransition = { state, effects: [] }
|
||||
|
||||
return events.reduce((result, event) => {
|
||||
const next = transitionQuoteComment(result.state, event)
|
||||
|
||||
return { state: next.state, effects: [...result.effects, ...next.effects] }
|
||||
}, initial)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
describe("transitionQuoteComment", () => {
|
||||
test("closes the editor when its quote leaves the draft, so restoring the quote does not reopen it", () => {
|
||||
const result = replay([
|
||||
{ type: "opened", key },
|
||||
{ type: "retained", keys: ["file:a.ts"] },
|
||||
])
|
||||
|
||||
expect(result.state).toEqual({ status: "closed", issued: 0 })
|
||||
expect(selectQuoteCommentKey(result.state)).toBeUndefined()
|
||||
expect(replay([{ type: "retained", keys: [key] }], result.state).state).toBe(result.state)
|
||||
})
|
||||
|
||||
test("a send that fails or times out settles to failed and keeps the draft", () => {
|
||||
const sending = replay([
|
||||
{ type: "opened", key },
|
||||
{ type: "send.requested", draft: "note" },
|
||||
])
|
||||
|
||||
expect(sending.state).toMatchObject({ status: "sending", attempt: 1, key, draft: "note" })
|
||||
expect(sending.effects).toEqual([
|
||||
{ type: "send.run", attempt: 1, key, draft: "note", timeoutMs: QUOTE_SEND_TIMEOUT_MS },
|
||||
])
|
||||
|
||||
for (const event of [
|
||||
{ type: "send.timed-out", attempt: 1 },
|
||||
{ type: "send.settled", attempt: 1, sent: false },
|
||||
] satisfies QuoteCommentEvent[]) {
|
||||
const result = transitionQuoteComment(sending.state, event)
|
||||
|
||||
expect(result.state).toEqual({ status: "failed", issued: 1, key, draft: "note", anchor: undefined })
|
||||
expect(result.effects).toEqual([{ type: "timer.clear" }])
|
||||
expect(selectQuoteCommentView(result.state, key, "")).toMatchObject({ draft: "note", failed: true })
|
||||
}
|
||||
|
||||
expect(transitionQuoteComment(sending.state, { type: "send.settled", attempt: 1, sent: true }).state).toEqual({
|
||||
status: "closed",
|
||||
issued: 1,
|
||||
})
|
||||
})
|
||||
|
||||
test("ignores chip toggles, edits and a second send while a send is in flight", () => {
|
||||
const sending = replay([
|
||||
{ type: "opened", key },
|
||||
{ type: "send.requested", draft: "note" },
|
||||
]).state
|
||||
|
||||
for (const event of [
|
||||
{ type: "closed" },
|
||||
{ type: "opened", key: "quote:c=2" },
|
||||
{ type: "draft.changed", draft: "other" },
|
||||
{ type: "send.requested", draft: "note" },
|
||||
] satisfies QuoteCommentEvent[])
|
||||
expect(transitionQuoteComment(sending, event)).toEqual({ state: sending, effects: [] })
|
||||
})
|
||||
|
||||
test("ignores a late send result once the quote left, and an edit clears a failure", () => {
|
||||
const closed = replay([
|
||||
{ type: "opened", key },
|
||||
{ type: "send.requested", draft: "note" },
|
||||
{ type: "retained", keys: [] },
|
||||
])
|
||||
|
||||
expect(closed.effects.at(-1)).toEqual({ type: "timer.clear" })
|
||||
expect(transitionQuoteComment(closed.state, { type: "send.settled", attempt: 1, sent: false }).state).toBe(
|
||||
closed.state,
|
||||
)
|
||||
|
||||
const failed = replay([
|
||||
{ type: "opened", key },
|
||||
{ type: "send.requested", draft: "note" },
|
||||
{ type: "send.settled", attempt: 1, sent: false },
|
||||
{ type: "draft.changed", draft: "fixed" },
|
||||
])
|
||||
|
||||
expect(failed.state).toEqual({ status: "open", issued: 1, key, draft: "fixed", anchor: undefined })
|
||||
})
|
||||
|
||||
test("disposing clears a running send timer and ignores later events", () => {
|
||||
const disposed = replay([{ type: "opened", key }, { type: "send.requested", draft: "note" }, { type: "disposed" }])
|
||||
|
||||
expect(disposed.state).toEqual({ status: "disposed" })
|
||||
expect(disposed.effects.at(-1)).toEqual({ type: "timer.clear" })
|
||||
expect(transitionQuoteComment(disposed.state, { type: "opened", key }).state).toBe(disposed.state)
|
||||
})
|
||||
})
|
||||
|
||||
describe("createQuoteCommentController", () => {
|
||||
test("a rejected or hung send fails instead of spinning forever", async () => {
|
||||
jest.useFakeTimers()
|
||||
const controller = createQuoteCommentController()
|
||||
|
||||
controller.set(key)
|
||||
controller.send("note", () => Promise.reject(new Error("offline")))
|
||||
expect(controller.state().status).toBe("sending")
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(controller.state()).toMatchObject({ status: "failed", draft: "note" })
|
||||
|
||||
controller.send("note", () => new Promise<boolean>(() => {}))
|
||||
jest.advanceTimersByTime(QUOTE_SEND_TIMEOUT_MS)
|
||||
expect(controller.state()).toMatchObject({ status: "failed", draft: "note" })
|
||||
})
|
||||
|
||||
test("removing a quote from the composer closes its editor and highlight before a failed send restores it", () => {
|
||||
createRoot((dispose) => {
|
||||
const composer = createMemoryComposerState()
|
||||
const quote = { type: "quote" as const, text: "passage", commentID: "1" }
|
||||
|
||||
composer.context.add(quote)
|
||||
composer.quoteSource.add(key, [{ partID: "part", revealID: "message", start: 0, end: 7, text: "passage" }])
|
||||
composer.quoteComment.set(key)
|
||||
expect(composer.quoteSource.state.pending).toBe(key)
|
||||
|
||||
composer.context.remove(key)
|
||||
composer.context.add(quote)
|
||||
expect(composer.quoteComment.key()).toBeUndefined()
|
||||
expect(composer.quoteSource.state.pending).toBeUndefined()
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
import { createSignal, getOwner, onCleanup, untrack } from "solid-js"
|
||||
import type { ComposerQuoteAnchor } from "@opencode/plugin/gui"
|
||||
import type { QuoteSource } from "./quote-source"
|
||||
|
||||
// A quote send that never answers turns into a failure the user can retry, rather than a spinner forever.
|
||||
export const QUOTE_SEND_TIMEOUT_MS = 30_000
|
||||
|
||||
/**
|
||||
* The quote whose comment editor is open, and its send.
|
||||
* - `closed`: no editor is open.
|
||||
* - `open`: the editor shows `key`; `draft` stays `undefined` until the user edits, so the saved comment shows.
|
||||
* - `sending`: a direct send of `draft` is in flight; the editor stays open and ignores chip toggles and edits.
|
||||
* - `failed`: the send did not go through; the editor keeps the draft and shows an alert until the next edit.
|
||||
* - `disposed`: the composer state was evicted; late results and timers are ignored.
|
||||
*/
|
||||
export type QuoteCommentState =
|
||||
| { readonly status: "closed"; readonly issued: number }
|
||||
| {
|
||||
readonly status: "open"
|
||||
readonly issued: number
|
||||
readonly key: string
|
||||
readonly draft: string | undefined
|
||||
readonly anchor: ComposerQuoteAnchor | undefined
|
||||
}
|
||||
| {
|
||||
readonly status: "sending"
|
||||
readonly issued: number
|
||||
readonly attempt: number
|
||||
readonly key: string
|
||||
readonly draft: string
|
||||
readonly anchor: ComposerQuoteAnchor | undefined
|
||||
}
|
||||
| {
|
||||
readonly status: "failed"
|
||||
readonly issued: number
|
||||
readonly key: string
|
||||
readonly draft: string
|
||||
readonly anchor: ComposerQuoteAnchor | undefined
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type QuoteCommentEvent =
|
||||
| { readonly type: "opened"; readonly key: string; readonly anchor?: ComposerQuoteAnchor }
|
||||
| { readonly type: "closed" }
|
||||
| { readonly type: "draft.changed"; readonly draft: string }
|
||||
| { readonly type: "send.requested"; readonly draft: string }
|
||||
| { readonly type: "send.settled"; readonly attempt: number; readonly sent: boolean }
|
||||
| { readonly type: "send.timed-out"; readonly attempt: number }
|
||||
/** The context items still in the draft; an editor whose quote is gone closes. */
|
||||
| { readonly type: "retained"; readonly keys: readonly string[] }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type QuoteCommentEffect =
|
||||
| {
|
||||
readonly type: "send.run"
|
||||
readonly attempt: number
|
||||
readonly key: string
|
||||
readonly draft: string
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
| { readonly type: "timer.clear" }
|
||||
|
||||
export type QuoteCommentTransition = {
|
||||
readonly state: QuoteCommentState
|
||||
readonly effects: readonly QuoteCommentEffect[]
|
||||
}
|
||||
|
||||
export type QuoteCommentView = {
|
||||
readonly draft: string
|
||||
readonly sending: boolean
|
||||
readonly failed: boolean
|
||||
/** A pointer down outside closes the editor only when nothing would be lost. */
|
||||
readonly canDismissOutside: boolean
|
||||
}
|
||||
|
||||
export const INITIAL_QUOTE_COMMENT_STATE: QuoteCommentState = Object.freeze({ status: "closed", issued: 0 })
|
||||
|
||||
const NO_EFFECTS: readonly QuoteCommentEffect[] = Object.freeze([])
|
||||
|
||||
const CLEAR_TIMER: readonly QuoteCommentEffect[] = Object.freeze([{ type: "timer.clear" }])
|
||||
|
||||
export function transitionQuoteComment(state: QuoteCommentState, event: QuoteCommentEvent): QuoteCommentTransition {
|
||||
if (state.status === "disposed") return stay(state)
|
||||
|
||||
if (event.type === "disposed")
|
||||
return { state: { status: "disposed" }, effects: state.status === "sending" ? CLEAR_TIMER : NO_EFFECTS }
|
||||
|
||||
if (event.type === "retained") {
|
||||
if (state.status === "closed" || event.keys.includes(state.key)) return stay(state)
|
||||
|
||||
return {
|
||||
state: { status: "closed", issued: state.issued },
|
||||
effects: state.status === "sending" ? CLEAR_TIMER : NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === "sending") {
|
||||
if ((event.type !== "send.settled" && event.type !== "send.timed-out") || event.attempt !== state.attempt)
|
||||
return stay(state)
|
||||
|
||||
if (event.type === "send.settled" && event.sent)
|
||||
return { state: { status: "closed", issued: state.issued }, effects: CLEAR_TIMER }
|
||||
|
||||
return {
|
||||
state: { status: "failed", issued: state.issued, key: state.key, draft: state.draft, anchor: state.anchor },
|
||||
effects: CLEAR_TIMER,
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "opened") {
|
||||
if (state.status !== "closed" && state.key === event.key) {
|
||||
if (state.anchor === event.anchor) return stay(state)
|
||||
|
||||
return { state: { ...state, anchor: event.anchor }, effects: NO_EFFECTS }
|
||||
}
|
||||
|
||||
return {
|
||||
state: { status: "open", issued: state.issued, key: event.key, draft: undefined, anchor: event.anchor },
|
||||
effects: NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === "closed") return stay(state)
|
||||
|
||||
if (event.type === "closed") return { state: { status: "closed", issued: state.issued }, effects: NO_EFFECTS }
|
||||
|
||||
if (event.type === "draft.changed") {
|
||||
if (state.status === "open" && state.draft === event.draft) return stay(state)
|
||||
|
||||
return {
|
||||
state: { status: "open", issued: state.issued, key: state.key, draft: event.draft, anchor: state.anchor },
|
||||
effects: NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "send.requested") {
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: { status: "sending", issued: attempt, attempt, key: state.key, draft: event.draft, anchor: state.anchor },
|
||||
effects: [{ type: "send.run", attempt, key: state.key, draft: event.draft, timeoutMs: QUOTE_SEND_TIMEOUT_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
return stay(state)
|
||||
}
|
||||
|
||||
/** The quote whose editor is open, or `undefined`. */
|
||||
export function selectQuoteCommentKey(state: QuoteCommentState) {
|
||||
return state.status === "closed" || state.status === "disposed" ? undefined : state.key
|
||||
}
|
||||
|
||||
export function selectQuoteCommentAnchor(state: QuoteCommentState) {
|
||||
return state.status === "closed" || state.status === "disposed" ? undefined : state.anchor
|
||||
}
|
||||
|
||||
/** The quote whose timeline source stays highlighted: the open editor's, when it has a source. */
|
||||
export function selectQuoteHighlightKey(
|
||||
key: string | undefined,
|
||||
sources: Readonly<Record<string, QuoteSource | undefined>>,
|
||||
) {
|
||||
return key && sources[key]?.length ? key : undefined
|
||||
}
|
||||
|
||||
export function selectQuoteCommentView(state: QuoteCommentState, key: string, saved: string): QuoteCommentView {
|
||||
const current = state.status !== "closed" && state.status !== "disposed" && state.key === key ? state : undefined
|
||||
const draft = current?.draft ?? saved
|
||||
const sending = current?.status === "sending"
|
||||
|
||||
return {
|
||||
draft,
|
||||
sending,
|
||||
failed: current?.status === "failed",
|
||||
canDismissOutside: !sending && draft.trim() === saved.trim(),
|
||||
}
|
||||
}
|
||||
|
||||
export type QuoteCommentController = ReturnType<typeof createQuoteCommentController>
|
||||
|
||||
export function createQuoteCommentController() {
|
||||
const [state, setState] = createSignal(INITIAL_QUOTE_COMMENT_STATE)
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
// Handed from `send` to the `send.run` effect it causes in the same dispatch.
|
||||
let submit: ((key: string, comment: string) => Promise<boolean>) | undefined
|
||||
|
||||
const dispatch = (event: QuoteCommentEvent) => {
|
||||
const previous = untrack(state)
|
||||
const next = transitionQuoteComment(previous, event)
|
||||
|
||||
if (next.state !== previous) setState(next.state)
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
const run = (effect: QuoteCommentEffect) => {
|
||||
clearTimeout(timer)
|
||||
timer = undefined
|
||||
|
||||
if (effect.type === "timer.clear") return
|
||||
const send = submit
|
||||
submit = undefined
|
||||
|
||||
if (!send) return dispatch({ type: "send.settled", attempt: effect.attempt, sent: false })
|
||||
timer = setTimeout(() => dispatch({ type: "send.timed-out", attempt: effect.attempt }), effect.timeoutMs)
|
||||
void Promise.try(() => send(effect.key, effect.draft)).then(
|
||||
(sent) => dispatch({ type: "send.settled", attempt: effect.attempt, sent }),
|
||||
() => dispatch({ type: "send.settled", attempt: effect.attempt, sent: false }),
|
||||
)
|
||||
}
|
||||
|
||||
if (getOwner()) onCleanup(() => dispatch({ type: "disposed" }))
|
||||
|
||||
return {
|
||||
state,
|
||||
key: () => selectQuoteCommentKey(state()),
|
||||
anchor: () => selectQuoteCommentAnchor(state()),
|
||||
set: (key?: string, anchor?: ComposerQuoteAnchor) =>
|
||||
dispatch(key ? { type: "opened", key, anchor } : { type: "closed" }),
|
||||
retain: (keys: readonly string[]) => dispatch({ type: "retained", keys }),
|
||||
setDraft: (draft: string) => dispatch({ type: "draft.changed", draft }),
|
||||
send: (draft: string, send: (key: string, comment: string) => Promise<boolean>) => {
|
||||
submit = send
|
||||
dispatch({ type: "send.requested", draft })
|
||||
submit = undefined
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function stay(state: QuoteCommentState): QuoteCommentTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -1,23 +1,34 @@
|
||||
import { createStore } from "solid-js/store"
|
||||
import { selectQuoteHighlightKey } from "./quote-comment-machine"
|
||||
import type { ComposerStore, TimelineQuoteSource } from "./schema"
|
||||
|
||||
/** App-only source coordinates, persisted with drafts but never included in requests. */
|
||||
export type QuoteSource = TimelineQuoteSource
|
||||
|
||||
export function createComposerQuoteSource(draft?: {
|
||||
get: () => ComposerStore["quoteSources"]
|
||||
set: (key: string, source: QuoteSource | undefined) => void
|
||||
}) {
|
||||
export function createComposerQuoteSource(
|
||||
draft?: {
|
||||
get: () => ComposerStore["quoteSources"]
|
||||
set: (key: string, source: QuoteSource | undefined) => void
|
||||
},
|
||||
quoteComment?: {
|
||||
/** The quote whose comment editor is open. */
|
||||
key: () => string | undefined
|
||||
retain: (keys: readonly string[]) => void
|
||||
},
|
||||
) {
|
||||
const [sources, setSources] = createStore<Record<string, QuoteSource | undefined>>({})
|
||||
|
||||
const [state, setState] = createStore<{
|
||||
const [state] = createStore<{
|
||||
sources: Record<string, QuoteSource | undefined>
|
||||
/** The quote whose open comment editor keeps its source highlighted. */
|
||||
pending?: string
|
||||
pending: string | undefined
|
||||
}>({
|
||||
get sources() {
|
||||
return draft?.get() ?? sources
|
||||
},
|
||||
get pending() {
|
||||
return selectQuoteHighlightKey(quoteComment?.key(), draft?.get() ?? sources)
|
||||
},
|
||||
})
|
||||
|
||||
const setSource = (key: string, source: QuoteSource | undefined) =>
|
||||
@@ -26,14 +37,12 @@ export function createComposerQuoteSource(draft?: {
|
||||
return {
|
||||
state,
|
||||
add: (key: string, source: QuoteSource) => setSource(key, source),
|
||||
pend: (key: string) => setState("pending", key),
|
||||
settle: () => setState("pending", undefined),
|
||||
retain: (keys: string[]) => {
|
||||
Object.keys(state.sources).forEach((key) => {
|
||||
if (!keys.includes(key)) setSource(key, undefined)
|
||||
})
|
||||
|
||||
if (state.pending && !keys.includes(state.pending)) setState("pending", undefined)
|
||||
quoteComment?.retain(keys)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { batch, untrack, type Accessor } from "solid-js"
|
||||
import type { ComposerQuoteAnchor } from "@opencode/plugin/gui"
|
||||
import { createStore, type SetStoreFunction } from "solid-js/store"
|
||||
import { batch, getOwner, onCleanup, untrack, type Accessor } from "solid-js"
|
||||
import { createStore, unwrap, type SetStoreFunction } from "solid-js/store"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import { ServerScope } from "@/runtime/server/scope"
|
||||
import type { Platform } from "@/runtime/platform/platform"
|
||||
import { clonePrompt } from "./prompt-parts"
|
||||
import { uploads } from "./attachments/uploads"
|
||||
import { createQuoteCommentController, type QuoteCommentController } from "./quote-comment-machine"
|
||||
import { createComposerQuoteSource } from "./quote-source"
|
||||
import {
|
||||
ComposerStore,
|
||||
@@ -114,11 +115,7 @@ export interface ComposerStateValue {
|
||||
replace(items: ContextItem[]): void
|
||||
replaceComments(items: ContextItem[]): void
|
||||
}
|
||||
readonly quoteComment: {
|
||||
readonly key: Accessor<string | undefined>
|
||||
readonly anchor: Accessor<ComposerQuoteAnchor | undefined>
|
||||
readonly set: (key?: string, anchor?: ComposerQuoteAnchor) => void
|
||||
}
|
||||
readonly quoteComment: QuoteCommentController
|
||||
readonly quoteSource: ReturnType<typeof createComposerQuoteSource>
|
||||
readonly set: (prompt: Prompt, cursorPosition?: number) => void
|
||||
readonly reset: () => void
|
||||
@@ -128,12 +125,18 @@ export interface ComposerStateValue {
|
||||
function createComposerStateValue(store: ComposerStore, setStore: SetStoreFunction<ComposerStore>): ComposerStateValue {
|
||||
const actions = createComposerActions(setStore)
|
||||
// The quote whose comment editor is open, by key; a request made before the composer shows waits for it.
|
||||
const [quoteComment, setQuoteComment] = createStore<{ key?: string; anchor?: ComposerQuoteAnchor }>({})
|
||||
const quoteComment = createQuoteCommentController()
|
||||
|
||||
const quoteSource = createComposerQuoteSource({
|
||||
get: () => store.quoteSources,
|
||||
set: (key, source) => setStore("quoteSources", (sources) => ({ ...sources, [key]: source })),
|
||||
})
|
||||
const quoteSource = createComposerQuoteSource(
|
||||
{
|
||||
get: () => store.quoteSources,
|
||||
set: (key, source) => setStore("quoteSources", (sources) => ({ ...sources, [key]: source })),
|
||||
},
|
||||
quoteComment,
|
||||
)
|
||||
|
||||
// Uploads outlive the composer view that started them, but not the draft they write into.
|
||||
if (getOwner()) onCleanup(() => uploads.cancelScope(unwrap(store)))
|
||||
|
||||
const retainQuoteSources = () => quoteSource.retain(store.context.items.map((item) => item.key))
|
||||
|
||||
@@ -223,21 +226,7 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti
|
||||
clearRetry()
|
||||
},
|
||||
},
|
||||
quoteComment: {
|
||||
key: () => quoteComment.key,
|
||||
anchor: () => quoteComment.anchor,
|
||||
set: (key?: string, anchor?: ComposerQuoteAnchor) => {
|
||||
setQuoteComment({ key, anchor: key ? anchor : undefined })
|
||||
|
||||
if (key && quoteSource.state.sources[key]) {
|
||||
quoteSource.pend(key)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
quoteSource.settle()
|
||||
},
|
||||
},
|
||||
quoteComment,
|
||||
quoteSource,
|
||||
set: (prompt: Prompt, cursorPosition?: number) => actions.set(prompt, cursorPosition),
|
||||
reset: () => actions.reset(),
|
||||
|
||||
@@ -386,11 +386,7 @@ export function createActiveSessionRegion(input: {
|
||||
|
||||
if (source.length) prompt.capture().quoteSource.add(contextItemKey(item), source)
|
||||
|
||||
if (anchor) {
|
||||
prompt.capture().quoteSource.pend(contextItemKey(item))
|
||||
|
||||
return prompt.capture().quoteComment.set(contextItemKey(item), anchor)
|
||||
}
|
||||
if (anchor) return prompt.capture().quoteComment.set(contextItemKey(item), anchor)
|
||||
|
||||
focusPrompt()
|
||||
},
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createStore, unwrap } from "solid-js/store"
|
||||
import { createComposerAttachments } from "@/composer/attachments/attachments"
|
||||
import { uploads } from "@/composer/attachments/uploads"
|
||||
import { createMemoryComposerState } from "@/composer/state"
|
||||
import type { ComposerPrompt } from "@/composer/types"
|
||||
|
||||
function target() {
|
||||
@@ -60,4 +62,71 @@ describe("Composer attachment ownership", () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
test("upload progress keeps each row's identity and writes only its own row", async () => {
|
||||
const scope = {}
|
||||
const reports: ((loaded: number) => void)[] = []
|
||||
|
||||
const work = (report: (loaded: number) => void) => {
|
||||
reports.push(report)
|
||||
|
||||
return new Promise<string>(() => {})
|
||||
}
|
||||
|
||||
const first = uploads.track({ id: "one", scope, filename: "one.bin", mime: "", size: 100 }, work)
|
||||
const second = uploads.track({ id: "two", scope, filename: "two.bin", mime: "", size: 100 }, work)
|
||||
const rows = [...uploads.items()]
|
||||
|
||||
reports[1]?.(40)
|
||||
expect(uploads.items()[0]).toBe(rows[0]!)
|
||||
expect(uploads.items()[1]).toBe(rows[1]!)
|
||||
expect(uploads.items().map((item) => item.loaded)).toEqual([0, 40])
|
||||
|
||||
uploads.cancelScope(scope)
|
||||
expect(await Promise.all([first, second])).toEqual([undefined, undefined])
|
||||
})
|
||||
|
||||
test("keeps an upload pending for its draft across a remount, and stops it when the draft closes", async () => {
|
||||
const draft = createRoot((dispose) => ({ state: createMemoryComposerState(), dispose }))
|
||||
const prompt = target()
|
||||
let signal: AbortSignal | undefined
|
||||
|
||||
const mount = () =>
|
||||
createRoot((dispose) => ({
|
||||
dispose,
|
||||
attachments: createComposerAttachments({
|
||||
capture: () => ({ ...prompt.capture, scope: unwrap(draft.state.store[0]()) }),
|
||||
editor: () => document.createElement("div"),
|
||||
focusEditor() {},
|
||||
addPart: () => false,
|
||||
setDraggingType() {},
|
||||
directory: () => "C:/repo",
|
||||
destination: () => ({
|
||||
input: { image: false, pdf: false },
|
||||
local: false,
|
||||
upload: (_file, _report, abort) => {
|
||||
signal = abort
|
||||
|
||||
return new Promise<string>(() => {})
|
||||
},
|
||||
}),
|
||||
isDialogActive: () => false,
|
||||
duplicate() {},
|
||||
onError() {},
|
||||
onUploadError() {},
|
||||
}),
|
||||
}))
|
||||
|
||||
const first = mount()
|
||||
await first.attachments.addAttachments([new File([new Uint8Array([0, 1, 2])], "data.bin")])
|
||||
first.dispose()
|
||||
|
||||
const second = mount()
|
||||
expect(second.attachments.pending().map((upload) => upload.filename)).toEqual(["data.bin"])
|
||||
|
||||
draft.dispose()
|
||||
expect(second.attachments.pending()).toEqual([])
|
||||
expect(signal?.aborted).toBe(true)
|
||||
second.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,7 +41,56 @@ test("Enter does not pick a file left over from the previous @ query while the n
|
||||
}
|
||||
})
|
||||
|
||||
function setup(results: Record<string, string[]>) {
|
||||
test("a failed @ search clears the previous query's files instead of leaving them unselectable", async () => {
|
||||
const value = setup({ re: ["re/plan.md"] })
|
||||
|
||||
try {
|
||||
await value.type("@re")
|
||||
await value.type("@rez", { search: false })
|
||||
expect(value.editor.suggestions().map((item) => item.id)).toEqual(["file:re/plan.md"])
|
||||
await value.search()
|
||||
expect(value.editor.suggestions()).toEqual([])
|
||||
} finally {
|
||||
value.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("closing @ aborts its session search, and reopening on the same word waits for a fresh one", async () => {
|
||||
const searches: { word: string; signal: AbortSignal; done: PromiseWithResolvers<void> }[] = []
|
||||
|
||||
const value = setup(
|
||||
{},
|
||||
{
|
||||
requestSessionSearch: (word, signal) => {
|
||||
const done = Promise.withResolvers<void>()
|
||||
searches.push({ word, signal, done })
|
||||
|
||||
return done.promise
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
try {
|
||||
await value.type("@auth", { search: false })
|
||||
searches[0]?.done.resolve()
|
||||
await flush()
|
||||
await value.type("", { search: false })
|
||||
await value.type("@auth", { search: false })
|
||||
await value.type("@auth ", { search: false })
|
||||
expect(searches.map((search) => search.word)).toEqual(["auth", "auth"])
|
||||
expect(value.editor.state.popover.type).toBe("context")
|
||||
|
||||
await value.type("", { search: false })
|
||||
expect(searches[1]?.signal.aborted).toBe(true)
|
||||
} finally {
|
||||
value.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
function setup(
|
||||
results: Record<string, string[]>,
|
||||
options?: { requestSessionSearch?: (word: string, signal: AbortSignal) => Promise<void> },
|
||||
) {
|
||||
jest.useFakeTimers()
|
||||
|
||||
return createRoot((dispose) => {
|
||||
@@ -55,7 +104,15 @@ function setup(results: Record<string, string[]>) {
|
||||
store,
|
||||
commands: () => [],
|
||||
context: () => [],
|
||||
searchContextFiles: (query) => (results[query] ?? []).map(file),
|
||||
searchContextFiles: (query) => {
|
||||
const paths = results[query]
|
||||
|
||||
if (!paths) return Promise.reject(new Error(`No results for ${query}`))
|
||||
|
||||
return paths.map(file)
|
||||
},
|
||||
searchSessions: () => [],
|
||||
requestSessionSearch: options?.requestSessionSearch,
|
||||
view: { submit: { stopping: () => false, onSubmit() {}, onStop() {} } },
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user