import type { SessionInfo } from "@opencode/client/promise" import { createEffect, createMemo, onCleanup } from "solid-js" import { createStore } from "solid-js/store" import { displayName } from "@opencode/ui/project-avatar" import { createDraftComposerState } from "@/composer/state" import { isAttachment } from "@/composer/prompt-parts" import { useGlobal, type ServerCtx } from "@/runtime/server/runtime" import { ServerConnection, serverName, useServers } from "@/runtime/server/registry" import { sessionLabel } from "@/session/title" import { needsUser } from "@/session/requests/auto-approve-machine" import { sessionFormRequest, sessionPermissionRequest } from "@/session/requests/session-request-tree" import { projectSettingsKey, useSettings } from "@/settings/model" import { sessionBusy } from "@/shell/layout/project-avatar-state" import { useLayout } from "@/shell/state/layout" import { pinKey, pinnedRefs } from "@/shell/tabs/pins" import { useTabs, type DraftTab } from "@/shell/tabs/tabs" import { createSessionInbox } from "@/shell/titlebar/inbox-model" import { workingSince } from "@/shell/titlebar/inbox-working" import { usePins } from "@/shell/titlebar/pinned-area" import { pathKey } from "@/workspaces/path-key" import { draftKey, navigationKey, type NavDraft, type NavProject, type NavServer, type NavSession, type RowKey, type Status, } from "./contract" type Tabs = ReturnType type SessionState = { busy: Set requestTimes: Record muted: boolean autoApprove: boolean } /** * The real data behind the New navigation view: every root session the Inbox index lists (archived ones too while * Archived is on), the subagents and pinned sessions this window has loaded, the window's drafts and tabs, pins, * servers and projects. Statuses are each session's own, except that a root runs while anything in its family runs; * the view gives roots their family's requests. Activity is the latest of the last reply (`time.idle`, else * `time.updated`), the current run's start and the pending request, so reading a session never moves it. * Runs under the Pins provider. Reads no resources, so nothing here suspends. */ export function createNavigationSource() { const global = useGlobal() const servers = useServers() const settings = useSettings() const layout = useLayout() const tabs = useTabs() const pins = usePins() const inbox = createSessionInbox({ get archived() { return settings.navigation.get().archived }, }) // Request snapshots have no timestamp; live events give newly waiting sessions their actual waiting age. const [requestTimes, setRequestTimes] = createStore>({}) const contexts = createMemo(() => servers.visible.flatMap((conn) => { const server = ServerConnection.key(conn) const ctx = global.serverCtx(server) return ctx ? [{ conn, server, ctx }] : [] }), ) createEffect(() => { contexts().forEach((item) => { const data = item.ctx.data const set = (id: string, value: number | undefined) => setRequestTimes(`${item.server}\0${id}`, value) onCleanup(data.on("permission.asked", (event) => set(event.data.id, event.created))) onCleanup(data.on("form.created", (event) => set(event.data.form.id, event.created))) onCleanup(data.on("permission.replied", (event) => set(event.data.requestID, undefined))) onCleanup(data.on("form.replied", (event) => set(event.data.id, undefined))) onCleanup(data.on("form.cancelled", (event) => set(event.data.id, undefined))) }) }) const sessions = createMemo(() => { const roots = Map.groupBy(inbox.entries(), (entry) => entry.server) const pinned = Map.groupBy(pinnedRefs(pins.state), (ref) => ref.server) return contexts().flatMap((item) => { const data = item.ctx.data const indexed = (roots.get(item.server) ?? []).map((entry) => entry.session) const ids = new Set(indexed.map((session) => session.id)) // Subagents of listed roots, and pinned sessions older than the index, as far as this window has loaded them. const extra = [ ...data.session.list().filter((session) => !!session.parentID && ids.has(data.session.root(session.id))), ...(pinned.get(item.server) ?? []).flatMap((ref) => { const session = data.session.get(ref.sessionId) return session ? [session] : [] }), ] // A root runs while any session in its family is busy. const busy = new Set( [...data.session.list().map((session) => session.id), ...data.session.active()].flatMap((id) => sessionBusy(data, id) ? [id, data.session.root(id)] : [], ), ) return [...new Map([...indexed, ...extra].map((session) => [session.id, session])).values()].map((session) => navSession(item.ctx, item.server, session, { busy, requestTimes, muted: global.sessionPreferences.muted(item.server, session.id), autoApprove: settings.permissions.autoApproves(projectSettingsKey(item.ctx.sdk.scope, session.projectID)), }), ) }) }) const drafts = createMemo(() => tabs.visible.flatMap((tab, index): NavDraft[] => { if (tab.type !== "draft") return [] const text = draftText(tabs, tab) if (!draftHolds(tabs, tab, text) && !draftSelected(layout, tab)) return [] return [ { key: draftKey(tab.draftID), draftID: tab.draftID, server: tab.server, projectID: global.serverCtx(tab.server)?.projects.forDirectory(tab.directory)?.id, directory: tab.directory, preview: text.split("\n")[0] ?? "", // Drafts carry no time; a later tab is a newer draft. updated: index, }, ] }), ) const open = createMemo(() => tabs.visible.map( (tab): RowKey => (tab.type === "draft" ? draftKey(tab.draftID) : navigationKey(tab.server, tab.sessionId)), ), ) // With Subagents off a subagent has no row, so its root is the selected one. const selected = createMemo((): RowKey | undefined => { const route = layout.route() if (route.type === "draft") return draftKey(route.draftID) if (route.type !== "session") return undefined if (settings.navigation.get().subagents) return navigationKey(route.server, route.sessionId) return navigationKey( route.server, global.serverCtx(route.server)?.data.session.root(route.sessionId) ?? route.sessionId, ) }) return { /** The Inbox index this source reads, for its loading state and session actions (open, archive, branches). */ inbox, sessions, drafts, pins: createMemo(() => pinnedRefs(pins.state).map(pinKey)), servers: createMemo(() => contexts().map((item): NavServer => ({ key: item.server, name: serverName(item.conn) }))), projects: createMemo(() => contexts().flatMap((item) => item.ctx.projects .list() .map((project): NavProject => ({ server: item.server, id: project.id, name: displayName(project) })), ), ), selected, open, /** A clock that ticks every minute, for Show's last 7 days. */ now: () => inbox.now("ready"), } } export type NavigationSource = ReturnType function navSession( ctx: ServerCtx, server: ServerConnection.Key, session: SessionInfo, state: SessionState, ): NavSession { const project = ctx.projects.forSession(session) const permission = sessionPermissionRequest([], ctx.data.session.permission.list, session.id, (item) => needsUser(ctx.autoApprove.state(item.id), state.autoApprove), ) const form = permission ? undefined : sessionFormRequest([], ctx.data.session.form.list, session.id) const request = permission ?? form const run = workingSince(session) const requestSince = request && (state.requestTimes[`${server}\0${request.id}`] ?? run ?? session.time.updated) return { key: navigationKey(server, session.id), id: session.id, server, title: sessionLabel(session), projectID: session.projectID ?? undefined, directory: session.location.directory, worktree: project && pathKey(project.worktree) !== pathKey(session.location.directory) ? session.location.directory : undefined, branch: ctx.data.location.vcs.info(session.location)?.branch.current ?? undefined, parentID: session.parentID ?? undefined, created: session.time.created, activity: Math.max(session.time.idle ?? session.time.updated, run ?? 0, requestSince ?? 0), archived: session.time.archived !== undefined, status: sessionStatus(ctx, session, state, !!permission, !!form), requestSince, runSince: state.busy.has(session.id) && !request ? run : undefined, muted: state.muted, } } // A request outranks a run, a run outranks unread, and mute silences unread. function sessionStatus( ctx: ServerCtx, session: SessionInfo, state: SessionState, permission: boolean, form: boolean, ): Status { if (permission) return "approval" if (form) return "question" if (state.busy.has(session.id)) return "working" if (state.muted || !ctx.notification.session.unread(session.id, session)) return "idle" return session.outcome === "failed" ? "failed" : "unread" } function draftComposer(tabs: Tabs, tab: DraftTab) { return tabs.state(tab, "prompt", () => createDraftComposerState(tab.draftID)) } function draftText(tabs: Tabs, tab: DraftTab) { return draftComposer(tabs, tab) .current() .flatMap((part) => (part.type === "text" ? [part.content] : [])) .join("") .trim() } // A draft shows while it holds something, as in the Inbox; an empty one only while it is open on screen. function draftHolds(tabs: Tabs, tab: DraftTab, text: string) { const composer = draftComposer(tabs, tab) return !!text || composer.current().some(isAttachment) || composer.context.items().length > 0 } function draftSelected(layout: ReturnType, tab: DraftTab) { const route = layout.route() return route.type === "draft" && route.draftID === tab.draftID }