@orbit-build/cli 3.2.1 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1073 -973
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -306126,6 +306126,7 @@ import { randomBytes as randomBytes5, randomUUID as randomUUID20, timingSafeEqua
306126
306126
  import { z as z86 } from "zod";
306127
306127
 
306128
306128
  // src/runtime/CommandRouter.ts
306129
+ import { createHash as createHash14 } from "node:crypto";
306129
306130
  import picocolors21 from "picocolors";
306130
306131
 
306131
306132
  // src/commands/customCommands.ts
@@ -306729,6 +306730,460 @@ var WEB_UI_CLIENT_DRAFTS_SCRIPT = String.raw` const drafts = (${createConversat
306729
306730
  }
306730
306731
  `;
306731
306732
 
306733
+ // src/runtime/webui/WebUiSecurity.ts
306734
+ import { timingSafeEqual } from "crypto";
306735
+ import { z as z68 } from "zod";
306736
+
306737
+ // src/runtime/webui/WebUiErrors.ts
306738
+ var WebUiRequestError = class extends Error {
306739
+ constructor(code, statusCode, message2) {
306740
+ super(message2);
306741
+ this.code = code;
306742
+ this.statusCode = statusCode;
306743
+ }
306744
+ code;
306745
+ statusCode;
306746
+ name = "WebUiRequestError";
306747
+ };
306748
+
306749
+ // src/runtime/webui/WebUiContracts.ts
306750
+ var WEB_UI_PROJECT_ERROR_CODES = [
306751
+ "absolute_path_required",
306752
+ "filesystem_root",
306753
+ "entrypoint_unavailable",
306754
+ "project_missing",
306755
+ "project_not_directory",
306756
+ "parent_missing",
306757
+ "parent_not_directory",
306758
+ "create_failed",
306759
+ "launch_failed",
306760
+ "startup_failed",
306761
+ "startup_timeout"
306762
+ ];
306763
+
306764
+ // src/runtime/webui/WebUiSecurity.ts
306765
+ var WEB_UI_PROJECT_ERROR_CODE_SET = new Set(
306766
+ WEB_UI_PROJECT_ERROR_CODES
306767
+ );
306768
+ function sanitizeWebEventPayload(type, payload) {
306769
+ if (!isRecord7(payload)) return void 0;
306770
+ switch (type) {
306771
+ case "ui_turn_started":
306772
+ return {
306773
+ turnId: safeWebText(payload.turnId, 200),
306774
+ source: payload.source === "terminal" ? "terminal" : "web",
306775
+ prompt: safeWebText(payload.prompt, 8e3)
306776
+ };
306777
+ case "ui_turn_completed":
306778
+ return {
306779
+ turnId: safeWebText(payload.turnId, 200),
306780
+ source: payload.source === "terminal" ? "terminal" : "web",
306781
+ status: payload.status === "failed" || payload.status === "aborted" ? payload.status : "completed",
306782
+ message: safeWebText(payload.message, 2e3)
306783
+ };
306784
+ case "model_request":
306785
+ return { model: safeWebText(payload.model, 200) };
306786
+ case "model_routing":
306787
+ return {
306788
+ model: safeWebText(payload.model, 200),
306789
+ lane: ["locked", "fallback", "fast", "balanced", "quality"].includes(
306790
+ String(payload.lane)
306791
+ ) ? String(payload.lane) : "balanced",
306792
+ reason: safeWebText(payload.reason, 100),
306793
+ confidence: payload.confidence === "high" ? "high" : "medium"
306794
+ };
306795
+ case "model_response":
306796
+ return {
306797
+ model: safeWebText(payload.model, 200),
306798
+ usage: sanitizeTokenUsage(payload.usage)
306799
+ };
306800
+ case "model_delta":
306801
+ case "thinking_delta":
306802
+ return { text: safeWebText(payload.text, 65536) };
306803
+ case "tool_proposal":
306804
+ return {
306805
+ toolCallId: safeWebText(payload.toolCallId, 200),
306806
+ toolName: safeWebText(payload.toolName, 200),
306807
+ ...summarizeWebToolValue(payload.arguments) ? { detail: summarizeWebToolValue(payload.arguments) } : {},
306808
+ explanation: safeWebText(payload.explanation, 500)
306809
+ };
306810
+ case "tool_result":
306811
+ return {
306812
+ toolCallId: safeWebText(payload.toolCallId, 200),
306813
+ toolName: safeWebText(payload.toolName, 200),
306814
+ display: safeWebText(payload.display, 500),
306815
+ error: safeWebText(payload.error, 1e3)
306816
+ };
306817
+ case "tool_approval":
306818
+ return {
306819
+ toolCallId: safeWebText(payload.toolCallId, 200),
306820
+ approved: payload.approved === true,
306821
+ reason: safeWebText(payload.reason, 500)
306822
+ };
306823
+ case "web_approval_requested":
306824
+ return {
306825
+ approvalId: safeWebText(payload.approvalId, 200),
306826
+ kind: payload.kind === "change" || payload.kind === "action" ? payload.kind : "tool",
306827
+ title: safeWebText(payload.title, 200),
306828
+ toolCallId: safeWebText(payload.toolCallId, 200),
306829
+ agentId: /^agent_[a-z0-9-]+$/.test(String(payload.agentId || "")) ? safeWebText(payload.agentId, 128) : "",
306830
+ agentRole: safeWebText(payload.agentRole, 80)
306831
+ };
306832
+ case "web_approval_resolved":
306833
+ return {
306834
+ ...["tool", "change", "action"].includes(String(payload.kind)) ? { kind: payload.kind } : {},
306835
+ approvalId: safeWebText(payload.approvalId, 200),
306836
+ approved: payload.approved === true
306837
+ };
306838
+ case "cost_update":
306839
+ return {
306840
+ turnCost: safeNumber(payload.turnCost),
306841
+ sessionCost: safeNumber(payload.sessionCost),
306842
+ costKnown: payload.costKnown !== false,
306843
+ totalInputTokens: safeNumber(payload.totalInputTokens),
306844
+ totalCacheReadTokens: safeNumber(payload.totalCacheReadTokens),
306845
+ totalOutputTokens: safeNumber(payload.totalOutputTokens)
306846
+ };
306847
+ case "cache_update":
306848
+ return {
306849
+ hitTokens: safeNumber(payload.hitTokens),
306850
+ missTokens: safeNumber(payload.missTokens),
306851
+ inputTokens: safeNumber(payload.inputTokens),
306852
+ hitRate: safeNumber(payload.hitRate),
306853
+ degraded: payload.degraded === true
306854
+ };
306855
+ case "agent_start": {
306856
+ const taskId = safeWebText(payload.taskId, 200);
306857
+ if (!taskId) return void 0;
306858
+ return {
306859
+ taskId,
306860
+ task: safeWebText(payload.task, 1e3)
306861
+ };
306862
+ }
306863
+ case "agent_spawn": {
306864
+ const childId = safeWebText(payload.childId, 200);
306865
+ if (!childId) return void 0;
306866
+ return {
306867
+ parentId: safeWebText(payload.parentId, 200),
306868
+ childId,
306869
+ role: safeWebText(payload.role, 100),
306870
+ task: safeWebText(payload.task, 1e3)
306871
+ };
306872
+ }
306873
+ case "agent_status": {
306874
+ const taskId = safeWebText(payload.taskId, 200);
306875
+ if (!taskId) return void 0;
306876
+ return {
306877
+ taskId,
306878
+ status: safeWebText(payload.status, 100),
306879
+ detail: safeWebText(payload.detail, 500)
306880
+ };
306881
+ }
306882
+ case "agent_completed": {
306883
+ const taskId = safeWebText(payload.taskId, 200);
306884
+ if (!taskId) return void 0;
306885
+ const status = ["completed", "failed", "aborted"].includes(
306886
+ String(payload.status)
306887
+ ) ? String(payload.status) : void 0;
306888
+ return {
306889
+ taskId,
306890
+ success: payload.success === true,
306891
+ ...status ? { status } : {},
306892
+ error: safeWebText(payload.error, 1e3)
306893
+ };
306894
+ }
306895
+ case "background_task_started":
306896
+ case "background_task_completed": {
306897
+ const taskId = safeWebText(payload.taskId, 200);
306898
+ if (!taskId) return void 0;
306899
+ const status = [
306900
+ "running",
306901
+ "completed",
306902
+ "failed",
306903
+ "killed",
306904
+ "timed_out"
306905
+ ].includes(String(payload.status)) ? String(payload.status) : "failed";
306906
+ return {
306907
+ taskId,
306908
+ sessionId: safeWebText(payload.sessionId, 200),
306909
+ status,
306910
+ durationMs: safeNumber(payload.durationMs),
306911
+ exitCode: typeof payload.exitCode === "number" && Number.isSafeInteger(payload.exitCode) ? payload.exitCode : null,
306912
+ outputTruncated: payload.outputTruncated === true
306913
+ };
306914
+ }
306915
+ case "agent_input_queued":
306916
+ case "agent_input_consumed":
306917
+ case "agent_input_removed":
306918
+ case "agent_input_updated":
306919
+ case "agent_input_moved": {
306920
+ const result = {
306921
+ inputId: safeWebText(payload.inputId, 200),
306922
+ sessionId: safeWebText(payload.sessionId, 200),
306923
+ mode: payload.mode === "steer" ? "steer" : "follow_up",
306924
+ source: ["terminal", "web", "api"].includes(String(payload.source)) ? String(payload.source) : "api",
306925
+ remaining: safeNumber(payload.remaining)
306926
+ };
306927
+ if (type === "agent_input_moved") {
306928
+ result.fromIndex = safeNumber(payload.fromIndex);
306929
+ result.toIndex = safeNumber(payload.toIndex);
306930
+ }
306931
+ return result;
306932
+ }
306933
+ case "agent_input_queue_cleared":
306934
+ return {
306935
+ sessionId: safeWebText(payload.sessionId, 200),
306936
+ removed: safeNumber(payload.removed)
306937
+ };
306938
+ case "loop_start":
306939
+ return { attempt: safeNumber(payload.attempt) };
306940
+ case "verification_started":
306941
+ return { type: safeWebText(payload.type, 100) };
306942
+ case "verification_ended":
306943
+ return { success: payload.success === true };
306944
+ case "hook_started":
306945
+ return {
306946
+ hookId: safeWebText(payload.hookId, 200),
306947
+ event: safeWebText(payload.event, 100),
306948
+ legacy: payload.legacy === true
306949
+ };
306950
+ case "hook_completed":
306951
+ return {
306952
+ hookId: safeWebText(payload.hookId, 200),
306953
+ event: safeWebText(payload.event, 100),
306954
+ success: payload.success === true,
306955
+ durationMs: safeNumber(payload.durationMs),
306956
+ action: ["continue", "warn", "blocked", "ignored"].includes(
306957
+ String(payload.action)
306958
+ ) ? String(payload.action) : "warn",
306959
+ error: safeWebText(payload.error, 1e3)
306960
+ };
306961
+ case "checkpoint_created":
306962
+ return {
306963
+ timestamp: safeWebText(payload.timestamp, 100),
306964
+ message: safeWebText(payload.message, 500)
306965
+ };
306966
+ case "file_change":
306967
+ return {
306968
+ filePath: safeWebText(payload.filePath, 500),
306969
+ type: safeWebText(payload.type, 20),
306970
+ explanation: safeWebText(payload.explanation, 500)
306971
+ };
306972
+ case "file_diff":
306973
+ return {
306974
+ filePath: safeWebText(payload.filePath, 500),
306975
+ diff: safeWebText(payload.diff, 48e3)
306976
+ };
306977
+ case "skill_activated":
306978
+ return {
306979
+ name: safeWebText(payload.name, 100),
306980
+ activation: payload.activation === "explicit" ? "explicit" : "auto",
306981
+ loadedBytes: safeNumber(payload.loadedBytes),
306982
+ truncated: payload.truncated === true,
306983
+ activationReason: [
306984
+ "explicit-marker",
306985
+ "name-match",
306986
+ "metadata-match"
306987
+ ].includes(String(payload.activationReason)) ? payload.activationReason : void 0,
306988
+ matchedTerms: safeNumber(payload.matchedTerms),
306989
+ truncationReason: [
306990
+ "skill-size-limit",
306991
+ "auto-size-limit",
306992
+ "context-budget"
306993
+ ].includes(String(payload.truncationReason)) ? payload.truncationReason : void 0
306994
+ };
306995
+ case "info":
306996
+ case "warning":
306997
+ case "error":
306998
+ return { message: safeWebText(payload.message, 2e3) };
306999
+ default:
307000
+ return void 0;
307001
+ }
307002
+ }
307003
+ function isAuthorizedWebRequest(req, expectedToken) {
307004
+ if (!expectedToken || !isRequestOriginAllowed(req)) return false;
307005
+ const authorization = req.headers.authorization;
307006
+ const cookieToken = readCookie(req, "orbit_web_token");
307007
+ const supplied = authorization?.startsWith("Bearer ") ? authorization.slice(7) : cookieToken;
307008
+ return safeTokenMatch(supplied, expectedToken);
307009
+ }
307010
+ function isBearerAuthorizedWebRequest(req, expectedToken) {
307011
+ if (!expectedToken || !isRequestOriginAllowed(req)) return false;
307012
+ const authorization = req.headers.authorization;
307013
+ const supplied = authorization?.startsWith("Bearer ") ? authorization.slice(7) : "";
307014
+ return safeTokenMatch(supplied, expectedToken);
307015
+ }
307016
+ function isAuthorizedWebEventRequest(req, expectedToken, url2) {
307017
+ if (!expectedToken || !isRequestOriginAllowed(req)) return false;
307018
+ return safeTokenMatch(
307019
+ url2.searchParams.get("access_token") || "",
307020
+ expectedToken
307021
+ );
307022
+ }
307023
+ function safeWebMessage(message2) {
307024
+ return sanitizeExternalErrorMessage(message2, { maxLength: 2e3 });
307025
+ }
307026
+ function safeWebErrorMessage(error) {
307027
+ if (error instanceof z68.ZodError) {
307028
+ const confirmation = "Full Access requires explicit confirmation.";
307029
+ return error.issues.some(
307030
+ (issue) => issue.code === "custom" && issue.message === confirmation
307031
+ ) ? confirmation : "Invalid request parameters.";
307032
+ }
307033
+ if (error instanceof WebUiRequestError) {
307034
+ switch (error.code) {
307035
+ case "invalid_json":
307036
+ return "Request body must contain valid JSON.";
307037
+ case "request_body_too_large":
307038
+ return "Request body too large.";
307039
+ case "attachment_too_large":
307040
+ return "Attachment is too large.";
307041
+ }
307042
+ }
307043
+ return "Request failed. Check the request, project permissions, and provider settings before retrying.";
307044
+ }
307045
+ function summarizeWebToolValue(value, options = {}) {
307046
+ let candidate = value;
307047
+ if (typeof candidate === "string") {
307048
+ const rawText = candidate;
307049
+ try {
307050
+ candidate = JSON.parse(rawText);
307051
+ } catch {
307052
+ return options.allowPlainText ? safeWebToolText(rawText, 700) : "";
307053
+ }
307054
+ }
307055
+ if (!isRecord7(candidate)) return "";
307056
+ const safeFields = [
307057
+ "path",
307058
+ "filePath",
307059
+ "file",
307060
+ "cwd",
307061
+ "query",
307062
+ "pattern",
307063
+ "symbol",
307064
+ "url",
307065
+ "language",
307066
+ "description",
307067
+ "command"
307068
+ ];
307069
+ const entries = [];
307070
+ for (const field of safeFields) {
307071
+ const fieldValue = candidate[field];
307072
+ if (typeof fieldValue !== "string" && typeof fieldValue !== "number" && typeof fieldValue !== "boolean") {
307073
+ continue;
307074
+ }
307075
+ const text2 = safeWebToolText(String(fieldValue), 220);
307076
+ if (text2) entries.push(`${field}: ${text2}`);
307077
+ if (entries.length >= 3) break;
307078
+ }
307079
+ return entries.join("\n");
307080
+ }
307081
+ function sanitizeActionResult(result) {
307082
+ return result.message ? { ok: result.ok, message: safeWebMessage(result.message) } : { ok: result.ok };
307083
+ }
307084
+ function sanitizeProjectActionResult(result) {
307085
+ const url2 = result.ok ? sanitizeLocalWebUiUrl(result.url) : void 0;
307086
+ const errorCode = !result.ok && WEB_UI_PROJECT_ERROR_CODE_SET.has(result.errorCode) ? result.errorCode : void 0;
307087
+ return {
307088
+ ok: result.ok,
307089
+ ...result.message ? { message: safeWebMessage(result.message) } : {},
307090
+ ...errorCode ? { errorCode } : {},
307091
+ ...result.ok && result.path ? { path: safeWebText(result.path, 4096) } : {},
307092
+ ...url2 ? { url: url2 } : {},
307093
+ ...result.ok && result.cancelled ? { cancelled: true } : {}
307094
+ };
307095
+ }
307096
+ function sanitizeLocalWebUiUrl(value) {
307097
+ if (typeof value !== "string") return void 0;
307098
+ try {
307099
+ const url2 = new URL(value);
307100
+ const fragment = new URLSearchParams(url2.hash.slice(1));
307101
+ const tokens = fragment.getAll("token");
307102
+ const token = tokens.length === 1 ? tokens[0] : void 0;
307103
+ if (url2.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(url2.hostname) || !/^\d{1,5}$/.test(url2.port) || Number(url2.port) < 1 || Number(url2.port) > 65535 || url2.username || url2.password || url2.pathname !== "/" || url2.search || Array.from(fragment.keys()).length !== 1 || !token || !/^[A-Za-z0-9_-]{32,128}$/.test(token)) {
307104
+ return void 0;
307105
+ }
307106
+ return url2.href;
307107
+ } catch {
307108
+ return void 0;
307109
+ }
307110
+ }
307111
+ function sanitizeBaseUrl(value) {
307112
+ if (typeof value !== "string" || !value) return "";
307113
+ try {
307114
+ const url2 = new URL(value);
307115
+ url2.username = "";
307116
+ url2.password = "";
307117
+ url2.search = "";
307118
+ url2.hash = "";
307119
+ return url2.toString().replace(/\/$/, "");
307120
+ } catch {
307121
+ return safeWebText(value, 500);
307122
+ }
307123
+ }
307124
+ function webRequestErrorStatus(error) {
307125
+ if (error instanceof z68.ZodError) return 400;
307126
+ if (error instanceof WebUiRequestError) return error.statusCode;
307127
+ return 500;
307128
+ }
307129
+ function isNodeError3(error) {
307130
+ return error instanceof Error;
307131
+ }
307132
+ function isRequestOriginAllowed(req) {
307133
+ const origin = req.headers.origin;
307134
+ return !origin || origin === `http://${req.headers.host}`;
307135
+ }
307136
+ function safeTokenMatch(supplied, expected) {
307137
+ const suppliedBuffer = Buffer.from(supplied);
307138
+ const expectedBuffer = Buffer.from(expected);
307139
+ return suppliedBuffer.length === expectedBuffer.length && timingSafeEqual(suppliedBuffer, expectedBuffer);
307140
+ }
307141
+ function readCookie(req, name) {
307142
+ const rawCookie = req.headers.cookie;
307143
+ if (!rawCookie) return "";
307144
+ for (const item of rawCookie.split(";")) {
307145
+ const separator = item.indexOf("=");
307146
+ if (separator < 0 || item.slice(0, separator).trim() !== name) continue;
307147
+ try {
307148
+ return decodeURIComponent(item.slice(separator + 1).trim());
307149
+ } catch {
307150
+ return "";
307151
+ }
307152
+ }
307153
+ return "";
307154
+ }
307155
+ function sanitizeTokenUsage(value) {
307156
+ if (!isRecord7(value)) return void 0;
307157
+ return {
307158
+ inputTokens: safeNumber(value.inputTokens),
307159
+ outputTokens: safeNumber(value.outputTokens),
307160
+ cacheReadTokens: safeNumber(value.cacheReadTokens),
307161
+ cacheWriteTokens: safeNumber(value.cacheWriteTokens)
307162
+ };
307163
+ }
307164
+ function safeNumber(value) {
307165
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
307166
+ }
307167
+ function safeWebText(value, maxLength) {
307168
+ if (typeof value !== "string") return "";
307169
+ return redactSecrets(stripAnsi2(value)).slice(0, maxLength);
307170
+ }
307171
+ function safeWebToolText(value, maxLength) {
307172
+ return safeWebText(value, maxLength).replace(
307173
+ /(--(?:api-?key|token|password|secret)(?:=|\s+))(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
307174
+ "$1***REDACTED***"
307175
+ ).replace(
307176
+ /((?:api[_-]?key|token|password|secret)\s*[=:]\s*)[^\s,;]+/gi,
307177
+ "$1***REDACTED***"
307178
+ ).trim();
307179
+ }
307180
+ function stripAnsi2(value) {
307181
+ return value.replace(/\u001b\[[0-9;]*m/g, "");
307182
+ }
307183
+ function isRecord7(value) {
307184
+ return typeof value === "object" && value !== null;
307185
+ }
307186
+
306732
307187
  // src/runtime/webui/WebUiClientBindings.ts
306733
307188
  var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListener('submit', (event) => {
306734
307189
  event.preventDefault();
@@ -307135,9 +307590,9 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307135
307590
  closeContextPicker({ skipRestore: true });
307136
307591
  void updateSession({ action: 'new' });
307137
307592
  });
307138
- const closeProjectDialog = (restoreFocus = true, force = false) => {
307593
+ const closeProjectDialog = (restoreFocus = true) => {
307139
307594
  if (elements.projectDialog.hidden) return;
307140
- if (state.projectLaunchPending && !force) return;
307595
+ if (state.projectLaunchPending || state.projectPickerPending) return;
307141
307596
  elements.projectDialog.hidden = true;
307142
307597
  elements.projectDialog.setAttribute('aria-hidden', 'true');
307143
307598
  syncApplicationModalState();
@@ -307145,7 +307600,7 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307145
307600
  state.projectDialogReturnFocus = null;
307146
307601
  };
307147
307602
  const openProjectDialog = () => {
307148
- if (state.busy || state.projectLaunchPending) return;
307603
+ if (!state.ready || state.busy || state.sessionChanging || state.projectLaunchPending || state.projectPickerPending) return;
307149
307604
  state.projectDialogReturnFocus = document.activeElement;
307150
307605
  elements.projectDialog.hidden = false;
307151
307606
  elements.projectDialog.setAttribute('aria-hidden', 'false');
@@ -307153,150 +307608,54 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307153
307608
  elements.projectPathInput.focus();
307154
307609
  elements.projectPathInput.select();
307155
307610
  };
307156
- const showReservedProjectStatus = (projectTab, label, failed = false) => {
307157
- if (!projectTab || projectTab.closed) return;
307158
- try {
307159
- const projectDocument = projectTab.document;
307160
- const sourceStyle = getComputedStyle(document.documentElement);
307161
- const themeValue = (name, fallback) =>
307162
- sourceStyle.getPropertyValue(name).trim() || fallback;
307163
- projectDocument.title = 'Orbit · ' + label;
307164
- projectDocument.documentElement.lang = document.documentElement.lang;
307165
- projectDocument.documentElement.style.colorScheme = sourceStyle.colorScheme;
307166
- projectDocument.body.replaceChildren();
307167
- Object.assign(projectDocument.body.style, {
307168
- minHeight: '100vh',
307169
- margin: '0',
307170
- display: 'grid',
307171
- placeItems: 'center',
307172
- color: themeValue('--ink', '#2c3834'),
307173
- background: themeValue('--canvas', '#f4f6f3'),
307174
- fontFamily: themeValue('--font-sans', 'Inter, ui-sans-serif, system-ui, sans-serif'),
307175
- });
307176
- const status = projectDocument.createElement('main');
307177
- status.setAttribute('role', 'status');
307178
- status.dataset.orbitProjectHandoff = failed ? 'failed' : 'pending';
307179
- Object.assign(status.style, {
307180
- display: 'grid',
307181
- gap: '10px',
307182
- justifyItems: 'center',
307183
- minWidth: 'min(360px, calc(100vw - 40px))',
307184
- padding: '28px',
307185
- textAlign: 'center',
307186
- background: themeValue('--surface-raised', '#ffffff'),
307187
- border: '1px solid ' + themeValue('--border', 'rgba(28, 49, 42, 0.105)'),
307188
- borderRadius: themeValue('--radius-lg', '18px'),
307189
- boxShadow: themeValue('--shadow-md', '0 18px 48px rgba(10, 24, 20, 0.14)'),
307190
- });
307191
- const brand = projectDocument.createElement('strong');
307192
- brand.textContent = 'Orbit';
307193
- Object.assign(brand.style, {
307194
- color: themeValue('--accent-strong', '#276a5f'),
307195
- fontSize: '24px',
307196
- letterSpacing: '-0.02em',
307197
- });
307198
- const message = projectDocument.createElement('span');
307199
- message.textContent = label;
307200
- Object.assign(message.style, {
307201
- maxWidth: '42ch',
307202
- color: failed
307203
- ? themeValue('--danger', '#bb5755')
307204
- : themeValue('--muted', '#596761'),
307205
- fontSize: '14px',
307206
- lineHeight: '1.55',
307207
- });
307208
- status.append(brand, message);
307209
- projectDocument.body.append(status);
307210
- } catch {
307211
- // A browser may isolate the placeholder before Orbit can decorate it.
307212
- }
307213
- };
307214
- const reserveProjectTab = (label) => {
307215
- const projectTab = window.open('about:blank', '_blank');
307216
- showReservedProjectStatus(projectTab, label);
307217
- return projectTab;
307218
- };
307219
- const closeReservedProjectTab = (projectTab, message = copy.projectSwitchFailed) => {
307220
- if (!projectTab || projectTab.closed) return;
307221
- showReservedProjectStatus(projectTab, message, true);
307222
- try {
307223
- projectTab.close();
307224
- } catch {
307225
- // The visible failure state remains if the browser refuses window.close().
307226
- }
307227
- };
307228
- const switchToProject = (result, projectTab) => {
307229
- if (!result || typeof result.url !== 'string') {
307230
- closeReservedProjectTab(projectTab);
307231
- throw new Error(copy.projectSwitchFailed);
307232
- }
307233
- const projectUrl = new URL(result.url);
307234
- const token = new URLSearchParams(projectUrl.hash.slice(1)).get('token');
307235
- if (
307236
- projectUrl.protocol !== 'http:' ||
307237
- !['127.0.0.1', '[::1]', 'localhost'].includes(projectUrl.hostname) ||
307238
- projectUrl.username ||
307239
- projectUrl.password ||
307240
- !token ||
307241
- !/^[A-Za-z0-9_-]{32,128}$/.test(token)
307242
- ) {
307243
- closeReservedProjectTab(projectTab);
307244
- throw new Error(copy.projectSwitchFailed);
307245
- }
307246
- if (projectTab && !projectTab.closed) {
307247
- projectTab.opener = null;
307248
- projectTab.location.replace(projectUrl.href);
307249
- projectTab.focus();
307250
- showToast(copy.projectOpened, 'success');
307251
- return;
307252
- }
307253
- window.location.assign(projectUrl.href);
307254
- };
307255
- const launchProject = async (selectedPath) => {
307256
- const path = String(selectedPath || elements.projectPathInput.value).trim();
307611
+ async function launchProject(path, trigger) {
307612
+ if (!state.ready || state.busy || state.sessionChanging || state.projectLaunchPending || state.projectPickerPending) return;
307613
+ const fromDialog = !trigger;
307614
+ path = String(fromDialog ? elements.projectPathInput.value : path).trim();
307257
307615
  if (!path) {
307258
307616
  showToast(copy.projectPathRequired, 'error');
307259
307617
  elements.projectPathInput.focus();
307260
307618
  return;
307261
307619
  }
307262
- if (elements.projectDialogCreate.disabled) return;
307263
- const pendingButton = elements.projectDialogCreate;
307264
- const pendingLabel = copy.projectCreating;
307265
- const projectTab = reserveProjectTab(pendingLabel);
307266
- const originalLabel = pendingButton.textContent;
307620
+ if (hasAttachmentDrafts() && !window.confirm(copy.leaveProjectImages)) return;
307621
+ drafts.save(elements.prompt.value);
307622
+ const button = trigger || elements.projectDialogCreate;
307623
+ const originalLabel = elements.projectDialogCreate.textContent;
307267
307624
  state.projectLaunchPending = true;
307268
- elements.projectDialog.setAttribute('aria-busy', 'true');
307269
- elements.projectDialogBackdrop.disabled = true;
307270
- elements.projectDialogCancel.disabled = true;
307271
- elements.projectDialogBrowse.disabled = true;
307272
- elements.projectDialogCreate.disabled = true;
307273
- pendingButton.textContent = pendingLabel;
307274
- pendingButton.setAttribute('aria-busy', 'true');
307625
+ updateSendButtonState();
307626
+ button.setAttribute('aria-busy', 'true');
307627
+ if (fromDialog) {
307628
+ elements.projectDialog.setAttribute('aria-busy', 'true');
307629
+ elements.projectDialogBackdrop.disabled = elements.projectDialogCancel.disabled = true;
307630
+ elements.projectDialogBrowse.disabled = elements.projectDialogCreate.disabled = true;
307631
+ elements.projectDialogCreate.textContent = copy.projectCreating;
307632
+ } else {
307633
+ button.classList.add('is-switching');
307634
+ showToast(copy.projectOpening);
307635
+ }
307275
307636
  try {
307276
307637
  const result = await api('/api/project', {
307277
307638
  method: 'POST',
307278
307639
  headers: { 'Content-Type': 'application/json' },
307279
- body: JSON.stringify({ action: 'create', path }),
307640
+ body: JSON.stringify({ action: fromDialog ? 'create' : 'open', path }),
307280
307641
  });
307281
- await loadStatus().catch(() => {});
307282
- closeProjectDialog(false, true);
307283
- elements.projectPathInput.value = '';
307284
- switchToProject(result, projectTab);
307642
+ const url = (${sanitizeLocalWebUiUrl.toString()})(result.url);
307643
+ if (!url) throw new Error(copy.projectSwitchFailed);
307644
+ window.location.replace(url);
307285
307645
  } catch (error) {
307286
- const message = projectErrorMessage(error);
307287
- closeReservedProjectTab(projectTab, message);
307288
- showToast(message, 'error');
307289
- } finally {
307290
307646
  state.projectLaunchPending = false;
307291
307647
  elements.projectDialog.removeAttribute('aria-busy');
307292
- elements.projectDialogBackdrop.disabled = false;
307293
- elements.projectDialogCancel.disabled = false;
307294
- pendingButton.textContent = originalLabel;
307295
- pendingButton.removeAttribute('aria-busy');
307296
- elements.projectDialogBrowse.disabled = false;
307297
- elements.projectDialogCreate.disabled = false;
307648
+ elements.projectDialogBackdrop.disabled = elements.projectDialogCancel.disabled = false;
307649
+ elements.projectDialogBrowse.disabled = elements.projectDialogCreate.disabled = false;
307650
+ elements.projectDialogCreate.textContent = originalLabel;
307651
+ button.classList.remove('is-switching');
307652
+ button.removeAttribute('aria-busy');
307653
+ updateSendButtonState();
307654
+ showToast(projectErrorMessage(error), 'error');
307655
+ if (fromDialog) elements.projectPathInput.focus();
307656
+ else button.focus();
307298
307657
  }
307299
- };
307658
+ }
307300
307659
  const pickProjectFolder = async () => {
307301
307660
  if (state.busy || state.projectPickerPending) return;
307302
307661
  state.projectPickerPending = true;
@@ -307321,7 +307680,7 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307321
307680
  elements.projectDialogBrowse.disabled = false;
307322
307681
  elements.projectDialogBrowse.removeAttribute('aria-busy');
307323
307682
  elements.projectDialogCreate.disabled = false;
307324
- elements.newProjectButton.disabled = false;
307683
+ updateSendButtonState();
307325
307684
  }
307326
307685
  };
307327
307686
  elements.newProjectButton.addEventListener('click', openProjectDialog);
@@ -307331,7 +307690,8 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307331
307690
  elements.projectDialogCreate.addEventListener('click', () => void launchProject());
307332
307691
  elements.projectList.addEventListener('click', (event) => {
307333
307692
  const remove = event.target.closest('[data-project-action="remove"]');
307334
- if (remove && !state.busy) {
307693
+ if (!state.ready || state.busy || state.projectLaunchPending || state.sessionChanging) return;
307694
+ if (remove) {
307335
307695
  if (remove.dataset.confirmRemove !== 'true') {
307336
307696
  remove.dataset.confirmRemove = 'true';
307337
307697
  remove.title = copy.confirmRemoveProject;
@@ -307343,7 +307703,8 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307343
307703
  }, 3000);
307344
307704
  return;
307345
307705
  }
307346
- state.busy = true;
307706
+ state.projectLaunchPending = true;
307707
+ updateSendButtonState();
307347
307708
  api('/api/project', {
307348
307709
  method: 'POST',
307349
307710
  headers: { 'Content-Type': 'application/json' },
@@ -307352,30 +307713,11 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307352
307713
  showToast(copy.projectRemoved, 'success');
307353
307714
  await loadStatus();
307354
307715
  }).catch((error) => showToast(error.message || String(error), 'error'))
307355
- .finally(() => { state.busy = false; });
307716
+ .finally(() => { state.projectLaunchPending = false; updateSendButtonState(); });
307356
307717
  return;
307357
307718
  }
307358
307719
  const button = event.target.closest('[data-project-path]');
307359
- if (!button || button.disabled || state.busy) return;
307360
- state.busy = true;
307361
- const projectTab = reserveProjectTab(copy.projectOpening);
307362
- button.classList.add('is-switching');
307363
- button.setAttribute('aria-busy', 'true');
307364
- showToast(copy.projectOpening);
307365
- api('/api/project', {
307366
- method: 'POST',
307367
- headers: { 'Content-Type': 'application/json' },
307368
- body: JSON.stringify({ action: 'open', path: button.dataset.projectPath || '' }),
307369
- }).then((result) => switchToProject(result, projectTab))
307370
- .catch((error) => {
307371
- closeReservedProjectTab(projectTab, error.message || String(error));
307372
- showToast(error.message || String(error), 'error');
307373
- })
307374
- .finally(() => {
307375
- state.busy = false;
307376
- button.classList.remove('is-switching');
307377
- button.removeAttribute('aria-busy');
307378
- });
307720
+ if (button) void launchProject(button.dataset.projectPath, button);
307379
307721
  });
307380
307722
  onShortcutKeydown(elements.projectPathInput, (event) => {
307381
307723
  if (event.key === 'Enter') {
@@ -307433,7 +307775,11 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307433
307775
  return;
307434
307776
  }
307435
307777
  const button = event.target.closest('.recent-session[data-session-id]');
307436
- if (!button || state.busy || button.closest('.is-archived') || button.closest('.is-active')) return;
307778
+ if (!button || state.busy || button.closest('.is-archived')) return;
307779
+ if (button.closest('.is-active')) {
307780
+ focusMessageComposer();
307781
+ return;
307782
+ }
307437
307783
  void updateSession({ action: 'resume', sessionId: button.dataset.sessionId });
307438
307784
  };
307439
307785
  elements.recentSessions.addEventListener('click', handleSessionListClick);
@@ -307555,7 +307901,9 @@ var WEB_UI_CLIENT_BINDINGS_SCRIPT = String.raw` elements.composer.addEventListe
307555
307901
  first.focus();
307556
307902
  }
307557
307903
  });
307558
- elements.commandsButton.addEventListener('click', openCommandPalette);
307904
+ byId('findConversation').addEventListener('click', (event) => openCommandPalette('navigation', event.currentTarget));
307905
+ elements.commandsButton.addEventListener('click', (event) => openCommandPalette(null, event.currentTarget));
307906
+ byId('commandPaletteClose').addEventListener('click', closeCommandPalette);
307559
307907
  elements.commandPaletteBackdrop.addEventListener('click', closeCommandPalette);
307560
307908
  elements.commandSearch.addEventListener('input', () => {
307561
307909
  paletteSelection = 0;
@@ -308036,6 +308384,7 @@ function parseWebUiStreamEvent(raw) {
308036
308384
  if (typeof event.kind !== "string" || ![
308037
308385
  "system",
308038
308386
  "heartbeat",
308387
+ "sessions_changed",
308039
308388
  "replay_gap",
308040
308389
  "turn_started",
308041
308390
  "turn_done",
@@ -308061,7 +308410,13 @@ function parseWebUiStreamEvent(raw) {
308061
308410
  }
308062
308411
  return event;
308063
308412
  }
308064
- var WEB_UI_CLIENT_STREAM_PARSER_SCRIPT = ` const parseWebUiStreamEvent = (${parseWebUiStreamEvent.toString()});
308413
+ function requiresSessionRefresh(event, activeId) {
308414
+ if (event.kind === "sessions_changed") return true;
308415
+ if (!event.sessionId || event.sessionId === activeId) return false;
308416
+ return event.kind === "heartbeat" || Boolean(activeId && (event.kind === "turn_started" || event.kind === "turn_done"));
308417
+ }
308418
+ var WEB_UI_CLIENT_STREAM_PARSER_SCRIPT = ` const requiresSessionRefresh = (${requiresSessionRefresh.toString()});
308419
+ const parseWebUiStreamEvent = (${parseWebUiStreamEvent.toString()});
308065
308420
 
308066
308421
  `;
308067
308422
 
@@ -308803,6 +309158,9 @@ function createAttachmentController(runtime) {
308803
309158
  }
308804
309159
  group.length = 0;
308805
309160
  }
309161
+ function syncAttachmentButton() {
309162
+ elements.attachmentButton.disabled = !state.ready || state.sessionChanging || state.projectLaunchPending || state.attachments.length >= 4 || Boolean(uploads.get(state.attachments));
309163
+ }
308806
309164
  function renderAttachments() {
308807
309165
  elements.attachmentList.replaceChildren();
308808
309166
  elements.attachmentShelf.hidden = state.attachments.length === 0;
@@ -308812,7 +309170,6 @@ function createAttachmentController(runtime) {
308812
309170
  "aria-label",
308813
309171
  String(state.attachments.length)
308814
309172
  );
308815
- elements.attachmentButton.disabled = state.attachments.length >= 4;
308816
309173
  for (const attachment of state.attachments) {
308817
309174
  const card = document.createElement("div");
308818
309175
  card.className = "attachment-card";
@@ -308849,7 +309206,7 @@ function createAttachmentController(runtime) {
308849
309206
  return;
308850
309207
  }
308851
309208
  uploads.set(group, (uploads.get(group) ?? 0) + 1);
308852
- if (group === state.attachments) elements.attachmentButton.disabled = true;
309209
+ syncAttachmentButton();
308853
309210
  try {
308854
309211
  const result = await api(
308855
309212
  `/api/attachment?name=${encodeURIComponent(file.name || "image")}`,
@@ -308882,11 +309239,12 @@ function createAttachmentController(runtime) {
308882
309239
  );
308883
309240
  } finally {
308884
309241
  uploads.set(group, (uploads.get(group) ?? 1) - 1);
308885
- elements.attachmentButton.disabled = state.attachments.length + (uploads.get(state.attachments) ?? 0) >= 4;
309242
+ syncAttachmentButton();
308886
309243
  elements.attachmentInput.value = "";
308887
309244
  }
308888
309245
  }
308889
309246
  async function addAttachmentFiles(files) {
309247
+ if (!state.ready || state.projectLaunchPending || state.sessionChanging) return;
308890
309248
  const group = state.attachments;
308891
309249
  for (const file of Array.from(files || []).slice(
308892
309250
  0,
@@ -308935,6 +309293,10 @@ function createAttachmentController(runtime) {
308935
309293
  renderAttachments();
308936
309294
  }
308937
309295
  return {
309296
+ hasAttachmentDrafts: () => [state.attachments, ...inactive.values()].some(
309297
+ (group) => group.length > 0 || Boolean(uploads.get(group))
309298
+ ),
309299
+ syncAttachmentButton,
308938
309300
  switchAttachmentDraft,
308939
309301
  discardAttachmentDraft,
308940
309302
  renderAttachments,
@@ -308944,7 +309306,7 @@ function createAttachmentController(runtime) {
308944
309306
  consumeAttachments
308945
309307
  };
308946
309308
  }
308947
- var WEB_UI_CLIENT_ATTACHMENTS_SCRIPT = ` const { switchAttachmentDraft, discardAttachmentDraft, renderAttachments, uploadAttachment, addAttachmentFiles, removeAttachment, consumeAttachments } = (${createAttachmentController.toString()})({ copy, elements, state, api, showToast, updateSendButtonState });
309309
+ var WEB_UI_CLIENT_ATTACHMENTS_SCRIPT = ` const { hasAttachmentDrafts, syncAttachmentButton, switchAttachmentDraft, discardAttachmentDraft, renderAttachments, uploadAttachment, addAttachmentFiles, removeAttachment, consumeAttachments } = (${createAttachmentController.toString()})({ copy, elements, state, api, showToast, updateSendButtonState });
308948
309310
 
308949
309311
  `;
308950
309312
 
@@ -309411,9 +309773,9 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
309411
309773
  sessionArchived: '对话已归档',
309412
309774
  sessionRestored: '对话已恢复',
309413
309775
  sessionDeleted: '对话已删除',
309414
- projectOpening: '正在新标签页打开项目…',
309415
- projectCreating: '正在准备项目并打开新标签页…',
309416
- projectOpened: '项目已在新标签页中打开',
309776
+ projectOpening: '正在切换项目…',
309777
+ projectCreating: '正在打开项目…',
309778
+ leaveProjectImages: '此项目有未发送的图片。切换后需要重新添加。仍要切换吗?',
309417
309779
  projectSwitchFailed: '项目已启动,但无法安全打开页面',
309418
309780
  projectRemoved: '项目已从 Orbit 移除,磁盘文件未删除',
309419
309781
  removeProject: '从 Orbit 移除项目',
@@ -309574,9 +309936,9 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
309574
309936
  sessionArchived: 'Chat archived',
309575
309937
  sessionRestored: 'Chat restored',
309576
309938
  sessionDeleted: 'Chat deleted',
309577
- projectOpening: 'Opening project in a new tab…',
309578
- projectCreating: 'Preparing project in a new tab…',
309579
- projectOpened: 'Project opened in a new tab',
309939
+ projectOpening: 'Switching project…',
309940
+ projectCreating: 'Opening project…',
309941
+ leaveProjectImages: 'This project has unsent images. You will need to attach them again after switching. Switch projects?',
309580
309942
  projectSwitchFailed: 'The project started, but Orbit could not open it safely',
309581
309943
  projectRemoved: 'Project removed from Orbit; files were not deleted',
309582
309944
  removeProject: 'Remove project from Orbit',
@@ -309693,9 +310055,9 @@ var WEB_UI_CLIENT_FOUNDATION_SCRIPT = String.raw` const byId = (id) => document
309693
310055
  sessionArchived: '對話已封存',
309694
310056
  sessionRestored: '對話已復原',
309695
310057
  sessionDeleted: '對話已刪除',
309696
- projectOpening: '正在新分頁開啟專案…',
309697
- projectCreating: '正在準備專案並開啟新分頁…',
309698
- projectOpened: '專案已在新分頁中開啟',
310058
+ projectOpening: '正在切換專案…',
310059
+ projectCreating: '正在開啟專案…',
310060
+ leaveProjectImages: '此專案有未傳送的圖片。切換後需要重新加入,仍要切換嗎?',
309699
310061
  projectSwitchFailed: '專案已啟動,但無法安全開啟頁面',
309700
310062
  projectRemoved: '專案已從 Orbit 移除,磁碟檔案未刪除',
309701
310063
  removeProject: '從 Orbit 移除專案',
@@ -310300,6 +310662,7 @@ ${WEB_UI_CLIENT_TRANSPORT_SCRIPT}
310300
310662
  }
310301
310663
 
310302
310664
  function updateMessageNavigation() {
310665
+ elements.jumpEarlier.disabled = state.loadingEarlierMessages;
310303
310666
  const overflow = elements.messageScroll.scrollHeight > elements.messageScroll.clientHeight + 8;
310304
310667
  const awayFromTop = elements.messageScroll.scrollTop > 72;
310305
310668
  const hasEarlierPage = state.earliestMessagePosition > 0;
@@ -310361,8 +310724,23 @@ ${WEB_UI_CLIENT_TRANSPORT_SCRIPT}
310361
310724
  else elements.applyModel.removeAttribute('aria-label');
310362
310725
  }
310363
310726
 
310727
+ let lastNavigationDisabled;
310728
+ function syncNavigationControls(refreshRows = false) {
310729
+ const disabled = !state.ready || state.sessionChanging || state.projectLaunchPending || state.busy;
310730
+ elements.newProjectButton.disabled = disabled || state.projectPickerPending;
310731
+ if (lastNavigationDisabled === disabled && !refreshRows) return;
310732
+ lastNavigationDisabled = disabled;
310733
+ elements.newTaskButton.disabled = disabled;
310734
+ for (const list of [elements.recentSessions, elements.archivedSessions, elements.projectList]) {
310735
+ list.querySelectorAll(disabled ? 'button:enabled' : 'button:disabled').forEach(button => { button.disabled = disabled; });
310736
+ }
310737
+ }
310738
+
310364
310739
  function updateSendButtonState() {
310365
- const ready = state.ready && !state.sessionChanging;
310740
+ const ready = state.ready && !state.sessionChanging && !state.projectLaunchPending;
310741
+ syncNavigationControls();
310742
+ elements.prompt.readOnly = state.sessionChanging || state.projectLaunchPending;
310743
+ syncAttachmentButton();
310366
310744
  elements.prompt.setAttribute('aria-busy', String(!ready));
310367
310745
  const hasPrompt = Boolean(elements.prompt.value.trim());
310368
310746
  elements.contextPickerButton.disabled = state.busy || !ready;
@@ -310415,6 +310793,24 @@ function createHistoryController(runtime) {
310415
310793
  updateMessageNavigation,
310416
310794
  scrollToBottom
310417
310795
  } = runtime;
310796
+ let generation = 0;
310797
+ let latest = 0;
310798
+ function resetConversationHistory() {
310799
+ generation++;
310800
+ state.messageCache.clear();
310801
+ state.messageSessionId = "";
310802
+ state.messageTotal = state.earliestMessagePosition = 0;
310803
+ state.streaming = null;
310804
+ state.streamingTurnId = null;
310805
+ state.streamingTools.clear();
310806
+ state.loadingEarlierMessages = false;
310807
+ rebuildMessageTimeline();
310808
+ updateMessageNavigation();
310809
+ }
310810
+ function belongsToChat(data) {
310811
+ const current = state.status?.session?.activeId;
310812
+ return !current || data.page?.sessionId === current;
310813
+ }
310418
310814
  function captureMessageAnchor() {
310419
310815
  const scrollBounds = elements.messageScroll.getBoundingClientRect();
310420
310816
  const node = Array.from(elements.messages.children).find(
@@ -310492,6 +310888,8 @@ function createHistoryController(runtime) {
310492
310888
  state.earliestMessagePosition = positions.length ? Math.min(...positions) : Math.max(0, Number(page.start) || 0);
310493
310889
  }
310494
310890
  async function renderMessages(options) {
310891
+ const request = ++latest;
310892
+ const current = generation;
310495
310893
  const forceBottom = Boolean(options?.forceBottom);
310496
310894
  const resetHistory = Boolean(options?.resetHistory);
310497
310895
  const preservePosition = !forceBottom && !state.stickToBottom;
@@ -310499,6 +310897,7 @@ function createHistoryController(runtime) {
310499
310897
  const data = await api(
310500
310898
  "/api/messages?limit=60"
310501
310899
  );
310900
+ if (current !== generation || request !== latest || !belongsToChat(data)) return;
310502
310901
  mergeMessagePage(data, resetHistory);
310503
310902
  rebuildMessageTimeline();
310504
310903
  state.streaming = null;
@@ -310515,6 +310914,7 @@ function createHistoryController(runtime) {
310515
310914
  if (state.loadingEarlierMessages || state.earliestMessagePosition <= 0) {
310516
310915
  return false;
310517
310916
  }
310917
+ const current = generation;
310518
310918
  state.loadingEarlierMessages = true;
310519
310919
  elements.jumpEarlier.disabled = true;
310520
310920
  const anchor = captureMessageAnchor();
@@ -310522,6 +310922,7 @@ function createHistoryController(runtime) {
310522
310922
  const data = await api(
310523
310923
  "/api/messages?limit=60&before=" + encodeURIComponent(String(state.earliestMessagePosition))
310524
310924
  );
310925
+ if (current !== generation || !belongsToChat(data)) return false;
310525
310926
  mergeMessagePage(data, false);
310526
310927
  rebuildMessageTimeline();
310527
310928
  if (options?.revealStart) {
@@ -310533,13 +310934,15 @@ function createHistoryController(runtime) {
310533
310934
  }
310534
310935
  return true;
310535
310936
  } finally {
310536
- state.loadingEarlierMessages = false;
310537
- elements.jumpEarlier.disabled = false;
310937
+ if (current === generation) {
310938
+ state.loadingEarlierMessages = false;
310939
+ updateMessageNavigation();
310940
+ }
310538
310941
  }
310539
310942
  }
310540
- return { renderMessages, loadEarlierMessages };
310943
+ return { renderMessages, loadEarlierMessages, resetConversationHistory };
310541
310944
  }
310542
- var WEB_UI_CLIENT_HISTORY_SCRIPT = ` const { renderMessages, loadEarlierMessages } = (${createHistoryController.toString()})({ elements, state, api, createMessage, renderControlTurn, setEmptyState, updateMessageNavigation, scrollToBottom });
310945
+ var WEB_UI_CLIENT_HISTORY_SCRIPT = ` const { renderMessages, loadEarlierMessages, resetConversationHistory } = (${createHistoryController.toString()})({ elements, state, api, createMessage, renderControlTurn, setEmptyState, updateMessageNavigation, scrollToBottom });
310543
310946
 
310544
310947
  `;
310545
310948
 
@@ -312075,7 +312478,54 @@ var WEB_UI_CLIENT_MISSION_CONTROL_SCRIPT = ` const { renderTaskOverview, render
312075
312478
 
312076
312479
  `;
312077
312480
 
312481
+ // src/runtime/webui/WebUiIcon.ts
312482
+ function renderUiIcon(name) {
312483
+ const paths = {
312484
+ add: '<path d="M12 5v14M5 12h14" />',
312485
+ tasks: '<rect x="5" y="4.5" width="14" height="15" rx="2" /><path d="m8 9 1.5 1.5L12 8M13.5 10h2.5M8 14h8M8 17h5" />',
312486
+ diagnostics: '<path d="M4.5 12h3l1.7-4 3.1 8 1.7-4h5.5" /><path d="M6 5.5h12v13H6z" />',
312487
+ changes: '<path d="M5 7h14M5 12h14M5 17h14" /><path d="M8 5v4M15 10v4M11 15v4" />',
312488
+ context: '<path d="M7 4.5h7l3 3v12H7z" /><path d="M14 4.5v3h3M9.5 12h5M12 9.5v5" />',
312489
+ image: '<rect x="4.5" y="5" width="15" height="14" rx="2" /><circle cx="9" cy="9.5" r="1.5" /><path d="m6.5 17 4-4 2.5 2 2.5-3 2.5 5" />',
312490
+ commands: '<rect x="4.5" y="5.5" width="15" height="13" rx="2" /><path d="m8 10 2 2-2 2M12.5 14h3.5" />',
312491
+ menu: '<path d="M5 7h14M5 12h14M5 17h14" />',
312492
+ panel: '<rect x="4.5" y="5" width="15" height="14" rx="2" /><path d="M14 5v14" />',
312493
+ close: '<path d="m7 7 10 10M17 7 7 17" />',
312494
+ back: '<path d="m10 6-6 6 6 6M4 12h16" />',
312495
+ up: '<path d="m7 14 5-5 5 5" />',
312496
+ down: '<path d="m7 10 5 5 5-5" />',
312497
+ archive: '<path d="M5.5 8.5h13v10h-13zM4.5 5h15v3.5h-15zM9.5 12h5" />',
312498
+ restore: '<path d="M8 8H4V4M4.5 8a8 8 0 1 1-.2 7" />',
312499
+ delete: '<path d="M8 7v11M12 7v11M16 7v11M5 5h14M9 5V3h6v2M6.5 5l1 16h9l1-16" />',
312500
+ search: '<circle cx="10.5" cy="10.5" r="5.5" /><path d="m14.7 14.7 4.3 4.3" />',
312501
+ chat: '<path d="M5 4.5h14a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5h-8L5 20v-3.5A1.5 1.5 0 0 1 3.5 15V6A1.5 1.5 0 0 1 5 4.5Z" />',
312502
+ folder: '<path d="M3.5 7V6a1 1 0 0 1 1-1H10l2 2h7.5a1 1 0 0 1 1 1v9a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 17V7z" />',
312503
+ review: '<circle cx="10.5" cy="10.5" r="5.5" /><path d="m14.7 14.7 4.3 4.3M10.5 8v5M8 10.5h5" />',
312504
+ fix: '<path d="M14.5 5.5a4 4 0 0 0-4.8 5.2L5 15.4 8.6 19l4.7-4.7a4 4 0 0 0 5.2-4.8l-2.7 2.7-3-3z" />',
312505
+ explain: '<path d="m9 7-5 5 5 5M15 7l5 5-5 5M13 5l-2 14" />',
312506
+ improve: '<path d="M12 4l1.2 4.1L17 10l-3.8 1.9L12 16l-1.2-4.1L7 10l3.8-1.9zM18 16v4M16 18h4M5 4v3M3.5 5.5h3" />'
312507
+ };
312508
+ return `<svg class="ui-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">${paths[name]}</svg>`;
312509
+ }
312510
+
312078
312511
  // src/runtime/webui/WebUiClientPalette.ts
312512
+ function renderCommandPaletteMarkup(copy) {
312513
+ return `<div class="command-palette" id="commandPalette" aria-hidden="true" hidden>
312514
+ <button class="command-palette-backdrop" id="commandPaletteBackdrop" type="button" aria-label="${copy.close}" tabindex="-1"></button>
312515
+ <section class="command-palette-dialog" role="dialog" aria-modal="true" aria-labelledby="commandPaletteTitle">
312516
+ <h2 class="sr-only" id="commandPaletteTitle">${copy.commands}</h2>
312517
+ <div class="command-search">
312518
+ <span aria-hidden="true" class="command-search-glyph">\u2318</span>
312519
+ <span aria-hidden="true" class="command-search-lens">${renderUiIcon("search")}</span>
312520
+ <input id="commandSearch" type="search" aria-label="${copy.commandSearch}" aria-controls="commandResults" aria-autocomplete="list" autocomplete="off" spellcheck="false" placeholder="${copy.commandSearch}" />
312521
+ <button id="commandPaletteClose" class="icon-button" type="button" aria-label="${copy.close}">${renderUiIcon("close")}</button>
312522
+ </div>
312523
+ <div class="command-results" id="commandResults" role="listbox"></div>
312524
+ <p class="command-empty" id="commandEmpty" data-default="${copy.noCommands}" hidden>${copy.noCommands}</p>
312525
+ <footer class="command-palette-footer">${copy.commandHint}</footer>
312526
+ </section>
312527
+ </div>`;
312528
+ }
312079
312529
  function paletteMatches(action, query) {
312080
312530
  if (!query) return true;
312081
312531
  const haystack = (action.label + " " + action.detail + " " + action.keywords).toLocaleLowerCase();
@@ -312085,8 +312535,12 @@ var WEB_UI_CLIENT_PALETTE_SCRIPT = String.raw` const paletteMatches = ${palette
312085
312535
  let paletteActions = [];
312086
312536
  let paletteSelection = 0;
312087
312537
  let paletteReturnFocus = null;
312538
+ let navigationPalette = false;
312539
+ const commandSearchLabel = elements.commandSearch.placeholder;
312540
+ const commandDialogLabel = byId('commandPaletteTitle').textContent;
312088
312541
 
312089
312542
  function focusMessageComposer() {
312543
+ closeSidebar();
312090
312544
  if (elements.inspector.classList.contains('is-open')) setInspector(false);
312091
312545
  showConversation();
312092
312546
  elements.prompt.focus();
@@ -312127,16 +312581,25 @@ var WEB_UI_CLIENT_PALETTE_SCRIPT = String.raw` const paletteMatches = ${palette
312127
312581
  });
312128
312582
  }
312129
312583
  const status = state.status || {};
312584
+ for (const button of elements.projectList.querySelectorAll('[data-project-path]')) {
312585
+ actions.push({
312586
+ navigation: 'project', icon: '▱', label: button.querySelector('strong').textContent, detail: button.title,
312587
+ keywords: 'project workspace folder 项目 專案 ' + button.dataset.projectPath,
312588
+ idle: true, run: () => button.click(),
312589
+ });
312590
+ }
312130
312591
  const session = status.session || {};
312131
312592
  for (const item of session.recent || []) {
312132
- if (item.active) continue;
312593
+ if (item.active && !navigationPalette) continue;
312133
312594
  actions.push({
312134
- icon: '○',
312595
+ navigation: 'chat', current: item.active, icon: '○',
312135
312596
  label: item.title || copy.untitledTask,
312136
- detail: copy.recentSession + (item.model ? ' · ' + item.model : ''),
312597
+ detail: navigationPalette
312598
+ ? [item.active ? stageCopy('Current chat', '当前聊天', '目前對話') : '', item.model, relativeSessionTime(item.updatedAt)].filter(Boolean).join(' · ')
312599
+ : copy.recentSession + ' · ' + workspaceName(status.workspace),
312137
312600
  keywords: 'session recent history ' + item.id + ' ' + (item.model || ''),
312138
312601
  idle: true,
312139
- run: () => updateSession({ action: 'resume', sessionId: item.id }),
312602
+ run: () => item.active ? focusMessageComposer() : updateSession({ action: 'resume', sessionId: item.id }),
312140
312603
  });
312141
312604
  }
312142
312605
  for (const model of status.modelOptions || []) {
@@ -312166,10 +312629,25 @@ var WEB_UI_CLIENT_PALETTE_SCRIPT = String.raw` const paletteMatches = ${palette
312166
312629
 
312167
312630
  function renderCommandPalette() {
312168
312631
  const query = elements.commandSearch.value.trim().toLocaleLowerCase();
312169
- paletteActions = buildPaletteActions().filter((action) => paletteMatches(action, query));
312632
+ paletteActions = buildPaletteActions().filter((action) => (!navigationPalette || action.navigation) && paletteMatches(action, query));
312170
312633
  paletteSelection = Math.max(0, Math.min(paletteSelection, paletteActions.length - 1));
312171
312634
  elements.commandResults.replaceChildren();
312635
+ let container = elements.commandResults, groupKind;
312172
312636
  paletteActions.forEach((action, index) => {
312637
+ if (navigationPalette && groupKind !== action.navigation) {
312638
+ groupKind = action.navigation;
312639
+ container = document.createElement('div');
312640
+ container.className = 'navigation-results-group';
312641
+ container.setAttribute('role', 'group');
312642
+ const heading = document.createElement('div');
312643
+ heading.className = 'navigation-results-heading';
312644
+ heading.id = 'navigation-' + groupKind;
312645
+ heading.textContent = groupKind === 'project' ? stageCopy('Projects', '项目', '專案')
312646
+ : stageCopy('Chats', '聊天', '對話') + ' · ' + workspaceName(state.status?.workspace);
312647
+ container.setAttribute('aria-labelledby', heading.id);
312648
+ container.append(heading);
312649
+ elements.commandResults.append(container);
312650
+ }
312173
312651
  const button = document.createElement('button');
312174
312652
  button.type = 'button';
312175
312653
  button.id = 'command-result-' + index;
@@ -312179,7 +312657,10 @@ var WEB_UI_CLIENT_PALETTE_SCRIPT = String.raw` const paletteMatches = ${palette
312179
312657
  button.disabled = Boolean(action.idle && state.busy);
312180
312658
  const icon = document.createElement('span');
312181
312659
  icon.className = 'command-result-icon';
312182
- icon.textContent = action.icon;
312660
+ if (action.navigation) {
312661
+ icon.innerHTML = action.navigation === 'project' ? '${renderUiIcon("folder")}' : '${renderUiIcon("chat")}';
312662
+ if (action.current) button.setAttribute('aria-current', 'page');
312663
+ } else icon.textContent = action.icon;
312183
312664
  const body = document.createElement('span');
312184
312665
  body.className = 'command-result-copy';
312185
312666
  const label = document.createElement('strong');
@@ -312193,7 +312674,7 @@ var WEB_UI_CLIENT_PALETTE_SCRIPT = String.raw` const paletteMatches = ${palette
312193
312674
  syncPaletteSelection();
312194
312675
  });
312195
312676
  button.addEventListener('click', () => executePaletteAction(index));
312196
- elements.commandResults.append(button);
312677
+ container.append(button);
312197
312678
  });
312198
312679
  elements.commandEmpty.hidden = paletteActions.length !== 0;
312199
312680
  syncPaletteSelection();
@@ -312212,9 +312693,16 @@ var WEB_UI_CLIENT_PALETTE_SCRIPT = String.raw` const paletteMatches = ${palette
312212
312693
  else elements.commandSearch.removeAttribute('aria-activedescendant');
312213
312694
  }
312214
312695
 
312215
- function openCommandPalette() {
312696
+ function openCommandPalette(mode, trigger) {
312216
312697
  if (!elements.commandPalette.hidden) return;
312217
- paletteReturnFocus = document.activeElement;
312698
+ navigationPalette = mode === 'navigation';
312699
+ const label = navigationPalette ? byId('findConversation').title : commandSearchLabel;
312700
+ elements.commandPalette.classList.toggle('is-navigation', navigationPalette);
312701
+ elements.commandEmpty.textContent = navigationPalette ? stageCopy('No matching projects or chats', '没有匹配的项目或聊天', '沒有相符的專案或對話') : elements.commandEmpty.dataset.default;
312702
+ elements.commandSearch.placeholder = label;
312703
+ elements.commandSearch.setAttribute('aria-label', label);
312704
+ byId('commandPaletteTitle').textContent = navigationPalette ? label : commandDialogLabel;
312705
+ paletteReturnFocus = trigger || document.activeElement;
312218
312706
  elements.commandPalette.hidden = false;
312219
312707
  elements.commandPalette.setAttribute('aria-hidden', 'false');
312220
312708
  syncApplicationModalState();
@@ -312552,35 +313040,6 @@ var WEB_UI_CLIENT_SELECT_SCRIPT = String.raw` const selectControls = new Map();
312552
313040
 
312553
313041
  `;
312554
313042
 
312555
- // src/runtime/webui/WebUiIcon.ts
312556
- function renderUiIcon(name) {
312557
- const paths = {
312558
- add: '<path d="M12 5v14M5 12h14" />',
312559
- tasks: '<rect x="5" y="4.5" width="14" height="15" rx="2" /><path d="m8 9 1.5 1.5L12 8M13.5 10h2.5M8 14h8M8 17h5" />',
312560
- diagnostics: '<path d="M4.5 12h3l1.7-4 3.1 8 1.7-4h5.5" /><path d="M6 5.5h12v13H6z" />',
312561
- changes: '<path d="M5 7h14M5 12h14M5 17h14" /><path d="M8 5v4M15 10v4M11 15v4" />',
312562
- context: '<path d="M7 4.5h7l3 3v12H7z" /><path d="M14 4.5v3h3M9.5 12h5M12 9.5v5" />',
312563
- image: '<rect x="4.5" y="5" width="15" height="14" rx="2" /><circle cx="9" cy="9.5" r="1.5" /><path d="m6.5 17 4-4 2.5 2 2.5-3 2.5 5" />',
312564
- commands: '<rect x="4.5" y="5.5" width="15" height="13" rx="2" /><path d="m8 10 2 2-2 2M12.5 14h3.5" />',
312565
- menu: '<path d="M5 7h14M5 12h14M5 17h14" />',
312566
- panel: '<rect x="4.5" y="5" width="15" height="14" rx="2" /><path d="M14 5v14" />',
312567
- close: '<path d="m7 7 10 10M17 7 7 17" />',
312568
- back: '<path d="m10 6-6 6 6 6M4 12h16" />',
312569
- up: '<path d="m7 14 5-5 5 5" />',
312570
- down: '<path d="m7 10 5 5 5-5" />',
312571
- archive: '<path d="M5.5 8.5h13v10h-13zM4.5 5h15v3.5h-15zM9.5 12h5" />',
312572
- restore: '<path d="M8 8H4V4M4.5 8a8 8 0 1 1-.2 7" />',
312573
- delete: '<path d="M8 7v11M12 7v11M16 7v11M5 5h14M9 5V3h6v2M6.5 5l1 16h9l1-16" />',
312574
- search: '<circle cx="10.5" cy="10.5" r="5.5" /><path d="m14.7 14.7 4.3 4.3" />',
312575
- folder: '<path d="M3.5 7V6a1 1 0 0 1 1-1H10l2 2h7.5a1 1 0 0 1 1 1v9a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 17V7z" />',
312576
- review: '<circle cx="10.5" cy="10.5" r="5.5" /><path d="m14.7 14.7 4.3 4.3M10.5 8v5M8 10.5h5" />',
312577
- fix: '<path d="M14.5 5.5a4 4 0 0 0-4.8 5.2L5 15.4 8.6 19l4.7-4.7a4 4 0 0 0 5.2-4.8l-2.7 2.7-3-3z" />',
312578
- explain: '<path d="m9 7-5 5 5 5M15 7l5 5-5 5M13 5l-2 14" />',
312579
- improve: '<path d="M12 4l1.2 4.1L17 10l-3.8 1.9L12 16l-1.2-4.1L7 10l3.8-1.9zM18 16v4M16 18h4M5 4v3M3.5 5.5h3" />'
312580
- };
312581
- return `<svg class="ui-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">${paths[name]}</svg>`;
312582
- }
312583
-
312584
313043
  // src/runtime/webui/WebUiClientReview.ts
312585
313044
  function verificationSummary(checks, t2) {
312586
313045
  const failures = checks.filter((check) => check.success === false).length;
@@ -313084,7 +313543,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313084
313543
  );
313085
313544
  renderList(elements.recentSessions, visibleSessions, false);
313086
313545
  renderList(elements.archivedSessions, archivedSessions, true);
313087
- elements.sessionSearchField.hidden = sessions.length < 12;
313546
+ elements.sessionSearchField.hidden = sessions.length < 12 && !query;
313088
313547
  elements.sessionShowMore.hidden = visibleSessions.length >= matchingSessions.length;
313089
313548
  elements.recentEmpty.textContent = query ? copy.noMatchingChats : copy.noRecentTasks;
313090
313549
  elements.recentEmpty.hidden = matchingSessions.length > 0;
@@ -313100,8 +313559,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313100
313559
  function renderProjectNavigation(projects, currentWorkspace) {
313101
313560
  const current = projectPathKey(currentWorkspace || '');
313102
313561
  const recentProjects = (Array.isArray(projects) ? projects : [])
313103
- .filter((item) => item.available === true && projectPathKey(item.path || '') !== current)
313104
- .slice(0, 6);
313562
+ .filter((item) => item.available === true && projectPathKey(item.path || '') !== current);
313105
313563
  const hints = projectFolderHints([
313106
313564
  { name: workspaceName(currentWorkspace), path: currentWorkspace || '' },
313107
313565
  ...recentProjects.map(p => ({name: p.name || workspaceName(p.path), path: p.path})),
@@ -313146,12 +313604,13 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313146
313604
  }
313147
313605
 
313148
313606
  async function updateSession(action) {
313149
- if (!state.ready || state.busy || state.sessionChanging) return;
313607
+ if (!state.ready || state.busy || state.sessionChanging || state.projectLaunchPending) return;
313150
313608
  state.sessionChanging = true;
313609
+ const target = Array.from(elements.recentSessions.querySelectorAll('[data-session-id]'))
313610
+ .find(button => button.dataset.sessionId === action.sessionId && button.classList.contains('recent-session'));
313611
+ if (action.action === 'resume' && target) target.setAttribute('aria-busy', 'true');
313612
+ const navigates = action.action === 'new' || action.action === 'resume';
313151
313613
  updateSendButtonState();
313152
- elements.newTaskButton.disabled = true;
313153
- elements.recentSessions.querySelectorAll('button').forEach((button) => { button.disabled = true; });
313154
- elements.archivedSessions.querySelectorAll('button').forEach((button) => { button.disabled = true; });
313155
313614
  try {
313156
313615
  await api('/api/session', {
313157
313616
  method: 'POST',
@@ -313163,14 +313622,8 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313163
313622
  drafts.write(deleted, '');
313164
313623
  discardAttachmentDraft(deleted);
313165
313624
  }
313166
- const navigates = action.action === 'new' || action.action === 'resume';
313167
313625
  if (navigates) {
313168
- clearActivity();
313169
- state.controlTurns.clear();
313170
- const [, snapshot] = await Promise.all([
313171
- renderMessages({ forceBottom: true, resetHistory: true }),
313172
- loadStatus(),
313173
- ]);
313626
+ const snapshot = await loadStatus();
313174
313627
  if (!snapshot) connectEvents();
313175
313628
  } else {
313176
313629
  await loadStatus();
@@ -313191,11 +313644,9 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313191
313644
  showToast(error.message || String(error), 'error');
313192
313645
  connectEvents();
313193
313646
  } finally {
313647
+ target?.removeAttribute('aria-busy');
313194
313648
  state.sessionChanging = false;
313195
313649
  updateSendButtonState();
313196
- elements.newTaskButton.disabled = false;
313197
- elements.recentSessions.querySelectorAll('button').forEach((button) => { button.disabled = false; });
313198
- elements.archivedSessions.querySelectorAll('button').forEach((button) => { button.disabled = false; });
313199
313650
  }
313200
313651
  }
313201
313652
 
@@ -313203,7 +313654,14 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313203
313654
  const epoch = state.statusEpoch, request = ++state.statusRequest;
313204
313655
  const requestedTurn = state.activeTurnId, data = await api('/api/status');
313205
313656
  if (epoch !== state.statusEpoch || request !== state.statusRequest) return;
313206
- activateComposerDraft(data.workspace || '', data.session?.activeId || '');
313657
+ const sessionId = data.session?.activeId || '';
313658
+ const previousId = state.status?.session?.activeId;
313659
+ if (previousId !== undefined && previousId !== sessionId) {
313660
+ clearActivity();
313661
+ state.controlTurns.clear();
313662
+ resetConversationHistory();
313663
+ }
313664
+ activateComposerDraft(data.workspace || '', sessionId);
313207
313665
  state.status = data;
313208
313666
  state.promptQueue = Array.isArray(data.inputQueue) ? data.inputQueue : [];
313209
313667
  renderPromptQueue();
@@ -313232,6 +313690,9 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313232
313690
  elements.projectToggle.title = data.workspace || '';
313233
313691
  renderProjectNavigation(data.projects || [], data.workspace);
313234
313692
  renderSessionNavigation(data.session || {});
313693
+ syncNavigationControls(true);
313694
+ if (previousId !== undefined && state.messageSessionId !== sessionId) await renderMessages({ forceBottom: true, resetHistory: true });
313695
+ if (epoch !== state.statusEpoch || request !== state.statusRequest) return;
313235
313696
  elements.runtimeUpdated.textContent = formatTime(data.updatedAt);
313236
313697
  fillRuntime(data);
313237
313698
  syncProviderOptions(data);
@@ -313589,7 +314050,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313589
314050
 
313590
314051
  async function queuePrompt(prompt, mode) {
313591
314052
  const value = String(prompt || '').trim();
313592
- if (!state.ready || state.sessionChanging || state.stopping || state.queueSubmitting || !value || state.promptQueue.length >= 12) return;
314053
+ if (!state.ready || state.sessionChanging || state.projectLaunchPending || state.stopping || state.queueSubmitting || !value || state.promptQueue.length >= 12) return;
313593
314054
  const attachmentIds = state.attachments.map((attachment) => attachment.id);
313594
314055
  const scope = drafts.active;
313595
314056
  const attachments = state.attachments;
@@ -313601,7 +314062,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313601
314062
  await api('/api/input-queue', {
313602
314063
  method: 'POST',
313603
314064
  headers: { 'Content-Type': 'application/json' },
313604
- body: JSON.stringify({ action: 'enqueue', prompt: value, mode: mode === 'steer' ? 'steer' : 'follow_up', attachmentIds }),
314065
+ body: JSON.stringify({ action: 'enqueue', prompt: value, sessionId: state.status?.session?.activeId || undefined, mode: mode === 'steer' ? 'steer' : 'follow_up', attachmentIds }),
313605
314066
  });
313606
314067
  consumeAttachments(attachmentIds, attachments);
313607
314068
  if (drafts.active !== scope && scope && drafts.read(scope) === prompt) drafts.write(scope, '');
@@ -313686,12 +314147,13 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313686
314147
 
313687
314148
  async function submitTurn(prompt, options) {
313688
314149
  const value = String(prompt || '').trim();
313689
- if (!value || state.busy || state.sessionChanging) return;
314150
+ if (!value || state.busy || state.sessionChanging || state.projectLaunchPending) return;
313690
314151
  if (!state.ready) {
313691
314152
  showToast(copy.waitForConnection, 'warning');
313692
314153
  elements.prompt.focus();
313693
314154
  return;
313694
314155
  }
314156
+ const sessionId = state.status?.session?.activeId || undefined;
313695
314157
  if (state.settingsPromise) {
313696
314158
  setBusy(true, copy.settingsSaving);
313697
314159
  try {
@@ -313703,6 +314165,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313703
314165
  }
313704
314166
  setBusy(false, '');
313705
314167
  }
314168
+ if (sessionId !== (state.status?.session?.activeId || undefined)) return;
313706
314169
  closeContextPicker({ skipRestore: true });
313707
314170
  closeSlashCommands();
313708
314171
  const turnId = crypto.randomUUID ? crypto.randomUUID() : String(Date.now()) + '-' + Math.random().toString(16).slice(2);
@@ -313737,7 +314200,7 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
313737
314200
  const result = await api('/api/chat', {
313738
314201
  method: 'POST',
313739
314202
  headers: { 'Content-Type': 'application/json' },
313740
- body: JSON.stringify({ prompt: value, turnId, attachmentIds }),
314203
+ body: JSON.stringify({ prompt: value, sessionId, turnId, attachmentIds }),
313741
314204
  });
313742
314205
  if (result.turnId) state.activeTurnId = result.turnId;
313743
314206
  consumeAttachments(attachmentIds, attachments);
@@ -314066,7 +314529,9 @@ var WEB_UI_CLIENT_SESSION_SCRIPT = String.raw` const controlCommands = ${WEB_UI
314066
314529
  const event = parseWebUiStreamEvent(message.data);
314067
314530
  if (!event) return;
314068
314531
  if (state.eventSource !== source) return;
314069
- if (event.kind === 'system' || event.kind === 'heartbeat') {
314532
+ if (requiresSessionRefresh(event, state.status?.session?.activeId)) {
314533
+ if (!state.sessionChanging) void loadStatus().catch(error => showToast(error.message, 'error'));
314534
+ } else if (event.kind === 'system' || event.kind === 'heartbeat') {
314070
314535
  if (!state.ready) syncConnection();
314071
314536
  } else if (event.kind === 'replay_gap') {
314072
314537
  // The server retained only a bounded replay window. Reconcile the
@@ -314406,460 +314871,6 @@ function ensureSessionTitle(loop, prompt) {
314406
314871
  }
314407
314872
  }
314408
314873
 
314409
- // src/runtime/webui/WebUiSecurity.ts
314410
- import { timingSafeEqual } from "crypto";
314411
- import { z as z68 } from "zod";
314412
-
314413
- // src/runtime/webui/WebUiErrors.ts
314414
- var WebUiRequestError = class extends Error {
314415
- constructor(code, statusCode, message2) {
314416
- super(message2);
314417
- this.code = code;
314418
- this.statusCode = statusCode;
314419
- }
314420
- code;
314421
- statusCode;
314422
- name = "WebUiRequestError";
314423
- };
314424
-
314425
- // src/runtime/webui/WebUiContracts.ts
314426
- var WEB_UI_PROJECT_ERROR_CODES = [
314427
- "absolute_path_required",
314428
- "filesystem_root",
314429
- "entrypoint_unavailable",
314430
- "project_missing",
314431
- "project_not_directory",
314432
- "parent_missing",
314433
- "parent_not_directory",
314434
- "create_failed",
314435
- "launch_failed",
314436
- "startup_failed",
314437
- "startup_timeout"
314438
- ];
314439
-
314440
- // src/runtime/webui/WebUiSecurity.ts
314441
- var WEB_UI_PROJECT_ERROR_CODE_SET = new Set(
314442
- WEB_UI_PROJECT_ERROR_CODES
314443
- );
314444
- function sanitizeWebEventPayload(type, payload) {
314445
- if (!isRecord7(payload)) return void 0;
314446
- switch (type) {
314447
- case "ui_turn_started":
314448
- return {
314449
- turnId: safeWebText(payload.turnId, 200),
314450
- source: payload.source === "terminal" ? "terminal" : "web",
314451
- prompt: safeWebText(payload.prompt, 8e3)
314452
- };
314453
- case "ui_turn_completed":
314454
- return {
314455
- turnId: safeWebText(payload.turnId, 200),
314456
- source: payload.source === "terminal" ? "terminal" : "web",
314457
- status: payload.status === "failed" || payload.status === "aborted" ? payload.status : "completed",
314458
- message: safeWebText(payload.message, 2e3)
314459
- };
314460
- case "model_request":
314461
- return { model: safeWebText(payload.model, 200) };
314462
- case "model_routing":
314463
- return {
314464
- model: safeWebText(payload.model, 200),
314465
- lane: ["locked", "fallback", "fast", "balanced", "quality"].includes(
314466
- String(payload.lane)
314467
- ) ? String(payload.lane) : "balanced",
314468
- reason: safeWebText(payload.reason, 100),
314469
- confidence: payload.confidence === "high" ? "high" : "medium"
314470
- };
314471
- case "model_response":
314472
- return {
314473
- model: safeWebText(payload.model, 200),
314474
- usage: sanitizeTokenUsage(payload.usage)
314475
- };
314476
- case "model_delta":
314477
- case "thinking_delta":
314478
- return { text: safeWebText(payload.text, 65536) };
314479
- case "tool_proposal":
314480
- return {
314481
- toolCallId: safeWebText(payload.toolCallId, 200),
314482
- toolName: safeWebText(payload.toolName, 200),
314483
- ...summarizeWebToolValue(payload.arguments) ? { detail: summarizeWebToolValue(payload.arguments) } : {},
314484
- explanation: safeWebText(payload.explanation, 500)
314485
- };
314486
- case "tool_result":
314487
- return {
314488
- toolCallId: safeWebText(payload.toolCallId, 200),
314489
- toolName: safeWebText(payload.toolName, 200),
314490
- display: safeWebText(payload.display, 500),
314491
- error: safeWebText(payload.error, 1e3)
314492
- };
314493
- case "tool_approval":
314494
- return {
314495
- toolCallId: safeWebText(payload.toolCallId, 200),
314496
- approved: payload.approved === true,
314497
- reason: safeWebText(payload.reason, 500)
314498
- };
314499
- case "web_approval_requested":
314500
- return {
314501
- approvalId: safeWebText(payload.approvalId, 200),
314502
- kind: payload.kind === "change" || payload.kind === "action" ? payload.kind : "tool",
314503
- title: safeWebText(payload.title, 200),
314504
- toolCallId: safeWebText(payload.toolCallId, 200),
314505
- agentId: /^agent_[a-z0-9-]+$/.test(String(payload.agentId || "")) ? safeWebText(payload.agentId, 128) : "",
314506
- agentRole: safeWebText(payload.agentRole, 80)
314507
- };
314508
- case "web_approval_resolved":
314509
- return {
314510
- ...["tool", "change", "action"].includes(String(payload.kind)) ? { kind: payload.kind } : {},
314511
- approvalId: safeWebText(payload.approvalId, 200),
314512
- approved: payload.approved === true
314513
- };
314514
- case "cost_update":
314515
- return {
314516
- turnCost: safeNumber(payload.turnCost),
314517
- sessionCost: safeNumber(payload.sessionCost),
314518
- costKnown: payload.costKnown !== false,
314519
- totalInputTokens: safeNumber(payload.totalInputTokens),
314520
- totalCacheReadTokens: safeNumber(payload.totalCacheReadTokens),
314521
- totalOutputTokens: safeNumber(payload.totalOutputTokens)
314522
- };
314523
- case "cache_update":
314524
- return {
314525
- hitTokens: safeNumber(payload.hitTokens),
314526
- missTokens: safeNumber(payload.missTokens),
314527
- inputTokens: safeNumber(payload.inputTokens),
314528
- hitRate: safeNumber(payload.hitRate),
314529
- degraded: payload.degraded === true
314530
- };
314531
- case "agent_start": {
314532
- const taskId = safeWebText(payload.taskId, 200);
314533
- if (!taskId) return void 0;
314534
- return {
314535
- taskId,
314536
- task: safeWebText(payload.task, 1e3)
314537
- };
314538
- }
314539
- case "agent_spawn": {
314540
- const childId = safeWebText(payload.childId, 200);
314541
- if (!childId) return void 0;
314542
- return {
314543
- parentId: safeWebText(payload.parentId, 200),
314544
- childId,
314545
- role: safeWebText(payload.role, 100),
314546
- task: safeWebText(payload.task, 1e3)
314547
- };
314548
- }
314549
- case "agent_status": {
314550
- const taskId = safeWebText(payload.taskId, 200);
314551
- if (!taskId) return void 0;
314552
- return {
314553
- taskId,
314554
- status: safeWebText(payload.status, 100),
314555
- detail: safeWebText(payload.detail, 500)
314556
- };
314557
- }
314558
- case "agent_completed": {
314559
- const taskId = safeWebText(payload.taskId, 200);
314560
- if (!taskId) return void 0;
314561
- const status = ["completed", "failed", "aborted"].includes(
314562
- String(payload.status)
314563
- ) ? String(payload.status) : void 0;
314564
- return {
314565
- taskId,
314566
- success: payload.success === true,
314567
- ...status ? { status } : {},
314568
- error: safeWebText(payload.error, 1e3)
314569
- };
314570
- }
314571
- case "background_task_started":
314572
- case "background_task_completed": {
314573
- const taskId = safeWebText(payload.taskId, 200);
314574
- if (!taskId) return void 0;
314575
- const status = [
314576
- "running",
314577
- "completed",
314578
- "failed",
314579
- "killed",
314580
- "timed_out"
314581
- ].includes(String(payload.status)) ? String(payload.status) : "failed";
314582
- return {
314583
- taskId,
314584
- sessionId: safeWebText(payload.sessionId, 200),
314585
- status,
314586
- durationMs: safeNumber(payload.durationMs),
314587
- exitCode: typeof payload.exitCode === "number" && Number.isSafeInteger(payload.exitCode) ? payload.exitCode : null,
314588
- outputTruncated: payload.outputTruncated === true
314589
- };
314590
- }
314591
- case "agent_input_queued":
314592
- case "agent_input_consumed":
314593
- case "agent_input_removed":
314594
- case "agent_input_updated":
314595
- case "agent_input_moved": {
314596
- const result = {
314597
- inputId: safeWebText(payload.inputId, 200),
314598
- sessionId: safeWebText(payload.sessionId, 200),
314599
- mode: payload.mode === "steer" ? "steer" : "follow_up",
314600
- source: ["terminal", "web", "api"].includes(String(payload.source)) ? String(payload.source) : "api",
314601
- remaining: safeNumber(payload.remaining)
314602
- };
314603
- if (type === "agent_input_moved") {
314604
- result.fromIndex = safeNumber(payload.fromIndex);
314605
- result.toIndex = safeNumber(payload.toIndex);
314606
- }
314607
- return result;
314608
- }
314609
- case "agent_input_queue_cleared":
314610
- return {
314611
- sessionId: safeWebText(payload.sessionId, 200),
314612
- removed: safeNumber(payload.removed)
314613
- };
314614
- case "loop_start":
314615
- return { attempt: safeNumber(payload.attempt) };
314616
- case "verification_started":
314617
- return { type: safeWebText(payload.type, 100) };
314618
- case "verification_ended":
314619
- return { success: payload.success === true };
314620
- case "hook_started":
314621
- return {
314622
- hookId: safeWebText(payload.hookId, 200),
314623
- event: safeWebText(payload.event, 100),
314624
- legacy: payload.legacy === true
314625
- };
314626
- case "hook_completed":
314627
- return {
314628
- hookId: safeWebText(payload.hookId, 200),
314629
- event: safeWebText(payload.event, 100),
314630
- success: payload.success === true,
314631
- durationMs: safeNumber(payload.durationMs),
314632
- action: ["continue", "warn", "blocked", "ignored"].includes(
314633
- String(payload.action)
314634
- ) ? String(payload.action) : "warn",
314635
- error: safeWebText(payload.error, 1e3)
314636
- };
314637
- case "checkpoint_created":
314638
- return {
314639
- timestamp: safeWebText(payload.timestamp, 100),
314640
- message: safeWebText(payload.message, 500)
314641
- };
314642
- case "file_change":
314643
- return {
314644
- filePath: safeWebText(payload.filePath, 500),
314645
- type: safeWebText(payload.type, 20),
314646
- explanation: safeWebText(payload.explanation, 500)
314647
- };
314648
- case "file_diff":
314649
- return {
314650
- filePath: safeWebText(payload.filePath, 500),
314651
- diff: safeWebText(payload.diff, 48e3)
314652
- };
314653
- case "skill_activated":
314654
- return {
314655
- name: safeWebText(payload.name, 100),
314656
- activation: payload.activation === "explicit" ? "explicit" : "auto",
314657
- loadedBytes: safeNumber(payload.loadedBytes),
314658
- truncated: payload.truncated === true,
314659
- activationReason: [
314660
- "explicit-marker",
314661
- "name-match",
314662
- "metadata-match"
314663
- ].includes(String(payload.activationReason)) ? payload.activationReason : void 0,
314664
- matchedTerms: safeNumber(payload.matchedTerms),
314665
- truncationReason: [
314666
- "skill-size-limit",
314667
- "auto-size-limit",
314668
- "context-budget"
314669
- ].includes(String(payload.truncationReason)) ? payload.truncationReason : void 0
314670
- };
314671
- case "info":
314672
- case "warning":
314673
- case "error":
314674
- return { message: safeWebText(payload.message, 2e3) };
314675
- default:
314676
- return void 0;
314677
- }
314678
- }
314679
- function isAuthorizedWebRequest(req, expectedToken) {
314680
- if (!expectedToken || !isRequestOriginAllowed(req)) return false;
314681
- const authorization = req.headers.authorization;
314682
- const cookieToken = readCookie(req, "orbit_web_token");
314683
- const supplied = authorization?.startsWith("Bearer ") ? authorization.slice(7) : cookieToken;
314684
- return safeTokenMatch(supplied, expectedToken);
314685
- }
314686
- function isBearerAuthorizedWebRequest(req, expectedToken) {
314687
- if (!expectedToken || !isRequestOriginAllowed(req)) return false;
314688
- const authorization = req.headers.authorization;
314689
- const supplied = authorization?.startsWith("Bearer ") ? authorization.slice(7) : "";
314690
- return safeTokenMatch(supplied, expectedToken);
314691
- }
314692
- function isAuthorizedWebEventRequest(req, expectedToken, url2) {
314693
- if (!expectedToken || !isRequestOriginAllowed(req)) return false;
314694
- return safeTokenMatch(
314695
- url2.searchParams.get("access_token") || "",
314696
- expectedToken
314697
- );
314698
- }
314699
- function safeWebMessage(message2) {
314700
- return sanitizeExternalErrorMessage(message2, { maxLength: 2e3 });
314701
- }
314702
- function safeWebErrorMessage(error) {
314703
- if (error instanceof z68.ZodError) {
314704
- const confirmation = "Full Access requires explicit confirmation.";
314705
- return error.issues.some(
314706
- (issue) => issue.code === "custom" && issue.message === confirmation
314707
- ) ? confirmation : "Invalid request parameters.";
314708
- }
314709
- if (error instanceof WebUiRequestError) {
314710
- switch (error.code) {
314711
- case "invalid_json":
314712
- return "Request body must contain valid JSON.";
314713
- case "request_body_too_large":
314714
- return "Request body too large.";
314715
- case "attachment_too_large":
314716
- return "Attachment is too large.";
314717
- }
314718
- }
314719
- return "Request failed. Check the request, project permissions, and provider settings before retrying.";
314720
- }
314721
- function summarizeWebToolValue(value, options = {}) {
314722
- let candidate = value;
314723
- if (typeof candidate === "string") {
314724
- const rawText = candidate;
314725
- try {
314726
- candidate = JSON.parse(rawText);
314727
- } catch {
314728
- return options.allowPlainText ? safeWebToolText(rawText, 700) : "";
314729
- }
314730
- }
314731
- if (!isRecord7(candidate)) return "";
314732
- const safeFields = [
314733
- "path",
314734
- "filePath",
314735
- "file",
314736
- "cwd",
314737
- "query",
314738
- "pattern",
314739
- "symbol",
314740
- "url",
314741
- "language",
314742
- "description",
314743
- "command"
314744
- ];
314745
- const entries = [];
314746
- for (const field of safeFields) {
314747
- const fieldValue = candidate[field];
314748
- if (typeof fieldValue !== "string" && typeof fieldValue !== "number" && typeof fieldValue !== "boolean") {
314749
- continue;
314750
- }
314751
- const text2 = safeWebToolText(String(fieldValue), 220);
314752
- if (text2) entries.push(`${field}: ${text2}`);
314753
- if (entries.length >= 3) break;
314754
- }
314755
- return entries.join("\n");
314756
- }
314757
- function sanitizeActionResult(result) {
314758
- return result.message ? { ok: result.ok, message: safeWebMessage(result.message) } : { ok: result.ok };
314759
- }
314760
- function sanitizeProjectActionResult(result) {
314761
- const url2 = result.ok ? sanitizeLocalWebUiUrl(result.url) : void 0;
314762
- const errorCode = !result.ok && WEB_UI_PROJECT_ERROR_CODE_SET.has(result.errorCode) ? result.errorCode : void 0;
314763
- return {
314764
- ok: result.ok,
314765
- ...result.message ? { message: safeWebMessage(result.message) } : {},
314766
- ...errorCode ? { errorCode } : {},
314767
- ...result.ok && result.path ? { path: safeWebText(result.path, 4096) } : {},
314768
- ...url2 ? { url: url2 } : {},
314769
- ...result.ok && result.cancelled ? { cancelled: true } : {}
314770
- };
314771
- }
314772
- function sanitizeLocalWebUiUrl(value) {
314773
- if (typeof value !== "string") return void 0;
314774
- try {
314775
- const url2 = new URL(value);
314776
- const fragment = new URLSearchParams(url2.hash.slice(1));
314777
- const tokens = fragment.getAll("token");
314778
- const token = tokens.length === 1 ? tokens[0] : void 0;
314779
- if (url2.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(url2.hostname) || !/^\d{1,5}$/.test(url2.port) || Number(url2.port) < 1 || Number(url2.port) > 65535 || url2.username || url2.password || url2.pathname !== "/" || url2.search || Array.from(fragment.keys()).length !== 1 || !token || !/^[A-Za-z0-9_-]{32,128}$/.test(token)) {
314780
- return void 0;
314781
- }
314782
- return url2.href;
314783
- } catch {
314784
- return void 0;
314785
- }
314786
- }
314787
- function sanitizeBaseUrl(value) {
314788
- if (typeof value !== "string" || !value) return "";
314789
- try {
314790
- const url2 = new URL(value);
314791
- url2.username = "";
314792
- url2.password = "";
314793
- url2.search = "";
314794
- url2.hash = "";
314795
- return url2.toString().replace(/\/$/, "");
314796
- } catch {
314797
- return safeWebText(value, 500);
314798
- }
314799
- }
314800
- function webRequestErrorStatus(error) {
314801
- if (error instanceof z68.ZodError) return 400;
314802
- if (error instanceof WebUiRequestError) return error.statusCode;
314803
- return 500;
314804
- }
314805
- function isNodeError3(error) {
314806
- return error instanceof Error;
314807
- }
314808
- function isRequestOriginAllowed(req) {
314809
- const origin = req.headers.origin;
314810
- return !origin || origin === `http://${req.headers.host}`;
314811
- }
314812
- function safeTokenMatch(supplied, expected) {
314813
- const suppliedBuffer = Buffer.from(supplied);
314814
- const expectedBuffer = Buffer.from(expected);
314815
- return suppliedBuffer.length === expectedBuffer.length && timingSafeEqual(suppliedBuffer, expectedBuffer);
314816
- }
314817
- function readCookie(req, name) {
314818
- const rawCookie = req.headers.cookie;
314819
- if (!rawCookie) return "";
314820
- for (const item of rawCookie.split(";")) {
314821
- const separator = item.indexOf("=");
314822
- if (separator < 0 || item.slice(0, separator).trim() !== name) continue;
314823
- try {
314824
- return decodeURIComponent(item.slice(separator + 1).trim());
314825
- } catch {
314826
- return "";
314827
- }
314828
- }
314829
- return "";
314830
- }
314831
- function sanitizeTokenUsage(value) {
314832
- if (!isRecord7(value)) return void 0;
314833
- return {
314834
- inputTokens: safeNumber(value.inputTokens),
314835
- outputTokens: safeNumber(value.outputTokens),
314836
- cacheReadTokens: safeNumber(value.cacheReadTokens),
314837
- cacheWriteTokens: safeNumber(value.cacheWriteTokens)
314838
- };
314839
- }
314840
- function safeNumber(value) {
314841
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
314842
- }
314843
- function safeWebText(value, maxLength) {
314844
- if (typeof value !== "string") return "";
314845
- return redactSecrets(stripAnsi2(value)).slice(0, maxLength);
314846
- }
314847
- function safeWebToolText(value, maxLength) {
314848
- return safeWebText(value, maxLength).replace(
314849
- /(--(?:api-?key|token|password|secret)(?:=|\s+))(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,
314850
- "$1***REDACTED***"
314851
- ).replace(
314852
- /((?:api[_-]?key|token|password|secret)\s*[=:]\s*)[^\s,;]+/gi,
314853
- "$1***REDACTED***"
314854
- ).trim();
314855
- }
314856
- function stripAnsi2(value) {
314857
- return value.replace(/\u001b\[[0-9;]*m/g, "");
314858
- }
314859
- function isRecord7(value) {
314860
- return typeof value === "object" && value !== null;
314861
- }
314862
-
314863
314874
  // src/runtime/webui/WebUiAgentData.ts
314864
314875
  function summarizeWebUiAgentRuns(value) {
314865
314876
  if (!Array.isArray(value)) return [];
@@ -315023,7 +315034,7 @@ function collectWebUiStatus(options, activeTurn) {
315023
315034
  const archivedSessions = normalizedSessions.filter(
315024
315035
  (session) => !session.active && session.archived
315025
315036
  );
315026
- const projects = (safeCall(() => options.getProjects?.()) || []).filter((project) => project && typeof project.path === "string").slice(0, 20).map((project) => ({
315037
+ const projects = (safeCall(() => options.getProjects?.()) || []).filter((project) => project && typeof project.path === "string").slice(0, 200).map((project) => ({
315027
315038
  id: String(project.id || "").slice(0, 64),
315028
315039
  path: redactSecrets(project.path).slice(0, 4096),
315029
315040
  name: redactSecrets(project.name || "Orbit").slice(0, 200),
@@ -315765,6 +315776,24 @@ async function readBinaryBody(req, limitBytes) {
315765
315776
  }
315766
315777
  return Buffer.concat(chunks);
315767
315778
  }
315779
+ function listenOnLoopback(server2, port) {
315780
+ return new Promise((resolveListen, reject) => {
315781
+ const onError = (error) => {
315782
+ server2.off("listening", onListening);
315783
+ reject(error);
315784
+ };
315785
+ const onListening = () => {
315786
+ server2.off("error", onError);
315787
+ const address = server2.address();
315788
+ resolveListen(
315789
+ typeof address === "object" && address ? address.port : port
315790
+ );
315791
+ };
315792
+ server2.once("error", onError);
315793
+ server2.once("listening", onListening);
315794
+ server2.listen(port, "127.0.0.1");
315795
+ });
315796
+ }
315768
315797
 
315769
315798
  // src/runtime/webui/WebUiEventStream.ts
315770
315799
  var WEB_UI_SSE_HEARTBEAT_MS = 15e3;
@@ -315882,7 +315911,11 @@ var WebUiEventStream = class {
315882
315911
  }
315883
315912
  try {
315884
315913
  const writable = res.write(
315885
- `data: ${JSON.stringify({ kind: "heartbeat", timestamp: (/* @__PURE__ */ new Date()).toISOString() })}
315914
+ `data: ${JSON.stringify({
315915
+ kind: "heartbeat",
315916
+ sessionId: this.getSessionId?.(),
315917
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
315918
+ })}
315886
315919
 
315887
315920
  `
315888
315921
  );
@@ -316034,6 +316067,7 @@ var BASE_COPY = {
316034
316067
  projects: "Projects",
316035
316068
  recentProjects: "Recent projects",
316036
316069
  newProject: "Add project",
316070
+ findConversation: "Find projects and chats",
316037
316071
  projectDialogTitle: "Open or create a project",
316038
316072
  projectDialogBody: "Choose an existing folder to add it to Orbit, or enter the absolute path of a new folder whose parent already exists. Orbit opens it in a separate local browser tab with its own chats and context.",
316039
316073
  projectPath: "Project folder path",
@@ -316223,6 +316257,7 @@ var BASE_COPY = {
316223
316257
  projects: "\u9879\u76EE",
316224
316258
  recentProjects: "\u6700\u8FD1\u9879\u76EE",
316225
316259
  newProject: "\u6DFB\u52A0\u9879\u76EE",
316260
+ findConversation: "\u67E5\u627E\u9879\u76EE\u548C\u804A\u5929",
316226
316261
  projectDialogTitle: "\u6253\u5F00\u6216\u521B\u5EFA\u9879\u76EE",
316227
316262
  projectDialogBody: "\u9009\u62E9\u5DF2\u6709\u6587\u4EF6\u5939\u53EF\u76F4\u63A5\u52A0\u5165 Orbit\uFF1B\u4E5F\u53EF\u4EE5\u8F93\u5165\u7236\u76EE\u5F55\u5DF2\u5B58\u5728\u7684\u65B0\u6587\u4EF6\u5939\u7EDD\u5BF9\u8DEF\u5F84\u3002Orbit \u4F1A\u5728\u72EC\u7ACB\u7684\u672C\u5730\u6D4F\u89C8\u5668\u6807\u7B7E\u9875\u4E2D\u6253\u5F00\uFF0C\u5E76\u4FDD\u7559\u81EA\u5DF1\u7684\u804A\u5929\u548C\u4E0A\u4E0B\u6587\u3002",
316228
316263
  projectPath: "\u9879\u76EE\u6587\u4EF6\u5939\u8DEF\u5F84",
@@ -316416,6 +316451,7 @@ var COPY = {
316416
316451
  projects: "\u5C08\u6848",
316417
316452
  recentProjects: "\u6700\u8FD1\u5C08\u6848",
316418
316453
  newProject: "\u52A0\u5165\u5C08\u6848",
316454
+ findConversation: "\u5C0B\u627E\u5C08\u6848\u8207\u5C0D\u8A71",
316419
316455
  projectDialogTitle: "\u958B\u555F\u6216\u5EFA\u7ACB\u5C08\u6848",
316420
316456
  projectDialogBody: "\u9078\u64C7\u73FE\u6709\u8CC7\u6599\u593E\u53EF\u76F4\u63A5\u52A0\u5165 Orbit\uFF1B\u4E5F\u53EF\u4EE5\u8F38\u5165\u7236\u8CC7\u6599\u593E\u5DF2\u5B58\u5728\u7684\u65B0\u8CC7\u6599\u593E\u7D55\u5C0D\u8DEF\u5F91\u3002Orbit \u6703\u5728\u7368\u7ACB\u7684\u672C\u6A5F\u700F\u89BD\u5668\u5206\u9801\u958B\u555F\uFF0C\u4E26\u4FDD\u7559\u81EA\u5DF1\u7684\u804A\u5929\u548C\u4E0A\u4E0B\u6587\u3002",
316421
316457
  projectPath: "\u5C08\u6848\u8CC7\u6599\u593E\u8DEF\u5F91",
@@ -316692,6 +316728,7 @@ function renderWebUiPage(language) {
316692
316728
 
316693
316729
  <div class="project-heading">
316694
316730
  <span>${copy.projects}</span>
316731
+ <button class="new-project-button" id="findConversation" type="button" aria-label="${copy.findConversation}" title="${copy.findConversation}" aria-haspopup="dialog" aria-controls="commandPalette">${renderUiIcon("search")}</button>
316695
316732
  <button class="new-project-button" id="newProjectButton" type="button" aria-label="${copy.newProject}" aria-haspopup="dialog" aria-controls="projectDialog">${renderUiIcon("add")}</button>
316696
316733
  </div>
316697
316734
  <section class="project-section" id="projectSection" data-testid="active-project" aria-label="${copy.projects}">
@@ -317090,20 +317127,7 @@ function renderWebUiPage(language) {
317090
317127
  </aside>
317091
317128
 
317092
317129
  </div>
317093
- <div class="command-palette" id="commandPalette" aria-hidden="true" hidden>
317094
- <button class="command-palette-backdrop" id="commandPaletteBackdrop" type="button" aria-label="${copy.close}" tabindex="-1"></button>
317095
- <section class="command-palette-dialog" role="dialog" aria-modal="true" aria-labelledby="commandPaletteTitle">
317096
- <h2 class="sr-only" id="commandPaletteTitle">${copy.commands}</h2>
317097
- <label class="command-search" for="commandSearch">
317098
- <span aria-hidden="true">\u2318</span>
317099
- <input id="commandSearch" type="search" aria-label="${copy.commandSearch}" aria-controls="commandResults" aria-autocomplete="list" autocomplete="off" spellcheck="false" placeholder="${copy.commandSearch}" />
317100
- <kbd aria-hidden="true">Esc</kbd>
317101
- </label>
317102
- <div class="command-results" id="commandResults" role="listbox"></div>
317103
- <p class="command-empty" id="commandEmpty" hidden>${copy.noCommands}</p>
317104
- <footer class="command-palette-footer">${copy.commandHint}</footer>
317105
- </section>
317106
- </div>
317130
+ ${renderCommandPaletteMarkup(copy)}
317107
317131
  <div class="session-delete-dialog" id="sessionDeleteDialog" aria-hidden="true" hidden>
317108
317132
  <button class="session-delete-backdrop" id="sessionDeleteBackdrop" type="button" aria-label="${copy.cancel}" tabindex="-1"></button>
317109
317133
  <section class="session-delete-card" role="dialog" aria-modal="true" aria-labelledby="sessionDeleteTitle" aria-describedby="sessionDeleteBody">
@@ -321972,8 +321996,7 @@ var WEB_UI_PALETTE_STYLES = String.raw`
321972
321996
  height: 14px;
321973
321997
  }
321974
321998
 
321975
- .command-trigger kbd,
321976
- .command-search kbd {
321999
+ .command-trigger kbd {
321977
322000
  padding: 2px 5px;
321978
322001
  color: var(--faint);
321979
322002
  background: var(--surface-subtle);
@@ -322044,6 +322067,12 @@ var WEB_UI_PALETTE_STYLES = String.raw`
322044
322067
  font: 700 11px/1 var(--font-mono);
322045
322068
  }
322046
322069
 
322070
+ .command-search .command-search-lens,
322071
+ .is-navigation .command-search-glyph { display: none; }
322072
+ .is-navigation .command-search-lens { display: grid; }
322073
+ .command-search-lens .ui-icon { width: 16px; height: 16px; }
322074
+ .command-search .icon-button { width: 36px; height: 36px; }
322075
+
322047
322076
  .command-search input {
322048
322077
  width: 100%;
322049
322078
  height: 56px;
@@ -322112,6 +322141,16 @@ var WEB_UI_PALETTE_STYLES = String.raw`
322112
322141
  font: 650 11px/1 var(--font-mono);
322113
322142
  }
322114
322143
 
322144
+ .navigation-results-group { display: grid; gap: 1px; }
322145
+ .navigation-results-heading {
322146
+ padding: 10px 11px 5px; color: var(--muted); font: 600 12px/1.4 var(--font-sans);
322147
+ }
322148
+ .navigation-results-group + .navigation-results-group { border-top: 1px solid var(--border); margin-top: 4px; }
322149
+ .is-navigation .command-result-icon { color: var(--accent-strong); background: transparent; border: 0; }
322150
+ .command-result-icon .ui-icon { width: 17px; height: 17px; }
322151
+ .is-navigation .command-result-copy strong { font-size: 13px; }
322152
+ .is-navigation .command-result-copy small { color: var(--muted); font: 12px/1.35 var(--font-sans); }
322153
+ .is-navigation .command-result[aria-current="page"] .command-result-icon { background: var(--accent-soft); }
322115
322154
  .command-result-copy {
322116
322155
  min-width: 0;
322117
322156
  display: grid;
@@ -323227,6 +323266,12 @@ var WEB_UI_SHELL_STYLES = String.raw`
323227
323266
  font: 600 12px/1.4 var(--font-sans);
323228
323267
  }
323229
323268
 
323269
+ .project-heading > span { margin-inline-end: auto; }
323270
+ .project-heading { gap: 3px; }
323271
+ @media (max-width: 760px) {
323272
+ .project-heading .new-project-button { width: 36px; height: 36px; }
323273
+ }
323274
+
323230
323275
  .new-project-button {
323231
323276
  width: 23px;
323232
323277
  height: 23px;
@@ -323351,10 +323396,31 @@ var WEB_UI_SHELL_STYLES = String.raw`
323351
323396
  }
323352
323397
  .registered-project-open:focus-visible { outline-offset: -2px; }
323353
323398
 
323354
- .registered-project-open.is-switching {
323399
+ .registered-project-open.is-switching,
323400
+ .recent-session[aria-busy="true"] {
323355
323401
  cursor: progress;
323356
- opacity: 0.58;
323402
+ color: var(--accent-strong);
323403
+ background: var(--accent-soft);
323404
+ }
323405
+ .registered-project-open.is-switching .project-folder-icon,
323406
+ .recent-session[aria-busy="true"] .recent-session-meta { visibility: hidden; }
323407
+ .registered-project-open.is-switching::after,
323408
+ .recent-session[aria-busy="true"]::after {
323409
+ content: "";
323410
+ position: absolute;
323411
+ top: calc(50% - 6px);
323412
+ width: 12px; height: 12px;
323413
+ border: 1.5px solid currentColor;
323414
+ border-inline-end-color: transparent;
323415
+ border-radius: 50%;
323357
323416
  }
323417
+ .registered-project-open.is-switching::after { inset-inline-start: 12px; }
323418
+ .recent-session[aria-busy="true"]::after { inset-inline-end: 8px; }
323419
+ @media (prefers-reduced-motion: no-preference) {
323420
+ .registered-project-open.is-switching::after,
323421
+ .recent-session[aria-busy="true"]::after { animation: orbit-nav-progress .8s linear infinite; }
323422
+ }
323423
+ @keyframes orbit-nav-progress { to { transform: rotate(1turn); } }
323358
323424
 
323359
323425
  .registered-project-remove {
323360
323426
  position: absolute;
@@ -324306,6 +324372,7 @@ var MessagePageQuerySchema = z70.object({
324306
324372
  }).strict();
324307
324373
  var ChatRequestSchema = z70.object({
324308
324374
  prompt: z70.string().trim().min(1).max(1e5),
324375
+ sessionId: z70.string().min(1).max(1e3).optional(),
324309
324376
  turnId: WebTurnIdSchema.optional(),
324310
324377
  attachmentIds: AttachmentIdsSchema.optional()
324311
324378
  }).strict();
@@ -324313,6 +324380,7 @@ var InputQueueIdSchema = z70.string().trim().regex(/^input_[a-zA-Z0-9_-]+$/).max
324313
324380
  var InputQueueActionSchema = z70.discriminatedUnion("action", [
324314
324381
  z70.object({
324315
324382
  action: z70.literal("enqueue"),
324383
+ sessionId: z70.string().min(1).max(1e3).optional(),
324316
324384
  prompt: z70.string().trim().min(1).max(1e5),
324317
324385
  mode: z70.enum(["follow_up", "steer"]).prefault("follow_up"),
324318
324386
  attachmentIds: AttachmentIdsSchema.optional()
@@ -324459,24 +324527,6 @@ function safeCall2(fn) {
324459
324527
  return void 0;
324460
324528
  }
324461
324529
  }
324462
- function listen(server2, port) {
324463
- return new Promise((resolveListen, reject) => {
324464
- const onError = (error) => {
324465
- server2.off("listening", onListening);
324466
- reject(error);
324467
- };
324468
- const onListening = () => {
324469
- server2.off("error", onError);
324470
- const address = server2.address();
324471
- resolveListen(
324472
- typeof address === "object" && address ? address.port : port
324473
- );
324474
- };
324475
- server2.once("error", onError);
324476
- server2.once("listening", onListening);
324477
- server2.listen(port, "127.0.0.1");
324478
- });
324479
- }
324480
324530
  var OrbitWebUiRuntime = class {
324481
324531
  options;
324482
324532
  events;
@@ -324533,8 +324583,14 @@ var OrbitWebUiRuntime = class {
324533
324583
  }
324534
324584
  this.state = "starting";
324535
324585
  this.token = randomBytes4(32).toString("base64url");
324536
- const preferredPort = this.options.port ?? 6047;
324537
- const attempts = preferredPort === 0 ? [0] : Array.from({ length: 20 }, (_, index) => preferredPort + index);
324586
+ const preferredPort = this.options.port ?? this.options.preferredPort ?? 6047;
324587
+ const attempts = preferredPort === 0 ? [0] : [
324588
+ ...Array.from(
324589
+ { length: Math.min(20, 65536 - preferredPort) },
324590
+ (_, index) => preferredPort + index
324591
+ ),
324592
+ 0
324593
+ ];
324538
324594
  let lastError;
324539
324595
  for (const port of attempts) {
324540
324596
  const server2 = http2.createServer((req, res) => {
@@ -324546,7 +324602,7 @@ var OrbitWebUiRuntime = class {
324546
324602
  });
324547
324603
  });
324548
324604
  try {
324549
- const actualPort = await listen(server2, port);
324605
+ const actualPort = await listenOnLoopback(server2, port);
324550
324606
  const token = this.token;
324551
324607
  if (!token) throw new Error("Orbit Web UI authentication failed.");
324552
324608
  this.server = server2;
@@ -324901,15 +324957,15 @@ var OrbitWebUiRuntime = class {
324901
324957
  });
324902
324958
  return;
324903
324959
  }
324904
- if (this.activeTurn) {
324905
- sendJson(res, 409, {
324906
- ok: false,
324907
- message: "Wait for the active task to finish before opening a project."
324908
- });
324909
- return;
324910
- }
324911
324960
  try {
324912
324961
  const action = ProjectActionSchema.parse(await readJsonBody(req));
324962
+ if (this.activeTurn) {
324963
+ sendJson(res, 409, {
324964
+ ok: false,
324965
+ message: "Wait for the active task to finish before opening a project."
324966
+ });
324967
+ return;
324968
+ }
324913
324969
  if (this.projectActionPending) {
324914
324970
  sendJson(res, 409, {
324915
324971
  ok: false,
@@ -324922,6 +324978,9 @@ var OrbitWebUiRuntime = class {
324922
324978
  const result = sanitizeProjectActionResult(
324923
324979
  await options.openProject(action)
324924
324980
  );
324981
+ if (result.ok && result.url && (action.action === "open" || action.action === "create") && options.onProjectHandoff) {
324982
+ res.once("finish", options.onProjectHandoff);
324983
+ }
324925
324984
  sendJson(
324926
324985
  res,
324927
324986
  result.ok ? action.action === "remove" || action.action === "pick" ? 200 : 202 : 409,
@@ -324974,6 +325033,18 @@ var OrbitWebUiRuntime = class {
324974
325033
  }
324975
325034
  try {
324976
325035
  const body = ChatRequestSchema.parse(await readJsonBody(req));
325036
+ const sessionId = safeCall2(() => options.loop?.getSessionId?.()) || "";
325037
+ if (body.sessionId !== void 0 && body.sessionId !== sessionId) {
325038
+ sendJson(res, 409, {
325039
+ ok: false,
325040
+ message: "The active chat changed. Your message was not sent."
325041
+ });
325042
+ return;
325043
+ }
325044
+ if (this.projectActionPending) {
325045
+ sendJson(res, 409, { ok: false, message: "A project action is in progress." });
325046
+ return;
325047
+ }
324977
325048
  if (this.activeTurn) {
324978
325049
  sendJson(res, 409, {
324979
325050
  ok: false,
@@ -324984,7 +325055,7 @@ var OrbitWebUiRuntime = class {
324984
325055
  }
324985
325056
  const turn = {
324986
325057
  id: body.turnId || randomUUID14(),
324987
- sessionId: safeCall2(() => options.loop?.getSessionId?.()) || "",
325058
+ sessionId,
324988
325059
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
324989
325060
  cancelRequested: false
324990
325061
  };
@@ -325024,6 +325095,13 @@ var OrbitWebUiRuntime = class {
325024
325095
  let action;
325025
325096
  let queuedAttachments = [];
325026
325097
  if (request.action === "enqueue") {
325098
+ if (request.sessionId !== void 0 && request.sessionId !== options.loop?.getSessionId?.()) {
325099
+ sendJson(res, 409, {
325100
+ ok: false,
325101
+ message: "The active chat changed. Your message was not queued."
325102
+ });
325103
+ return;
325104
+ }
325027
325105
  queuedAttachments = (request.attachmentIds || []).map((id) => {
325028
325106
  const attachment = this.attachments.get(id);
325029
325107
  if (!attachment) {
@@ -325067,6 +325145,10 @@ var OrbitWebUiRuntime = class {
325067
325145
  try {
325068
325146
  const body = TaskActionSchema.parse(await readJsonBody(req));
325069
325147
  const action = { action: body.action };
325148
+ if (this.projectActionPending) {
325149
+ sendJson(res, 409, { ok: false, message: "A project action is in progress." });
325150
+ return;
325151
+ }
325070
325152
  if (this.activeTurn) {
325071
325153
  sendJson(res, 409, {
325072
325154
  ok: false,
@@ -325257,7 +325339,15 @@ var OrbitWebUiRuntime = class {
325257
325339
  }
325258
325340
  try {
325259
325341
  const action = SessionActionSchema.parse(await readJsonBody(req));
325342
+ if (this.activeTurn || this.projectActionPending) {
325343
+ sendJson(res, 409, {
325344
+ ok: false,
325345
+ message: "Wait for the current operation before changing chats."
325346
+ });
325347
+ return;
325348
+ }
325260
325349
  const result = await options.updateSession(action);
325350
+ if (result.ok) this.events.broadcast({ kind: "sessions_changed" });
325261
325351
  sendJson(res, result.ok ? 200 : 409, sanitizeActionResult(result));
325262
325352
  } catch (error) {
325263
325353
  sendJson(res, webRequestErrorStatus(error), {
@@ -327325,189 +327415,6 @@ function copyBooleanCapability(source, sourceKey, target, targetKey) {
327325
327415
  }
327326
327416
  }
327327
327417
 
327328
- // src/runtime/ProjectLauncher.ts
327329
- import { spawn as spawn5 } from "child_process";
327330
- import { existsSync as existsSync21, mkdirSync as mkdirSync7, realpathSync as realpathSync5, statSync as statSync7 } from "fs";
327331
- import { dirname as dirname13, isAbsolute as isAbsolute9, parse as parse5, resolve as resolve14 } from "path";
327332
- var PROJECT_WEB_UI_READY_MESSAGE = "orbit-webui-ready";
327333
- var ProjectLaunchError = class extends Error {
327334
- constructor(code, message2, options) {
327335
- super(message2, options);
327336
- this.code = code;
327337
- }
327338
- code;
327339
- name = "ProjectLaunchError";
327340
- };
327341
- async function launchOrbitProject(request, options = {}) {
327342
- if (!isAbsolute9(request.path)) {
327343
- throw new ProjectLaunchError(
327344
- "absolute_path_required",
327345
- "Enter an absolute project folder path."
327346
- );
327347
- }
327348
- const requestedPath = resolve14(request.path);
327349
- rejectFilesystemRoot(requestedPath);
327350
- const entryPoint = options.entryPoint || process.argv[1];
327351
- if (!entryPoint) {
327352
- throw new ProjectLaunchError(
327353
- "entrypoint_unavailable",
327354
- "Orbit CLI entry point is unavailable."
327355
- );
327356
- }
327357
- if (request.action === "create") {
327358
- ensureProjectDirectory(requestedPath);
327359
- } else {
327360
- requireProjectDirectory(requestedPath);
327361
- }
327362
- const projectPath = realpathSync5.native(requestedPath);
327363
- rejectFilesystemRoot(projectPath);
327364
- const launch = options.launch || spawn5;
327365
- let child;
327366
- try {
327367
- child = launch(
327368
- options.executable || process.execPath,
327369
- [entryPoint, "webui", "--cwd", projectPath],
327370
- {
327371
- ...HIDDEN_CHILD_PROCESS_OPTIONS,
327372
- cwd: projectPath,
327373
- detached: true,
327374
- stdio: ["ignore", "ignore", "ignore", "ipc"]
327375
- }
327376
- );
327377
- } catch (error) {
327378
- throw new ProjectLaunchError(
327379
- "launch_failed",
327380
- "Orbit project could not be started.",
327381
- { cause: error }
327382
- );
327383
- }
327384
- return await new Promise(
327385
- (resolveLaunch, rejectLaunch) => {
327386
- let settled = false;
327387
- const finish = (result, error) => {
327388
- if (settled) return;
327389
- settled = true;
327390
- clearTimeout(timeout);
327391
- child.removeListener("message", onMessage);
327392
- child.removeListener("error", onError);
327393
- child.removeListener("exit", onExit2);
327394
- if (child.connected) {
327395
- try {
327396
- child.disconnect();
327397
- } catch {
327398
- }
327399
- }
327400
- child.unref();
327401
- if (result) resolveLaunch(result);
327402
- else
327403
- rejectLaunch(
327404
- error || new Error("Orbit Web UI could not be started.")
327405
- );
327406
- };
327407
- const onMessage = (message2) => {
327408
- const url2 = parseReadyUrl(message2);
327409
- if (url2) finish({ path: projectPath, url: url2 });
327410
- };
327411
- const onError = (error) => finish(
327412
- void 0,
327413
- new ProjectLaunchError(
327414
- "launch_failed",
327415
- `Orbit project could not be opened: ${error.message}`,
327416
- { cause: error }
327417
- )
327418
- );
327419
- const onExit2 = (code) => finish(
327420
- void 0,
327421
- new ProjectLaunchError(
327422
- "startup_failed",
327423
- `Orbit project exited before its Web UI was ready${code === null ? "." : ` (code ${code}).`}`
327424
- )
327425
- );
327426
- const timeout = setTimeout(
327427
- () => {
327428
- child.kill();
327429
- finish(
327430
- void 0,
327431
- new ProjectLaunchError(
327432
- "startup_timeout",
327433
- "Timed out while starting the Orbit project."
327434
- )
327435
- );
327436
- },
327437
- Math.max(1e3, options.startupTimeoutMs ?? 15e3)
327438
- );
327439
- timeout.unref();
327440
- child.on("message", onMessage);
327441
- child.once("error", onError);
327442
- child.once("exit", onExit2);
327443
- }
327444
- );
327445
- }
327446
- function parseReadyUrl(message2) {
327447
- if (typeof message2 !== "object" || message2 === null || !("type" in message2) || !("url" in message2) || message2.type !== PROJECT_WEB_UI_READY_MESSAGE || typeof message2.url !== "string") {
327448
- return void 0;
327449
- }
327450
- return sanitizeLocalWebUiUrl(message2.url);
327451
- }
327452
- function ensureProjectDirectory(projectPath) {
327453
- if (existsSync21(projectPath)) {
327454
- requireProjectDirectory(projectPath);
327455
- return;
327456
- }
327457
- const parentPath = dirname13(projectPath);
327458
- if (!existsSync21(parentPath)) {
327459
- throw new ProjectLaunchError(
327460
- "parent_missing",
327461
- "The parent folder does not exist. Choose an existing location first."
327462
- );
327463
- }
327464
- if (!statSync7(parentPath).isDirectory()) {
327465
- throw new ProjectLaunchError(
327466
- "parent_not_directory",
327467
- "The project parent path must be a directory."
327468
- );
327469
- }
327470
- try {
327471
- mkdirSync7(projectPath);
327472
- } catch (error) {
327473
- if (isNodeError4(error) && error.code === "EEXIST") {
327474
- requireProjectDirectory(projectPath);
327475
- return;
327476
- }
327477
- throw new ProjectLaunchError(
327478
- "create_failed",
327479
- "Orbit could not create the project folder.",
327480
- { cause: error }
327481
- );
327482
- }
327483
- }
327484
- function requireProjectDirectory(projectPath) {
327485
- if (!existsSync21(projectPath)) {
327486
- throw new ProjectLaunchError(
327487
- "project_missing",
327488
- "Project folder does not exist."
327489
- );
327490
- }
327491
- if (!statSync7(projectPath).isDirectory()) {
327492
- throw new ProjectLaunchError(
327493
- "project_not_directory",
327494
- "Project path must point to a directory."
327495
- );
327496
- }
327497
- }
327498
- function rejectFilesystemRoot(projectPath) {
327499
- const normalized = resolve14(projectPath);
327500
- if (normalized === parse5(normalized).root) {
327501
- throw new ProjectLaunchError(
327502
- "filesystem_root",
327503
- "A filesystem root cannot be opened as an Orbit project."
327504
- );
327505
- }
327506
- }
327507
- function isNodeError4(error) {
327508
- return error instanceof Error;
327509
- }
327510
-
327511
327418
  // src/runtime/ProjectFolderPicker.ts
327512
327419
  import { execFile as execFile6 } from "child_process";
327513
327420
  import { promisify as promisify4 } from "util";
@@ -327721,6 +327628,224 @@ function isPickerCancellation(error, platform) {
327721
327628
  return stderr.includes("User canceled") || platform === "linux" && candidate.code === 1 && stderr.length === 0;
327722
327629
  }
327723
327630
 
327631
+ // src/runtime/ProjectLauncher.ts
327632
+ import { spawn as spawn5 } from "child_process";
327633
+ import { existsSync as existsSync21, mkdirSync as mkdirSync7, realpathSync as realpathSync5, statSync as statSync7 } from "fs";
327634
+ import { dirname as dirname13, isAbsolute as isAbsolute9, parse as parse5, resolve as resolve14 } from "path";
327635
+ var PROJECT_WEB_UI_READY_MESSAGE = "orbit-webui-ready";
327636
+ var ProjectLaunchError = class extends Error {
327637
+ constructor(code, message2, options) {
327638
+ super(message2, options);
327639
+ this.code = code;
327640
+ }
327641
+ code;
327642
+ name = "ProjectLaunchError";
327643
+ };
327644
+ async function launchOrbitProject(request, options = {}) {
327645
+ if (!isAbsolute9(request.path)) {
327646
+ throw new ProjectLaunchError(
327647
+ "absolute_path_required",
327648
+ "Enter an absolute project folder path."
327649
+ );
327650
+ }
327651
+ const requestedPath = resolve14(request.path);
327652
+ rejectFilesystemRoot(requestedPath);
327653
+ const entryPoint = options.entryPoint || process.argv[1];
327654
+ if (!entryPoint) {
327655
+ throw new ProjectLaunchError(
327656
+ "entrypoint_unavailable",
327657
+ "Orbit CLI entry point is unavailable."
327658
+ );
327659
+ }
327660
+ if (request.action === "create") {
327661
+ ensureProjectDirectory(requestedPath);
327662
+ } else {
327663
+ requireProjectDirectory(requestedPath);
327664
+ }
327665
+ const projectPath = realpathSync5.native(requestedPath);
327666
+ rejectFilesystemRoot(projectPath);
327667
+ const launch = options.launch || spawn5;
327668
+ let child;
327669
+ try {
327670
+ child = launch(
327671
+ options.executable || process.execPath,
327672
+ [entryPoint, "webui", "--cwd", projectPath],
327673
+ {
327674
+ ...HIDDEN_CHILD_PROCESS_OPTIONS,
327675
+ cwd: projectPath,
327676
+ detached: true,
327677
+ stdio: ["ignore", "ignore", "ignore", "ipc"]
327678
+ }
327679
+ );
327680
+ } catch (error) {
327681
+ throw new ProjectLaunchError(
327682
+ "launch_failed",
327683
+ "Orbit project could not be started.",
327684
+ { cause: error }
327685
+ );
327686
+ }
327687
+ return await new Promise(
327688
+ (resolveLaunch, rejectLaunch) => {
327689
+ let settled = false;
327690
+ const finish = (result, error) => {
327691
+ if (settled) return;
327692
+ settled = true;
327693
+ clearTimeout(timeout);
327694
+ child.removeListener("message", onMessage);
327695
+ child.removeListener("error", onError);
327696
+ child.removeListener("exit", onExit2);
327697
+ if (child.connected) {
327698
+ try {
327699
+ child.disconnect();
327700
+ } catch {
327701
+ }
327702
+ }
327703
+ child.unref();
327704
+ if (result) resolveLaunch(result);
327705
+ else
327706
+ rejectLaunch(
327707
+ error || new Error("Orbit Web UI could not be started.")
327708
+ );
327709
+ };
327710
+ const onMessage = (message2) => {
327711
+ const url2 = parseReadyUrl(message2);
327712
+ if (url2) finish({ path: projectPath, url: url2 });
327713
+ };
327714
+ const onError = (error) => finish(
327715
+ void 0,
327716
+ new ProjectLaunchError(
327717
+ "launch_failed",
327718
+ `Orbit project could not be opened: ${error.message}`,
327719
+ { cause: error }
327720
+ )
327721
+ );
327722
+ const onExit2 = (code) => finish(
327723
+ void 0,
327724
+ new ProjectLaunchError(
327725
+ "startup_failed",
327726
+ `Orbit project exited before its Web UI was ready${code === null ? "." : ` (code ${code}).`}`
327727
+ )
327728
+ );
327729
+ const timeout = setTimeout(
327730
+ () => {
327731
+ child.kill();
327732
+ finish(
327733
+ void 0,
327734
+ new ProjectLaunchError(
327735
+ "startup_timeout",
327736
+ "Timed out while starting the Orbit project."
327737
+ )
327738
+ );
327739
+ },
327740
+ Math.max(1e3, options.startupTimeoutMs ?? 15e3)
327741
+ );
327742
+ timeout.unref();
327743
+ child.on("message", onMessage);
327744
+ child.once("error", onError);
327745
+ child.once("exit", onExit2);
327746
+ }
327747
+ );
327748
+ }
327749
+ function parseReadyUrl(message2) {
327750
+ if (typeof message2 !== "object" || message2 === null || !("type" in message2) || !("url" in message2) || message2.type !== PROJECT_WEB_UI_READY_MESSAGE || typeof message2.url !== "string") {
327751
+ return void 0;
327752
+ }
327753
+ return sanitizeLocalWebUiUrl(message2.url);
327754
+ }
327755
+ function ensureProjectDirectory(projectPath) {
327756
+ if (existsSync21(projectPath)) {
327757
+ requireProjectDirectory(projectPath);
327758
+ return;
327759
+ }
327760
+ const parentPath = dirname13(projectPath);
327761
+ if (!existsSync21(parentPath)) {
327762
+ throw new ProjectLaunchError(
327763
+ "parent_missing",
327764
+ "The parent folder does not exist. Choose an existing location first."
327765
+ );
327766
+ }
327767
+ if (!statSync7(parentPath).isDirectory()) {
327768
+ throw new ProjectLaunchError(
327769
+ "parent_not_directory",
327770
+ "The project parent path must be a directory."
327771
+ );
327772
+ }
327773
+ try {
327774
+ mkdirSync7(projectPath);
327775
+ } catch (error) {
327776
+ if (isNodeError4(error) && error.code === "EEXIST") {
327777
+ requireProjectDirectory(projectPath);
327778
+ return;
327779
+ }
327780
+ throw new ProjectLaunchError(
327781
+ "create_failed",
327782
+ "Orbit could not create the project folder.",
327783
+ { cause: error }
327784
+ );
327785
+ }
327786
+ }
327787
+ function requireProjectDirectory(projectPath) {
327788
+ if (!existsSync21(projectPath)) {
327789
+ throw new ProjectLaunchError(
327790
+ "project_missing",
327791
+ "Project folder does not exist."
327792
+ );
327793
+ }
327794
+ if (!statSync7(projectPath).isDirectory()) {
327795
+ throw new ProjectLaunchError(
327796
+ "project_not_directory",
327797
+ "Project path must point to a directory."
327798
+ );
327799
+ }
327800
+ }
327801
+ function rejectFilesystemRoot(projectPath) {
327802
+ const normalized = resolve14(projectPath);
327803
+ if (normalized === parse5(normalized).root) {
327804
+ throw new ProjectLaunchError(
327805
+ "filesystem_root",
327806
+ "A filesystem root cannot be opened as an Orbit project."
327807
+ );
327808
+ }
327809
+ }
327810
+ function isNodeError4(error) {
327811
+ return error instanceof Error;
327812
+ }
327813
+ async function handleWebUiProjectAction(action, coordinator) {
327814
+ if (action.action === "pick") {
327815
+ const path10 = await selectOrbitProjectFolder();
327816
+ return path10 ? { ok: true, path: path10 } : { ok: true, cancelled: true };
327817
+ }
327818
+ if (action.action === "remove") {
327819
+ const removed = new ProjectRegistry().remove(action.projectId);
327820
+ return {
327821
+ ok: removed,
327822
+ message: removed ? "Project was removed from Orbit. Files were not deleted." : "Project is no longer registered."
327823
+ };
327824
+ }
327825
+ const release = coordinator.acquire("web");
327826
+ if (!release)
327827
+ return {
327828
+ ok: false,
327829
+ message: "Wait for the active task before switching projects."
327830
+ };
327831
+ try {
327832
+ const launched = await launchOrbitProject(action);
327833
+ return {
327834
+ ok: true,
327835
+ message: `Opening Orbit project: ${launched.path}`,
327836
+ url: launched.url
327837
+ };
327838
+ } catch (error) {
327839
+ return {
327840
+ ok: false,
327841
+ ...error instanceof ProjectLaunchError ? { errorCode: error.code } : {},
327842
+ message: error instanceof Error ? error.message : "Orbit could not open the selected project."
327843
+ };
327844
+ } finally {
327845
+ release();
327846
+ }
327847
+ }
327848
+
327724
327849
  // src/runtime/commands/SessionMetadataCommandHandler.ts
327725
327850
  import picocolors17 from "picocolors";
327726
327851
  import { z as z76 } from "zod";
@@ -329353,12 +329478,15 @@ var CommandRouter = class {
329353
329478
  const isZh = config.language !== "en";
329354
329479
  const { port, open } = parseWebUiArgs(parts.slice(1).join(" "), process.env);
329355
329480
  try {
329481
+ const savedPort = this.getLocalState().webUiPort;
329482
+ const preferredPort = savedPort ?? (process.connected ? 16e3 + createHash14("sha256").update(cwd).digest().readUInt16BE() % 32e3 : void 0);
329356
329483
  const handle = await startOrbitWebUi({
329357
329484
  cwd,
329358
329485
  config,
329359
329486
  loop,
329360
329487
  port,
329361
- getProjects: () => new ProjectRegistry().list().slice(0, 20),
329488
+ preferredPort,
329489
+ getProjects: () => new ProjectRegistry().list(),
329362
329490
  getAgentRuns: () => {
329363
329491
  const store = new AgentRunStore(cwd);
329364
329492
  store.initialize();
@@ -329423,38 +329551,15 @@ var CommandRouter = class {
329423
329551
  };
329424
329552
  },
329425
329553
  exportTrace: (includeHistory) => loop.exportSessionTrace(includeHistory),
329426
- openProject: async (action) => {
329427
- if (action.action === "pick") {
329428
- const path10 = await selectOrbitProjectFolder();
329429
- return path10 ? { ok: true, path: path10 } : { ok: true, cancelled: true };
329430
- }
329431
- if (action.action === "remove") {
329432
- const removed = new ProjectRegistry().remove(action.projectId);
329433
- return {
329434
- ok: removed,
329435
- message: removed ? "Project was removed from Orbit. Files were not deleted." : "Project is no longer registered."
329436
- };
329437
- }
329438
- try {
329439
- const launched = await launchOrbitProject(action);
329440
- this.onProjectHandoff?.();
329441
- return {
329442
- ok: true,
329443
- message: `Opening Orbit project: ${launched.path}`,
329444
- url: launched.url
329445
- };
329446
- } catch (error) {
329447
- return {
329448
- ok: false,
329449
- ...error instanceof ProjectLaunchError ? { errorCode: error.code } : {},
329450
- message: error instanceof Error ? error.message : "Orbit could not open the selected project."
329451
- };
329452
- }
329453
- },
329554
+ onProjectHandoff: this.onProjectHandoff,
329555
+ openProject: (action) => handleWebUiProjectAction(action, this.runCoordinator),
329454
329556
  getPendingApproval: () => this.webApprovalBroker.getPending(),
329455
329557
  respondToApproval: (decision2) => this.webApprovalBroker.respond(decision2),
329456
329558
  invalidateSkills: () => loop.invalidateSkillsCache()
329457
329559
  });
329560
+ if (handle.port >= 1024 && savedPort !== handle.port && (port !== void 0 || !savedPort)) {
329561
+ this.saveLocalState({ webUiPort: handle.port });
329562
+ }
329458
329563
  if (typeof process.send === "function" && process.connected) {
329459
329564
  try {
329460
329565
  process.send({
@@ -331128,6 +331233,7 @@ var LocalSkillsStateSchema = z85.object({
331128
331233
  disabled: z85.array(z85.string().min(1).max(128)).max(1e3).optional()
331129
331234
  });
331130
331235
  var LocalRuntimeStateSchema = z85.object({
331236
+ webUiPort: z85.number().int().min(1024).max(65535).optional().catch(void 0),
331131
331237
  lastSessionId: z85.string().min(1).max(1e3).optional(),
331132
331238
  lastProvider: z85.string().min(1).max(256).optional(),
331133
331239
  lastModel: z85.string().max(512).optional(),
@@ -331856,14 +331962,8 @@ Risk Warning: ${reason}`);
331856
331962
  resolveProjectHandoff = resolveHandoff;
331857
331963
  });
331858
331964
  const handleProjectHandoff = () => {
331859
- const timer = setTimeout(() => {
331860
- if (this.webUiOnly) {
331861
- resolveProjectHandoff?.();
331862
- } else {
331863
- void stopOrbitWebUi();
331864
- }
331865
- }, 750);
331866
- timer.unref();
331965
+ if (this.webUiOnly) resolveProjectHandoff?.();
331966
+ else void stopOrbitWebUi();
331867
331967
  };
331868
331968
  const commandRouter = new CommandRouter(
331869
331969
  this.cwd,
@@ -333536,7 +333636,7 @@ function errorMessage4(error) {
333536
333636
 
333537
333637
  // src/commands/acp.ts
333538
333638
  import picocolors29 from "picocolors";
333539
- import { createHash as createHash15 } from "node:crypto";
333639
+ import { createHash as createHash16 } from "node:crypto";
333540
333640
  import { dirname as dirname15 } from "node:path";
333541
333641
  import { existsSync as existsSync29, mkdirSync as mkdirSync9 } from "node:fs";
333542
333642
 
@@ -337245,7 +337345,7 @@ var legacyClientNotificationMethods = /* @__PURE__ */ new Set([
337245
337345
  ]);
337246
337346
 
337247
337347
  // ../acp/dist/index.js
337248
- import { createHash as createHash14, createPublicKey as createPublicKey4, verify as verifySignature4 } from "node:crypto";
337348
+ import { createHash as createHash15, createPublicKey as createPublicKey4, verify as verifySignature4 } from "node:crypto";
337249
337349
  import { homedir as homedir12 } from "node:os";
337250
337350
  import { existsSync as existsSync28, lstatSync as lstatSync10 } from "node:fs";
337251
337351
  import { join as join19, resolve as resolve27 } from "node:path";
@@ -337944,7 +338044,7 @@ function buildAcpRegistrySignaturePayload(file) {
337944
338044
  agents: file.agents,
337945
338045
  ...file.metadata ? { metadata: file.metadata } : {}
337946
338046
  };
337947
- const digest = createHash14("sha256").update(canonicalJsonStringify(unsigned), "utf8").digest("hex");
338047
+ const digest = createHash15("sha256").update(canonicalJsonStringify(unsigned), "utf8").digest("hex");
337948
338048
  return {
337949
338049
  digest,
337950
338050
  payload: canonicalJsonStringify({ registry: unsigned, digest })
@@ -338643,7 +338743,7 @@ async function importAcpHistory(cwd, agentId, externalSessionId, config, options
338643
338743
  if (messages.length === 0) {
338644
338744
  throw new Error("ACP session/load returned no importable history.");
338645
338745
  }
338646
- const digest = createHash15("sha256").update(
338746
+ const digest = createHash16("sha256").update(
338647
338747
  canonicalJsonStringify({
338648
338748
  externalSessionId,
338649
338749
  updates: history.updates.map(({ sessionUpdate, data }) => ({
@@ -340031,7 +340131,7 @@ import {
340031
340131
  writeFileSync as writeFileSync10
340032
340132
  } from "fs";
340033
340133
  import { basename as basename9, dirname as dirname17, join as join27, relative as relative14, resolve as resolve18 } from "path";
340034
- import { createHash as createHash16, randomUUID as randomUUID26 } from "crypto";
340134
+ import { createHash as createHash17, randomUUID as randomUUID26 } from "crypto";
340035
340135
  import { promisify as promisify5 } from "util";
340036
340136
  import picocolors33 from "picocolors";
340037
340137
  import { parse as parseYaml5 } from "yaml";
@@ -340373,7 +340473,7 @@ function computeAcceptanceFixtureHash(cwd, fixturePaths) {
340373
340473
  const normalized = relative14(resolve18(cwd), absolutePath).replace(/\\/g, "/");
340374
340474
  visit(normalized, absolutePath);
340375
340475
  }
340376
- const digest = createHash16("sha256");
340476
+ const digest = createHash17("sha256");
340377
340477
  for (const directory of directories.sort()) {
340378
340478
  digest.update(`directory\0${directory}\0`, "utf8");
340379
340479
  }
@@ -340896,7 +340996,7 @@ import picocolors35 from "picocolors";
340896
340996
  // ../daemon/dist/index.js
340897
340997
  import { z as z105 } from "zod";
340898
340998
  import { z as z312 } from "zod";
340899
- import { createHash as createHash17 } from "crypto";
340999
+ import { createHash as createHash18 } from "crypto";
340900
341000
  import {
340901
341001
  appendFileSync,
340902
341002
  closeSync as closeSync7,
@@ -341187,7 +341287,7 @@ var DaemonAuditLog = class {
341187
341287
  const now = input.now ?? /* @__PURE__ */ new Date();
341188
341288
  const base = {
341189
341289
  schemaVersion: 1,
341190
- id: `audit_${createHash17("sha256").update(`${now.toISOString()}\0${this.entries}\0${this.lastDigest}`).digest("hex").slice(0, 32)}`,
341290
+ id: `audit_${createHash18("sha256").update(`${now.toISOString()}\0${this.entries}\0${this.lastDigest}`).digest("hex").slice(0, 32)}`,
341191
341291
  timestamp: now.toISOString(),
341192
341292
  principalId: input.principalId,
341193
341293
  authMethod: input.authMethod,
@@ -341198,7 +341298,7 @@ var DaemonAuditLog = class {
341198
341298
  metadata: sanitizeMetadata(input.metadata),
341199
341299
  previousDigest: this.lastDigest
341200
341300
  };
341201
- const digest = createHash17("sha256").update(canonicalJsonStringify(base), "utf8").digest("hex");
341301
+ const digest = createHash18("sha256").update(canonicalJsonStringify(base), "utf8").digest("hex");
341202
341302
  const entry = DaemonAuditEntrySchema.parse({ ...base, digest });
341203
341303
  const serialized = `${JSON.stringify(entry)}
341204
341304
  `;
@@ -341264,7 +341364,7 @@ var DaemonAuditLog = class {
341264
341364
  if (entry.previousDigest !== previous)
341265
341365
  throw new Error(`hash-chain break at entry ${index + 1}`);
341266
341366
  const { digest, ...base } = entry;
341267
- const expected = createHash17("sha256").update(canonicalJsonStringify(base), "utf8").digest("hex");
341367
+ const expected = createHash18("sha256").update(canonicalJsonStringify(base), "utf8").digest("hex");
341268
341368
  if (digest !== expected)
341269
341369
  throw new Error(`digest mismatch at entry ${index + 1}`);
341270
341370
  previous = digest;
@@ -343719,7 +343819,7 @@ import {
343719
343819
  rmSync as rmSync13,
343720
343820
  writeFileSync as writeFileSync12
343721
343821
  } from "fs";
343722
- import { createHash as createHash18, randomUUID as randomUUID27 } from "crypto";
343822
+ import { createHash as createHash19, randomUUID as randomUUID27 } from "crypto";
343723
343823
  import { dirname as dirname19, isAbsolute as isAbsolute12, join as join31, relative as relative16, resolve as resolve30, sep as sep5 } from "path";
343724
343824
  import { z as z107 } from "zod";
343725
343825
  var MAX_BACKUP_BYTES = 64 * 1024 * 1024;
@@ -344046,7 +344146,7 @@ function normalizeBundlePath(filePath) {
344046
344146
  return normalized;
344047
344147
  }
344048
344148
  function hash2(content) {
344049
- return createHash18("sha256").update(content).digest("hex");
344149
+ return createHash19("sha256").update(content).digest("hex");
344050
344150
  }
344051
344151
  function formatBytes3(bytes) {
344052
344152
  return `${Math.round(bytes / (1024 * 1024))} MiB`;