The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import { |
| 3 | combineTerminalSessionState, |
| 4 | EMPTY_TERMINAL_BUFFER_STATE, |
| 5 | EMPTY_TERMINAL_SESSION_STATE, |
| 6 | selectRunningSubprocessTerminalIds, |
| 7 | type KnownTerminalSession, |
| 8 | type TerminalSessionState, |
| 9 | } from "@t3tools/client-runtime/state/terminal"; |
| 10 | import { |
| 11 | EnvironmentId, |
| 12 | ThreadId, |
| 13 | AuthTerminalReadScope, |
| 14 | AuthTerminalOperateScope, |
| 15 | TerminalAttachInput, |
| 16 | type TerminalSummary, |
| 17 | } from "@t3tools/contracts"; |
| 18 | |
| 19 | import * as Option from "effect/Option"; |
| 20 | import * as Schema from "effect/Schema"; |
| 21 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 22 | |
| 23 | import { formatEnvironmentQueryError } from "./query"; |
| 24 | import { terminalEnvironment } from "./terminal"; |
| 25 | import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; |
| 26 | import { msg } from "gt-react"; |
| 27 | import { m } from "../i18n/messages"; |
| 28 | |
| 29 | const EMPTY_KNOWN_TERMINAL_SESSIONS = Object.freeze<ReadonlyArray<KnownTerminalSession>>([]); |
| 30 | |
| 31 | interface TerminalMetadataIndex { |
| 32 | readonly all: ReadonlyArray<TerminalSummary>; |
| 33 | readonly byThreadId: ReadonlyMap<string, ReadonlyArray<TerminalSummary>>; |
| 34 | readonly views: Map<EnvironmentId, Map<ThreadId | null, ReadonlyArray<KnownTerminalSession>>>; |
| 35 | } |
| 36 | |
| 37 | const metadataIndexes = new WeakMap<ReadonlyArray<TerminalSummary>, TerminalMetadataIndex>(); |
| 38 | const sessionsBySummary = new WeakMap<TerminalSummary, Map<EnvironmentId, KnownTerminalSession>>(); |
| 39 | // Reuse held groups without retaining old members when their anchor survives in newer snapshots. |
| 40 | const groupsByAnchor = new WeakMap< |
| 41 | TerminalSummary, |
| 42 | Map< |
| 43 | EnvironmentId, |
| 44 | { |
| 45 | readonly all?: WeakRef<ReadonlyArray<KnownTerminalSession>>; |
| 46 | readonly thread?: WeakRef<ReadonlyArray<KnownTerminalSession>>; |
| 47 | } |
| 48 | > |
| 49 | >(); |
| 50 | |
| 51 | function knownSession( |
| 52 | summary: TerminalSummary, |
| 53 | environmentId: EnvironmentId, |
| 54 | ): KnownTerminalSession { |
| 55 | let byEnvironment = sessionsBySummary.get(summary); |
| 56 | const previous = byEnvironment?.get(environmentId); |
| 57 | if (previous) return previous; |
| 58 | const session = { |
| 59 | target: { |
| 60 | environmentId, |
| 61 | threadId: ThreadId.make(summary.threadId), |
| 62 | terminalId: summary.terminalId, |
| 63 | }, |
| 64 | state: combineTerminalSessionState(summary, EMPTY_TERMINAL_BUFFER_STATE), |
| 65 | }; |
| 66 | if (!byEnvironment) { |
| 67 | byEnvironment = new Map(); |
| 68 | sessionsBySummary.set(summary, byEnvironment); |
| 69 | } |
| 70 | byEnvironment.set(environmentId, session); |
| 71 | return session; |
| 72 | } |
| 73 | |
| 74 | function terminalMetadataIndex(metadata: ReadonlyArray<TerminalSummary>): TerminalMetadataIndex { |
| 75 | let index = metadataIndexes.get(metadata); |
| 76 | if (!index) { |
| 77 | const compare = new Intl.Collator(undefined, { numeric: true }).compare; |
| 78 | const all = metadata.toSorted((left, right) => compare(left.terminalId, right.terminalId)); |
| 79 | const byThreadId = new Map<string, TerminalSummary[]>(); |
| 80 | for (const summary of all) { |
| 81 | const group = byThreadId.get(summary.threadId); |
| 82 | if (group) group.push(summary); |
| 83 | else byThreadId.set(summary.threadId, [summary]); |
| 84 | } |
| 85 | index = { all, byThreadId, views: new Map() }; |
| 86 | metadataIndexes.set(metadata, index); |
| 87 | } |
| 88 | return index; |
| 89 | } |
| 90 | |
| 91 | export function selectKnownTerminalSessions( |
| 92 | metadata: ReadonlyArray<TerminalSummary> | null, |
| 93 | environmentId: EnvironmentId | null, |
| 94 | threadId: ThreadId | null, |
| 95 | ): ReadonlyArray<KnownTerminalSession> { |
| 96 | if (environmentId === null || metadata === null || metadata.length === 0) { |
| 97 | return EMPTY_KNOWN_TERMINAL_SESSIONS; |
| 98 | } |
| 99 | const index = terminalMetadataIndex(metadata); |
| 100 | let views = index.views.get(environmentId); |
| 101 | const cached = views?.get(threadId); |
| 102 | if (cached) return cached; |
| 103 | const summaries = threadId === null ? index.all : index.byThreadId.get(threadId); |
| 104 | if (!summaries || summaries.length === 0) return EMPTY_KNOWN_TERMINAL_SESSIONS; |
| 105 | |
| 106 | const anchor = summaries[0]!; |
| 107 | const kind = threadId === null ? "all" : "thread"; |
| 108 | let groups = groupsByAnchor.get(anchor); |
| 109 | const previousGroups = groups?.get(environmentId); |
| 110 | const previous = previousGroups?.[kind]?.deref(); |
| 111 | const sessions = |
| 112 | previous?.length === summaries.length && |
| 113 | previous.every((session, index) => session.state.summary === summaries[index]) |
| 114 | ? previous |
| 115 | : summaries.map((summary) => knownSession(summary, environmentId)); |
| 116 | if (!groups) { |
| 117 | groups = new Map(); |
| 118 | groupsByAnchor.set(anchor, groups); |
| 119 | } |
| 120 | if (sessions !== previous) { |
| 121 | groups.set(environmentId, { ...previousGroups, [kind]: new WeakRef(sessions) }); |
| 122 | } |
| 123 | if (!views) { |
| 124 | views = new Map(); |
| 125 | index.views.set(environmentId, views); |
| 126 | } |
| 127 | views.set(threadId, sessions); |
| 128 | return sessions; |
| 129 | } |
| 130 | |
| 131 | const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe( |
| 132 | Atom.withLabel("web-terminal-session:empty"), |
| 133 | ); |
| 134 | |
| 135 | const decodeAttachKey = Schema.decodeUnknownOption( |
| 136 | Schema.fromJsonString(Schema.Tuple([EnvironmentId, TerminalAttachInput])), |
| 137 | ); |
| 138 | |
| 139 | // The family key carries the whole launch so an idle atom leaves nothing behind. |
| 140 | const attachedTerminalSessionFamily = Atom.family((key: string) => { |
| 141 | const decoded = decodeAttachKey(key); |
| 142 | if (Option.isNone(decoded)) { |
| 143 | return Atom.make<TerminalSessionState>({ |
| 144 | ...EMPTY_TERMINAL_SESSION_STATE, |
| 145 | error: m(msg("Invalid terminal launch input")), |
| 146 | status: "error", |
| 147 | }).pipe(Atom.withLabel(`web-terminal-session:${key}`)); |
| 148 | } |
| 149 | const [environmentId, terminal] = decoded.value; |
| 150 | return Atom.make((get): TerminalSessionState => { |
| 151 | const session = get(environmentSession.sessionStateAtom(environmentId)); |
| 152 | const canRead = sessionHasScope(session, AuthTerminalReadScope); |
| 153 | const canOperate = sessionHasScope(session, AuthTerminalOperateScope); |
| 154 | const attach = canOperate |
| 155 | ? get(terminalEnvironment.attach({ environmentId, input: terminal })) |
| 156 | : canRead |
| 157 | ? get( |
| 158 | terminalEnvironment.observe({ |
| 159 | environmentId, |
| 160 | input: { threadId: terminal.threadId, terminalId: terminal.terminalId }, |
| 161 | }), |
| 162 | ) |
| 163 | : null; |
| 164 | const metadata = canRead |
| 165 | ? AsyncResult.getOrElse( |
| 166 | get(terminalEnvironment.metadata({ environmentId, input: null })), |
| 167 | () => null, |
| 168 | ) |
| 169 | : null; |
| 170 | const summary = |
| 171 | (metadata === null |
| 172 | ? null |
| 173 | : terminalMetadataIndex(metadata) |
| 174 | .byThreadId.get(terminal.threadId) |
| 175 | ?.find((candidate) => candidate.terminalId === terminal.terminalId)) ?? null; |
| 176 | const buffer = |
| 177 | attach === null |
| 178 | ? EMPTY_TERMINAL_BUFFER_STATE |
| 179 | : AsyncResult.getOrElse(attach, () => EMPTY_TERMINAL_BUFFER_STATE); |
| 180 | const state = combineTerminalSessionState(summary, buffer); |
| 181 | return attach?._tag === "Failure" |
| 182 | ? { ...state, error: formatEnvironmentQueryError(attach.cause), status: "error" } |
| 183 | : state; |
| 184 | }).pipe(Atom.withLabel(`web-terminal-session:${key}`)); |
| 185 | }); |
| 186 | |
| 187 | /** |
| 188 | * One shown terminal's session: its attach (or read-only observe) buffer |
| 189 | * combined with the metadata summary. Surfaces subscribe to it imperatively so |
| 190 | * output chunks never re-render React. |
| 191 | */ |
| 192 | export function attachedTerminalSessionAtom( |
| 193 | environmentId: EnvironmentId | null, |
| 194 | terminal: TerminalAttachInput | null, |
| 195 | ): Atom.Atom<TerminalSessionState> { |
| 196 | if (environmentId === null || terminal === null) return EMPTY_TERMINAL_SESSION_ATOM; |
| 197 | return attachedTerminalSessionFamily(JSON.stringify([environmentId, terminal])); |
| 198 | } |
| 199 | |
| 200 | const NO_KNOWN_TERMINAL_SESSIONS_ATOM = Atom.make<ReadonlyArray<KnownTerminalSession> | null>(null); |
| 201 | |
| 202 | const decodeKnownSessionsKey = Schema.decodeUnknownOption( |
| 203 | Schema.fromJsonString(Schema.Tuple([EnvironmentId, Schema.NullOr(ThreadId)])), |
| 204 | ); |
| 205 | |
| 206 | // Derived per thread, so a terminal update elsewhere in the environment notifies no one here. |
| 207 | const knownTerminalSessionsFamily = Atom.family((key: string) => { |
| 208 | const [environmentId, threadId] = Option.getOrThrow(decodeKnownSessionsKey(key)); |
| 209 | return Atom.make((get) => { |
| 210 | const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); |
| 211 | return metadata._tag === "Success" |
| 212 | ? selectKnownTerminalSessions(metadata.value, environmentId, threadId) |
| 213 | : null; |
| 214 | }).pipe(Atom.withLabel(`web-known-terminal-sessions:${key}`)); |
| 215 | }); |
| 216 | |
| 217 | export function knownTerminalSessionsAtom( |
| 218 | environmentId: EnvironmentId, |
| 219 | threadId: ThreadId | null, |
| 220 | ): Atom.Atom<ReadonlyArray<KnownTerminalSession> | null> { |
| 221 | return knownTerminalSessionsFamily(JSON.stringify([environmentId, threadId])); |
| 222 | } |
| 223 | |
| 224 | export function useKnownTerminalSessions(input: { |
| 225 | readonly environmentId: EnvironmentId | null; |
| 226 | readonly threadId: ThreadId | null; |
| 227 | }): ReadonlyArray<KnownTerminalSession> | null { |
| 228 | const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope); |
| 229 | return useAtomValue( |
| 230 | input.environmentId === null || !canRead |
| 231 | ? NO_KNOWN_TERMINAL_SESSIONS_ATOM |
| 232 | : knownTerminalSessionsAtom(input.environmentId, input.threadId), |
| 233 | ); |
| 234 | } |
| 235 | |
| 236 | interface TerminalDrawerSessions { |
| 237 | readonly sessions: ReadonlyArray<KnownTerminalSession>; |
| 238 | readonly snapshotId: string | symbol; |
| 239 | } |
| 240 | |
| 241 | const noTerminalDrawerSessions = Atom.make<TerminalDrawerSessions | null>(null); |
| 242 | |
| 243 | const terminalDrawerSessionsFamily = Atom.family((key: string) => { |
| 244 | const [environmentId, threadId] = Option.getOrThrow(decodeKnownSessionsKey(key)); |
| 245 | return Atom.make((get): TerminalDrawerSessions | null => { |
| 246 | const metadata = get(terminalEnvironment.metadataFeed({ environmentId, input: null })); |
| 247 | if (!AsyncResult.isSuccess(metadata)) return null; |
| 248 | const { terminals, snapshotId } = metadata.value; |
| 249 | return { |
| 250 | sessions: selectKnownTerminalSessions(terminals, environmentId, threadId), |
| 251 | snapshotId, |
| 252 | }; |
| 253 | }).pipe( |
| 254 | Atom.withEquality<TerminalDrawerSessions | null>( |
| 255 | (left, right) => left?.sessions === right?.sessions && left?.snapshotId === right?.snapshotId, |
| 256 | ), |
| 257 | Atom.withLabel(`web-terminal-drawer-sessions:${key}`), |
| 258 | ); |
| 259 | }); |
| 260 | |
| 261 | export function useTerminalDrawerSessions(environmentId: EnvironmentId, threadId: ThreadId) { |
| 262 | const canRead = useEnvironmentScope(environmentId, AuthTerminalReadScope); |
| 263 | return useAtomValue( |
| 264 | canRead |
| 265 | ? terminalDrawerSessionsFamily(JSON.stringify([environmentId, threadId])) |
| 266 | : noTerminalDrawerSessions, |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | export function useThreadRunningTerminalIds(input: { |
| 271 | readonly environmentId: EnvironmentId | null; |
| 272 | readonly threadId: ThreadId | null; |
| 273 | }): ReadonlyArray<string> { |
| 274 | const sessions = useKnownTerminalSessions(input); |
| 275 | return selectRunningSubprocessTerminalIds(sessions ?? []); |
| 276 | } |