mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 17:01:37 +03:00
fix(app): steady Home's first load and restore its shortcuts (#57299)
This commit is contained in:
committed by
GitHub
Unverified
parent
13400db9d2
commit
a419c36568
@@ -318,16 +318,12 @@ function bunTranspilerCache() {
|
||||
async function waitForHome(page: Page, mark: (name: Milestone) => void) {
|
||||
await expect.poll(() => page.evaluate(() => document.visibilityState), { timeout: 120_000 }).toBe("visible")
|
||||
|
||||
const projects = page.getByRole("complementary", { name: "Projects", exact: true })
|
||||
const sessions = page.getByRole("region", { name: "Recent sessions", exact: true })
|
||||
const search = page.getByRole("textbox", { name: "Search sessions", exact: true })
|
||||
const addProject = projects.locator('button[data-action="home-add-project-row"]')
|
||||
await expect(projects).toBeVisible({ timeout: 120_000 })
|
||||
await expect(sessions).toBeVisible()
|
||||
await expect(search).toBeEditable()
|
||||
await expect(sessions.getByText("Nothing here yet", { exact: true })).toBeVisible()
|
||||
await expect(addProject).toHaveCount(1)
|
||||
await addProject.click({ trial: true })
|
||||
const home = page.locator('[data-slot="home-panel"]')
|
||||
const newSession = home.getByRole("button", { name: "New session", exact: true })
|
||||
await expect(home).toBeVisible({ timeout: 120_000 })
|
||||
await expect(home.locator("section").getByText("Nothing needs you", { exact: true })).toBeVisible()
|
||||
await expect(newSession).toHaveCount(1)
|
||||
await newSession.click({ trial: true })
|
||||
mark("homeReady")
|
||||
}
|
||||
|
||||
|
||||
@@ -269,8 +269,9 @@ for (const scenario of ["visible-output", "hidden-output", "full-scrollback-tear
|
||||
const start = await page.evaluate(() => performance.now())
|
||||
await close.click()
|
||||
await expect(page).toHaveURL("/")
|
||||
await expect(page.locator('[data-component="home-session-search"]')).toBeVisible()
|
||||
await expect(page.locator('[data-component="home-session-search"] input')).toBeEditable()
|
||||
await expect(
|
||||
page.locator('[data-slot="home-panel"]').getByRole("button", { name: "New session", exact: true }),
|
||||
).toBeEnabled()
|
||||
await expect.poll(() => page.evaluate(() => window.terminalProbe.serialized.length)).toBe(1)
|
||||
interaction = await page.evaluate(
|
||||
(start) => ({
|
||||
|
||||
@@ -7,7 +7,7 @@ import { fixture as stress } from "../../utils/session-fixture"
|
||||
import { createHomeIndexFixture, type HomeIndexFixture } from "./home-session-index.fixture"
|
||||
|
||||
// Home fetches the root-session index on mount. These cases hold the visible
|
||||
// output constant (newest 64 rows, same order) while the index size grows, so
|
||||
// output constant (the 8 newest read sessions under Earlier, same order) while the index size grows, so
|
||||
// bytes, main-thread work, time to actionable rows, and retained heap can be
|
||||
// attributed to index handling rather than to what the user sees.
|
||||
const sizes = (process.env.HOME_INDEX_SIZES ?? "500,5000,10000").split(",").map(Number)
|
||||
@@ -19,9 +19,7 @@ const updates = Number(process.env.HOME_INDEX_UPDATES ?? 20)
|
||||
// Forced GC changes timing; retention runs stay separate from clean timing runs.
|
||||
const memory = process.env.OPENCODE_PERFORMANCE_MEMORY === "1"
|
||||
|
||||
const rowContainer = '[data-component="home-session-row-container"]'
|
||||
|
||||
const row = '[data-component="home-session-row"]'
|
||||
const row = '[data-slot="start-row"]'
|
||||
|
||||
type Probe = {
|
||||
expected: number
|
||||
@@ -58,12 +56,11 @@ benchmark.describe("performance: home session index", () => {
|
||||
await page.goto("/")
|
||||
const rows = page.locator(row)
|
||||
await expect(rows).toHaveCount(fixture.expected.visible, { timeout: APP_READY_TIMEOUT })
|
||||
const first = page.locator(rowContainer).filter({ hasText: fixture.expected.newestTitle })
|
||||
await expect(first).toHaveAttribute("data-session-id", fixture.expected.newestID)
|
||||
await expect(first.locator(row)).toBeEnabled()
|
||||
// Row order is part of the held-constant output: the DOM must list the
|
||||
// newest session first.
|
||||
await expect(page.locator(rowContainer).nth(0)).toHaveAttribute("data-session-id", fixture.expected.newestID)
|
||||
const first = rows.nth(0)
|
||||
await expect(first.locator('span[dir="auto"]')).toHaveText(fixture.expected.newestTitle)
|
||||
await expect(first).toHaveAttribute("data-status", "ready")
|
||||
|
||||
const probe = await readProbe(page)
|
||||
const metrics = await performanceMetrics(cdp)
|
||||
@@ -117,26 +114,24 @@ benchmark.describe("performance: home session index", () => {
|
||||
benchmark.setTimeout(180_000)
|
||||
const fixture = createHomeIndexFixture({ count: churnSize, now: Date.now() })
|
||||
const target = fixture.sessions[fixture.sessions.length - 1]
|
||||
const network = await setup(page, fixture)
|
||||
// Home reads every running session, which makes the target locally known
|
||||
// and therefore part of every later index merge, like an open session.
|
||||
// Each completed run then re-reads it and moves it to Done.
|
||||
const network = await setup(page, fixture, { [target.id]: { type: "running" } })
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await cdp.send("Performance.enable")
|
||||
|
||||
// Home prefetches the two newest sessions, which makes them locally known
|
||||
// and therefore part of every later index merge, like an open session.
|
||||
const prefetch = page.waitForResponse(
|
||||
(response) => response.request().method() === "GET" && response.url().includes(`/api/session/${target.id}`),
|
||||
)
|
||||
|
||||
await page.goto("/")
|
||||
await expect(page.locator(row)).toHaveCount(fixture.expected.visible, { timeout: APP_READY_TIMEOUT })
|
||||
const titles = page.locator(row).locator('span[dir="auto"]')
|
||||
await expect(titles.getByText(fixture.expected.newestTitle, { exact: true })).toBeVisible({
|
||||
timeout: APP_READY_TIMEOUT,
|
||||
})
|
||||
await prefetch
|
||||
|
||||
const titleLocator = page.locator(
|
||||
`${rowContainer}[data-session-id="${target.id}"] [data-component="home-session-title"]`,
|
||||
)
|
||||
|
||||
await expect(titleLocator).toHaveText(fixture.expected.newestTitle)
|
||||
|
||||
const before = await performanceMetrics(cdp)
|
||||
const samples: number[] = []
|
||||
|
||||
@@ -172,7 +167,7 @@ benchmark.describe("performance: home session index", () => {
|
||||
},
|
||||
)
|
||||
|
||||
await expect(titleLocator).toHaveText(title)
|
||||
await expect(titles.getByText(title, { exact: true })).toBeVisible()
|
||||
|
||||
const seen = await page.evaluate(({ title }) => (window as ProbeWindow).__homeIndexProbe?.titles[title], {
|
||||
title,
|
||||
@@ -211,9 +206,10 @@ benchmark.describe("performance: home session index", () => {
|
||||
)
|
||||
})
|
||||
|
||||
async function setup(page: Page, fixture: HomeIndexFixture) {
|
||||
async function setup(page: Page, fixture: HomeIndexFixture, sessionStatus: Record<string, { type: string }> = {}) {
|
||||
const primary = fixture.directories[0]
|
||||
await mockOpenCodeServer(page, {
|
||||
sessionStatus,
|
||||
directory: primary.directory,
|
||||
project: {
|
||||
id: primary.projectID,
|
||||
@@ -247,7 +243,7 @@ async function setup(page: Page, fixture: HomeIndexFixture) {
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
if (probe.rows === undefined) {
|
||||
const count = document.querySelectorAll('[data-component="home-session-row"]').length
|
||||
const count = document.querySelectorAll('[data-slot="start-row"]').length
|
||||
|
||||
if (count >= probe.expected) {
|
||||
probe.rows = performance.now()
|
||||
@@ -258,11 +254,9 @@ async function setup(page: Page, fixture: HomeIndexFixture) {
|
||||
}
|
||||
|
||||
for (const [id, title] of Object.entries(probe.pending)) {
|
||||
const element = document.querySelector(
|
||||
`[data-component="home-session-row-container"][data-session-id="${id}"] [data-component="home-session-title"]`,
|
||||
)
|
||||
const titles = [...document.querySelectorAll('[data-slot="start-row"] span[dir="auto"]')]
|
||||
|
||||
if (element?.textContent !== title) continue
|
||||
if (!titles.some((element) => element.textContent === title)) continue
|
||||
probe.titles[title] = performance.now()
|
||||
delete probe.pending[id]
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { currentSession } from "../../utils/mock-server"
|
||||
|
||||
export const HOME_INDEX_FIXTURE_VERSION = 1
|
||||
export const HOME_INDEX_FIXTURE_VERSION = 2
|
||||
|
||||
// Home shows the newest 64 root sessions; the fixture asserts that many rows.
|
||||
export const HOME_INDEX_VISIBLE_LIMIT = 64
|
||||
// Home lists read sessions under Earlier, newest first, up to 8; every fixture session is read, so it shows that many.
|
||||
export const HOME_INDEX_VISIBLE_LIMIT = 8
|
||||
|
||||
export type HomeIndexSession = {
|
||||
id: string
|
||||
@@ -14,7 +14,7 @@ export type HomeIndexSession = {
|
||||
cost: number
|
||||
tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
|
||||
outcome: "succeeded" | "failed" | "interrupted"
|
||||
time: { created: number; updated: number; idle: number; viewed?: number }
|
||||
time: { created: number; updated: number; idle: number; viewed: number }
|
||||
location: { directory: string }
|
||||
}
|
||||
|
||||
@@ -174,7 +174,8 @@ export function createHomeIndexFixture(input: { count: number; now: number; dire
|
||||
created: updated - duration,
|
||||
updated,
|
||||
idle: updated - Math.floor(random() * 2_000),
|
||||
...(random() < 0.8 ? { viewed: updated } : {}),
|
||||
// Unread sessions list under Done without a cap, which would change the visible rows with the index size.
|
||||
viewed: updated,
|
||||
},
|
||||
location: { directory: directory.directory },
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import {
|
||||
import { sessionHref } from "../../utils/app"
|
||||
import { waitForStableTimeline } from "./session-tab-switch-probe"
|
||||
|
||||
const homeRow = '[data-component="home-session-row"]'
|
||||
const homeRow = '[data-slot="start-row"]'
|
||||
|
||||
const homeShell = '[data-component="home-session-search"]'
|
||||
const homeShell = '[data-slot="home-panel"]'
|
||||
|
||||
benchmark.describe("performance: home and tab navigation", () => {
|
||||
benchmark("opens a home session and paints its titlebar tab", async ({ page, report }) => {
|
||||
|
||||
@@ -19,7 +19,9 @@ for (const entry of ["home", "session"] as const) {
|
||||
await page.goto(entry === "home" ? "/" : sessionHref(fixture.sourceID))
|
||||
|
||||
if (entry === "session") await waitForStableTimeline(page, fixture.expected.sourceMessageIDs.at(-1)!)
|
||||
const trigger = entry === "home" ? '[data-action="home-new-session"]' : 'button[aria-label="New session"]'
|
||||
// New session is Home's only text button here: no fixture session needs the user or is unread, so no row actions render.
|
||||
const trigger =
|
||||
entry === "home" ? '[data-slot="home-panel"] [data-component="button-v2"]' : 'button[aria-label="New session"]'
|
||||
await expect(page.locator(trigger)).toBeVisible()
|
||||
await expect(page.locator('[data-component="new-session"]')).toHaveCount(0)
|
||||
const writes: string[] = []
|
||||
@@ -68,8 +70,9 @@ benchmark("entry: cold session from Home", async ({ page, report }) => {
|
||||
})
|
||||
await installStressSessionTabs(page, { sessionIDs: [] })
|
||||
await page.goto("/")
|
||||
const selector = `[data-component="home-session-row-container"][data-session-id="${fixture.targetID}"] [data-component="home-session-row"]`
|
||||
await expect(page.locator(selector)).toBeVisible()
|
||||
const selector = '[data-slot="start-row"]'
|
||||
const row = page.locator(selector).filter({ hasText: fixture.expected.targetTitle })
|
||||
await expect(row).toBeVisible()
|
||||
expect(requests).not.toContain(fixture.targetID)
|
||||
const href = sessionHref(fixture.targetID)
|
||||
await benchmarkDiagnostics(page).startTrace()
|
||||
@@ -82,7 +85,7 @@ benchmark("entry: cold session from Home", async ({ page, report }) => {
|
||||
href,
|
||||
triggerSelector: selector,
|
||||
switch: async () => {
|
||||
await page.locator(selector).click()
|
||||
await row.click()
|
||||
await waitForStableTimeline(page, fixture.expected.targetMessageIDs.at(-1)!)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -210,10 +210,7 @@ test("navigation replaces commands without retaining disposed owners", async ({
|
||||
const palette = await openCommandPalette(page, true)
|
||||
await palette.input.press("Escape")
|
||||
await expect(palette.dialog).toHaveCount(0)
|
||||
await page
|
||||
.getByRole("region", { name: "Recent sessions" })
|
||||
.getByRole("button", { name: /Palette fixture session/ })
|
||||
.click()
|
||||
await page.locator('[data-slot="start-row"]').filter({ hasText: paletteSession.title }).click()
|
||||
const editor = page.locator('[data-component="composer-editor"]')
|
||||
await expect(editor).toBeEditable()
|
||||
await page.keyboard.press("ControlOrMeta+t")
|
||||
|
||||
@@ -1,209 +1,75 @@
|
||||
import type { OpenCodeEvent } from "@opencode/client/promise"
|
||||
import { expect, test, type Page } from "@playwright/test"
|
||||
import { expectPath, holdRoute, NO_PROVIDER, project, REMOTE_SERVER, seed, sessionHref, T0 } from "../utils/app"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
import { expectPath, holdRoute, project, seed, sessionHref } from "../utils/app"
|
||||
import { fixture, mockStressTimeline } from "../utils/session-fixture"
|
||||
import { mockRemoteServer, newSessionLocation } from "../utils/workspace"
|
||||
import { mockWorkspace, newSessionLocation, openSession } from "../utils/workspace"
|
||||
import { APP_READY_TIMEOUT, expectAppVisible } from "../utils/waits"
|
||||
|
||||
test.use({ serviceWorkers: "block" })
|
||||
const row = (page: Page, title: string) => page.locator('[data-slot="start-row"]').filter({ hasText: title })
|
||||
|
||||
const row = (page: Page, title: string) =>
|
||||
page.locator('[data-component="home-session-row"]').filter({ hasText: title })
|
||||
|
||||
async function openHome(page: Page, input: Parameters<typeof mockStressTimeline>[1] = {}) {
|
||||
await mockStressTimeline(page, input)
|
||||
await seed(page, { usedProjects: { local: [fixture.project.id] } })
|
||||
await page.goto("/")
|
||||
}
|
||||
|
||||
test("the session context menu renames, exports, and deletes a Home session", async ({ page }) => {
|
||||
await openHome(page)
|
||||
const target = row(page, fixture.expected.targetTitle)
|
||||
await expect(target).toBeVisible()
|
||||
|
||||
await target.focus()
|
||||
await target.press("Shift+F10")
|
||||
await expect(page.getByRole("menuitem", { name: "Rename" })).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(page.getByRole("menuitem", { name: "Rename" })).toBeHidden()
|
||||
await expect(target).toBeFocused()
|
||||
|
||||
const box = await target.boundingBox()
|
||||
await target.click({ button: "right", position: { x: 48, y: 12 } })
|
||||
await expect(page).toHaveURL("/")
|
||||
await expect(page.getByRole("menuitem")).toHaveText(["Rename", "Export…", "Delete…"])
|
||||
const menu = await page.locator('[data-component="menu-v2-content"]').boundingBox()
|
||||
expect(Math.abs((menu?.x ?? 0) - (box?.x ?? 0) - 48)).toBeLessThan(4)
|
||||
|
||||
await page.getByRole("menuitem", { name: "Rename" }).click()
|
||||
const title = page.locator('[data-component="home-session-rename"]')
|
||||
await expect(title).toBeFocused()
|
||||
await expect(title).toHaveValue(fixture.expected.targetTitle)
|
||||
await title.fill("Renamed from Home")
|
||||
|
||||
const renamed = page.waitForRequest(
|
||||
(request) =>
|
||||
request.method() === "PATCH" && new URL(request.url()).pathname.endsWith(`/session/${fixture.targetID}`),
|
||||
)
|
||||
|
||||
await title.press("Enter")
|
||||
expect((await renamed).postDataJSON()).toEqual({ title: "Renamed from Home" })
|
||||
const renamedRow = row(page, "Renamed from Home")
|
||||
await renamedRow.click()
|
||||
await expect(page).toHaveURL(new RegExp(`/session/${fixture.targetID}$`))
|
||||
await expect(page.locator('[data-slot="titlebar-tabs"] a').filter({ hasText: "Renamed from Home" })).toBeVisible()
|
||||
await page.getByRole("button", { name: "Home" }).click()
|
||||
await expect(page).toHaveURL("/")
|
||||
|
||||
await renamedRow.click({ button: "right" })
|
||||
const download = page.waitForEvent("download")
|
||||
await page.getByRole("menuitem", { name: "Export…" }).click()
|
||||
expect((await download).suggestedFilename()).toBe("renamed-from-home.json")
|
||||
|
||||
await renamedRow.click({ button: "right" })
|
||||
await page.getByRole("menuitem", { name: "Delete…" }).click()
|
||||
const dialog = page.getByRole("dialog")
|
||||
await expect(dialog).toContainText('Delete session "Renamed from Home"?')
|
||||
await expect(dialog.getByRole("button", { name: "Cancel", exact: true })).toBeFocused()
|
||||
|
||||
const removed = page.waitForRequest(
|
||||
(request) => request.method() === "DELETE" && new URL(request.url()).pathname.endsWith(`/${fixture.targetID}`),
|
||||
)
|
||||
|
||||
await dialog.getByRole("button", { name: "Delete session" }).click()
|
||||
await removed
|
||||
await expect(renamedRow).toBeHidden()
|
||||
})
|
||||
|
||||
test("the Home shortcut focuses session search, and the Home button leaves focus alone", async ({ page }) => {
|
||||
await mockStressTimeline(page)
|
||||
await seed(page, {
|
||||
tabs: [fixture.sourceID],
|
||||
})
|
||||
await page.goto(sessionHref(fixture.sourceID))
|
||||
const editor = page.locator('[data-component="composer-editor"]')
|
||||
await expect(editor).toBeEditable({ timeout: APP_READY_TIMEOUT })
|
||||
await editor.click()
|
||||
|
||||
await page.keyboard.press("ControlOrMeta+b")
|
||||
const search = page.getByRole("textbox", { name: /Search sessions/ })
|
||||
await expect(search).toBeFocused()
|
||||
await page.keyboard.type("jump")
|
||||
await expect(page.getByRole("option")).toHaveCount(1)
|
||||
await expect(page.getByRole("option")).toContainText(fixture.expected.targetTitle)
|
||||
|
||||
await page.keyboard.press("ControlOrMeta+b")
|
||||
await expectPath(page, sessionHref(fixture.sourceID))
|
||||
|
||||
await page.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await expect(search).toHaveValue("")
|
||||
await expect(search).not.toBeFocused()
|
||||
})
|
||||
|
||||
const entry = (name: string, active: number, id = `proj_${name}`) =>
|
||||
project({
|
||||
id,
|
||||
directory: `C:/OpenCode/${name}`,
|
||||
name,
|
||||
time: { created: T0, updated: T0, active: T0 + active },
|
||||
})
|
||||
|
||||
async function homeProjects(page: Page, projects: unknown[]) {
|
||||
const directory = "C:/OpenCode/home"
|
||||
const server = await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: project({ id: "proj_home", directory }),
|
||||
projects: () => projects,
|
||||
provider: NO_PROVIDER,
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
|
||||
return { server, rows: page.locator('[data-component="home-project-row"] [data-slot="home-row-label"]') }
|
||||
}
|
||||
|
||||
test("Home lists the used server projects by recent activity, hides them, and lists them again once used", async ({
|
||||
page,
|
||||
}) => {
|
||||
// `recent` was first resolved under another ID, so one directory has two projects.
|
||||
const listed = [entry("unused", 4), entry("recent", 3), entry("older", 2), entry("oldest", 1)]
|
||||
listed.push(entry("recent", 0, "proj_recent_before_git"))
|
||||
const view = await homeProjects(page, listed)
|
||||
await seed(page, { usedProjects: { local: ["proj_recent_before_git", "proj_older", "proj_oldest"] } })
|
||||
await page.goto("/")
|
||||
await expect(view.rows).toHaveText(["recent", "older", "oldest"])
|
||||
|
||||
// Activity moves a project up and an archived project leaves; a project this client never used stays out.
|
||||
const active = { ...listed[3]!, time: { ...listed[3]!.time, active: T0 + 5 } }
|
||||
const archived = { ...listed[2]!, time: { ...listed[2]!.time, archived: T0 + 6 } }
|
||||
const fresh = entry("fresh", 7)
|
||||
listed.splice(0, listed.length, fresh, active, listed[0]!, listed[1]!, listed[4]!)
|
||||
await view.server.push(
|
||||
[active, archived, fresh].map((data, index) => ({
|
||||
id: `evt_home_project_${index}`,
|
||||
created: T0 + index,
|
||||
type: "project.updated",
|
||||
data,
|
||||
})) as OpenCodeEvent[],
|
||||
)
|
||||
await expect(view.rows).toHaveText(["oldest", "recent"])
|
||||
|
||||
const recent = page.locator('[data-component="home-project-row"]').filter({ hasText: "recent" })
|
||||
await recent.locator("..").getByRole("button", { name: "More options", exact: true }).click()
|
||||
await page.getByRole("menuitem", { name: "Close", exact: true }).click()
|
||||
await expect(view.rows).toHaveText(["oldest"])
|
||||
|
||||
// The location dialog lists every server project once: used ones first, then the rest, each by recency.
|
||||
await page
|
||||
.locator('[data-component="home-project-row"]')
|
||||
.filter({ hasText: "oldest" })
|
||||
.locator("..")
|
||||
.getByRole("button", { name: "New session", exact: true })
|
||||
.click()
|
||||
await newSessionLocation(page).click()
|
||||
const options = page.getByRole("dialog").getByRole("option")
|
||||
await expect(options.locator(".command-palette-title")).toHaveText([
|
||||
"oldest",
|
||||
"fresh",
|
||||
"unused",
|
||||
"recent",
|
||||
"Add project",
|
||||
])
|
||||
await options.filter({ hasText: "C:/OpenCode/recent" }).click()
|
||||
await expect(newSessionLocation(page)).toContainText("recent")
|
||||
await page.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await expect(view.rows).toHaveText(["oldest", "recent"])
|
||||
})
|
||||
|
||||
test("Home migrates the directories an older build listed to the server's current projects", async ({ page }) => {
|
||||
const view = await homeProjects(page, [
|
||||
entry("api", 3),
|
||||
entry("web", 2),
|
||||
entry("api", 1, "proj_api_before_remote"),
|
||||
entry("docs", 0),
|
||||
])
|
||||
await seed(page, {
|
||||
legacyProjects: {
|
||||
local: [
|
||||
{ worktree: "C:/OpenCode/api", expanded: true },
|
||||
{ worktree: "C:/OpenCode/web/packages/app" },
|
||||
{ worktree: "C:/OpenCode/gone" },
|
||||
test("Home sorts sessions by what they need, approves inline, and a row opens its session", async ({ page }) => {
|
||||
const replies: { sessionID: string; permissionID: string; body: unknown }[] = []
|
||||
const waiting = { id: "ses_home_waiting", title: "Waiting on approval" }
|
||||
const earlier = { id: "ses_home_earlier", title: "Finished earlier" }
|
||||
await mockWorkspace(page, {
|
||||
name: "Home",
|
||||
sessions: [earlier, waiting],
|
||||
// Pending requests load for running sessions, so the waiting one runs.
|
||||
sessionStatus: { [waiting.id]: { type: "running" } },
|
||||
sessionPermissions: {
|
||||
[waiting.id]: [
|
||||
{ id: "per_home", sessionID: waiting.id, action: "shell", resources: ["git status"], metadata: {}, save: [] },
|
||||
],
|
||||
},
|
||||
onPermissionReply: (reply) => replies.push(reply),
|
||||
})
|
||||
const location = await holdRoute(page, /\/api\/location(\?|$)/)
|
||||
await page.goto("/")
|
||||
await expect(view.rows).toHaveText(["api", "web"])
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("opencode.global.dat:server") ?? "{}")))
|
||||
.toMatchObject({ usedProjectIDs: { local: ["proj_api", "proj_web"] }, projects: {} })
|
||||
|
||||
// Loaded sessions show before the location request resolves.
|
||||
await expectAppVisible(row(page, earlier.title))
|
||||
location.release()
|
||||
await expect(row(page, earlier.title)).toHaveAttribute("data-status", "ready")
|
||||
const approval = row(page, waiting.title)
|
||||
await expect(approval).toHaveAttribute("data-status", "approval")
|
||||
await expect(approval).toContainText("git status")
|
||||
|
||||
await approval.getByRole("button", { name: "Allow", exact: true }).click()
|
||||
await expect.poll(() => replies).toEqual([{ sessionID: waiting.id, permissionID: "per_home", body: { decision: "once" } }])
|
||||
await expect(approval).toHaveAttribute("data-status", "working")
|
||||
|
||||
await row(page, earlier.title).click()
|
||||
await expectPath(page, sessionHref(earlier.id))
|
||||
await expect(page.locator('[data-titlebar-tab][data-active="true"]')).toContainText(earlier.title)
|
||||
})
|
||||
|
||||
test("Home shows loaded sessions before the location request resolves", async ({ page }) => {
|
||||
const location = await holdRoute(page, (url) => url.pathname === "/api/location")
|
||||
await openHome(page)
|
||||
await expectAppVisible(row(page, fixture.expected.sourceTitle))
|
||||
location.release()
|
||||
test("the Home shortcut opens Home and returns to the session", async ({ page }) => {
|
||||
const view = await openSession(page, { name: "Shortcut" })
|
||||
await view.editor.click()
|
||||
|
||||
await page.keyboard.press("ControlOrMeta+b")
|
||||
await expect(page).toHaveURL(new URL("/", page.url()).href)
|
||||
await expect(row(page, view.session.title)).toBeVisible()
|
||||
|
||||
await page.keyboard.press("ControlOrMeta+b")
|
||||
await expectPath(page, sessionHref(view.session.id))
|
||||
})
|
||||
|
||||
test("the projects rail starts a draft in the chosen project", async ({ page }) => {
|
||||
// The rail shows beside the sessions only on wide screens.
|
||||
await page.setViewportSize({ width: 1440, height: 900 })
|
||||
await mockWorkspace(page, {
|
||||
name: "Rail",
|
||||
projects: [
|
||||
project({ id: "proj_rail", directory: "C:/OpenCode/Rail" }),
|
||||
project({ id: "proj_rail_other", directory: "C:/OpenCode/Other" }),
|
||||
],
|
||||
})
|
||||
await page.goto("/")
|
||||
|
||||
await page.getByRole("button", { name: "New session in Other", exact: true }).click({ timeout: APP_READY_TIMEOUT })
|
||||
await expect(page).toHaveURL(/\/new-session\?draftId=/)
|
||||
await expect(page.locator('[data-component="new-session"] [data-component="composer-editor"]')).toBeEditable()
|
||||
await expect(newSessionLocation(page)).toContainText("Other")
|
||||
})
|
||||
|
||||
test("Home and the directory picker load without newer browser APIs", async ({ page }) => {
|
||||
@@ -216,91 +82,14 @@ test("Home and the directory picker load without newer browser APIs", async ({ p
|
||||
// SAFETY: as above, for the real global `Promise`.
|
||||
delete (Promise as Partial<typeof Promise>).try
|
||||
})
|
||||
await openHome(page, { fileList: () => [] })
|
||||
const target = row(page, fixture.expected.targetTitle)
|
||||
await expect(target).toBeVisible()
|
||||
await mockWorkspace(page, { name: "Safari", fileList: () => [] })
|
||||
await page.goto("/")
|
||||
await expectAppVisible(row(page, "Safari"))
|
||||
|
||||
await page.getByRole("button", { name: "Add project", exact: true }).click()
|
||||
const dialog = page.getByRole("dialog")
|
||||
await expect(dialog.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click()
|
||||
await expect(dialog).toBeHidden()
|
||||
await expect(target).toBeVisible()
|
||||
})
|
||||
|
||||
test("adding a project to a signed-out server re-pairs it, then continues at the paired address", async ({ page }) => {
|
||||
// The saved address rejects the new token, so saving moves the server to the link's address.
|
||||
const paired = "http://127.0.0.1:4098"
|
||||
await mockRemoteServer(page, { name: "Remote", password: "old-password" })
|
||||
await mockOpenCodeServer(page, {
|
||||
server: paired,
|
||||
directory: "/remote/paired",
|
||||
project: project({ id: "proj_paired", directory: "/remote/paired" }),
|
||||
provider: NO_PROVIDER,
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
fileList: () => [],
|
||||
password: "session-token",
|
||||
pairing: { code: "one-time-code", token: "session-token" },
|
||||
})
|
||||
await openHome(page, { fileList: () => [] })
|
||||
const remote = page.locator("[data-home-row]").filter({ hasText: "Remote" })
|
||||
await expect(page.getByRole("button", { name: "Authenticate", exact: true })).toBeVisible()
|
||||
|
||||
await remote.getByRole("button", { name: "Add project", exact: true }).click()
|
||||
const editor = page.getByRole("dialog", { name: "Edit server" })
|
||||
await editor.getByLabel("Pairing link", { exact: true }).fill(`${paired}/auth/connect/one-time-code`)
|
||||
await editor.getByRole("button", { name: "Save", exact: true }).click()
|
||||
|
||||
// The folder picker reads the paired address; the removed one would reject the request.
|
||||
const picker = page.getByRole("dialog").filter({ has: page.getByRole("button", { name: "Select folder" }) })
|
||||
await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
|
||||
await expect(picker.getByText("Unable to read this folder")).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("a server whose saved password changes works with the new password", async ({ page }) => {
|
||||
const accepted = { password: "old-password" }
|
||||
await mockOpenCodeServer(page, {
|
||||
server: REMOTE_SERVER,
|
||||
directory: "/remote/project",
|
||||
project: project({ id: "proj_remote", directory: "/remote/project" }),
|
||||
provider: NO_PROVIDER,
|
||||
sessions: [],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
fileList: () => [],
|
||||
password: () => accepted.password,
|
||||
})
|
||||
// Saved with the password the server accepts until the test changes it.
|
||||
await seed(page, {
|
||||
storage: {
|
||||
"opencode.global.dat:server": {
|
||||
list: [{ type: "http", displayName: "Remote", http: { url: REMOTE_SERVER, password: "old-password" } }],
|
||||
},
|
||||
},
|
||||
})
|
||||
await openHome(page, { fileList: () => [] })
|
||||
const remote = page.locator("[data-home-row]").filter({ hasText: "Remote" })
|
||||
const picker = page.getByRole("dialog").filter({ has: page.getByRole("button", { name: "Select folder" }) })
|
||||
|
||||
// Use the server once, so its controller exists with the old password.
|
||||
await remote.getByRole("button", { name: "Add project", exact: true }).click()
|
||||
await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
|
||||
await picker.getByRole("button", { name: "Cancel", exact: true }).click()
|
||||
await expect(picker).toHaveCount(0)
|
||||
|
||||
await remote.getByRole("button", { name: "More options", exact: true }).click()
|
||||
await page.getByRole("menuitem", { name: "Edit", exact: true }).click()
|
||||
const editor = page.getByRole("dialog", { name: "Edit server" })
|
||||
await editor.getByPlaceholder("password").fill("new-password")
|
||||
// The server now rejects the old password, as after `opencode service set password`.
|
||||
accepted.password = "new-password"
|
||||
await editor.getByRole("button", { name: "Save", exact: true }).click()
|
||||
await expect(editor).toHaveCount(0)
|
||||
|
||||
// The picker reads the folder through the server's controller, which must use the saved password now.
|
||||
await remote.getByRole("button", { name: "Add project", exact: true }).click()
|
||||
await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
|
||||
await expect(picker.getByText("Unable to read this folder")).toHaveCount(0)
|
||||
await page.locator('[data-slot="home-panel"]').getByRole("button", { name: "New session", exact: true }).click()
|
||||
await newSessionLocation(page).click()
|
||||
await page.getByRole("dialog").getByRole("option", { name: "Add project" }).click()
|
||||
await expect(page.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
|
||||
})
|
||||
|
||||
const recovery = "C:/OpenCode/Worktrees/project-menu-recovery"
|
||||
@@ -380,11 +169,7 @@ for (const state of [
|
||||
await trigger.click()
|
||||
await projectItem.click()
|
||||
await expect(page).toHaveURL(new URL("/", page.url()).href)
|
||||
const project = page.locator('[data-component="home-project-row"]').filter({ hasText: name })
|
||||
await expect(project).toHaveAttribute("data-selected", "")
|
||||
await expect(
|
||||
page.locator(`[data-component="home-session-row-container"][data-session-id="${fixture.targetID}"]`),
|
||||
).toBeVisible()
|
||||
await expect(row(page, fixture.expected.targetTitle)).toBeVisible()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -326,18 +326,10 @@ test.describe("touch", () => {
|
||||
await mockStressTimeline(page)
|
||||
await openStress(page)
|
||||
await page.goto("/")
|
||||
await expect(page.locator('[data-component="home-session-row"]')).toHaveCount(rows)
|
||||
await expect(page.locator('[data-slot="start-row"]')).toHaveCount(rows)
|
||||
})
|
||||
|
||||
test("mobile project selection and drawer navigation preserve session identity", async ({ page }) => {
|
||||
const projects = page.getByRole("button", { name: "Projects", exact: true })
|
||||
await projects.click()
|
||||
const picker = page.getByRole("dialog", { name: "Projects", exact: true })
|
||||
await expect(picker.getByRole("button", { name: "All projects", exact: true })).toBeVisible()
|
||||
await picker.getByRole("button", { name: new RegExp(` ${fixture.project.name}$`) }).click()
|
||||
await expect(picker).toBeHidden()
|
||||
await expect(projects).toContainText(fixture.project.name)
|
||||
|
||||
test("mobile drawer navigation preserves session identity", async ({ page }) => {
|
||||
const trigger = page.locator('[data-slot="mobile-tabs-trigger"]')
|
||||
const drawer = page.locator('[data-slot="mobile-tabs-drawer"]')
|
||||
await trigger.click()
|
||||
@@ -357,7 +349,7 @@ test.describe("touch", () => {
|
||||
await drawer.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await expect(page).toHaveURL("/")
|
||||
await expect(drawer).toBeHidden()
|
||||
await expect(page.locator('[data-component="home-session-row"]')).toHaveCount(rows)
|
||||
await expect(page.locator('[data-slot="start-row"]')).toHaveCount(rows)
|
||||
})
|
||||
|
||||
test("mobile settings section menu stays above a full-width panel", async ({ page }) => {
|
||||
@@ -394,7 +386,7 @@ test.describe("touch", () => {
|
||||
await settings.getByRole("button", { name: "Back to app", exact: true }).click()
|
||||
await expect(page).toHaveURL("/")
|
||||
await expect(settings).toBeHidden()
|
||||
await expect(page.locator('[data-component="home-session-row"]')).toHaveCount(rows)
|
||||
await expect(page.locator('[data-slot="start-row"]')).toHaveCount(rows)
|
||||
})
|
||||
|
||||
test.describe("tab drawer", () => {
|
||||
|
||||
@@ -150,7 +150,7 @@ test.describe("rename", () => {
|
||||
})
|
||||
await mockStressTimeline(page)
|
||||
await page.goto("/")
|
||||
await page.locator('[data-component="home-session-row"]').filter({ hasText: fixture.expected.targetTitle }).click()
|
||||
await page.locator('[data-slot="start-row"]').filter({ hasText: fixture.expected.targetTitle }).click()
|
||||
await expect(heading(page, fixture.expected.targetTitle)).toBeVisible()
|
||||
})
|
||||
|
||||
@@ -228,14 +228,12 @@ test.describe("rename", () => {
|
||||
await page.getByRole("menuitem", { name: "Close tab", exact: true }).click()
|
||||
await expect(renamed).toBeHidden()
|
||||
await page.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await expect(
|
||||
page.locator('[data-component="home-session-row"]').filter({ hasText: "Renamed from tab" }),
|
||||
).toBeVisible()
|
||||
await expect(page.locator('[data-slot="start-row"]').filter({ hasText: "Renamed from tab" })).toBeVisible()
|
||||
})
|
||||
|
||||
test("renames an inactive tab without switching sessions", async ({ page }) => {
|
||||
await page.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await page.locator('[data-component="home-session-row"]').filter({ hasText: fixture.expected.sourceTitle }).click()
|
||||
await page.locator('[data-slot="start-row"]').filter({ hasText: fixture.expected.sourceTitle }).click()
|
||||
await expect(heading(page, fixture.expected.sourceTitle)).toBeVisible()
|
||||
await tabs(page).filter({ hasText: fixture.expected.targetTitle }).click({ button: "right" })
|
||||
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
|
||||
|
||||
@@ -108,8 +108,6 @@ test("pointer selection, keyboard navigation, the empty state, and the local fin
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await view.settings.getByRole("button", { name: "Back to app", exact: true }).click()
|
||||
await expect(view.settings).toBeHidden()
|
||||
await findShortcut(page)
|
||||
await expect(page.getByRole("textbox", { name: /Search sessions/ })).toBeFocused()
|
||||
})
|
||||
|
||||
test("a long empty-state query keeps its closing quote beside the ellipsis while typing and resizing", async ({
|
||||
|
||||
@@ -464,10 +464,9 @@ test.describe("pages open before slow data", () => {
|
||||
inventory.release()
|
||||
await expect(settings.getByText(sandboxes[0]!, { exact: true })).toBeVisible()
|
||||
await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible()
|
||||
// Home already listed this session; it renders while the directory reads are still held.
|
||||
await sessions.arrived
|
||||
await expect(settings.getByText("Workspace 1 session", { exact: true })).toBeVisible()
|
||||
sessions.release()
|
||||
await expect(settings.getByText("Workspace 1 session", { exact: true })).toBeVisible()
|
||||
|
||||
const refresh = await holdRoute(page, (url) => url.pathname === "/api/worktree", { method: "GET" })
|
||||
await settings.getByRole("tab", { name: "Preferences", exact: true }).click()
|
||||
|
||||
@@ -2,7 +2,7 @@ import { expect, test } from "@playwright/test"
|
||||
import { project, provider, sessionHref } from "../utils/app"
|
||||
import { mockOpenCodeServer } from "../utils/mock-server"
|
||||
import { expectAppVisible } from "../utils/waits"
|
||||
import { openSession } from "../utils/workspace"
|
||||
import { newSessionLocation, openSession } from "../utils/workspace"
|
||||
|
||||
const directory = "C:/OpenCode/NewProject"
|
||||
|
||||
@@ -72,9 +72,13 @@ test("creates a session in a new project and selects its model", async ({ page }
|
||||
})
|
||||
|
||||
await page.goto("/")
|
||||
const addProject = page.locator('[data-action="home-add-project-row"]')
|
||||
await expectAppVisible(addProject)
|
||||
await addProject.click()
|
||||
const home = page.locator('[data-slot="home-panel"]')
|
||||
// A server without projects adds them in Settings; Home only lists them.
|
||||
await expectAppVisible(home.getByRole("button", { name: "Settings", exact: true }))
|
||||
await home.getByRole("button", { name: "Settings", exact: true }).click()
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
await settings.getByRole("tab", { name: "Projects", exact: true }).click()
|
||||
await settings.getByRole("button", { name: "Add project", exact: true }).click()
|
||||
const picker = page.getByRole("dialog", { name: "Open project", exact: true })
|
||||
await expect(picker.getByRole("combobox")).toHaveValue("C:\\OpenCode\\NewProject")
|
||||
|
||||
@@ -95,9 +99,12 @@ test("creates a session in a new project and selects its model", async ({ page }
|
||||
await expect(selectFolder).toBeEnabled()
|
||||
await selectFolder.click()
|
||||
await expect(picker).toBeHidden()
|
||||
await expect(settings.getByRole("textbox", { name: "Project name", exact: true })).toHaveValue("NewProject")
|
||||
await settings.getByRole("button", { name: "Back to projects", exact: true }).click()
|
||||
await settings.getByRole("button", { name: "Back to app", exact: true }).click()
|
||||
|
||||
await page.locator('[data-action="home-new-session"]').click()
|
||||
await expectAppVisible(page.locator('[data-component="composer"]'))
|
||||
await home.getByRole("button", { name: "New session", exact: true }).click()
|
||||
await expect(newSessionLocation(page)).toContainText("NewProject")
|
||||
|
||||
const modelControl = page.locator('[data-action="composer-model"]')
|
||||
await expect(modelControl).toContainText("Go Model 1")
|
||||
|
||||
@@ -49,9 +49,9 @@ export async function openPaletteWorkspace(page: Page, home = false) {
|
||||
await page.goto(home ? "/" : sessionHref(paletteSession.id))
|
||||
|
||||
if (home) {
|
||||
await expect(
|
||||
page.getByRole("region", { name: "Recent sessions" }).getByRole("button", { name: /Palette fixture session/ }),
|
||||
).toBeEnabled({ timeout: APP_READY_TIMEOUT })
|
||||
await expect(page.locator('[data-slot="start-row"]').filter({ hasText: paletteSession.title })).toBeVisible({
|
||||
timeout: APP_READY_TIMEOUT,
|
||||
})
|
||||
}
|
||||
|
||||
if (!home) {
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { SESSION_TABS_REMOVED_EVENT, readSessionTabsRemovedDetail } from "@/shell/titlebar/session-events"
|
||||
import { archiveHomeSession } from "./archive"
|
||||
import type { ServerConnection } from "@/runtime/server/registry"
|
||||
|
||||
const remote = "remote" as ServerConnection.Key
|
||||
|
||||
test("archiving a Home session removes its open titlebar tab", async () => {
|
||||
let detail: ReturnType<typeof readSessionTabsRemovedDetail>
|
||||
let removed = false
|
||||
window.addEventListener(
|
||||
SESSION_TABS_REMOVED_EVENT,
|
||||
(event) => {
|
||||
detail = readSessionTabsRemovedDetail(event)
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
|
||||
await archiveHomeSession({
|
||||
server: remote,
|
||||
session: { id: "ses_1", location: { directory: "/workspace" } },
|
||||
archive: async () => undefined,
|
||||
remove: () => {
|
||||
removed = true
|
||||
},
|
||||
})
|
||||
|
||||
expect(removed).toBe(true)
|
||||
expect(detail).toEqual({ server: remote, directory: "/workspace", sessionIDs: ["ses_1"] })
|
||||
})
|
||||
|
||||
test("reports archive failures without removing the session", async () => {
|
||||
const failure = new Error("offline")
|
||||
let error: unknown
|
||||
let removed = false
|
||||
|
||||
await archiveHomeSession({
|
||||
server: remote,
|
||||
session: { id: "ses_1", location: { directory: "/workspace" } },
|
||||
archive: async () => Promise.reject(failure),
|
||||
remove: () => {
|
||||
removed = true
|
||||
},
|
||||
onError: (value) => {
|
||||
error = value
|
||||
},
|
||||
})
|
||||
|
||||
expect(error).toBe(failure)
|
||||
expect(removed).toBe(false)
|
||||
})
|
||||
@@ -1,25 +0,0 @@
|
||||
import { notifySessionTabsRemoved } from "@/shell/titlebar/session-events"
|
||||
import type { ServerConnection } from "@/runtime/server/registry"
|
||||
import type { SessionInfo } from "@opencode/client/promise"
|
||||
|
||||
type HomeSession = Pick<SessionInfo, "id" | "location">
|
||||
|
||||
export async function archiveHomeSession(input: {
|
||||
server: ServerConnection.Key
|
||||
session: HomeSession
|
||||
archive: (sessionID: string) => Promise<unknown>
|
||||
remove: () => void
|
||||
onError?: (error: unknown) => void
|
||||
}) {
|
||||
await input
|
||||
.archive(input.session.id)
|
||||
.then(() => {
|
||||
input.remove()
|
||||
notifySessionTabsRemoved({
|
||||
server: input.server,
|
||||
directory: input.session.location.directory,
|
||||
sessionIDs: [input.session.id],
|
||||
})
|
||||
})
|
||||
.catch((error) => input.onError?.(error))
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { SessionInfo } from "@opencode/client/promise"
|
||||
import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "@/runtime/server/global-sync/types"
|
||||
import {
|
||||
HOME_SESSION_INDEX_LIMIT,
|
||||
HOME_SESSION_LIMIT,
|
||||
HOME_V2_SESSION_PAGE_LIMIT,
|
||||
loadHomeSessionIndex,
|
||||
mergeHomeSessionIndex,
|
||||
parseHomeSessionIndex,
|
||||
retainHomeSessions,
|
||||
} from "./index"
|
||||
|
||||
const session = (id: string, input: Partial<SessionInfo> = {}) =>
|
||||
({
|
||||
id,
|
||||
projectID: "project",
|
||||
title: id,
|
||||
time: { created: 1, updated: 1 },
|
||||
location: { directory: "/repo" },
|
||||
...input,
|
||||
}) as SessionInfo
|
||||
|
||||
// The loader anchors its recent window on the wall clock, so fixtures do too.
|
||||
const now = Date.now()
|
||||
|
||||
const minute = 60_000
|
||||
|
||||
// One session per minute going back from `now`; index 0 is the newest, which
|
||||
// is the server's list order.
|
||||
const history = (directory: string, count: number) =>
|
||||
Array.from({ length: count }, (_, index) =>
|
||||
session(`${directory}-${String(index).padStart(5, "0")}`, {
|
||||
time: { created: now - (index + 1) * minute - 1000, updated: now - (index + 1) * minute },
|
||||
location: { directory },
|
||||
}),
|
||||
)
|
||||
|
||||
const ids = (sessions: SessionInfo[]) => sessions.map((item) => item.id)
|
||||
|
||||
describe("Home session index", () => {
|
||||
test("follows cursors across pages and bounds the result per directory", async () => {
|
||||
const all = history("/repo", HOME_V2_SESSION_PAGE_LIMIT + 1)
|
||||
const calls: Array<{ cursor?: string; parentID: null }> = []
|
||||
|
||||
const result = await loadHomeSessionIndex(async (input) => {
|
||||
calls.push(input)
|
||||
|
||||
if (!input.cursor) return { data: all.slice(0, HOME_V2_SESSION_PAGE_LIMIT), cursor: { next: "next" } }
|
||||
|
||||
return { data: all.slice(HOME_V2_SESSION_PAGE_LIMIT), cursor: {} }
|
||||
})
|
||||
|
||||
expect(calls.map((call) => call.cursor)).toEqual([undefined, "next"])
|
||||
expect(calls.every((call) => call.parentID === null)).toBe(true)
|
||||
// Newest rows in server order, plus the recent window beyond the limit.
|
||||
expect(ids(result)).toEqual(ids(all.slice(0, HOME_SESSION_INDEX_LIMIT + SESSION_RECENT_LIMIT)))
|
||||
})
|
||||
|
||||
test("folds pages so every directory keeps its newest sessions", async () => {
|
||||
const busy = history("/busy", HOME_V2_SESSION_PAGE_LIMIT + 300)
|
||||
|
||||
const quiet = history("/quiet", 3).map((item) => ({
|
||||
...item,
|
||||
time: { created: item.time.created - 6000 * minute, updated: item.time.updated - 6000 * minute },
|
||||
}))
|
||||
|
||||
// Server order is global by updated time: /quiet is older than all of /busy
|
||||
// and only arrives on the second page.
|
||||
const result = await loadHomeSessionIndex(async (input) => {
|
||||
if (!input.cursor) return { data: busy.slice(0, HOME_V2_SESSION_PAGE_LIMIT), cursor: { next: "next" } }
|
||||
|
||||
return { data: [...busy.slice(HOME_V2_SESSION_PAGE_LIMIT), ...quiet], cursor: {} }
|
||||
})
|
||||
|
||||
expect(ids(result.filter((item) => item.location.directory === "/quiet"))).toEqual(ids(quiet))
|
||||
expect(ids(result.filter((item) => item.location.directory === "/busy"))).toEqual(
|
||||
ids(busy.slice(0, HOME_SESSION_INDEX_LIMIT + SESSION_RECENT_LIMIT)),
|
||||
)
|
||||
})
|
||||
|
||||
test("drops archived sessions before they can occupy a retained slot", async () => {
|
||||
const archived = history("/repo", 200).map((item) => ({ ...item, time: { ...item.time, archived: now } }))
|
||||
|
||||
const live = history("/repo", 10).map((item) => ({
|
||||
...item,
|
||||
id: `live-${item.id}`,
|
||||
time: { created: item.time.created - 300 * minute, updated: item.time.updated - 300 * minute },
|
||||
}))
|
||||
|
||||
const result = await loadHomeSessionIndex(async () => ({ data: [...archived, ...live], cursor: {} }))
|
||||
expect(ids(result)).toEqual(ids(live))
|
||||
})
|
||||
|
||||
test("keeps only visible roots", () => {
|
||||
expect(
|
||||
parseHomeSessionIndex([
|
||||
session("root"),
|
||||
session("child", { parentID: "root" }),
|
||||
session("archived", { time: { created: 1, updated: 1, archived: 2 } }),
|
||||
]).map((item) => item.id),
|
||||
).toEqual(["root"])
|
||||
})
|
||||
})
|
||||
|
||||
// Home merges locally known sessions and pending removals into the fetched
|
||||
// index on every store change, then retains per directory for display and
|
||||
// search. The loaded subset must resolve to the same set as the complete index.
|
||||
describe("Home session index parity with the complete index", () => {
|
||||
const complete = [...history("/a", 400), ...history("/b", 90), ...history("/c", 5)]
|
||||
|
||||
const view = (index: SessionInfo[], known: SessionInfo[], removed = new Set<string>()) =>
|
||||
ids(
|
||||
retainHomeSessions(
|
||||
mergeHomeSessionIndex(index, known).filter((item) => !removed.has(item.id)),
|
||||
HOME_SESSION_LIMIT,
|
||||
now,
|
||||
),
|
||||
).toSorted()
|
||||
|
||||
const loaded = () => loadHomeSessionIndex(async () => ({ data: complete, cursor: {} }))
|
||||
|
||||
test("without local changes", async () => {
|
||||
const result = view(await loaded(), [])
|
||||
expect(result).toEqual(view(complete, []))
|
||||
expect(result).toHaveLength(HOME_SESSION_LIMIT + SESSION_RECENT_LIMIT + 90 + 5)
|
||||
})
|
||||
|
||||
test("with new, re-timed, and unlisted-directory local sessions", async () => {
|
||||
const known = [
|
||||
session("a-fresh", { time: { created: now, updated: now }, location: { directory: "/a" } }),
|
||||
// A fetched session that fell outside retention but was updated locally.
|
||||
{ ...complete[300], time: { created: now - 1, updated: now } },
|
||||
session("d-new", { time: { created: now, updated: now }, location: { directory: "/d" } }),
|
||||
]
|
||||
|
||||
const result = view(await loaded(), known)
|
||||
expect(result).toEqual(view(complete, known))
|
||||
expect(result).toContain("a-fresh")
|
||||
expect(result).toContain(complete[300].id)
|
||||
expect(result).toContain("d-new")
|
||||
})
|
||||
|
||||
test("with pending removals up to the recent-window bucket size", async () => {
|
||||
const removed = new Set(ids(complete.slice(0, SESSION_RECENT_LIMIT)))
|
||||
const result = view(await loaded(), [], removed)
|
||||
expect(result).toEqual(view(complete, [], removed))
|
||||
expect(result).toHaveLength(HOME_SESSION_LIMIT + SESSION_RECENT_LIMIT + 90 + 5)
|
||||
expect(result.some((id) => removed.has(id))).toBe(false)
|
||||
})
|
||||
|
||||
test("with a directory entirely inside the recent window", async () => {
|
||||
const hot = history("/hot", 300).map((item, index) => ({
|
||||
...item,
|
||||
time: { created: now - index * 1000 - 500, updated: now - index * 1000 },
|
||||
}))
|
||||
|
||||
expect(hot.every((item) => item.time.updated > now - SESSION_RECENT_WINDOW)).toBe(true)
|
||||
const index = await loadHomeSessionIndex(async () => ({ data: hot, cursor: {} }))
|
||||
expect(index).toHaveLength(HOME_SESSION_INDEX_LIMIT + SESSION_RECENT_LIMIT)
|
||||
expect(view(index, [])).toEqual(view(hot, []))
|
||||
})
|
||||
})
|
||||
@@ -1,79 +1,6 @@
|
||||
import type { SessionInfo, SessionsResponse } from "@opencode/client/promise"
|
||||
import { pathKey } from "@/workspaces/path-key"
|
||||
import { SESSION_RECENT_LIMIT, SESSION_RECENT_WINDOW } from "@/runtime/server/global-sync/types"
|
||||
import type { SessionInfo } from "@opencode/client/promise"
|
||||
|
||||
export const HOME_V2_SESSION_PAGE_LIMIT = 5_000
|
||||
|
||||
export const HOME_SESSION_LIMIT = 64
|
||||
|
||||
// Rows kept per directory from the fetched index: the visible limit plus the
|
||||
// recent-window search bucket. Merging locally known sessions and pending
|
||||
// removals into this subset resolves exactly like merging into the complete
|
||||
// index, so Home shows the same rows, order, and search results while the
|
||||
// query cache and every per-update re-merge stay bounded by directory count.
|
||||
export const HOME_SESSION_INDEX_LIMIT = HOME_SESSION_LIMIT + SESSION_RECENT_LIMIT
|
||||
|
||||
export async function loadHomeSessionIndex(
|
||||
list: (
|
||||
input: {
|
||||
limit: number
|
||||
order: "desc"
|
||||
parentID: null
|
||||
cursor?: string
|
||||
},
|
||||
options: { signal?: AbortSignal },
|
||||
) => Promise<SessionsResponse>,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const now = Date.now()
|
||||
let retained: SessionInfo[] = []
|
||||
let cursor: string | undefined
|
||||
|
||||
for (;;) {
|
||||
const response = await list(
|
||||
{
|
||||
limit: HOME_V2_SESSION_PAGE_LIMIT,
|
||||
order: "desc",
|
||||
parentID: null,
|
||||
...(cursor ? { cursor } : {}),
|
||||
},
|
||||
{ signal },
|
||||
)
|
||||
|
||||
// Fold each page in as it arrives: pages are newest first, so later pages
|
||||
// can only fill directories that still have room. Peak allocation is one
|
||||
// page plus the retained subset, not the whole history.
|
||||
retained = retainHomeSessions([...retained, ...parseHomeSessionIndex(response.data)], HOME_SESSION_INDEX_LIMIT, now)
|
||||
|
||||
if (response.data.length < HOME_V2_SESSION_PAGE_LIMIT || !response.cursor.next) return retained
|
||||
cursor = response.cursor.next
|
||||
}
|
||||
}
|
||||
|
||||
// Keep this filter for locally known sessions merged into the fetched index.
|
||||
// Home lists live root sessions only.
|
||||
export function parseHomeSessionIndex(sessions: SessionInfo[]) {
|
||||
return sessions.filter((session) => !session.parentID && typeof session.time.archived !== "number")
|
||||
}
|
||||
|
||||
export function mergeHomeSessionIndex(fetched: SessionInfo[], known: SessionInfo[]) {
|
||||
return parseHomeSessionIndex([
|
||||
...new Map([...fetched, ...known].map((session) => [session.id, session] as const)).values(),
|
||||
])
|
||||
}
|
||||
|
||||
export function retainHomeSessions(sessions: SessionInfo[], limit: number, now: number) {
|
||||
return [...Map.groupBy(sessions, (session) => pathKey(session.location.directory)).values()].flatMap((items) => {
|
||||
const sorted = items.toSorted((a, b) => {
|
||||
const updated = (b.time.updated ?? b.time.created) - (a.time.updated ?? a.time.created)
|
||||
|
||||
return updated || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
||||
})
|
||||
|
||||
const recent = sorted
|
||||
.slice(limit)
|
||||
.filter((session) => (session.time.updated ?? session.time.created) > now - SESSION_RECENT_WINDOW)
|
||||
.slice(0, SESSION_RECENT_LIMIT)
|
||||
|
||||
return [...sorted.slice(0, limit), ...recent]
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { createMemo, onCleanup } from "solid-js"
|
||||
import { commandPaletteOptions, useCommand } from "@/shell/commands/command"
|
||||
import { useGlobal } from "@/runtime/server/runtime"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ServerConnection } from "@/runtime/server/registry"
|
||||
import {
|
||||
createCommandPaletteCommandEntry,
|
||||
createServerSessionEntries,
|
||||
type CommandPaletteEntry,
|
||||
type PaletteHighlight,
|
||||
} from "@/shell/commands/palette"
|
||||
import { CommandPaletteView, matchesCommandPaletteEntry } from "@/shell/commands/dialog"
|
||||
|
||||
export function HomeCommandPalette(props: {
|
||||
server: ServerConnection.Any
|
||||
onSelectSession: (entry: CommandPaletteEntry) => void
|
||||
}) {
|
||||
const command = useCommand()
|
||||
const dialog = useDialog()
|
||||
const global = useGlobal()
|
||||
const language = useLanguage()
|
||||
const server = global.ensureServerCtx(props.server)
|
||||
const state: PaletteHighlight = { cleanup: undefined, committed: false }
|
||||
|
||||
const commandEntries = createMemo(() => {
|
||||
const category = language.t("palette.group.commands")
|
||||
|
||||
return commandPaletteOptions(command.options).map((option) => createCommandPaletteCommandEntry(option, category))
|
||||
})
|
||||
|
||||
const sessions = createServerSessionEntries({
|
||||
server: ServerConnection.key(props.server),
|
||||
projects: server.projects.list,
|
||||
load: (search, signal) => server.sdk.api.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
||||
get: (sessionID, signal) => server.sdk.api.session.get({ sessionID }, { signal }),
|
||||
untitled: () => language.t("command.session.new"),
|
||||
category: () => language.t("command.category.session"),
|
||||
recentCategory: () => language.t("palette.group.recentSessions"),
|
||||
})
|
||||
|
||||
const highlight = (item: CommandPaletteEntry | undefined) => {
|
||||
state.cleanup?.()
|
||||
state.cleanup = undefined
|
||||
|
||||
if (item?.type !== "command") return
|
||||
state.cleanup = item.option?.onHighlight?.()
|
||||
}
|
||||
|
||||
const select = (item: CommandPaletteEntry | undefined) => {
|
||||
if (!item) return
|
||||
state.committed = true
|
||||
state.cleanup = undefined
|
||||
dialog.close()
|
||||
|
||||
if (item.type === "command") {
|
||||
void item.option?.onSelect?.("palette")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (item.type === "session") props.onSelectSession(item)
|
||||
}
|
||||
|
||||
const items = (query: string) => {
|
||||
if (!query) return commandEntries().slice(0, 5)
|
||||
|
||||
return commandEntries().filter((entry) => matchesCommandPaletteEntry(entry, query))
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (state.committed) return
|
||||
state.cleanup?.()
|
||||
})
|
||||
|
||||
return (
|
||||
<CommandPaletteView
|
||||
placeholder={language.t("palette.search.placeholder.home")}
|
||||
items={items}
|
||||
sources={[sessions]}
|
||||
highlight={highlight}
|
||||
select={select}
|
||||
close={() => dialog.close()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -103,9 +103,14 @@ export function createStartModel() {
|
||||
)
|
||||
|
||||
// The account this computer's server runs as is the best name the app has for the person.
|
||||
const name = createMemo(() => {
|
||||
const health = () => {
|
||||
const conn = ordered()[0]
|
||||
const account = conn ? global.servers.health[ServerConnection.key(conn)]?.username : undefined
|
||||
|
||||
return conn ? global.servers.health[ServerConnection.key(conn)] : undefined
|
||||
}
|
||||
|
||||
const name = createMemo(() => {
|
||||
const account = health()?.username
|
||||
|
||||
return account ? account.charAt(0).toUpperCase() + account.slice(1) : undefined
|
||||
})
|
||||
@@ -124,6 +129,9 @@ export function createStartModel() {
|
||||
projectServers,
|
||||
unreachable,
|
||||
name,
|
||||
/** The greeting waits for the first health check, so the name never pops in after it. */
|
||||
greeted: () => !!health() && !health()?.checking,
|
||||
loading: inbox.loading,
|
||||
newSession: () => command.trigger("tab.new"),
|
||||
openProject: (server: StartServer, item: StartProject) => {
|
||||
global.ensureServerCtx(server.conn).projects.touch(item.project.worktree)
|
||||
|
||||
@@ -2,16 +2,24 @@ import { Button } from "@opencode/ui/button"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { IconButton } from "@opencode/ui/icon-button"
|
||||
import { Keybind } from "@opencode/ui/keybind"
|
||||
import { displayName, getProjectAvatarSource, getProjectAvatarVariant, ProjectAvatar } from "@opencode/ui/project-avatar"
|
||||
import {
|
||||
displayName,
|
||||
getProjectAvatarSource,
|
||||
getProjectAvatarVariant,
|
||||
ProjectAvatar,
|
||||
} from "@opencode/ui/project-avatar"
|
||||
import { TextShimmer } from "@opencode/ui/text-shimmer"
|
||||
import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { createEffect, createMemo, For, Match, Show, Switch, type JSX } from "solid-js"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { createEffect, createMemo, For, Match, Show, startTransition, Switch, type JSX } from "solid-js"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useGlobal } from "@/runtime/server/runtime"
|
||||
import { ServerConnection, useServers } from "@/runtime/server/registry"
|
||||
import { useSettingsCommand } from "@/settings/command"
|
||||
import { useSettingsSurface } from "@/settings/surface"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { useCommand } from "@/shell/commands/command"
|
||||
import { useTabs } from "@/shell/tabs/tabs"
|
||||
import { SessionTabAvatarView } from "@/shell/layout/session-tab-avatar"
|
||||
import { sessionTabTitle } from "@/shell/titlebar/tab-title"
|
||||
import type { InboxEntry } from "@/shell/titlebar/inbox-model"
|
||||
@@ -22,6 +30,7 @@ type Language = ReturnType<typeof useLanguage>
|
||||
/** Home: a greeting, every session sorted by what it needs from you, and recent projects beside them. */
|
||||
export function StartHome() {
|
||||
const model = createStartModel()
|
||||
useStartCommands()
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -46,12 +55,49 @@ export function StartHome() {
|
||||
)
|
||||
}
|
||||
|
||||
/** Home's own palette lists commands and this computer's sessions; Settings opens from Home like from a session. */
|
||||
function useStartCommands() {
|
||||
const command = useCommand()
|
||||
const dialog = useDialog()
|
||||
const global = useGlobal()
|
||||
const language = useLanguage()
|
||||
const servers = useServers()
|
||||
const tabs = useTabs()
|
||||
|
||||
useSettingsCommand()
|
||||
command.register("home.palette", () => [
|
||||
{
|
||||
id: "command.palette",
|
||||
title: language.t("command.palette"),
|
||||
hidden: true,
|
||||
onSelect: async () => {
|
||||
const conn = servers.visible.find((item) => servers.current(item)) ?? servers.visible[0]
|
||||
|
||||
if (!conn) return
|
||||
const { HomeCommandPalette } = await import("./command-palette")
|
||||
void dialog.show(() => (
|
||||
<HomeCommandPalette
|
||||
server={conn}
|
||||
onSelectSession={(entry) => {
|
||||
if (!entry.sessionID || !entry.directory || !entry.server) return
|
||||
const sessionID = entry.sessionID
|
||||
const server = entry.server
|
||||
global.ensureServerCtx(conn).projects.touch(entry.project?.worktree ?? entry.directory)
|
||||
void startTransition(() => {
|
||||
tabs.select(tabs.addSessionTab({ server, sessionId: sessionID }))
|
||||
})
|
||||
}}
|
||||
/>
|
||||
))
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
function StartGreeting(props: { model: StartModel }) {
|
||||
const language = useLanguage()
|
||||
const command = useCommand()
|
||||
const platform = usePlatform()
|
||||
// `settings.open` is registered only by the session and new-session routes, so Home opens the surface directly.
|
||||
const settings = useSettingsSurface()
|
||||
const groups = props.model.groups
|
||||
const hour = () => new Date(props.model.inbox.now()).getHours()
|
||||
const period = () => (hour() < 12 ? "morning" : hour() < 18 ? "afternoon" : "evening")
|
||||
@@ -73,11 +119,19 @@ function StartGreeting(props: { model: StartModel }) {
|
||||
|
||||
return (
|
||||
<div class="flex items-end justify-between gap-4 px-2">
|
||||
{/* Both lines keep their height while they wait, so nothing below moves when they fill in. */}
|
||||
<div class="min-w-0">
|
||||
<h1 class="truncate text-[20px] font-medium leading-7 text-v2-text-text-base">{greeting()}</h1>
|
||||
<p class="truncate text-[13px] leading-5 text-v2-text-text-muted">
|
||||
<Show when={summary().length > 0} fallback={language.t("start.caughtUp")}>
|
||||
{summary().join(" · ")}
|
||||
<h1
|
||||
class="truncate text-[20px] font-medium leading-7 text-v2-text-text-base transition-opacity duration-200"
|
||||
classList={{ "opacity-0": !props.model.greeted() }}
|
||||
>
|
||||
{greeting()}
|
||||
</h1>
|
||||
<p class="flex h-5 items-center truncate text-[13px] leading-5 text-v2-text-text-muted">
|
||||
<Show when={!props.model.loading()} fallback={<Bar class="w-44" />}>
|
||||
<Show when={summary().length > 0} fallback={language.t("start.caughtUp")}>
|
||||
{summary().join(" · ")}
|
||||
</Show>
|
||||
</Show>
|
||||
</p>
|
||||
</div>
|
||||
@@ -107,7 +161,7 @@ function StartGreeting(props: { model: StartModel }) {
|
||||
size="large"
|
||||
aria-label={language.t("sidebar.settings")}
|
||||
icon={<Icon name="settings-gear" />}
|
||||
onClick={() => settings.open()}
|
||||
onClick={() => command.trigger("settings.open")}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip
|
||||
@@ -154,7 +208,11 @@ function StartUnreachable(props: { model: StartModel }) {
|
||||
{ server: servers.label(conn) },
|
||||
)}
|
||||
</span>
|
||||
<Button size="small" variant="ghost-muted" onClick={() => settings.openServers(ServerConnection.key(conn))}>
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost-muted"
|
||||
onClick={() => settings.openServers(ServerConnection.key(conn))}
|
||||
>
|
||||
{language.t("start.server.manage")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -175,40 +233,74 @@ function StartSections(props: { model: StartModel }) {
|
||||
)
|
||||
|
||||
return (
|
||||
<div class="flex flex-col gap-6">
|
||||
<Show when={groups().needs.length > 0} fallback={<InboxZero />}>
|
||||
<Section title={language.t("start.section.needsYou")} count={groups().needs.length} icon="warning">
|
||||
<For each={groups().needs}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={groups().done.length > 0}>
|
||||
<Section
|
||||
title={language.t("start.section.done")}
|
||||
count={groups().done.length}
|
||||
icon="circle-check"
|
||||
action={
|
||||
<Button size="small" variant="ghost-muted" onClick={props.model.markAllViewed}>
|
||||
{language.t("start.markAllRead")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<For each={groups().done}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={groups().working.length > 0}>
|
||||
<Section title={language.t("start.section.running")} count={groups().working.length} icon="status-active">
|
||||
<For each={groups().working}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={groups().earlier.length > 0}>
|
||||
<Section title={language.t("start.section.earlier")} icon="reset">
|
||||
<For each={groups().earlier}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={!props.model.loading()} fallback={<Skeleton />}>
|
||||
<div class="flex flex-col gap-6">
|
||||
<Show when={groups().needs.length > 0} fallback={<InboxZero />}>
|
||||
<Section title={language.t("start.section.needsYou")} count={groups().needs.length} icon="warning">
|
||||
<For each={groups().needs}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={groups().done.length > 0}>
|
||||
<Section
|
||||
title={language.t("start.section.done")}
|
||||
count={groups().done.length}
|
||||
icon="circle-check"
|
||||
action={
|
||||
<Button size="small" variant="ghost-muted" onClick={props.model.markAllViewed}>
|
||||
{language.t("start.markAllRead")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<For each={groups().done}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={groups().working.length > 0}>
|
||||
<Section title={language.t("start.section.running")} count={groups().working.length} icon="status-active">
|
||||
<For each={groups().working}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
<Show when={groups().earlier.length > 0}>
|
||||
<Section title={language.t("start.section.earlier")} icon="reset">
|
||||
<For each={groups().earlier}>{(entry) => <StartRow model={props.model} entry={entry} />}</For>
|
||||
</Section>
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
/** Row-shaped placeholders while the first load settles; claiming inbox zero before then would be wrong. */
|
||||
function Skeleton() {
|
||||
return (
|
||||
<div class="flex flex-col gap-1" aria-hidden="true">
|
||||
<div class="flex h-7 items-center gap-3 px-2">
|
||||
<span class="size-4 shrink-0" />
|
||||
<Bar class="w-20" />
|
||||
</div>
|
||||
<For each={[56, 44, 64, 38]}>
|
||||
{(width) => (
|
||||
<div class="flex h-12 items-center gap-3 px-2">
|
||||
<span class="size-4 shrink-0 animate-pulse rounded-[4px] bg-v2-background-bg-layer-03" />
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-1.5">
|
||||
<Bar style={{ width: `${width}%` }} />
|
||||
<Bar class="w-28" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Bar(props: { class?: string; style?: JSX.CSSProperties }) {
|
||||
return (
|
||||
<span
|
||||
class={`block h-2.5 max-w-full animate-pulse rounded-full bg-v2-background-bg-layer-03 ${props.class ?? ""}`}
|
||||
style={props.style}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Recent projects per server. Choosing one starts a session there; projects are added on the server, not here. */
|
||||
function StartProjects(props: { model: StartModel }) {
|
||||
const language = useLanguage()
|
||||
@@ -222,7 +314,11 @@ function StartProjects(props: { model: StartModel }) {
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex h-7 items-center gap-1.5 px-2 text-[12px] leading-4 font-medium text-v2-text-text-muted">
|
||||
<Show when={several()} fallback={language.t("start.projects")}>
|
||||
<Icon name={servers.current(server.conn) ? "monitor" : "server"} size="small" class="shrink-0 text-v2-icon-icon-faint" />
|
||||
<Icon
|
||||
name={servers.current(server.conn) ? "monitor" : "server"}
|
||||
size="small"
|
||||
class="shrink-0 text-v2-icon-icon-faint"
|
||||
/>
|
||||
<span class="min-w-0 truncate">{servers.label(server.conn)}</span>
|
||||
</Show>
|
||||
<Show when={!several() && index() === 0 && servers.tag(server.conn)}>
|
||||
@@ -245,7 +341,11 @@ function ProjectList(props: { model: StartModel; server: StartServer }) {
|
||||
|
||||
return new Set(names.filter((name, index) => names.indexOf(name) !== index))
|
||||
})
|
||||
const parent = (worktree: string) => worktree.replace(/[/\\]+$/, "").split(/[/\\]/).at(-2)
|
||||
const parent = (worktree: string) =>
|
||||
worktree
|
||||
.replace(/[/\\]+$/, "")
|
||||
.split(/[/\\]/)
|
||||
.at(-2)
|
||||
|
||||
return (
|
||||
<For each={props.server.projects}>
|
||||
|
||||
@@ -10,10 +10,8 @@ import { useLayout } from "@/shell/state/layout"
|
||||
import { useTabs } from "@/shell/tabs/tabs"
|
||||
import { sessionBusy, sessionRequests } from "@/shell/layout/project-avatar-state"
|
||||
import { pathKey } from "@/workspaces/path-key"
|
||||
import { notifySessionTabsRemoved } from "./session-events"
|
||||
import { loadHomeSessionIndex } from "@/home/sessions/index"
|
||||
import { archiveHomeSession } from "@/home/sessions/archive"
|
||||
import { sessionFormRequest, sessionPermissionRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
import { parseHomeSessionIndex } from "@/home/sessions/index"
|
||||
import { sessionFormRequest, sessionPermissionRequest } from "@/session/requests/session-request-tree"
|
||||
import { errorMessage } from "@/shell/layout/helpers"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
|
||||
@@ -23,8 +21,8 @@ const selectSessions = (sessions: SessionInfo[]) => () => sessions
|
||||
// Branch lookups each run git on the server, so load them a few at a time.
|
||||
const BRANCH_BATCH = 4
|
||||
|
||||
// The Home index excludes archived sessions, so the inbox loads the newest archived ones separately.
|
||||
const ARCHIVED_LIMIT = 50
|
||||
// Root sessions fetched per server.
|
||||
const INDEX_LIMIT = 200
|
||||
|
||||
export type InboxStatus = "approval" | "input" | "working" | "failed" | "done" | "ready"
|
||||
|
||||
@@ -39,9 +37,9 @@ export type InboxEntry = {
|
||||
|
||||
/**
|
||||
* Root sessions across every visible server with the state a person acts on: waiting for an answer, working,
|
||||
* finished and unread, or read. Shared by the sidebar inbox and the new session start screen.
|
||||
* finished and unread, or read. Home lists them.
|
||||
*/
|
||||
export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
export function createSessionInbox() {
|
||||
const global = useGlobal()
|
||||
const servers = useServers()
|
||||
const settings = useSettings()
|
||||
@@ -61,9 +59,6 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
queryClient.setQueryData<SessionInfo[]>(["home-sessions", conn], (current) =>
|
||||
current?.filter((session) => session.id !== sessionID),
|
||||
)
|
||||
queryClient.setQueryData<SessionInfo[]>(["inbox-archived-sessions", conn], (current) =>
|
||||
current?.filter((session) => session.id !== sessionID),
|
||||
)
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
@@ -72,29 +67,16 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
})
|
||||
})
|
||||
|
||||
// Shares the Home query cache so renames and deletions there refresh the inbox too.
|
||||
// One page of the newest root sessions: what needs a person is recent, and paging the whole history first made the
|
||||
// first paint wait on every session the server has.
|
||||
const queries = useQueries(() => ({
|
||||
queries: connections().map((item) => ({
|
||||
queryKey: ["home-sessions", item.conn] as const,
|
||||
enabled: item.ctx.sdk.connection.status() === "connected",
|
||||
queryFn: ({ signal }: { signal: AbortSignal }) =>
|
||||
loadHomeSessionIndex((list, options) => item.ctx.sdk.api.session.list(list, options), signal),
|
||||
retry: false,
|
||||
staleTime: 30_000,
|
||||
refetchOnMount: true,
|
||||
refetchOnReconnect: true,
|
||||
select: selectSessions,
|
||||
})),
|
||||
}))
|
||||
|
||||
const archivedQueries = useQueries(() => ({
|
||||
queries: connections().map((item) => ({
|
||||
queryKey: ["inbox-archived-sessions", item.conn] as const,
|
||||
enabled: !!input.archived && item.ctx.sdk.connection.status() === "connected",
|
||||
queryFn: ({ signal }: { signal: AbortSignal }) =>
|
||||
item.ctx.sdk.api.session
|
||||
.list({ limit: ARCHIVED_LIMIT, order: "desc", parentID: null, archived: true }, { signal })
|
||||
.then((response) => response.data),
|
||||
.list({ limit: INDEX_LIMIT, order: "desc", parentID: null }, { signal })
|
||||
.then((response) => parseHomeSessionIndex(response.data)),
|
||||
retry: false,
|
||||
staleTime: 30_000,
|
||||
refetchOnMount: true,
|
||||
@@ -134,11 +116,9 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
|
||||
// Locally known sessions come last so live archive and unarchive events win over cached indexes.
|
||||
const sessions = new Map(
|
||||
[
|
||||
...(queries[index]?.data?.() ?? []),
|
||||
...(input.archived ? (archivedQueries[index]?.data?.() ?? []) : []),
|
||||
...data.session.list(),
|
||||
].map((session) => [session.id, session] as const),
|
||||
[...(queries[index]?.data?.() ?? []), ...data.session.list()].map(
|
||||
(session) => [session.id, session] as const,
|
||||
),
|
||||
)
|
||||
|
||||
return data.session.apply([...sessions.values()].filter((session) => !session.parentID)).map(
|
||||
@@ -156,15 +136,37 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
)
|
||||
|
||||
// Pending permissions and questions only load for sessions the client has opened. A running session may be waiting
|
||||
// on one, so load them for every working root; events keep them current from then on.
|
||||
// on one, so load them for every working root; events keep them current from then on. `checked` marks the roots
|
||||
// whose first load ended, so the first paint can wait for them instead of moving rows a moment later.
|
||||
const [requests, setRequests] = createStore({ checked: {} as Record<string, true> })
|
||||
|
||||
createEffect(() => {
|
||||
entries().forEach((entry) => {
|
||||
if (entry.status !== "working") return
|
||||
void entry.ctx.data.session.permission.sync(entry.session.id).catch(() => undefined)
|
||||
void entry.ctx.data.session.form.sync(entry.session.id).catch(() => undefined)
|
||||
if (entry.status !== "working" || requests.checked[entry.key]) return
|
||||
void Promise.allSettled([
|
||||
entry.ctx.data.session.permission.sync(entry.session.id),
|
||||
entry.ctx.data.session.form.sync(entry.session.id),
|
||||
]).then(() => setRequests("checked", entry.key, true))
|
||||
})
|
||||
})
|
||||
|
||||
// Settled once every reachable server answered the index and every working root's requests loaded. A server that
|
||||
// never connects or fails its health check does not hold the screen.
|
||||
// Once settled it stays settled, so a session starting later never blanks the screen again.
|
||||
const settled = createMemo(
|
||||
(previous: boolean) =>
|
||||
previous ||
|
||||
(connections().every((item, index) => {
|
||||
const health = global.servers.health[ServerConnection.key(item.conn)]
|
||||
|
||||
if (health && !health.checking && !health.healthy) return true
|
||||
|
||||
return !!queries[index]?.isSuccess || !!queries[index]?.isError
|
||||
}) &&
|
||||
entries().every((entry) => entry.status !== "working" || !!requests.checked[entry.key])),
|
||||
false,
|
||||
)
|
||||
|
||||
// Rows are keyed by stable strings so live session updates do not remount them.
|
||||
const byKey = createMemo(() => new Map(entries().map((entry) => [entry.key, entry])))
|
||||
|
||||
@@ -224,17 +226,6 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
// Move the session between the cached indexes so it changes section before either refetches.
|
||||
const move = (entry: InboxEntry, archivedAt: number | undefined) => {
|
||||
const session = { ...entry.session, time: { ...entry.session.time, archived: archivedAt } }
|
||||
|
||||
forget(entry.conn, entry.session.id)
|
||||
queryClient.setQueryData<SessionInfo[]>(
|
||||
[archivedAt === undefined ? "home-sessions" : "inbox-archived-sessions", entry.conn],
|
||||
(current) => current && [session, ...current],
|
||||
)
|
||||
}
|
||||
|
||||
const requestFailed = (cause: unknown) =>
|
||||
showToast({
|
||||
title: language.t("common.requestFailed"),
|
||||
@@ -252,8 +243,8 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
return {
|
||||
now,
|
||||
entries,
|
||||
/** The first index load is still running on some connected server. */
|
||||
loading: () => queries.some((query) => query.isPending && query.fetchStatus !== "idle"),
|
||||
/** The first load has not settled: lists would still move or claim nothing needs you. */
|
||||
loading: () => !settled(),
|
||||
byKey,
|
||||
selected,
|
||||
open,
|
||||
@@ -270,40 +261,12 @@ export function createSessionInbox(input: { archived?: boolean } = {}) {
|
||||
const request = sessionPermissionRequest(family(entry), entry.ctx.data.session.permission.list, entry.session.id)
|
||||
|
||||
if (!request) return
|
||||
void entry.ctx.sdk.api.permission
|
||||
// The data store's reply drops the request at once, so the row leaves Needs you without waiting for an event.
|
||||
void entry.ctx.data.session.permission
|
||||
.reply({ sessionID: request.sessionID, requestID: request.id, decision })
|
||||
.catch(requestFailed)
|
||||
},
|
||||
markViewed: (entry: InboxEntry) => entry.ctx.notification.session.markViewed(entry.session.id),
|
||||
archive: (entry: InboxEntry) =>
|
||||
archiveHomeSession({
|
||||
server: entry.server,
|
||||
session: entry.session,
|
||||
archive: (sessionID) => entry.ctx.sdk.api.session.update({ sessionID, archived: true }),
|
||||
remove: () => move(entry, Date.now()),
|
||||
onError: requestFailed,
|
||||
}),
|
||||
unarchive: (entry: InboxEntry) =>
|
||||
entry.ctx.sdk.api.session
|
||||
.update({ sessionID: entry.session.id, archived: false })
|
||||
.then(() => move(entry, undefined))
|
||||
.catch(requestFailed),
|
||||
remove: (entry: InboxEntry) => {
|
||||
const ids = sessionTreeIDs(entry.ctx.data.session.list(), entry.session.id)
|
||||
|
||||
return entry.ctx.data.session
|
||||
.remove(entry.session.id)
|
||||
.then(() => {
|
||||
forget(entry.conn, entry.session.id)
|
||||
notifySessionTabsRemoved({ server: entry.server, directory: entry.session.location.directory, sessionIDs: ids })
|
||||
})
|
||||
.catch((cause) =>
|
||||
showToast({
|
||||
title: language.t("session.delete.failed.title"),
|
||||
description: errorMessage(cause, language.t("session.delete.failed.title")),
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user