+ >
+ ) : null}
>
)}
diff --git a/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx b/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx
index 79621746c6..25e4bc288e 100644
--- a/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx
+++ b/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx
@@ -69,7 +69,9 @@ import {
ensureBwrapToastKind,
probeRootDir,
rootDirProbeMessage,
+ createWorkspaceSelection,
shouldProbeRootDir,
+ shouldProbeWorkspaceDir,
supportsHostSkillPackages,
validatePathMappings,
type PathMapping,
@@ -236,6 +238,8 @@ export default function CreateFromExpertDrawer({
backend_choice: string;
composite_default: string;
root_dir?: string;
+ workspace_dir?: string;
+ workspace_dir_auto?: string;
skill_package_ids?: string[];
knowledge_base_ids?: string[];
mcp_servers?: string[];
@@ -333,6 +337,8 @@ export default function CreateFromExpertDrawer({
conversation_mode: DEFAULT_CONVERSATION_MODE,
backend_choice: DEFAULT_BACKEND,
composite_default: DEFAULT_BACKEND,
+ workspace_dir: "",
+ workspace_dir_auto: "",
skill_package_ids: [],
knowledge_base_ids: [],
mcp_servers: [],
@@ -430,6 +436,33 @@ export default function CreateFromExpertDrawer({
return;
}
}
+ const autoWorkspaceDir = form.getFieldValue("workspace_dir_auto");
+ const workspaceSelection = createWorkspaceSelection({
+ backendChoice: values.backend_choice,
+ rootDir: values.root_dir,
+ workspaceDir: values.workspace_dir,
+ autoWorkspaceDir,
+ agentId: values.agent_id,
+ });
+ const workspaceDir = workspaceSelection.workspaceDir;
+ if (
+ workspaceDir &&
+ shouldProbeWorkspaceDir(
+ values.backend_choice,
+ workspaceDir,
+ autoWorkspaceDir,
+ )
+ ) {
+ const probe = await probeRootDir(workspaceDir);
+ if (!probe.ok) {
+ message.error(
+ `${rootDirProbeMessage(probe, t)}\n${t(
+ "experts.rootDirProbe.guidance",
+ )}`,
+ );
+ return;
+ }
+ }
setSubmitting(true);
let bwrapToast: { kind: "success" | "warning"; text: string } | null = null;
try {
@@ -462,9 +495,10 @@ export default function CreateFromExpertDrawer({
const payload = {
name: values.name,
description: values.description || undefined,
- agent_id: values.agent_id?.trim() || undefined,
+ agent_id: workspaceSelection.agentId,
default_model: defaultModelFromForm(values.default_model) ?? undefined,
backend: backendSpec,
+ ...(workspaceDir ? { workspace_dir: workspaceDir } : {}),
skill_package_ids: skillPackagesSupported
? values.skill_package_ids ?? []
: [],
diff --git a/dashboard/src/pages/Experts/components/EditAgentDrawer.tsx b/dashboard/src/pages/Experts/components/EditAgentDrawer.tsx
index 30d28d26a4..213c328732 100644
--- a/dashboard/src/pages/Experts/components/EditAgentDrawer.tsx
+++ b/dashboard/src/pages/Experts/components/EditAgentDrawer.tsx
@@ -152,6 +152,7 @@ interface EditFormValues {
backend_choice: string;
composite_default: string;
root_dir?: string;
+ workspace_dir?: string;
max_iters?: number;
max_input_length?: number;
temperature?: number;
@@ -331,6 +332,8 @@ function EditAgentDrawerBody({
backend_choice: parsedBackend.backendChoice,
composite_default: parsedBackend.compositeDefault,
root_dir: parsedBackend.rootDir,
+ workspace_dir:
+ typeof cfg.workspace_dir === "string" ? cfg.workspace_dir : "",
...readAgentRuntimeFormValues(ag),
enable_trajectory: cfg.enable_trajectory !== false,
knowledge_base_ids: Array.isArray(ag.knowledge_base_ids)
diff --git a/dashboard/src/pages/Experts/components/ExpertAvatarPicker.tsx b/dashboard/src/pages/Experts/components/ExpertAvatarPicker.tsx
index 61e8b805d1..270095d81b 100644
--- a/dashboard/src/pages/Experts/components/ExpertAvatarPicker.tsx
+++ b/dashboard/src/pages/Experts/components/ExpertAvatarPicker.tsx
@@ -1,5 +1,6 @@
import {
EXPERT_AVATAR_PRESETS,
+ canonicalExpertPresetId,
expertPresetSrc,
ResourceAvatarPicker,
splitExpertAvatarUrl,
@@ -30,8 +31,8 @@ export default function ExpertAvatarPicker({
onRemove,
}: ExpertAvatarPickerProps) {
const { imageUrl, presetId: rawPresetId } = splitExpertAvatarUrl(iconUrl);
- // First grid tile is ``default.svg``; keep that URL on the same tile.
- const presetId = rawPresetId === "default" ? null : rawPresetId;
+ // First grid tile is ``default.svg``. Duplicate drawings share that tile.
+ const presetId = canonicalExpertPresetId(rawPresetId);
return (
();
- const { models, modelsLoading } = useAgentFormResources(open);
+ const { models, modelsLoading, backends, backendsLoading } =
+ useAgentFormResources(open);
const [submitting, setSubmitting] = useState(false);
+ const [pathMappings, setPathMappings] = useState([]);
const [templateFiles, setTemplateFiles] = useState([]);
const [templateLoading, setTemplateLoading] = useState(false);
const [rosterExtras, setRosterExtras] = useState([]);
@@ -80,11 +104,14 @@ export default function TeamDrawer({
() => mergeTeamPickerExperts(experts, rosterExtras),
[experts, rosterExtras],
);
+ const backendChoice =
+ Form.useWatch("backend_choice", form) ?? DEFAULT_BACKEND;
useEffect(() => {
if (!open) {
iconTouchedRef.current = false;
setRosterExtras([]);
+ setPathMappings([]);
return;
}
iconTouchedRef.current = false;
@@ -95,10 +122,35 @@ export default function TeamDrawer({
default_model: defaultModelToForm(team.default_model),
welcome_message: team.welcome_message ?? "",
member_ids: team.member_ids ?? [],
+ backend_choice: DEFAULT_BACKEND,
+ composite_default: DEFAULT_BACKEND,
+ root_dir: undefined,
+ workspace_dir: "",
});
+ setPathMappings([]);
setIconUrl(team.icon_url?.trim() || TEAM_AVATAR_URL);
setAvatarFile(null);
let cancelled = false;
+ void request<{
+ config?: { backend?: unknown; workspace_dir?: unknown };
+ }>(`/agents/${team.agent_id}`)
+ .then((detail) => {
+ if (cancelled) return;
+ const cfg = detail.config ?? {};
+ const parsed = parseBackendSpec(cfg.backend);
+ const workspace =
+ typeof cfg.workspace_dir === "string" ? cfg.workspace_dir : "";
+ setPathMappings(parsed.pathMappings);
+ form.setFieldsValue({
+ backend_choice: parsed.backendChoice,
+ composite_default: parsed.compositeDefault,
+ root_dir: parsed.rootDir,
+ workspace_dir: workspace,
+ });
+ })
+ .catch(() => {
+ if (!cancelled) setPathMappings([]);
+ });
void teamsApi
.get(team.agent_id)
.then((record) => {
@@ -139,7 +191,13 @@ export default function TeamDrawer({
default_model: MODEL_AUTO_VALUE,
welcome_message: t("experts.teams.welcomeDefault"),
member_ids: [],
+ backend_choice: DEFAULT_BACKEND,
+ composite_default: DEFAULT_BACKEND,
+ root_dir: undefined,
+ workspace_dir: "",
+ workspace_dir_auto: "",
});
+ setPathMappings([]);
setIconUrl(TEAM_AVATAR_URL);
setAvatarFile(null);
setRosterExtras([]);
@@ -169,8 +227,74 @@ export default function TeamDrawer({
const blocked = submitting || hasNoModels;
const { imageUrl, presetId } = splitExpertAvatarUrl(iconUrl);
+ const addPathMapping = () =>
+ setPathMappings((prev) => [...prev, { path: "", backend: "" }]);
+ const removePathMapping = (index: number) =>
+ setPathMappings((prev) => prev.filter((_, i) => i !== index));
+ const updatePathMapping = (
+ index: number,
+ field: keyof PathMapping,
+ value: string,
+ ) =>
+ setPathMappings((prev) =>
+ prev.map((mapping, i) =>
+ i === index ? { ...mapping, [field]: value } : mapping,
+ ),
+ );
+
const handleSubmit = async () => {
const values = await form.validateFields();
+ if (mode === "create" && values.backend_choice === "composite") {
+ const pathError = validatePathMappings(pathMappings, t);
+ if (pathError) {
+ message.error(pathError);
+ return;
+ }
+ }
+ if (
+ mode === "create" &&
+ shouldProbeRootDir(values.backend_choice, values.root_dir)
+ ) {
+ const probe = await probeRootDir(values.root_dir ?? "/");
+ if (!probe.ok) {
+ message.error(
+ `${rootDirProbeMessage(probe, t)}\n${t(
+ "experts.rootDirProbe.guidance",
+ )}`,
+ );
+ return;
+ }
+ }
+ const autoWorkspaceDir =
+ mode === "create" ? form.getFieldValue("workspace_dir_auto") : undefined;
+ const workspaceSelection =
+ mode === "create"
+ ? createWorkspaceSelection({
+ backendChoice: values.backend_choice,
+ rootDir: values.root_dir,
+ workspaceDir: values.workspace_dir,
+ autoWorkspaceDir,
+ })
+ : { workspaceDir: undefined, agentId: undefined };
+ const workspaceDir = workspaceSelection.workspaceDir;
+ if (
+ workspaceDir &&
+ shouldProbeWorkspaceDir(
+ values.backend_choice,
+ workspaceDir,
+ autoWorkspaceDir,
+ )
+ ) {
+ const probe = await probeRootDir(workspaceDir);
+ if (!probe.ok) {
+ message.error(
+ `${rootDirProbeMessage(probe, t)}\n${t(
+ "experts.rootDirProbe.guidance",
+ )}`,
+ );
+ return;
+ }
+ }
const body = {
name: values.name.trim(),
description: values.description?.trim() || null,
@@ -182,8 +306,25 @@ export default function TeamDrawer({
welcome_message: values.welcome_message?.trim() || null,
member_ids: selectedRosterIds(values.member_ids, pickerExperts),
};
+ const backendSpec = buildBackendSpec(
+ values.backend_choice,
+ values.composite_default ?? DEFAULT_BACKEND,
+ pathMappings,
+ values.root_dir,
+ );
setSubmitting(true);
+ let bwrapToast: { kind: "success" | "warning"; text: string } | null = null;
try {
+ if (
+ mode === "create" &&
+ shouldProbeRootDir(values.backend_choice, values.root_dir)
+ ) {
+ const bwrap = await ensureBubblewrapAfterProbe();
+ const kind = ensureBwrapToastKind(bwrap.status);
+ if (kind !== "none") {
+ bwrapToast = { kind, text: ensureBwrapMessage(bwrap, t) };
+ }
+ }
const saved =
mode === "edit" && team
? await teamsApi.update(team.agent_id, body)
@@ -191,6 +332,13 @@ export default function TeamDrawer({
...body,
name: body.name,
member_ids: body.member_ids,
+ ...(workspaceSelection.agentId
+ ? { agent_id: workspaceSelection.agentId }
+ : {}),
+ config: {
+ backend: backendSpec,
+ ...(workspaceDir ? { workspace_dir: workspaceDir } : {}),
+ },
});
if (avatarFile) {
try {
@@ -208,6 +356,11 @@ export default function TeamDrawer({
? t("experts.teams.updated")
: t("experts.teams.created"),
);
+ if (bwrapToast?.kind === "success") {
+ message.success(bwrapToast.text);
+ } else if (bwrapToast?.kind === "warning") {
+ message.warning(bwrapToast.text);
+ }
onSaved(saved);
} catch (err: unknown) {
message.error(apiErrorMessage(err, t("experts.createFailed"), t));
@@ -435,6 +588,17 @@ export default function TeamDrawer({
optionFilterProp="label"
/>
+ WORKSPACE_ID_ALPHABET[b & 31]).join("");
+ if (!RESERVED_WORKSPACE_IDS.has(id.toLowerCase())) return id;
+ }
+}
+
+export function joinWorkspaceDir(parent: string, agentId: string): string {
+ return `${parent.replace(/[/\\]+$/, "")}/${agentId}`;
+}
+
+export function workspaceDirBasename(path: string): string {
+ const trimmed = path.trim().replace(/[/\\]+$/, "");
+ const idx = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
+ return idx >= 0 ? trimmed.slice(idx + 1) : trimmed;
+}
+
+/**
+ * Workspace directory the user may assign.
+ *
+ * Only host-rooted ``local_shell`` / ``filesystem`` accept one. A blank value
+ * means "let the server pick the default".
+ */
+export function userWorkspaceDir(options: {
+ backendChoice: string;
+ rootDir?: string | null;
+ workspaceDir?: string | null;
+}): string | undefined {
+ if (
+ options.backendChoice !== "local_shell" &&
+ options.backendChoice !== "filesystem"
+ ) {
+ return undefined;
+ }
+ if (!isHostRootDir(options.rootDir)) return undefined;
+ const text = options.workspaceDir?.trim() ?? "";
+ return text || undefined;
+}
+
+/**
+ * Create payload for a host-root workspace.
+ *
+ * The prefilled default is ``{OCTOP_HOME}/agents/``. Sending that path
+ * together with the same id keeps the folder the server would have chosen.
+ */
+export function createWorkspaceSelection(options: {
+ backendChoice: string;
+ rootDir?: string | null;
+ workspaceDir?: string | null;
+ autoWorkspaceDir?: string | null;
+ agentId?: string | null;
+}): { workspaceDir?: string; agentId?: string } {
+ const workspaceDir = userWorkspaceDir(options);
+ const typed = options.agentId?.trim() || undefined;
+ const auto = options.autoWorkspaceDir?.trim() || "";
+ if (workspaceDir && auto && workspaceDir === auto) {
+ const fromPath = workspaceDirBasename(workspaceDir);
+ return { workspaceDir, agentId: typed || fromPath || undefined };
+ }
+ return { workspaceDir, agentId: typed };
+}
+
+export function shouldProbeWorkspaceDir(
+ choice: string,
+ workspaceDir?: string | null,
+ autoWorkspaceDir?: string | null,
+): boolean {
+ const text = workspaceDir?.trim() ?? "";
+ if (!text) return false;
+ const auto = autoWorkspaceDir?.trim() || "";
+ if (auto && text === auto) return false;
+ return shouldProbeRootDir(choice, text);
+}
+
export function shouldProbeRootDir(choice: string, rootDir?: string): boolean {
if (!needsRootDirProbe(choice)) return false;
return !isHostRootDir(rootDir);
diff --git a/dashboard/src/pages/Experts/components/agentBackendForm.workspaceDir.test.ts b/dashboard/src/pages/Experts/components/agentBackendForm.workspaceDir.test.ts
new file mode 100644
index 0000000000..177a8e8af2
--- /dev/null
+++ b/dashboard/src/pages/Experts/components/agentBackendForm.workspaceDir.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import {
+ createWorkspaceSelection,
+ joinWorkspaceDir,
+ newWorkspaceAgentId,
+ userWorkspaceDir,
+} from "./agentBackendForm";
+
+describe("userWorkspaceDir", () => {
+ it("returns a trimmed path for host-root local backends", () => {
+ expect(
+ userWorkspaceDir({
+ backendChoice: "local_shell",
+ rootDir: "/",
+ workspaceDir: " /data/work ",
+ }),
+ ).toBe("/data/work");
+ expect(
+ userWorkspaceDir({
+ backendChoice: "filesystem",
+ rootDir: "C:/",
+ workspaceDir: "D:/projects",
+ }),
+ ).toBe("D:/projects");
+ });
+
+ it("omits the field when the root is scoped or the value is blank", () => {
+ expect(
+ userWorkspaceDir({
+ backendChoice: "local_shell",
+ rootDir: "/data/jail",
+ workspaceDir: "/data/work",
+ }),
+ ).toBeUndefined();
+ expect(
+ userWorkspaceDir({
+ backendChoice: "composite",
+ rootDir: "/",
+ workspaceDir: "/data/work",
+ }),
+ ).toBeUndefined();
+ expect(
+ userWorkspaceDir({
+ backendChoice: "filesystem",
+ rootDir: "/",
+ workspaceDir: " ",
+ }),
+ ).toBeUndefined();
+ });
+
+ it("keeps the prefilled default path tied to its id", () => {
+ const id = newWorkspaceAgentId();
+ expect(id).toMatch(/^[0-9A-HJKMNP-TV-Z]{6}$/);
+ const path = joinWorkspaceDir("/home/u/.octop/agents", id);
+ expect(
+ createWorkspaceSelection({
+ backendChoice: "local_shell",
+ rootDir: "/",
+ workspaceDir: path,
+ autoWorkspaceDir: path,
+ }),
+ ).toEqual({ workspaceDir: path, agentId: id });
+ expect(
+ createWorkspaceSelection({
+ backendChoice: "local_shell",
+ rootDir: "/",
+ workspaceDir: "/data/work",
+ autoWorkspaceDir: path,
+ agentId: "custom1",
+ }),
+ ).toEqual({ workspaceDir: "/data/work", agentId: "custom1" });
+ });
+});
diff --git a/dashboard/src/pages/Experts/components/sharedExpert.test.ts b/dashboard/src/pages/Experts/components/sharedExpert.test.ts
index b5d95b6f86..8472f0eb78 100644
--- a/dashboard/src/pages/Experts/components/sharedExpert.test.ts
+++ b/dashboard/src/pages/Experts/components/sharedExpert.test.ts
@@ -39,6 +39,12 @@ describe("isSharedExpertViewer", () => {
false,
);
});
+
+ it("keeps workspace tools for the owning account even if is_owner is false", () => {
+ const owned = { is_shared: true, is_owner: false, user_id: 7 };
+ expect(isSharedExpertViewer(owned, { id: 7 })).toBe(false);
+ expect(isSharedExpertViewer(owned, { id: 8 })).toBe(true);
+ });
});
describe("chatSkillCatalogAgentId", () => {
diff --git a/dashboard/src/utils/parseHarnessChunk.ts b/dashboard/src/utils/parseHarnessChunk.ts
index ad596c9bd5..47a16ae3c6 100644
--- a/dashboard/src/utils/parseHarnessChunk.ts
+++ b/dashboard/src/utils/parseHarnessChunk.ts
@@ -24,6 +24,8 @@ export interface TokenChunk {
team_live?: boolean;
/** Host wrap-up after members finish — start a new bubble, do not continue dispatch. */
team_wrapup?: boolean;
+ /** Server turn. Chunks from another turn must not join this bubble. */
+ turn_id?: string;
}
export interface ReasoningChunk {
@@ -31,6 +33,8 @@ export interface ReasoningChunk {
content: string;
/** Team-room speaker when this reasoning was fanned in from another agent. */
agent_id?: string;
+ /** Server turn. A new id starts a new thinking block. */
+ turn_id?: string;
}
export interface ToolCallChunk {
@@ -195,12 +199,14 @@ export function parseHarnessChunk(line: string): HarnessChunk | null {
team_snapshot: obj.team_snapshot === true,
team_live: obj.team_live === true,
team_wrapup: obj.team_wrapup === true,
+ turn_id: optionalTurnId(obj),
};
case "reasoning":
return {
type: "reasoning",
content: typeof obj.content === "string" ? obj.content : "",
agent_id: agentId,
+ turn_id: optionalTurnId(obj),
};
case "usage":
return {
@@ -337,6 +343,13 @@ export function streamSpeakerId(
return optionalAgentId(chunk as Record);
}
+function optionalTurnId(obj: Record): string | undefined {
+ const raw = obj.turn_id;
+ if (typeof raw !== "string") return undefined;
+ const value = raw.trim();
+ return value || undefined;
+}
+
function optionalAgentId(obj: Record): string | undefined {
for (const key of ["agent_id", "agent", "speaker_agent_id"] as const) {
const raw = obj[key];
diff --git a/dashboard/src/utils/sharedExpert.ts b/dashboard/src/utils/sharedExpert.ts
index 4f2c6daa3d..e7c217c3c3 100644
--- a/dashboard/src/utils/sharedExpert.ts
+++ b/dashboard/src/utils/sharedExpert.ts
@@ -3,6 +3,8 @@ import { isTeamAgent } from "./teamAgent";
export interface SharedExpertAccess {
is_shared?: boolean;
is_owner?: boolean;
+ /** Owning user id from the agent list. Used when ``is_owner`` is missing or stale. */
+ user_id?: number | null;
}
/** Owner or admin. Matches ``assert_agent_owner`` on ``GET /agents/{id}/status``. */
@@ -14,7 +16,26 @@ export function canReadAgentRuntimeStatus(
return agent.is_owner !== false;
}
-export function isSharedExpertViewer(agent: SharedExpertAccess): boolean {
+function sameUserId(
+ left: number | null | undefined,
+ right: number | null | undefined,
+): boolean {
+ if (left == null || right == null) return false;
+ return Number(left) === Number(right);
+}
+
+/**
+ * Share-only viewer: the expert is shared and this account does not own it.
+ *
+ * The owner keeps workspace and file tools after sharing. A matching
+ * ``user_id`` counts as ownership even if ``is_owner`` was dropped or false.
+ */
+export function isSharedExpertViewer(
+ agent: SharedExpertAccess,
+ viewer?: { id?: number | null } | null,
+): boolean {
+ if (agent.is_owner === true) return false;
+ if (sameUserId(agent.user_id, viewer?.id)) return false;
return agent.is_shared === true && agent.is_owner === false;
}
diff --git a/src/octop/api/routers/agents.py b/src/octop/api/routers/agents.py
index f4c4dbf933..0ec5b9d518 100644
--- a/src/octop/api/routers/agents.py
+++ b/src/octop/api/routers/agents.py
@@ -171,6 +171,16 @@ def _viewer_mcp_servers(
return list(present(owner_id, viewer_user_id, names))
+def _same_user_id(left: Any, right: Any) -> bool:
+ """True when both ids are present and numerically equal."""
+ if left is None or right is None:
+ return False
+ try:
+ return int(left) == int(right)
+ except (TypeError, ValueError):
+ return False
+
+
def _row_dict(
row: Any,
*,
@@ -220,7 +230,7 @@ def _row_dict(
"published_expert_id": row.published_expert_id,
"welcome_message": welcome_from_row(row),
"is_shared": bool(int(getattr(row, "is_shared", 0) or 0)),
- "is_owner": row.user_id is not None and row.user_id == viewer_user_id,
+ "is_owner": _same_user_id(row.user_id, viewer_user_id),
"owner_username": owner_username,
"kind": getattr(row, "kind", None) or "expert",
**agent_runtime_values(cfg),
diff --git a/src/octop/api/routers/chat/ws.py b/src/octop/api/routers/chat/ws.py
index 0460a85ab5..6783c8e04a 100644
--- a/src/octop/api/routers/chat/ws.py
+++ b/src/octop/api/routers/chat/ws.py
@@ -223,6 +223,23 @@ def _subscribe(tid: str = thread_id, cid: str = connection_id) -> None:
# connections that are not subscribed yet.
hub.subscribe(prepared_early.thread_id, connection_id)
+ thread_row = gateway.thread_registry.get_thread(prepared_early.thread_id)
+ if gateway.steer.blocks_other_sender(prepared_early.thread_id, user.id) and bool(
+ getattr(thread_row, "contributed", False)
+ ):
+ active = gateway.steer.get_state(prepared_early.thread_id)
+ await send_frame(
+ {
+ "type": "turn.busy",
+ "thread_id": prepared_early.thread_id,
+ "reason": "shared_turn_busy",
+ "message_id": _ws_client_message_id(frame),
+ "client_pending_id": frame.client_pending_id,
+ "active_turn_id": active.turn_id if active is not None else None,
+ }
+ )
+ continue
+
hitl_paused = _thread_hitl_paused(gateway, prepared_early.thread_id, agent_id)
if not hitl_paused:
# A turn parked at an HITL interrupt leaves ``phase='hitl_paused'``
@@ -613,6 +630,14 @@ def _clear_stale_hitl_park(gateway: Any, thread_id: str) -> None:
logger.exception("failed to clear stale hitl park thread=%s", thread_id)
+def _ws_client_message_id(frame: UserTurnWsFrame) -> str | None:
+ for item in frame.messages or []:
+ raw = item.get("id") if isinstance(item, dict) else None
+ if isinstance(raw, str) and raw.strip():
+ return raw.strip()
+ return None
+
+
def _thread_hitl_paused(gateway: Any, thread_id: str, agent_id: str) -> bool:
processor = getattr(gateway, "processor", None)
hitl = getattr(processor, "hitl_coordinator", None) if processor is not None else None
diff --git a/src/octop/api/routers/experts.py b/src/octop/api/routers/experts.py
index 46902a36c5..94820c119c 100644
--- a/src/octop/api/routers/experts.py
+++ b/src/octop/api/routers/experts.py
@@ -148,6 +148,14 @@ class FromExpertBody(AgentRuntimeFields):
providers: list[str] | None = None
default_model: str | None = None
backend: dict[str, Any] | None = None
+ workspace_dir: str | None = Field(
+ default=None,
+ description=(
+ "Workspace directory when backend is local_shell or filesystem "
+ "rooted at the filesystem root. Ignored for other backends and "
+ "for a scoped root_dir. Omit to use the server default."
+ ),
+ )
skill_package_ids: list[str] | None = None
knowledge_base_ids: list[str] | None = None
mcp_servers: list[str] | None = None
@@ -195,6 +203,14 @@ class InstallPublishedExpertBody(AgentRuntimeFields):
providers: list[str] | None = None
default_model: str | None = None
backend: dict[str, Any] | None = None
+ workspace_dir: str | None = Field(
+ default=None,
+ description=(
+ "Workspace directory when backend is local_shell or filesystem "
+ "rooted at the filesystem root. Ignored for other backends and "
+ "for a scoped root_dir. Omit to use the server default."
+ ),
+ )
skill_package_ids: list[str] | None = None
knowledge_base_ids: list[str] | None = None
mcp_servers: list[str] | None = None
@@ -777,6 +793,7 @@ async def install_published_expert(
providers=body.providers,
default_model=body.default_model,
backend=body.backend,
+ workspace_dir=body.workspace_dir,
skill_package_ids=body.skill_package_ids,
knowledge_base_ids=kb_ids,
mcp_servers=servers,
@@ -924,6 +941,7 @@ async def install_expert_hub_item(
providers=body.providers,
default_model=body.default_model,
backend=body.backend,
+ workspace_dir=body.workspace_dir,
color=body.color,
agent_id=body.agent_id,
welcome_message=body.welcome_message,
@@ -1049,6 +1067,9 @@ async def create_agent_from_expert(
config_extra["providers"] = list(body.providers)
if body.backend:
config_extra["backend"] = body.backend
+ from octop.infra.agents.workspace.dir import apply_explicit_workspace_dir # noqa: PLC0415
+
+ apply_explicit_workspace_dir(config_extra, body.workspace_dir)
apply_enable_trajectory(config_extra, body.enable_trajectory)
if body.conversation_mode:
config_extra["conversation_mode"] = body.conversation_mode
diff --git a/src/octop/api/routers/filesystem.py b/src/octop/api/routers/filesystem.py
index abc84059f0..e15e314c6e 100644
--- a/src/octop/api/routers/filesystem.py
+++ b/src/octop/api/routers/filesystem.py
@@ -24,6 +24,7 @@
from pydantic import BaseModel, Field
from octop.api.deps import current_user, get_server
+from octop.infra.agents.workspace.dir import default_workspace_parent_dir
from octop.infra.errors import ErrorCode, OctopError
from octop.infra.users.identity import User
from octop.infra.users.resource_policy import (
@@ -89,14 +90,20 @@ async def filesystem_defaults(
directory. ``jail_enforced`` reports whether a non-root ``root_dir`` really
gets OS-level confinement (Linux + bubblewrap) or only bounds the agent's
tool paths, so the UI does not promise a sandbox it cannot deliver.
+
+ ``default_workspace_dir`` is ``{OCTOP_HOME}/agents``. Create forms append
+ the new expert id, which is the path the server assigns when the caller
+ does not choose one.
"""
in_container = running_in_container()
+ workspace_parent = default_workspace_parent_dir()
allowed = _user_workspace_root(server, user)
if allowed:
return {
"default_root_dir": allowed,
"tree_root": allowed,
"browse_roots": [allowed],
+ "default_workspace_dir": workspace_parent,
"jail_enforced": host_jail_enforced(),
"in_container": in_container,
}
@@ -105,6 +112,7 @@ async def filesystem_defaults(
"default_root_dir": root,
"tree_root": root,
"browse_roots": host_browse_roots(),
+ "default_workspace_dir": workspace_parent,
"jail_enforced": host_jail_enforced(),
"in_container": in_container,
}
diff --git a/src/octop/api/routers/teams.py b/src/octop/api/routers/teams.py
index 74fd5c6317..bb2a233166 100644
--- a/src/octop/api/routers/teams.py
+++ b/src/octop/api/routers/teams.py
@@ -31,7 +31,18 @@ class TeamCreateBody(BaseModel):
icon_url: str | None = None
welcome_message: str | None = None
member_ids: list[str] = Field(default_factory=list)
- config: dict[str, Any] = Field(default_factory=dict)
+ agent_id: str | None = Field(
+ default=None,
+ max_length=64,
+ description="Optional custom agent id; auto-generated when omitted",
+ )
+ config: dict[str, Any] = Field(
+ default_factory=dict,
+ description=(
+ "Harness config. ``workspace_dir`` is kept only when ``backend`` is "
+ "local_shell or filesystem rooted at the filesystem root."
+ ),
+ )
class TeamPatchBody(BaseModel):
@@ -76,8 +87,17 @@ async def create_team(
teams = _teams(server)
member_ids = teams.validate_member_ids(user, body.member_ids)
assert server.app_runtime is not None
+ from octop.infra.agents.workspace.dir import apply_explicit_workspace_dir # noqa: PLC0415
+
+ config = dict(body.config)
+ raw_workspace = config.pop("workspace_dir", None)
+ apply_explicit_workspace_dir(
+ config,
+ raw_workspace if isinstance(raw_workspace, str) else None,
+ )
spec = AgentCreateSpec(
name=body.name.strip(),
+ agent_id=(body.agent_id or "").strip() or None,
user_id=user.id,
description=body.description,
default_model=body.default_model,
@@ -87,7 +107,7 @@ async def create_team(
welcome_message=body.welcome_message,
template_name=TEAM_TEMPLATE_NAME,
kind=TEAM_KIND,
- config=body.config,
+ config=config,
member_ids=member_ids,
mcp_servers=[],
)
diff --git a/src/octop/api/routers/usage.py b/src/octop/api/routers/usage.py
index a974f2f191..01f355da02 100644
--- a/src/octop/api/routers/usage.py
+++ b/src/octop/api/routers/usage.py
@@ -11,7 +11,7 @@
window = today | yesterday | last_7d | last_30d | all
| day:YYYY-MM-DD | month:YYYY-MM
| range:YYYY-MM-DD:YYYY-MM-DD (default last_30d)
- granularity = total | by_day | by_agent | by_model (default by_day)
+ granularity = total | by_day | by_agent | by_model | by_user (default by_day)
"""
from __future__ import annotations
@@ -121,6 +121,59 @@ def _label_agent_buckets(server: Any, payload: dict[str, Any]) -> dict[str, Any]
return {**payload, "buckets": labeled}
+def _user_chart_labels(server: Any) -> dict[int, str]:
+ """Display name for ``by_user`` slices; disambiguate shared display names."""
+ rows: list[tuple[int, str, str]] = []
+ for user in server.user_manager.list_all(include_disabled=True):
+ uid = getattr(user, "id", None)
+ if uid is None:
+ continue
+ username = str(getattr(user, "username", None) or uid).strip() or str(uid)
+ display = getattr(user, "display_name", None)
+ preferred = display.strip() if isinstance(display, str) and display.strip() else username
+ rows.append((int(uid), preferred, username))
+ counts: dict[str, int] = {}
+ for _uid, preferred, _username in rows:
+ counts[preferred] = counts.get(preferred, 0) + 1
+ labels: dict[int, str] = {}
+ for uid, preferred, username in rows:
+ if counts[preferred] > 1 and preferred != username:
+ labels[uid] = f"{preferred} ({username})"
+ else:
+ labels[uid] = preferred
+ return labels
+
+
+def _label_user_buckets(server: Any, payload: dict[str, Any]) -> dict[str, Any]:
+ """Replace ``by_user`` bucket labels with display names."""
+ if str(payload.get("granularity") or "") != "by_user":
+ return payload
+ names = _user_chart_labels(server)
+ labeled: list[Any] = []
+ for bucket in payload.get("buckets") or []:
+ if not isinstance(bucket, dict):
+ labeled.append(bucket)
+ continue
+ raw_key = bucket.get("key")
+ if isinstance(raw_key, bool) or not isinstance(raw_key, (int, str)):
+ labeled.append(bucket)
+ continue
+ try:
+ uid = int(raw_key)
+ except ValueError:
+ labeled.append(bucket)
+ continue
+ name = names.get(uid, "").strip()
+ if name:
+ bucket = {**bucket, "label": name}
+ labeled.append(bucket)
+ return {**payload, "buckets": labeled}
+
+
+def _present_summary(server: Any, payload: dict[str, Any]) -> dict[str, Any]:
+ return _label_user_buckets(server, _label_agent_buckets(server, payload))
+
+
def _username_map(server: Any) -> dict[int, str]:
out: dict[int, str] = {}
users = server.user_manager.list_all(include_disabled=True)
@@ -223,7 +276,7 @@ async def user_summary(
) -> dict[str, Any]:
user_id = _resolve_user_scope(user=user, as_user=as_user, server=server)
_assert_agent_exists(server, agent_id)
- return _label_agent_buckets(
+ return _present_summary(
server,
_summary_or_raise(
server=server,
@@ -277,7 +330,7 @@ async def admin_summary(
the scope; absent both fields mean *all rows*. Admin only."""
if not user.is_admin:
raise OctopError(ErrorCode.FORBIDDEN, "admin required")
- return _label_agent_buckets(
+ return _present_summary(
server,
_summary_or_raise(
server=server,
diff --git a/src/octop/infra/agents/experts/market_creation.py b/src/octop/infra/agents/experts/market_creation.py
index bdbdd2887f..0df620c37d 100644
--- a/src/octop/infra/agents/experts/market_creation.py
+++ b/src/octop/infra/agents/experts/market_creation.py
@@ -30,6 +30,7 @@ class SkillHubMarketAgentCreateOptions:
providers: list[str] | None = None
default_model: str | None = None
backend: dict[str, Any] | None = None
+ workspace_dir: str | None = None
color: str | None = None
agent_id: str | None = None
welcome_message: str | None = None
@@ -125,6 +126,9 @@ async def create_agent_from_skillhub_skillset(
config_extra["providers"] = list(options.providers)
if options.backend:
config_extra["backend"] = options.backend
+ from octop.infra.agents.workspace.dir import apply_explicit_workspace_dir # noqa: PLC0415
+
+ apply_explicit_workspace_dir(config_extra, options.workspace_dir)
apply_enable_trajectory(config_extra, options.enable_trajectory)
if options.conversation_mode:
config_extra["conversation_mode"] = options.conversation_mode
diff --git a/src/octop/infra/agents/experts/published_creation.py b/src/octop/infra/agents/experts/published_creation.py
index 5294dfc055..b16f3f29cb 100644
--- a/src/octop/infra/agents/experts/published_creation.py
+++ b/src/octop/infra/agents/experts/published_creation.py
@@ -60,6 +60,7 @@ class PublishedExpertInstallOptions:
providers: list[str] | None = None
default_model: str | None = None
backend: dict[str, Any] | None = None
+ workspace_dir: str | None = None
skill_package_ids: list[str] | None = None
knowledge_base_ids: list[str] | None = None
mcp_servers: list[str] | None = None
@@ -440,6 +441,9 @@ async def install_published_expert(
config_extra["providers"] = list(options.providers)
if options.backend:
config_extra["backend"] = options.backend
+ from octop.infra.agents.workspace.dir import apply_explicit_workspace_dir # noqa: PLC0415
+
+ apply_explicit_workspace_dir(config_extra, options.workspace_dir)
apply_enable_trajectory(config_extra, options.enable_trajectory)
if options.conversation_mode:
config_extra["conversation_mode"] = options.conversation_mode
diff --git a/src/octop/infra/agents/manager.py b/src/octop/infra/agents/manager.py
index ae944e4e39..3524e2b3bf 100644
--- a/src/octop/infra/agents/manager.py
+++ b/src/octop/infra/agents/manager.py
@@ -848,6 +848,7 @@ async def create(
apply_workspace_root_to_config,
assert_agent_quota_available,
raise_if_backend_outside_user_root,
+ raise_if_workspace_dir_outside_user_root,
)
if spec.user_id is not None:
@@ -869,6 +870,11 @@ async def create(
spec.user_id,
config.get("backend"),
)
+ raise_if_workspace_dir_outside_user_root(
+ self._repos.user_policy_repo,
+ spec.user_id,
+ config,
+ )
self._assert_named_storage_backends(spec.user_id, config.get("backend"))
self._assert_model_ref(spec.user_id, spec.default_model)
@@ -1058,10 +1064,10 @@ def _preserve_internal_layout(
layout, so a value a client invents is dropped.
``pin_workspace_dir`` additionally pins ``workspace_dir`` to the stored value. User-facing
- updates need it — rewriting the directory silently relocates the agent's workspace, so a
- scoped or container agent would resolve to the classic layout and lose sight of its
- skills, sessions and generated files. Internal persists do not: the resolver and the
- create path must still be able to write it.
+ updates need it — rewriting the directory relocates the agent's workspace, so a scoped or
+ container agent would resolve to the classic layout and lose sight of its skills, sessions
+ and generated files. The directory is chosen at create and stays fixed. Internal persists
+ do not pin: the resolver and the create path must still be able to write it.
"""
out = dict(cfg)
row = self._repos.agent_repo.get(agent_id)
diff --git a/src/octop/infra/agents/teams/team_manager.py b/src/octop/infra/agents/teams/team_manager.py
index 3299ec3abb..0845f15298 100644
--- a/src/octop/infra/agents/teams/team_manager.py
+++ b/src/octop/infra/agents/teams/team_manager.py
@@ -155,6 +155,7 @@ def __init__(
# Room text a member has already pushed and not yet persisted.
# A refresh mid-answer has no history row; the new subscriber gets this.
self._live_member_text: dict[str, dict[str, str]] = {}
+ self._live_member_turn: dict[str, str] = {}
self._member_wall_lock = asyncio.Lock()
def replace_thread_message_repo(self, repo: Any) -> None:
@@ -319,6 +320,12 @@ def compose_followup(
async def on_reply(self, event: ReplyEvent) -> None:
self._end_job_from_reply(event)
room = str(event.source_thread_id or "").strip()
+ try:
+ await self._publish_reply(event, room)
+ finally:
+ self._finish_room_turn(room)
+
+ async def _publish_reply(self, event: ReplyEvent, room: str) -> None:
speaker = event.source_agent_id
text = (
event.error_text or "Background task did not complete."
@@ -394,8 +401,8 @@ async def stream_peer_to_room(
hold_room = self._defer_member_wall(speaker_id, member_tid, room_thread_id)
host_id = self._room_agent_id(room_thread_id) if hold_room else ""
room_open = True
- if hold_room and self._host_turn_busy(host_id, room_thread_id):
- room_open = await self._wait_host_dispatch_idle(host_id, room_thread_id)
+ room_turn_id = ""
+ completed = False
buffered: list[dict[str, Any]] = []
resume_pending: str | None = None
@@ -421,7 +428,12 @@ async def release_held_room() -> None:
frames = list(buffered)
buffered.clear()
for frame in frames:
- await self._push_room_frame(frame, room_thread_id, speaker_id)
+ await self._push_room_frame(
+ frame,
+ room_thread_id,
+ speaker_id,
+ turn_id=room_turn_id,
+ )
note_visible(frame)
if str(frame.get("type") or "") == "hitl_required":
await self._announce_member_hitl(frame, room_thread_id, speaker_id)
@@ -435,6 +447,7 @@ async def emit(chunk: dict[str, Any]) -> None:
member_thread_id=member_tid,
speaker_id=speaker_id,
include_room=False,
+ turn_id=room_turn_id,
)
buffered.append(chunk)
return
@@ -444,12 +457,19 @@ async def emit(chunk: dict[str, Any]) -> None:
room_thread_id=room_thread_id,
member_thread_id=member_tid,
speaker_id=speaker_id,
+ turn_id=room_turn_id,
)
note_visible(chunk)
if str(chunk.get("type") or "") == "hitl_required":
await self._announce_member_hitl(chunk, room_thread_id, speaker_id)
try:
+ # Capture the host turn before waiting it out. ``end_turn`` drops
+ # steer state as soon as the host goes idle, which is when members
+ # usually start.
+ room_turn_id = self._pin_room_turn(room_thread_id)
+ if hold_room and self._host_turn_busy(host_id, room_thread_id):
+ room_open = await self._wait_host_dispatch_idle(host_id, room_thread_id)
agen = self._agent_manager.stream(speaker_id, payload)
while True:
pause: dict[str, Any] | None = None
@@ -518,6 +538,7 @@ async def emit(chunk: dict[str, Any]) -> None:
self._expire_hitl(pending_id)
resume_pending = pending_id
agen = self._agent_manager.resume_hitl(speaker_id, member_tid, decisions)
+ completed = True
except Exception:
if resume_pending:
self._expire_hitl(resume_pending)
@@ -539,9 +560,14 @@ async def emit(chunk: dict[str, Any]) -> None:
room_thread_id=room_thread_id,
member_thread_id=member_tid,
speaker_id=speaker_id,
+ turn_id=room_turn_id,
)
finally:
await self._clear_live_member(room_thread_id, speaker_id)
+ self._release_room_turn(
+ room_thread_id,
+ expect_wrapup=hold_room and completed,
+ )
stream_text = "".join(text_parts).strip()
return {
"messages": await self._peer_result_messages(
@@ -578,6 +604,40 @@ def _host_turn_busy(self, host_id: str, room_thread_id: str) -> bool:
host_busy = bool(host_id) and check_host(host_id) is True if callable(check_host) else False
return turn_active or host_busy
+ def _steer(self) -> Any:
+ gateway = self._gateway
+ if gateway is None:
+ return None
+ return getattr(gateway, "steer", None)
+
+ def _pin_room_turn(self, room_thread_id: str) -> str:
+ steer = self._steer()
+ pin = getattr(steer, "pin_room_followup", None)
+ if not callable(pin) or not room_thread_id:
+ return ""
+ turn_id = pin(room_thread_id)
+ return turn_id if isinstance(turn_id, str) else ""
+
+ def _release_room_turn(self, room_thread_id: str, *, expect_wrapup: bool) -> None:
+ steer = self._steer()
+ release = getattr(steer, "release_room_followup", None)
+ if callable(release) and room_thread_id:
+ release(room_thread_id, expect_wrapup=expect_wrapup)
+
+ def _finish_room_turn(self, room_thread_id: str) -> None:
+ steer = self._steer()
+ finish = getattr(steer, "finish_room_followup", None)
+ if callable(finish) and room_thread_id:
+ finish(room_thread_id)
+
+ def _room_followup_turn_id(self, room_thread_id: str) -> str:
+ steer = self._steer()
+ current = getattr(steer, "room_followup_turn_id", None)
+ if not callable(current) or not room_thread_id:
+ return ""
+ turn_id = current(room_thread_id)
+ return turn_id if isinstance(turn_id, str) else ""
+
async def _wait_host_dispatch_idle(self, host_id: str, room_thread_id: str) -> bool:
"""Wait until the host turn is idle.
@@ -1017,13 +1077,21 @@ def _title_member_thread(self, call: PeerCall, thread_id: str, user_id: int) ->
)
self._thread_registry.set_title_if_null(thread_id, title)
- def _append_live_member(self, room_thread_id: str, speaker_id: str, piece: str) -> None:
+ def _append_live_member(
+ self,
+ room_thread_id: str,
+ speaker_id: str,
+ piece: str,
+ turn_id: str = "",
+ ) -> None:
room = room_thread_id.strip()
speaker = speaker_id.strip()
if not room or not speaker or not piece:
return
bucket = self._live_member_text.setdefault(room, {})
bucket[speaker] = bucket.get(speaker, "") + piece
+ if turn_id:
+ self._live_member_turn[room] = turn_id
async def _clear_live_member(self, room_thread_id: str, speaker_id: str) -> None:
room = room_thread_id.strip()
@@ -1037,6 +1105,7 @@ async def _clear_live_member(self, room_thread_id: str, speaker_id: str) -> None
bucket.pop(speaker, None)
if not bucket:
self._live_member_text.pop(room, None)
+ self._live_member_turn.pop(room, None)
def _live_member_frames(self, room_thread_id: str) -> list[dict[str, Any]]:
room = room_thread_id.strip()
@@ -1045,17 +1114,17 @@ def _live_member_frames(self, room_thread_id: str) -> list[dict[str, Any]]:
for speaker, text in bucket.items():
if not speaker or not text:
continue
- frames.append(
- {
- "type": "token",
- "content": text,
- "agent_id": speaker,
- "agent": speaker,
- "team_snapshot": True,
- "team_live": True,
- "thread_id": room,
- }
- )
+ frame = {
+ "type": "token",
+ "content": text,
+ "agent_id": speaker,
+ "agent": speaker,
+ "team_snapshot": True,
+ "team_live": True,
+ "thread_id": room,
+ }
+ stamped = _with_room_turn_id(frame, self._live_member_turn.get(room, ""))
+ frames.append(stamped)
return frames
async def deliver_live_member_catchup(
@@ -1083,20 +1152,25 @@ async def _relay_chunk(
member_thread_id: str,
speaker_id: str,
include_room: bool = True,
+ turn_id: str = "",
) -> None:
hub = getattr(self._gateway, "ws_hub", None) if self._gateway is not None else None
if hub is None:
return
- stamped = stamp_stream_speaker(chunk, speaker_id, include_done=True)
+ stamped = _with_room_turn_id(
+ stamp_stream_speaker(chunk, speaker_id, include_done=True),
+ turn_id,
+ )
+ member_frame = _with_room_turn_id(chunk, turn_id)
piece = str(chunk.get("content") or "") if str(chunk.get("type") or "") == "token" else ""
try:
if include_room and room_thread_id:
async with self._member_wall_lock:
await hub.push_to_thread(room_thread_id, stamped)
if piece:
- self._append_live_member(room_thread_id, speaker_id, piece)
+ self._append_live_member(room_thread_id, speaker_id, piece, turn_id)
if member_thread_id and member_thread_id != room_thread_id:
- await hub.push_to_thread(member_thread_id, chunk)
+ await hub.push_to_thread(member_thread_id, member_frame)
except Exception:
logger.warning(
"failed to relay team peer chunk speaker=%s room=%s",
@@ -1110,18 +1184,22 @@ async def _push_room_frame(
chunk: dict[str, Any],
room_thread_id: str,
speaker_id: str,
+ turn_id: str = "",
) -> None:
"""Push one already-delivered member frame onto the room wall."""
hub = getattr(self._gateway, "ws_hub", None) if self._gateway is not None else None
if hub is None or not room_thread_id:
return
- stamped = stamp_stream_speaker(chunk, speaker_id, include_done=True)
+ stamped = _with_room_turn_id(
+ stamp_stream_speaker(chunk, speaker_id, include_done=True),
+ turn_id,
+ )
piece = str(chunk.get("content") or "") if str(chunk.get("type") or "") == "token" else ""
try:
async with self._member_wall_lock:
await hub.push_to_thread(room_thread_id, stamped)
if piece:
- self._append_live_member(room_thread_id, speaker_id, piece)
+ self._append_live_member(room_thread_id, speaker_id, piece, turn_id)
except Exception:
logger.warning(
"failed to flush team room frame speaker=%s room=%s",
@@ -1452,24 +1530,31 @@ async def _push_room_snapshot(
if hub is None:
return
extra = {"team_wrapup": True} if wrapup else {"team_snapshot": True}
+ turn_id = self._room_followup_turn_id(thread_id)
try:
await hub.push_to_thread(
thread_id,
- stamp_stream_speaker(
- (
- {"type": "error", "message": body, **extra}
- if error
- else {"type": "token", "content": body, **extra}
+ _with_room_turn_id(
+ stamp_stream_speaker(
+ (
+ {"type": "error", "message": body, **extra}
+ if error
+ else {"type": "token", "content": body, **extra}
+ ),
+ speaker_id,
),
- speaker_id,
+ turn_id,
),
)
await hub.push_to_thread(
thread_id,
- stamp_stream_speaker(
- {"type": "done", **extra},
- speaker_id,
- include_done=True,
+ _with_room_turn_id(
+ stamp_stream_speaker(
+ {"type": "done", **extra},
+ speaker_id,
+ include_done=True,
+ ),
+ turn_id,
),
)
except Exception:
@@ -1532,6 +1617,14 @@ def _chunk_speaker_id(chunk: dict[str, Any]) -> str:
return ""
+def _with_room_turn_id(frame: dict[str, Any], turn_id: str) -> dict[str, Any]:
+ """Keep a team room frame on the host turn that dispatched it."""
+ token = turn_id.strip()
+ if not token or frame.get("turn_id"):
+ return frame
+ return {**frame, "turn_id": token}
+
+
def stamp_stream_speaker(
chunk: dict[str, Any],
speaker_id: str,
diff --git a/src/octop/infra/agents/workspace/dir.py b/src/octop/infra/agents/workspace/dir.py
index b1600b1b17..85a9e2123e 100644
--- a/src/octop/infra/agents/workspace/dir.py
+++ b/src/octop/infra/agents/workspace/dir.py
@@ -235,6 +235,13 @@ def scoped_workspace_dir_str(agent_id: str) -> str:
return f"/{DEFAULT_SYSTEM_FILES_PATH}/{SCOPED_WORKSPACE_DIRNAME}/{agent_id}"
+def default_workspace_parent_dir() -> str:
+ """Host path of ``{OCTOP_HOME}/agents``, parent of the create-time default."""
+ from octop.infra.utils.host_dirs import host_path_text # noqa: PLC0415
+
+ return host_path_text(PathLayout.from_env().agents_dir)
+
+
def default_agent_workspace_dir(
paths: PathLayout,
agent_id: str,
@@ -263,6 +270,30 @@ def default_agent_workspace_dir(
return paths.agent_workspace(agent_id)
+def apply_explicit_workspace_dir(config: dict[str, Any], workspace_dir: str | None) -> None:
+ """Copy a user-chosen workspace onto *config* for a host-rooted local backend.
+
+ ``local_shell`` / ``filesystem`` rooted at the filesystem root (or with
+ ``root_dir`` omitted) keep *workspace_dir*. Scoped roots and other backends
+ ignore it so create still uses the agent-facing default. Blank input is
+ ignored.
+ """
+ text = (workspace_dir or "").strip()
+ if not text:
+ return
+ backend = config.get("backend")
+ if not isinstance(backend, dict):
+ return
+ kind = str(backend.get("type") or "").lower()
+ if kind not in {"local_shell", "filesystem"}:
+ return
+ raw = backend.get("root_dir")
+ root = str(raw).strip() if raw is not None and str(raw).strip() else ""
+ if root and not _is_host_root_sentinel(root):
+ return
+ config["workspace_dir"] = text
+
+
def seed_workspace_dir_on_create(
config: dict[str, Any],
*,
@@ -522,10 +553,12 @@ def workspace_dir_from_config_json(
"SCOPED_WORKSPACE_DIRNAME",
"agent_auth_dir",
"agent_facing_workspace_dir_from_config",
+ "apply_explicit_workspace_dir",
"agent_host_data_dirs",
"remove_agent_host_dirs",
"agent_facing_workspace_root",
"default_agent_workspace_dir",
+ "default_workspace_parent_dir",
"harness_workspace_path",
"host_system_dir",
"join_agent_facing",
diff --git a/src/octop/infra/db/repos/usage.py b/src/octop/infra/db/repos/usage.py
index 7a98ddad08..9fb2702007 100644
--- a/src/octop/infra/db/repos/usage.py
+++ b/src/octop/infra/db/repos/usage.py
@@ -376,6 +376,43 @@ def summary(
}
for r in bucket_rows
]
+ elif granularity == "by_user":
+ bucket_rows = conn.execute(
+ f"""
+ SELECT
+ user_id AS bucket,
+ SUM(input_tokens) AS input_tokens,
+ SUM(uncached_input_tokens) AS uncached_input_tokens,
+ SUM(cache_read_tokens) AS cache_read_tokens,
+ SUM(cache_write_tokens) AS cache_write_tokens,
+ SUM(output_tokens) AS output_tokens,
+ SUM(reasoning_tokens) AS reasoning_tokens,
+ SUM(total_tokens) AS total_tokens,
+ SUM(model_calls) AS model_calls,
+ COUNT(*) AS turns
+ FROM usage_log WHERE {where_sql}
+ GROUP BY bucket
+ ORDER BY total_tokens DESC
+ LIMIT 100
+ """,
+ params,
+ ).fetchall()
+ buckets = [
+ {
+ "key": str(int(r["bucket"])),
+ "label": str(int(r["bucket"])),
+ "input_tokens": int(r["input_tokens"] or 0),
+ "uncached_input_tokens": int(r["uncached_input_tokens"] or 0),
+ "cache_read_tokens": int(r["cache_read_tokens"] or 0),
+ "cache_write_tokens": int(r["cache_write_tokens"] or 0),
+ "output_tokens": int(r["output_tokens"] or 0),
+ "reasoning_tokens": int(r["reasoning_tokens"] or 0),
+ "total_tokens": int(r["total_tokens"] or 0),
+ "model_calls": int(r["model_calls"] or 0),
+ "turns": int(r["turns"] or 0),
+ }
+ for r in bucket_rows
+ ]
# ``total`` granularity → no buckets
avg = totals["total_tokens"] // totals["turns"] if totals["turns"] else 0
diff --git a/src/octop/infra/gateway/steer/coordinator.py b/src/octop/infra/gateway/steer/coordinator.py
index e0a9af08a5..a143cf1ed7 100644
--- a/src/octop/infra/gateway/steer/coordinator.py
+++ b/src/octop/infra/gateway/steer/coordinator.py
@@ -11,6 +11,7 @@
import logging
import threading
import time
+from collections import OrderedDict
from dataclasses import dataclass
from typing import Any
@@ -90,6 +91,30 @@ class RemoveResult:
already_gone: bool = False
+@dataclass
+class _RoomFollowup:
+ """Team speech that continues after the host steer turn has ended."""
+
+ turn_id: str
+ user_id: int | None
+ streams: int = 0
+ wrapup: bool = False
+
+
+def _other_user(owner: int | None, user_id: int) -> bool:
+ if owner is None:
+ return False
+ try:
+ return int(owner) != int(user_id)
+ except (TypeError, ValueError):
+ return False
+
+
+# Ended turns remembered so a team member can pin after ``end_turn`` drops
+# the live state. One entry per thread; the cap drops the oldest.
+_ENDED_TURN_CAP = 2048
+
+
class SteerCoordinator:
"""Per-thread steer state under one lock."""
@@ -98,9 +123,15 @@ def __init__(self, *, text_cap_bytes: int = STEER_TEXT_CAP_BYTES) -> None:
self._by_thread: dict[str, TurnSteerState] = {}
self._text_cap = text_cap_bytes
self._staged_hitl: dict[str, tuple[DrainBundle, int]] = {}
+ self._room_holds: dict[str, _RoomFollowup] = {}
+ self._ended_turns: OrderedDict[str, tuple[str, int | None]] = OrderedDict()
def begin_turn(
- self, thread_id: str, *, phase: TurnPhase = "streaming_text"
+ self,
+ thread_id: str,
+ *,
+ phase: TurnPhase = "streaming_text",
+ user_id: int | None = None,
) -> tuple[str, int, DiscardBundle | None]:
"""Start a steerable turn.
@@ -111,6 +142,7 @@ def begin_turn(
with self._lock:
previous = self._by_thread.pop(tid, None)
self._staged_hitl.pop(tid, None)
+ self._ended_turns.pop(tid, None)
discarded = None
if previous is not None and previous.queue:
reason: DiscardReason = (
@@ -125,7 +157,8 @@ def begin_turn(
)
discarded = self._discard_locked(previous, reason=reason)
turn_id = new_ulid()
- state = TurnSteerState(turn_id=turn_id, phase=phase)
+ owner = int(user_id) if isinstance(user_id, int) and user_id > 0 else None
+ state = TurnSteerState(turn_id=turn_id, phase=phase, user_id=owner)
state.last_allocated_seq = 1
self._by_thread[tid] = state
return turn_id, state.last_allocated_seq, discarded
@@ -146,6 +179,7 @@ def get_state(self, thread_id: str) -> TurnSteerState | None:
return TurnSteerState(
turn_id=state.turn_id,
phase=state.phase,
+ user_id=state.user_id,
queue=list(state.queue),
continuation_count=state.continuation_count,
last_allocated_seq=state.last_allocated_seq,
@@ -154,6 +188,99 @@ def get_state(self, thread_id: str) -> TurnSteerState | None:
continuation_meta=dict(state.continuation_meta),
)
+ def blocks_other_sender(self, thread_id: str, user_id: int) -> bool:
+ """True when a shared-session peer must wait for this turn to finish.
+
+ A team room stays busy after the host turn ends, while a member stream
+ or the host wrap-up is still open.
+ """
+ with self._lock:
+ state = self._by_thread.get(thread_id.strip())
+ if (
+ state is not None
+ and state.phase not in ("idle", "terminal")
+ and not self._park_expired(state)
+ and _other_user(state.user_id, user_id)
+ ):
+ return True
+ hold = self._room_holds.get(thread_id.strip())
+ if hold is not None and (hold.streams > 0 or hold.wrapup):
+ return _other_user(hold.user_id, user_id)
+ return False
+
+ def _remember_ended_turn(self, thread_id: str, turn_id: str, user_id: int | None) -> None:
+ """Caller holds ``_lock``."""
+ if not thread_id or not turn_id:
+ return
+ self._ended_turns[thread_id] = (turn_id, user_id)
+ self._ended_turns.move_to_end(thread_id)
+ while len(self._ended_turns) > _ENDED_TURN_CAP:
+ self._ended_turns.popitem(last=False)
+
+ def pin_room_followup(self, thread_id: str) -> str:
+ """Count one team member or wrap-up stream. Returns the turn id to stamp."""
+ tid = thread_id.strip()
+ if not tid:
+ return ""
+ with self._lock:
+ state = self._by_thread.get(tid)
+ hold = self._room_holds.get(tid)
+ if hold is None:
+ if state is None:
+ ended = self._ended_turns.get(tid)
+ if ended is None:
+ return ""
+ turn_id, owner = ended
+ hold = _RoomFollowup(turn_id=turn_id, user_id=owner)
+ else:
+ hold = _RoomFollowup(turn_id=state.turn_id, user_id=state.user_id)
+ self._room_holds[tid] = hold
+ self._ended_turns.pop(tid, None)
+ elif state is not None and hold.streams == 0 and not hold.wrapup:
+ hold.turn_id = state.turn_id
+ if state.user_id is not None:
+ hold.user_id = state.user_id
+ hold.streams += 1
+ return hold.turn_id
+
+ def release_room_followup(self, thread_id: str, *, expect_wrapup: bool = False) -> None:
+ """Drop one follow-up stream. The last member keeps the room locked for wrap-up."""
+ tid = thread_id.strip()
+ with self._lock:
+ hold = self._room_holds.get(tid)
+ if hold is None:
+ return
+ hold.streams = max(0, hold.streams - 1)
+ if expect_wrapup:
+ hold.wrapup = True
+ elif hold.streams == 0:
+ hold.wrapup = False
+ if hold.streams == 0 and not hold.wrapup:
+ self._room_holds.pop(tid, None)
+
+ def finish_room_followup(self, thread_id: str) -> None:
+ """The room has published its wrap-up, or no wrap-up is coming."""
+ tid = thread_id.strip()
+ with self._lock:
+ hold = self._room_holds.get(tid)
+ if hold is None:
+ return
+ hold.wrapup = False
+ if hold.streams == 0:
+ self._room_holds.pop(tid, None)
+
+ def room_followup_turn_id(self, thread_id: str) -> str:
+ """Turn id stamped on team frames that are still part of the open room generation."""
+ tid = thread_id.strip()
+ with self._lock:
+ hold = self._room_holds.get(tid)
+ if hold is not None and hold.turn_id:
+ return hold.turn_id
+ state = self._by_thread.get(tid)
+ if state is not None:
+ return state.turn_id
+ return ""
+
def is_active(self, thread_id: str) -> bool:
with self._lock:
state = self._by_thread.get(thread_id.strip())
@@ -559,8 +686,11 @@ def end_turn(self, thread_id: str, *, failed: bool = False) -> DiscardBundle | N
# without drain_for_continuation, treat as cancelled strand guard.
bundle = self._discard_locked(state, reason=reason)
state.phase = "idle"
- # Keep last_allocated_seq / forget turn after idle
- self._by_thread.pop(thread_id.strip(), None)
+ # Keep last_allocated_seq / forget turn after idle.
+ # Member streams often start after this pop; remember who spoke.
+ tid = thread_id.strip()
+ self._remember_ended_turn(tid, state.turn_id, state.user_id)
+ self._by_thread.pop(tid, None)
return bundle
def stage_hitl_pending(self, thread_id: str) -> tuple[DrainBundle, int] | None:
diff --git a/src/octop/infra/gateway/steer/types.py b/src/octop/infra/gateway/steer/types.py
index cf4c7a17cf..f29b543f4c 100644
--- a/src/octop/infra/gateway/steer/types.py
+++ b/src/octop/infra/gateway/steer/types.py
@@ -78,6 +78,8 @@ class PendingSteer:
class TurnSteerState:
turn_id: str
phase: TurnPhase = "streaming_text"
+ # Dashboard user who started this turn. Shared sessions reject other senders.
+ user_id: int | None = None
queue: list[PendingSteer] = field(default_factory=list)
continuation_count: int = 0
# client_pending_id -> pending_id while queued; drained remembers message_id
diff --git a/src/octop/infra/gateway/ws/ws_channel.py b/src/octop/infra/gateway/ws/ws_channel.py
index 91ce751f2a..eec7e4fa02 100644
--- a/src/octop/infra/gateway/ws/ws_channel.py
+++ b/src/octop/infra/gateway/ws/ws_channel.py
@@ -159,7 +159,11 @@ async def handle_inbound(self, raw_payload: Any) -> None:
await self._hub.push_to_thread(thread_id, {"type": "done"})
return
- turn_id, started_seq, replaced = self._steer.begin_turn(thread_id)
+ starter = resolve_user_id_for_message(message, agent_owner_id=None)
+ turn_id, started_seq, replaced = self._steer.begin_turn(
+ thread_id,
+ user_id=starter if starter > 0 else None,
+ )
if replaced is not None:
await _push_discarded(self._hub, thread_id, replaced)
self._steer.remember_context(
@@ -219,7 +223,10 @@ async def handle_inbound(self, raw_payload: Any) -> None:
# flaky client disconnect can stop generation mid-node and leave
# an incomplete checkpoint.
try:
- await self._hub.push_to_thread(thread_id, chunk)
+ payload = (
+ _with_turn_id(chunk, turn_id) if isinstance(chunk, dict) else chunk
+ )
+ await self._hub.push_to_thread(thread_id, payload)
except Exception:
logger.exception(
"websocket push failed thread=%s (turn continues)",
@@ -307,9 +314,15 @@ async def handle_inbound(self, raw_payload: Any) -> None:
try:
await self._hub.push_to_thread(
thread_id,
- {"type": "error", "message": format_stream_error(exc, locale)},
+ _with_turn_id(
+ {"type": "error", "message": format_stream_error(exc, locale)},
+ turn_id,
+ ),
+ )
+ await self._hub.push_to_thread(
+ thread_id,
+ _with_turn_id({"type": "done"}, turn_id),
)
- await self._hub.push_to_thread(thread_id, {"type": "done"})
except Exception:
logger.exception("websocket failed to deliver error frame thread=%s", thread_id)
finally:
@@ -398,6 +411,13 @@ async def _send_media(self, subject: ChannelSubject, media: ContentPart) -> None
await self._hub.push(conn_id, frame)
+def _with_turn_id(frame: dict[str, Any], turn_id: str) -> dict[str, Any]:
+ """Keep each streamed chunk tied to its turn so clients do not merge replies."""
+ if not turn_id or frame.get("turn_id"):
+ return frame
+ return {**frame, "turn_id": turn_id}
+
+
def _turn_user_frame(message: InboundMessage, thread_id: str, processor: Any) -> dict[str, Any]:
"""Question bubble for every subscriber, including someone who did not send it."""
meta = message.metadata if isinstance(message.metadata, dict) else {}
diff --git a/src/octop/infra/users/resource_policy.py b/src/octop/infra/users/resource_policy.py
index 61aa90da4e..3b55273db7 100644
--- a/src/octop/infra/users/resource_policy.py
+++ b/src/octop/infra/users/resource_policy.py
@@ -184,6 +184,32 @@ def assert_backend_within_user_root(
assert_safe_host_path(root_dir, restrict_to_root=allowed_root)
+def raise_if_workspace_dir_outside_user_root(
+ policy_repo: Any,
+ user_id: int,
+ config: Mapping[str, Any],
+) -> None:
+ """Raise when a user-assigned ``workspace_dir`` sits outside the allowed root.
+
+ No-op when the user has no workspace-root policy or the config omits
+ ``workspace_dir``. Call this only for a path the user just chose — a stored
+ directory that predates the policy must not block unrelated edits.
+ """
+ allowed = effective_workspace_root_dir(policy_repo.get(user_id, POLICY_WORKSPACE_ROOT_DIR))
+ if not allowed:
+ return
+ raw = config.get("workspace_dir")
+ if not isinstance(raw, str) or not raw.strip():
+ return
+ from octop.infra.agents.workspace.dir import resolve_workspace_host_path
+
+ try:
+ host = resolve_workspace_host_path(raw, dict(config))
+ assert_safe_host_path(os.fspath(host), restrict_to_root=allowed)
+ except ValueError as exc:
+ raise OctopError(ErrorCode.WORKSPACE_ROOT_RESTRICTED, str(exc)) from exc
+
+
def raise_if_backend_outside_user_root(
policy_repo: Any,
user_id: int,
diff --git a/tests/integration/test_agents_shared.py b/tests/integration/test_agents_shared.py
index d26ff09fff..0515fdabfb 100644
--- a/tests/integration/test_agents_shared.py
+++ b/tests/integration/test_agents_shared.py
@@ -37,6 +37,12 @@ async def test_shared_agent_appears_for_other_user(env) -> None:
assert response.status_code == 200, response.text
assert response.json()["is_shared"] is True
+ response = await client.get("/api/agents", headers=owner_auth)
+ assert response.status_code == 200
+ owned = {row["agent_id"]: row for row in response.json()}
+ assert owned[agent_id]["is_shared"] is True
+ assert owned[agent_id]["is_owner"] is True
+
response = await client.get("/api/agents", headers=peer_auth)
assert response.status_code == 200
agents = {row["agent_id"]: row for row in response.json()}
diff --git a/tests/integration/test_experts_api.py b/tests/integration/test_experts_api.py
index 0c90690f39..8aefc82f31 100644
--- a/tests/integration/test_experts_api.py
+++ b/tests/integration/test_experts_api.py
@@ -562,3 +562,56 @@ async def test_patch_agent_composer_defaults(env: Any) -> None:
assert cleared.status_code == 200, cleared.text
assert cleared.json()["knowledge_base_ids"] == []
assert cleared.json()["mcp_servers"] == []
+
+
+async def test_from_expert_workspace_dir_follows_storage_root(env: Any) -> None:
+ """Host-root local backends keep a chosen workspace; scoped roots ignore it."""
+ c, srv, auth = env
+ assert srv.app_runtime is not None
+ home = srv.app_runtime.agent_registry.paths.root
+ picked = home / "picked-ws"
+ created = await c.post(
+ "/api/agents/from-expert/default",
+ headers=auth,
+ json={
+ "name": "host-ws-bot",
+ "backend": {"type": "local_shell", "virtual_mode": True, "root_dir": "/"},
+ "workspace_dir": str(picked),
+ },
+ )
+ assert created.status_code == 201, created.text
+ agent_id = created.json()["agent_id"]
+ detail = (await c.get(f"/api/agents/{agent_id}", headers=auth)).json()
+ assert detail["config"]["workspace_dir"] == str(picked)
+ assert picked.is_dir()
+
+ jail = home / "jail"
+ jail.mkdir()
+ outside = home / "outside-ws"
+ scoped = await c.post(
+ "/api/agents/from-expert/default",
+ headers=auth,
+ json={
+ "name": "scoped-ws-bot",
+ "backend": {
+ "type": "filesystem",
+ "virtual_mode": True,
+ "root_dir": str(jail),
+ },
+ "workspace_dir": str(outside),
+ },
+ )
+ assert scoped.status_code == 201, scoped.text
+ scoped_id = scoped.json()["agent_id"]
+ scoped_detail = (await c.get(f"/api/agents/{scoped_id}", headers=auth)).json()
+ assert scoped_detail["config"]["workspace_dir"] == f"/.octop/workspaces/{scoped_id}"
+ assert not outside.exists()
+
+ patched = await c.patch(
+ f"/api/agents/{agent_id}",
+ headers=auth,
+ json={"config": {**detail["config"], "workspace_dir": str(home / "moved-ws")}},
+ )
+ assert patched.status_code == 200, patched.text
+ again = (await c.get(f"/api/agents/{agent_id}", headers=auth)).json()
+ assert again["config"]["workspace_dir"] == str(picked)
diff --git a/tests/integration/test_filesystem_api.py b/tests/integration/test_filesystem_api.py
index 7f7d05e60f..98add8761f 100644
--- a/tests/integration/test_filesystem_api.py
+++ b/tests/integration/test_filesystem_api.py
@@ -100,6 +100,7 @@ async def test_filesystem_defaults_for_admin(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
+ from octop.infra.agents.workspace.dir import default_workspace_parent_dir
from octop.infra.utils.host_dirs import (
host_browse_roots,
host_fs_tree_root,
@@ -115,9 +116,11 @@ async def test_filesystem_defaults_for_admin(
r = await client.get("/api/filesystem/defaults", headers=auth)
assert r.status_code == 200, r.text
body = r.json()
+
assert body["default_root_dir"] == host_fs_tree_root()
assert body["tree_root"] == host_fs_tree_root()
assert body["browse_roots"] == host_browse_roots()
+ assert body["default_workspace_dir"] == default_workspace_parent_dir()
assert body["jail_enforced"] == host_jail_enforced()
assert body["in_container"] is False
assert "home" not in body
diff --git a/tests/integration/test_teams_api.py b/tests/integration/test_teams_api.py
index 4e80e6e70f..d6a0bb6f46 100644
--- a/tests/integration/test_teams_api.py
+++ b/tests/integration/test_teams_api.py
@@ -57,3 +57,38 @@ async def test_patch_team_icon_url_persists_sample_portrait(env):
assert listed.status_code == 200, listed.text
row = next(item for item in listed.json() if item["agent_id"] == team_id)
assert row["icon_url"] == _CIRCLE
+
+
+async def test_team_workspace_dir_on_host_root(env):
+ c, srv, auth = env
+ assert srv.app_runtime is not None
+ alpha = await _expert(c, auth, "alpha-ws")
+ beta = await _expert(c, auth, "beta-ws")
+ home = srv.app_runtime.agent_registry.paths.root
+ picked = home / "team-picked-ws"
+ created = await c.post(
+ "/api/teams",
+ headers=auth,
+ json={
+ "name": "squad-ws",
+ "member_ids": [alpha, beta],
+ "config": {
+ "backend": {"type": "filesystem", "virtual_mode": True, "root_dir": "/"},
+ "workspace_dir": str(picked),
+ },
+ },
+ )
+ assert created.status_code == 200, created.text
+ team_id = created.json()["agent_id"]
+ detail = (await c.get(f"/api/agents/{team_id}", headers=auth)).json()
+ assert detail["config"]["workspace_dir"] == str(picked)
+ assert picked.is_dir()
+
+ patched = await c.patch(
+ f"/api/teams/{team_id}",
+ headers=auth,
+ json={"name": "squad-ws", "config": {"workspace_dir": str(home / "team-moved-ws")}},
+ )
+ assert patched.status_code == 200, patched.text
+ again = (await c.get(f"/api/agents/{team_id}", headers=auth)).json()
+ assert again["config"]["workspace_dir"] == str(picked)
diff --git a/tests/integration/test_usage_api.py b/tests/integration/test_usage_api.py
index 9b340b3b8b..473c44dcd5 100644
--- a/tests/integration/test_usage_api.py
+++ b/tests/integration/test_usage_api.py
@@ -472,6 +472,57 @@ async def test_summary_agent_id_filter_for_user(env: Any) -> None:
assert buckets[0]["total_tokens"] == 150
+async def test_repo_summary_by_user(env: Any) -> None:
+ _c, srv, _admin_auth, _alice_auth, ctx = env
+ repo = srv.services.usage_repo
+ repo.record(agent_id="x", user_id=1, input_tokens=100, output_tokens=50)
+ repo.record(agent_id="y", user_id=ctx["alice_id"], input_tokens=10, output_tokens=5)
+ repo.record(agent_id="y", user_id=ctx["alice_id"], input_tokens=4, output_tokens=1)
+ result = repo.summary(window="last_30d", granularity="by_user")
+ by_id = {b["key"]: b for b in result["buckets"]}
+ assert by_id["1"]["total_tokens"] == 150
+ assert by_id["1"]["turns"] == 1
+ assert by_id[str(ctx["alice_id"])]["total_tokens"] == 20
+ assert by_id[str(ctx["alice_id"])]["turns"] == 2
+
+
+async def test_by_user_summary_labels_display_name(env: Any) -> None:
+ c, srv, admin_auth, alice_auth, ctx = env
+ srv.services.user_repo.set_display_name(ctx["alice_id"], "爱丽丝")
+ srv.services.usage_repo.record(
+ agent_id="y",
+ user_id=ctx["alice_id"],
+ input_tokens=10,
+ output_tokens=5,
+ )
+ srv.services.usage_repo.record(
+ agent_id="x",
+ user_id=1,
+ input_tokens=100,
+ output_tokens=50,
+ )
+
+ r = await c.get(
+ "/api/admin/usage/summary?granularity=by_user&window=all",
+ headers=admin_auth,
+ )
+ assert r.status_code == 200
+ buckets = {b["key"]: b for b in r.json()["buckets"]}
+ assert buckets[str(ctx["alice_id"])]["label"] == "爱丽丝"
+ assert buckets[str(ctx["alice_id"])]["total_tokens"] == 15
+ assert buckets["1"]["total_tokens"] == 150
+
+ own = await c.get(
+ "/api/usage/summary?granularity=by_user&window=all",
+ headers=alice_auth,
+ )
+ assert own.status_code == 200
+ own_buckets = own.json()["buckets"]
+ assert len(own_buckets) == 1
+ assert own_buckets[0]["key"] == str(ctx["alice_id"])
+ assert own_buckets[0]["label"] == "爱丽丝"
+
+
async def test_by_agent_summary_labels_other_users_experts(env: Any) -> None:
"""Admin rollup names experts the caller does not own."""
c, srv, admin_auth, alice_auth, ctx = env
diff --git a/tests/unit/agents/test_agent_manager.py b/tests/unit/agents/test_agent_manager.py
index 10a4c5d6ec..5a491404e6 100644
--- a/tests/unit/agents/test_agent_manager.py
+++ b/tests/unit/agents/test_agent_manager.py
@@ -2571,6 +2571,71 @@ async def test_update_config_json_cannot_move_the_workspace(
assert manager.resolve_workspace_dir(row.agent_id) == Path(scoped)
+@pytest.mark.asyncio
+async def test_update_config_json_keeps_host_root_workspace(
+ manager: AgentManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A chosen host-root workspace stays put after create, even if a patch names another path."""
+ from octop.infra.agents.manager import AgentCreateSpec
+
+ monkeypatch.setattr(manager, "_schedule_reload", lambda _aid: None)
+ row = await manager.create(
+ AgentCreateSpec(
+ name="wsdir-fixed-host",
+ config={
+ **_MEMORY_OFF,
+ "backend": {"type": "local_shell", "root_dir": "/", "virtual_mode": True},
+ },
+ ),
+ defer_bootstrap=True,
+ )
+ stored = manager.get_config(row.agent_id).get("workspace_dir")
+ await manager.update_config_json(
+ row.agent_id,
+ json.dumps(
+ {**manager.get_config(row.agent_id), "workspace_dir": str(tmp_path / "elsewhere")}
+ ),
+ )
+ assert manager.get_config(row.agent_id).get("workspace_dir") == stored
+
+
+@pytest.mark.asyncio
+async def test_update_config_json_keeps_scoped_workspace(
+ manager: AgentManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A scoped root keeps its workspace even if the patch names another directory."""
+ from octop.infra.agents.manager import AgentCreateSpec
+
+ monkeypatch.setattr(manager, "_schedule_reload", lambda _aid: None)
+ jail = tmp_path / "jail"
+ jail.mkdir()
+ row = await manager.create(
+ AgentCreateSpec(
+ name="wsdir-scoped",
+ config={
+ **_MEMORY_OFF,
+ "backend": {
+ "type": "filesystem",
+ "root_dir": str(jail),
+ "virtual_mode": True,
+ },
+ },
+ ),
+ defer_bootstrap=True,
+ )
+ stored = manager.get_config(row.agent_id).get("workspace_dir")
+ await manager.update_config_json(
+ row.agent_id,
+ json.dumps(
+ {
+ **manager.get_config(row.agent_id),
+ "workspace_dir": str(tmp_path / "elsewhere"),
+ }
+ ),
+ )
+ assert manager.get_config(row.agent_id).get("workspace_dir") == stored
+
+
@pytest.mark.asyncio
async def test_internal_persist_can_still_set_the_workspace(manager: AgentManager) -> None:
"""The internal writer must keep writing ``workspace_dir`` (no over-pinning)."""
diff --git a/tests/unit/agents/test_workspace_dir.py b/tests/unit/agents/test_workspace_dir.py
index bdbaa11afb..5cc6a4048a 100644
--- a/tests/unit/agents/test_workspace_dir.py
+++ b/tests/unit/agents/test_workspace_dir.py
@@ -9,7 +9,9 @@
from octop.infra.agents.workspace.dir import (
agent_facing_workspace_dir_from_config,
agent_facing_workspace_root,
+ apply_explicit_workspace_dir,
default_agent_workspace_dir,
+ default_workspace_parent_dir,
harness_workspace_path,
join_agent_facing,
resolve_workspace_host_path,
@@ -17,9 +19,17 @@
seed_workspace_dir_on_create,
workspace_dir_from_config,
)
+from octop.infra.utils.host_dirs import host_path_text
from octop.infra.utils.paths import PathLayout
+def test_default_workspace_parent_dir_follows_octop_home(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("OCTOP_HOME", str(tmp_path))
+ assert default_workspace_parent_dir() == host_path_text(tmp_path / "agents")
+
+
def _scoped_cfg(root: Path, **extra: object) -> dict:
return {
"backend": {
@@ -178,3 +188,28 @@ def test_neutralize_unwritable_local_root(tmp_path: Path) -> None:
writable.mkdir()
keep = neutralize_unwritable_local_root(_scoped_cfg(writable))
assert keep["backend"]["root_dir"] == str(writable)
+
+
+def test_apply_explicit_workspace_dir_keeps_host_root_only() -> None:
+ host = {"backend": {"type": "local_shell", "root_dir": "/", "virtual_mode": True}}
+ apply_explicit_workspace_dir(host, " /data/work ")
+ assert host["workspace_dir"] == "/data/work"
+
+ omitted = {"backend": {"type": "filesystem", "virtual_mode": True}}
+ apply_explicit_workspace_dir(omitted, "/data/work")
+ assert omitted["workspace_dir"] == "/data/work"
+
+ scoped = {
+ "backend": {"type": "local_shell", "root_dir": "/data/jail", "virtual_mode": True},
+ "workspace_dir": "/.octop/workspaces/A1",
+ }
+ apply_explicit_workspace_dir(scoped, "/data/work")
+ assert scoped["workspace_dir"] == "/.octop/workspaces/A1"
+
+ named = {"backend": {"type": "named", "name": "cos"}}
+ apply_explicit_workspace_dir(named, "/data/work")
+ assert "workspace_dir" not in named
+
+ blank = {"backend": {"type": "local_shell", "root_dir": "/"}}
+ apply_explicit_workspace_dir(blank, " ")
+ assert "workspace_dir" not in blank
diff --git a/tests/unit/gateway/steer/test_coordinator.py b/tests/unit/gateway/steer/test_coordinator.py
index b53e76f50b..a536fcc8aa 100644
--- a/tests/unit/gateway/steer/test_coordinator.py
+++ b/tests/unit/gateway/steer/test_coordinator.py
@@ -291,3 +291,44 @@ def test_admit_attachment_only_and_drain_blocks() -> None:
assert isinstance(drained, DrainBundle)
assert drained.text == ""
assert drained.content_blocks == (block,)
+
+
+def test_blocks_other_sender_on_active_turn() -> None:
+ c = SteerCoordinator()
+ c.begin_turn("t1", user_id=1)
+ assert c.blocks_other_sender("t1", 2) is True
+ assert c.blocks_other_sender("t1", 1) is False
+ c.end_turn("t1")
+ assert c.blocks_other_sender("t1", 2) is False
+
+
+def test_team_followup_pins_after_host_turn_ends() -> None:
+ c = SteerCoordinator()
+ first, _, _ = c.begin_turn("room", user_id=1)
+ c.end_turn("room")
+ second, _, _ = c.begin_turn("room", user_id=2)
+ c.end_turn("room")
+ assert c.pin_room_followup("room") == second
+ assert first != second
+ assert c.blocks_other_sender("room", 1) is True
+ assert c.blocks_other_sender("room", 2) is False
+ c.release_room_followup("room", expect_wrapup=True)
+ assert c.blocks_other_sender("room", 1) is True
+ c.finish_room_followup("room")
+ assert c.blocks_other_sender("room", 1) is False
+
+
+def test_team_followup_keeps_other_senders_waiting() -> None:
+ c = SteerCoordinator()
+ turn_id, _, _ = c.begin_turn("room", user_id=1)
+ assert c.pin_room_followup("room") == turn_id
+ c.end_turn("room")
+ assert c.blocks_other_sender("room", 2) is True
+ assert c.blocks_other_sender("room", 1) is False
+ c.release_room_followup("room", expect_wrapup=True)
+ assert c.blocks_other_sender("room", 2) is True
+ assert c.room_followup_turn_id("room") == turn_id
+ wrap = c.pin_room_followup("room")
+ assert wrap == turn_id
+ c.release_room_followup("room")
+ assert c.blocks_other_sender("room", 2) is False
diff --git a/tests/unit/gateway/test_dashboard_ws.py b/tests/unit/gateway/test_dashboard_ws.py
index bc48b3a201..220160839a 100644
--- a/tests/unit/gateway/test_dashboard_ws.py
+++ b/tests/unit/gateway/test_dashboard_ws.py
@@ -59,6 +59,8 @@ def _stream_frames(frames: list[dict[str, Any]]) -> list[dict[str, Any]]:
continue
if ftype == "user" and isinstance(frame.get("meta"), dict) and frame["meta"].get("steer"):
continue
+ if "turn_id" in frame:
+ frame = {key: value for key, value in frame.items() if key != "turn_id"}
out.append(frame)
return out
@@ -256,8 +258,15 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
await channel.handle_inbound(msg)
assert _user("hi", "thread-1") in frames
- assert {"type": "token", "content": "hello", "thread_id": "thread-1"} in frames
- assert {"type": "done", "thread_id": "thread-1"} in frames
+ started = next(frame for frame in frames if frame["type"] == "turn.started")
+ turn_id = started["turn_id"]
+ assert {
+ "type": "token",
+ "content": "hello",
+ "thread_id": "thread-1",
+ "turn_id": turn_id,
+ } in frames
+ assert {"type": "done", "thread_id": "thread-1", "turn_id": turn_id} in frames
assert frames[-1]["type"] == "turn.ended"
assert frames[-1]["thread_id"] == "thread-1"
assert hub.is_turn_active("thread-1") is False
@@ -1052,7 +1061,13 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
types = [f["type"] for f in frames]
assert "steer.drained" in types
assert "turn.resumed" in types
- assert {"type": "token", "content": "steered answer", "thread_id": "thread-1"} in frames
+ resumed = next(frame for frame in frames if frame["type"] == "turn.resumed")
+ assert {
+ "type": "token",
+ "content": "steered answer",
+ "thread_id": "thread-1",
+ "turn_id": resumed["turn_id"],
+ } in frames
assert types[-1] == "turn.ended"
assert hub.is_turn_active("thread-1") is False
From 9931a27e10f85d32bb4109799522a8229b9eeabf Mon Sep 17 00:00:00 2001
From: liukewia
Date: Wed, 11 Nov 2026 10:09:13 +0800
Subject: [PATCH 19/20] feat(desktop): replace the Wails shell with an Electron
shell (#2445)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* feat(desktop): replace the Wails shell with an Electron shell
The desktop client now has one implementation: a frameless Electron shell that
owns the Python sidecar. The Wails v3 Go shell is gone, so there is a single
build entry point and a single release format again, and the dashboard reaches
the shell through one preload bridge (`window.octopDesktop`).
Shell (desktop/src, electron-vite; pnpm 12 + Node 24 scoped to the package):
- A privileged `octop://app/` protocol proxies `/api/*` to an OS-assigned
loopback port. Python is spawned detached in its own process group with
OCTOP_HOME / OCTOP_GREEN_PACKAGES / OCTOP_DESKTOP_SHELL, the portable runtime
is SHA-256 checked before extraction, and the "local runtime is newer than
the bundled one" guard runs before Python is spawned.
- Updates are shell-owned: manifest selection, streaming download, and a hard
requirement that Python exits by itself with code 0 before the OS installer
takes over. The renderer can only ask for the confirmation dialog, never name
a URL.
- Frameless chrome follows platform convention: macOS traffic lights top-left,
Windows/Linux caption buttons top-right, with single-sided CSS insets. The
splash is fixed white instead of following the theme.
- Shutdown owns the sidecar: `before-quit` waits for it, and SIGINT / SIGTERM /
SIGHUP run the same cleanup, so Ctrl+C in a dev terminal no longer orphans
Python. `run-dev.sh` forwards the signal and bounds the wait.
- The product version resolves from the bundled portable manifest, then the dev
runtime, and only then package.json, so release selection compares real
versions instead of a stale placeholder.
Dashboard keeps only the Electron path: `isDesktopShell()` / `getDesktopBridge()`
in desktopBridge.ts are the single source of truth, `-webkit-app-region` replaces
the JS drag listeners, and desktop downloads fall back to an anchor click. The
settings page gains the desktop update panel (channel preference, shell-side
check, confirmation-only button).
Python side: OCTOP_DESKTOP_SHELL=1 hides in-app upgrade entry points and rejects
`octop update` / self-update APIs, with `src/octop/infra/desktop.py` as the flag.
Tooling: pnpm settings move to pnpm-workspace.yaml; `pnpm dev`, `dev:start` and
`dev:no-sandbox` all drive `scripts/run-dev.sh`. CI drops the Go, WebKitGTK and
wails3 steps and keeps producing the green zips the shell bundles.
* refactor(envs): improve error message formatting for shell-owned environment keys
Updated the error handling in the batch_save_envs function to enhance readability by formatting the error message across multiple lines. This change maintains the existing functionality while improving code clarity.
* feat(icons): add new icon files for desktop application
Introduced new icon assets in various formats (ICNS, ICO, PNG) to enhance the visual identity of the desktop application. These icons will be used across the application interface.
* feat(workflows): enhance Octop Desktop packaging and release process
Updated the GitHub Actions workflow for Octop Desktop to include new steps for staging the Electron runtime and dashboard, installing dependencies, and building native installers for various platforms. Improved artifact handling by ensuring proper uploads for different formats (dmg, exe, AppImage, deb, rpm) and updated the release naming conventions. Enhanced error handling in the release download script to accommodate local and forked repository setups.
* feat(desktop): renew the session with a per-install device credential
Desktop installs run without a password: the wizard mints one nobody ever
types, so an expired JWT used to be a dead end (/auth/login is not a path a
desktop user can take, and the only way back was the CLI).
The shell now mints a 32-byte secret on first use, stores it encrypted with
safeStorage (Keychain / DPAPI / libsecret) at /desktop-device.json
with mode 0600, and trades it for a JWT when the previous one expired. The
credential never reaches the renderer: it only ever asks for a token.
- api: POST /api/auth/device/{register,token,revoke}. Only the SHA-256 digest
is persisted (secrets row `desktop_device`); the exchange is JWT-exempt but
requires the shell flag, a loopback peer, a constant-time digest match and a
per-host failure throttle. Registering replaces the previous token, so a
reinstall or a second machine takes over.
- shell: main/session/{device-credential,device-session,safe-storage-cipher}.ts
plus three IPC channels behind the preload `session` sub-bridge; a sidecar
that is down or refused degrades to "no session" instead of throwing.
- dashboard: renew once on 401 (business 401s are filtered first), bind the
credential after the first authenticated success, and try a refresh on the
login page so an expired session never lands on a password wall.
- OCTOP_ACCESS_TOKEN_TTL is no longer shell-owned. Stretching the token only
postpones the dead end and widens the blast radius of a stolen one, so the
TTL stays at the server default and renewal does the work instead.
Also isolates os.environ in tests/unit/test_desktop_shell.py: apply_env_file
writes past monkeypatch and leaked OCTOP_REQUIRE_SETUP_PASSWORD=0 into every
later module (test_config.py failed when ordered after it).
* chore(desktop): upgrade to Electron 45 and the async safeStorage API
Electron 33 → 45 (Node 20.18 → 24.22.0, Chromium 156), electron-builder
25 → 26 and @types/node 22 → 24. electron-vite stays on 3.1: it already
accepts vite 6, so the build toolchain needs no migration.
Electron 45 deprecates the synchronous safeStorage API (scheduled for
removal in 46), so the device credential moves to
isAsyncEncryptionAvailable / encryptStringAsync / decryptStringAsync and
`CredentialCipher` is async end to end.
That also closes a hole in the previous commit: on Linux the backend is
picked from the desktop environment rather than probed, and a headless
session silently falls back to `basic_text`, where the key is a hardcoded
passphrase. `isAsyncEncryptionAvailable` still reports true there, so the
cipher now treats `basic_text`/`unknown` as unavailable and the shell
stores the credential in the clear (0600) with a warning instead of
writing ciphertext that anyone can read.
Electron 45 also ships no postinstall: `node_modules/electron/dist/` is
populated on first use, so `electron` drops out of pnpm's `allowBuilds`
and the README documents `npx install-electron` for CI.
Verified: `pnpm typecheck`, 72 unit tests, `pnpm build`, and the binary
boots the built shell (octop:// scheme registered, windows and renderer
created).
* chore(desktop): run electron-builder with its config file
package.json still called a bare `electron-builder`, which only works
because the config happened to be discoverable. Pass
--config electron-builder.config.ts explicitly so the TS config is used
regardless of discovery rules.
* test(release): expect the Linux deb/AppImage/rpm assets
The release-link generator switched Linux from tar.gz to deb (default),
AppImage and rpm, but the test still asserted tar.gz and went red. Assert
the three real extensions per arch instead, and cover the fork behaviour:
GitHub Actions sets GITHUB_REPOSITORY, so a fork's notes must link to the
fork rather than upstream.
* feat(desktop): give the launcher its own React pages and a real error Result
The shell painted its first frame from a 30-line inline HTML splash and, when
boot could not continue, dumped a raw errno into a
on a blank page. That
is what a missing portable runtime looked like to the user: a full-screen
"ENOENT: no such file or directory" with no title and no way out.
renderer/ is now a small React app of its own — react + react-dom, esbuild's
automatic JSX runtime, no antd, no Dashboard components, no plugin-react:
- splash.tsx rebuilds the boot screen (brand mark inside the ring), matching the
Dashboard's own first paint so the swap reads as one continuous startup.
- error.html renders an antd-style Result: status glyph, headline, one sentence
the user can act on, the technical tail folded into a collapsed 技术详情, then
退出应用 / 复制错误信息 and the build version. Esc closes it.
The main process owns both pages: createEarlyWindow() returns a handle whose
showError() replaces the splash with the failure Result in place. The payload
travels as a base64url query parameter because the page is sandboxed — no
preload, no IPC — and shared/shell-error.ts is the encoder/decoder both sides
use, covered by tests for the round trip, URL safety, truncation and garbage
input.
Failure copy stops leaking internals: every call site now passes a sentence
plus an optional detail (runtime dir, zip digest, launcher path, port), and
dismissing the failure page quits the app instead of leaving macOS idling in
the Dock with no window.
Verified: `pnpm typecheck`, 79 unit tests, `pnpm build`, and a real launch —
the window lands on error.html with the encoded payload and renders the
Result, the copy button reports 已复制 on a real click, and window.close()
ends the process.
* fix(desktop): never store the device credential in the clear
On a host without a usable OS keychain — headless Linux, WSL, CI — the shell
wrote the 32-byte device secret as plain JSON in the data root. Mode 0600 keeps
other users out, but not backups, dotfile syncs, or anyone who copies the home
directory, and there is nothing on such a host to encrypt it against: a key kept
beside its own ciphertext would only look like encryption.
The secret no longer touches the disk there. DeviceCredentialStore holds it in
memory for the launch — renewal keeps working, the renderer still never sees it —
and the next launch starts without a credential, so that install signs in again.
That is cheap by construction: the server upserts a single `desktop_device` row,
so re-registering replaces the previous device instead of piling up rows.
Upgrading installs: a v1 file written by the old fallback is re-encrypted on the
next start when a keychain is available, and deleted otherwise. Either way its
secret is adopted for that one launch, so the upgrade itself forces no login.
`read()` no longer accepts a plaintext file at all — only `migrate()` may adopt
one, and `boot()` calls it once before the session client is constructed.
A keychain that is merely locked, or missing for one launch, no longer destroys
ciphertext it could read later: the no-keychain write path only drops files that
are not ciphertext.
Verified: `pnpm typecheck`, 86 unit tests (8 new: memory-only write, no survival
across launches, v1 ignored until migrated, re-encrypt, adopt-then-delete, empty
secret, locked keychain keeps its ciphertext, clear drops the in-memory copy),
`pnpm build`.
* chore(desktop): ignore the packaged runtime inputs
`desktop/src/resources/portable/` is not a source directory: the release
workflow runs `desktop/portable/package.sh` first, then copies the matching
`Octop-portable--.zip` in and writes `portable-version.json`
next to it (octop-desktop.yml, "Bundle portable runtime"). Committing it would
put a whole portable CPython plus site-packages in git.
`resources/dashboard` was already ignored for the same reason; the portable
sibling was simply missed. A local `pnpm package` run without both filled in
fails at boot with the shell's own error page, which is the intended signal.
* feat(dashboard): let the user reset this device's sign-in
The shell has exposed `session.revoke` since the device-credential work, but
nothing called it — the only way to drop the binding was to delete
`desktop-device.json` by hand or revoke server-side.
The desktop update panel (Settings → Advanced → Update, rendered only when the
shell is present) gains a 本机登录 section with a confirm dialog. It calls the
bridge with the JWT in hand and reports the outcome; the copy is explicit that
the current session keeps working and only renewal stops, because that is what
the backend actually does — revoking invalidates the token hash, not the JWT.
The button is hidden when `session` is missing from the bridge, so an older
shell without the method does not get a dead control.
* feat(desktop): relay WebSockets through the shell instead of the custom scheme
A page on `octop://app` could never open a socket: Chromium's upgrade bypasses
`protocol.handle`, and `onBeforeRequest` accepts `redirectURL` for a `webSocket`
request only to drop it (measured — the request is logged, the upstream never
sees a handshake). So every stream (terminal, browser, mobile, desktop, chat,
notifications, voice) silently failed under the shell.
`main/protocol/ws-relay.ts` binds a loopback port and forwards the handshake to
the sidecar, rewriting the request line, Host and Origin so the backend sees
itself. The page learns `ws://127.0.0.1:/` from a
new `wsEndpoint()` bridge call and appends `/api/...` — never the sidecar port,
which the relay re-reads per connection so a restart after an update needs no
new URL. Requests without the exact path segment (constant-time compare) or with
any Origin other than `octop://app` get 403; a sidecar that is down gets 503, an
unreachable one 504, and a backend refusal is passed through rather than being
turned into a tunnel. After 101 the two sockets are just piped, so backpressure
and cancellation survive.
The JWT still rides in the query exactly as it does in a browser: the relay
injects nothing and stores nothing, which is the point — it moves bytes, not
trust.
On the Dashboard side `resolveWsUrl()` replaces every `window.location.host`
builder, and returns the page origin when there is no bridge, so server mode and
older shells are untouched. `wsEndpoint()` is synchronous (and memoised) because
URL builders run inside render paths.
* docs(desktop): mark the pre-quit task check as a known gap
§3.4 asks the shell to ask the backend whether anything is running and to
confirm with the user before quitting. The cleanup chain itself (relay, then
Python over the grace window, then app.exit, second signal wins) is done, but
the check has no honest input yet: the backend has no in-flight task registry.
Terminals keep live PTYs in `_sessions`; browser streams, chat/Agent runs and
cron have no in-process "running" set at all, and /api/health's `agents_running`
counts loaded agents, not executing work.
Rather than ship a confirm dialog driven by a proxy-metric guess — which would
call an idle terminal "busy" and nag on every quit — this records what exists,
what the endpoint must return, and that the shell is expected to query it only
on a user-initiated quit (the signal path has no UI). Until then quitting stops
the sidecar without asking: no orphans, but work in progress is interrupted.
* docs(desktop): write down how the pre-quit task check should be built
§3.4's task check was deferred because the backend has no in-flight registry;
that note says what is missing but not how to fill it. This adds the plan so the
next person does not have to re-derive it from the codebase.
Grounded in what actually exists today: `terminal._sessions` is the only live
set; `GlobalProcessor.__call__` and `iter_turn_chunks` are two independent turn
entry points with no registry of their own; `chat/ws.py` enqueues the turn and
deliberately survives a WS disconnect, so "socket open" is neither necessary nor
sufficient; and `/api/health`'s `agents_running` counts loaded agents.
The design is one process-wide registry (`infra/runtime_activity.py`) filled at
those two seams, a read-only `GET /api/runtime/activity` gated by the same
shell-flag + loopback rule the device-token exchange already uses (deliberately
not reusing `/api/desktop/*`, which is the remote-desktop feature), and a
`quit-guard` in the shell that asks only on a user-initiated quit — never on the
installer hand-off, never on a signal — and treats a timeout or an error as
"unknown, let them leave" so quitting can never be blocked by a query.
* fix(desktop): give electron-builder the metadata deb/rpm require
The Linux job dies at `⨯ Please specify project homepage` before it writes an
AppImage or a deb/rpm, and macOS only warns (`author is missed`). Both come from
the same gap: `desktop/src/package.json` carries name/version/description and
nothing else.
`homepage` is not cosmetic for deb/rpm — electron-builder refuses to build them
without one. The value matches the endpoint the shell already talks to for
updates; `author`/`license` mirror pyproject so the two manifests agree.
* ci(desktop): retire the Node 20 actions and make the suite pass on Windows
Three warnings from the last six-platform run, none of which would ever have
turned into a failure on its own:
- `astral-sh/setup-uv@v6` and `pnpm/action-setup@v4` still declare
`runs.using: node20`. Moved to v7 / v6, which are the newest majors that run
on node24; `setup-uv@v10` does not exist as a floating tag, so the version
numbers were read off the actions' own action.yml rather than guessed.
`softprops/action-gh-release` had the same problem on the release path and
went to v3 for the same reason.
- `runs-on: ubuntu-latest` is announced to migrate to Ubuntu 26, which would
silently change the compiler and glibc a release is built against. Pinned to
ubuntu-24.04.
- The Windows job failed seven tests and the workflow printed a warning and
packaged anyway. The tests were asserting POSIX facts on Windows: 0600 file
modes, '/'-joined paths, and SIGTERM semantics that Windows does not have
(the tree is reaped with taskkill /T /F instead). Each is now either built
with node:path so the separator follows the host, or carries a named skip so
the reason is visible instead of the escape hatch. The `|| ::warning::` is
gone; Windows has to pass.
Also promotes the unsigned-package mode out of a throwaway branch and into a
`sign` dispatch input: without a certificate electron-builder does not skip
signing cleanly on macOS, it dies mid-pipeline with a misleading "not a file",
so the skip now blanks CSC_* explicitly and drops hardenedRuntime.
* test(desktop): give resolveStaticPath a root shaped like the one it gets in production
The strict Windows run found one survivor: the fixture passed "/root/dashboard"
as the web root while `path.resolve` resolves it against the current drive on
Windows, so the confinement check refused a legitimate asset and returned null.
That is the fixture being wrong, not the implementation being Windows-hostile:
the root arrives from `app.getAppPath()` and is therefore always host-shaped.
Building it with `resolve(sep, …)` makes the test say what production says.
Checked against both path implementations, including that traversal is still
refused and that the join() expectations agree with what resolve() returns.
* refactor(dashboard): replace custom window controls with native OS buttons
This update removes the custom DesktopWindowControls component and integrates native window buttons for macOS and Windows. The application now utilizes the shell's native controls, ensuring they follow the app's theme. The changes include the introduction of useNativeWindowChrome and useWindowFullscreen hooks to manage the appearance of these controls dynamically. Additionally, the layout has been adjusted to accommodate the native buttons, enhancing the overall user experience. Tests related to the removed component have also been deleted.
* feat(desktop): floor the window at the Dashboard's desktop layout
The Dashboard drops into its mobile layout under 767px, and the sidebar
already spends 220px of the width, so a window narrower than that is one
the app has no layout for. Both windows now refuse to go below 960×600:
the Dashboard window because that is the window worth using, and the
Early Window because the splash is swapped for the Dashboard in place, so
a size the Dashboard would reject has to be rejected there too.
The default size moves into the same module instead of being two loose
numbers in `createMainWindow`, so the floor and the opening size can be
compared in one place.
* feat(dashboard): give the shell one draggable title row across the window
Dragging used to be stitched together from whatever happened to opt in:
the sidebar carried its own 32px band for the macOS traffic lights, pages
opted in through PageShell, and Chat through its title bar. The top of
the window was therefore draggable in patches, and on Windows nothing
reserved the band at all — the caption buttons were drawn over the page's
title row.
MainLayout now renders that row once, above the sidebar and the content
column, so it is unbroken across the window: 32px, `app-region: drag`,
background inherited from the shell column (which is the same colour as
the sidebar, so no seam). It stops short of the Windows caption buttons
so they stay clickable, and it disappears in full screen, where the
system hides the buttons and the page can have the pixels back.
`chromeTopBandPx` follows: the band is no longer macOS-only, because it
is now the row both platforms put their buttons in. The sidebar's private
copy of it is gone, which also stops the brand row from being pushed down
twice on macOS.
* docs(dashboard): point the full screen note at the shell title row
The band the traffic lights need is no longer owned by the sidebar, so
the comment was describing a component that does not exist any more.
* feat(dashboard): give both left rails a control you can see, and a key
The two rails could only be collapsed through a 16px pill that stayed at
`opacity: 0` until the pointer crossed the seam, and the history rail's
pill sat 3px from the nav rail's, two chevrons pointing opposite ways on
one line. Neither had a shortcut. Everything worked, nothing was
findable.
Nav rail:
- The brand row carries the collapse button (PanelLeft glyph), always
visible and quiet until hovered, so the control lives in the rail it
moves instead of on its edge.
- Collapsed, the mark itself is the expand button: hovering swaps the
logo for the panel glyph without moving the hit target.
- The hover pill on that seam is gone — with two visible controls and
⌘B, it was a third way to do the same thing, and it was the one that
collided with the history rail's. The rail now draws its own border.
History rail:
- Its edge pill always straddles the seam (it used to jump to `after`
when collapsed, landing next to the nav pill).
- With the nav collapsed there is no Chat row to hang the toggle on, so
the icon rail gets a compact one — otherwise the only ways back were a
hover sliver and the keyboard.
Both: ⌘B / ⇧⌘B, advertised through `aria-keyshortcuts` and the tooltip.
Text fields keep the chord; contenteditable and open dialogs do not, and
IME composition is skipped. Escape now closes whichever rail is covering
the page on mobile. Reduced-motion users get the state change without the
width animation.
Toggles are also honest now: the nav toggle used to pop the history rail
open as a side effect when expanding on a chat route.
* fix(dashboard): keep the collapsed rail's history toggle on every page
The Chat row's toggle shows everywhere and reaches the history rail from
any route (opening it from /experts navigates to /chat first). The
collapsed rail's equivalent was gated to chat routes, which quietly took
the only visible control away on every other page.
* fix(dashboard): dock the collapsed rail's history toggle below the nav scroller
The toggle was appended to the end of the scrolling nav body. The nav list is
taller than the rail in a default 800px window, so the button landed past the
fold and only a scroll to the very bottom revealed it — the control was there,
just never on screen.
Dock it under the scroller instead, above the user footer: always visible,
still outside the nav flow, and centred on the 56px rail instead of 3px off.
* fix(dashboard): stop emitting an "undefined" class on the rail's brand row
The row asked for `styles.sidebarBrand`, a class that never existed in
Sidebar.module.less, so CSS Modules handed back undefined and every render
wrote class="undefined octop-desktop-drag". The styling already lives inline
and the drag class comes from desktopChrome, so the extra lookup only ever
produced noise in the DOM.
* fix(dashboard): give the collapsed rail's icons a name and a current page
Collapsing the rail drops every row label, and the icon buttons carried
neither an aria-label nor aria-current — a screen reader read a column of
identical unnamed buttons while the hover tooltip did all the work.
Name each icon from its row label and mark the active one as the current
page. The label stays the action-free row name so the tooltip and the
accessible name agree.
* fix(dashboard): answer a missing model with the setup prompt, not a red cross
"未配置可用模型" reaches the chat page as a failed agent start, so the empty
state rendered as antd's error Result: a red cross, "专家启动失败", and the raw
backend sentence ending in "然后重新启用此专家" — the alarm reserved for a
broken agent, in front of a first-run user who has done nothing wrong.
ModelConfigEmpty already says the same thing kindly, with the permission check
and the right call to action, but the only path that reached it required the
agent to have started first. Route the model-config failures there instead,
and only when the agent actually failed and no bridge is down: a disconnect is
still the state to act on, and last_error may just be a leftover.
* fix(dashboard): name the problem on an expert card instead of clipping a sentence
An expert card renders its error in one ellipsised 391px line, so the model
config sentence was cut at "…然后重新启用此专…" — losing the one instruction it
carried, while the card's own "去配置模型" button sat right underneath saying
the same thing.
Keep the full sentence in the tooltip and give the row the short form: model
config errors only have to name the diagnosis. Everything else still renders
at full length.
* fix(dashboard): tell an expert-less user apart from one whose expert is parked
The history rail lists only experts that can chat, so an expert waiting on a
model leaves the rail empty — and the empty state answered that with "从专家列表
选择模板,快速创建你的第一个 AI 专家" plus "去创建专家", pointing a first-run user
at creating something they already have.
Pass the count of not-yet-chat-ready experts down and answer that case with
"你的专家暂时都不能对话" and a link to the experts page. Users who own nothing
still get the create-first-expert nudge.
* fix(i18n): call it 专家 in the Chinese error strings too
The dashboard has been calling these things 专家 for a while — apiErrors says
"专家启动失败。", "专家正忙。", "未找到专家。" — but the server-side Chinese
catalogue still said "Agent", and the server's message is what reaches the
user, so a failed start surfaced as "Agent 启动失败。" in a toast.
Align the four expert lifecycle errors with the wording the UI already uses.
Slash-command vocabulary and product names (Agent Mail, Agent ID) are left
alone; only the messages a Chinese user reads about their own expert change.
* feat(desktop): make the loading and failure pages say what is happening
The splash was an 88px ring, a 60px icon and one gray line — about 7% of
a 1080x720 window, with no indication of what was being waited on or for
how long. It now carries the brand mark, the wordmark, one honest status
line ("正在准备本地服务…"), an indeterminate 200x3px bar that keeps
moving, and the version the shell is starting, so a slow boot never looks
like a frozen window.
The failure page was a generic ✕, a title, one sentence and a choice
between "quit" and "copy the error". Quitting was the only real option,
yet most boot failures are transient — a busy port, a sidecar that lost a
race — and the fix was "quit, find the icon, open it again". It now leads
with 重试启动 (app.relaunch + exit, so the retry starts from a clean
process), demotes 退出应用, and keeps the technical detail and the copy
action as secondary links below the fold.
The retry needs an IPC channel, so the shell's own pages get their own
single-method preload (preload/early.ts) rather than the Dashboard's
bridge: window.octopShell.restart, nothing else, and the button hides
itself when that bridge is absent.
EARLY_IPC lives in shared/early-ipc.ts instead of shared/ipc-contract.ts
on purpose. Both preload entries importing one module made Rollup emit it
as a shared chunk, and a sandboxed preload can only require electron and
Node built-ins — `require("./chunks/…")` throws, the bridge never
registers, and window.octopDesktop silently disappears. One module per
entry keeps every preload a single self-contained file.
* feat(dashboard): start the web app with the same splash as the shell
The first paint was an 88px spinner ring with a 60px vertical logo dropped
inside it — 60px of artwork inside an 88px circle with 14px of padding, so
the wordmark inside the logo sat on the ring itself — plus one line of gray
"splash" text. It also swapped assets by theme, which meant a second copy
of the brand to keep in sync with the shell.
It now uses the shell's composition verbatim: the 64px mark, the wordmark
as text, one honest line about what is being waited on ("正在加载界面…"),
and a 200x3px indeterminate bar. Both sides of the launch — Electron's
splash, then the Dashboard's boot screen — are now the same picture, so the
hand-off reads as one continuous startup instead of two different apps.
The mark is a single asset (favico.svg) because the tile carries its own
background; the white twin is gone. Theme still comes from data-theme so a
stored preference wins over the OS, and reduced-motion users get a static
bar instead of a sweep.
* feat(dashboard): show a crash the way the rest of the app fails
The boundary rendered antd's stock ``: a red ✕ in a
circle, and the raw exception as the subtitle — so a tab that lost a chunk
was greeted by "Failed to fetch dynamically imported module". It also had
nothing to do with the three other failure surfaces (offline panel, 404,
boot splash), which all speak in mascot + one sentence.
The fallback now uses the same shape: mascot, a title, one sentence, the
actions, and the exception folded into a "技术详情" disclosure that is
closed by default. It still reports what happened — just to whoever opens
it rather than to everyone.
The buttons are plain rather than antd's. This component renders above the
ConfigProvider, so an antd Button here inherits none of the app's theme:
measured in the running app it came out stock blue with the stock prefix,
next to a rose-branded UI. A crash page is the last place that should look
like a different product — and the last place worth depending on the theme
layer, which may be exactly what broke.
* feat(dashboard): let the offline page look like the product waiting
The PWA offline shell was hard-coded dark — light-theme users got a black
page — used the vertical lockup where the wordmark was already in the
heading, painted the heading itself in the accent color, and used a pill
button that exists nowhere else in the app.
It now shares the boot splash's composition (mark, title, one sentence,
one brand button, soft glow) and follows the theme the user actually
stored, read from localStorage the same way the app does, with the OS as
the fallback. Still zero dependencies: this page has to render when
nothing else will load.
* fix(desktop): make the whole splash/error surface the window handle
Both shell pages are chrome-less — the titlebar is hidden, so the only way
to move the window is a CSS drag region — and both offered exactly one: a
fixed 32px strip across the top. That is a strip you cannot see, on a page
whose entire content is centered in the middle of the window, so the
natural gesture (grab the page somewhere near the top) misses it and the
window does not budge.
The drag region now sits on `body` and covers the page, with the handful
of interactive things opting out through `no-drag`: buttons, the details
summary, links, inputs and the detail `
` (which stays selectable).
`app-region` inherits, so one declaration reaches every nested node —
verified in the running app: `.result__title` computes to `drag`,
`.result__button` and `.result__summary` to `no-drag`.
The fixed strip is gone; it was also the one structural difference from
the Dashboard's drag rows, which are in flow and have always worked.
* fix(dashboard): hold the boot mark still while it waits
Both waiting screens breathed — the desktop splash and the mark on the web
boot page — scaling to 0.96 and back on a 2.4s loop. On a retina display a
subpixel scale is exactly where a 64px logo goes soft, so the thing people
stare at longest was the thing that looked worst. The progress bar underneath
already says the app is alive; the mark does not need to pulse as well.
* feat(dashboard): give each rail its own collapse control
Two panel-collapse glyphs sat one above the other in the top-left corner:
the nav's own at the end of the brand row, and a second one hung inside the
"对话" nav item that folded the conversation rail. Same icon, 56px apart,
and neither said which panel it closed — you had to try one to find out.
Each rail now folds from its own header, where ChatGPT, Claude and deepseek
all put it: the nav's stays in the brand row, the conversation rail's moves
to the right of its search field. Both are 28px, share the hover fill and
the focus ring, and sit at the top-right of the panel they belong to, so
the control reads as "this panel" without a tooltip.
The nav row keeps its own layout back (no reserved padding for a button that
is no longer there).
Collapsed, the conversation rail has no header left to carry its control, so
the seam pill (`RailEdgeControl`) now stays painted instead of appearing on
hover only — otherwise the only way back was a 16px sliver nobody crosses on
purpose, plus the dock in the collapsed icon rail.
Web and desktop differ only in what may be dragged: in the shell the brand
row is a window handle, and its button still opts out with `app-region:
no-drag`. The rail header is not part of any drag region, so the new control
needs no opt-out — verified on the running client (computed `app-region` is
`no-drag` on the nav toggle, `none` on the rail one).
* fix(dashboard): run the rail seams to the window's top edge
The shell reserves a 32px band at the top for the native window buttons, and
it did that as a flow row above everything else. Every column therefore
started at y=32, which meant each rail's divider began with a blunt 1px tick
32px down — a line hanging in blank space, and the only thing that revealed
the band at all.
The band now floats over the columns instead of pushing them down: the rails
paint their surface and their seams from the window's top edge, the way
ChatGPT, Claude and deepseek draw theirs, and no junction is left to look at.
Nothing moves: every column insets its own content by the same 32px (published
as --octop-shell-top-band), so the band still owns exactly the strip it owned
before — empty in all of them — and stays one unbroken drag handle across the
window, above the rails (z-index 40, under every overlay at 100+) and clear of
the Windows caption buttons.
Full screen, mobile and the browser all resolve the band to 0, so the seams
simply reach the top and nothing is inset.
* feat(dashboard): fold both left rails from their seam
Each left column answered to a different control: the nav to a
`PanelLeftClose` glyph in the window's top row, the history rail to a
second glyph beside its search field, and a hover-only pill on the
divider in between that belonged to neither. Three ways to close two
panels, and the pill was an 18px sliver at 0 opacity — you found it by
accident or not at all.
Both now fold from one shape: a capsule straddling the rail's own seam,
centred on the line that actually moves. Quiet at rest (0.6) so two rails
side by side do not read as a strip of buttons, crisp under the pointer,
and always painted when its panel is collapsed — that state has no other
way back, so the handle is the way back.
The two-layer states are settled by position and ink, not by tooltips
alone:
- both open: one capsule per seam, each centred on its own divider;
- history closed: its handle lands on the nav's divider, where the nav
keeps one too. They stack 40px apart (nav above, history below) rather
than overlap, and only the collapsed one is painted bright — the faint
handle closes a panel, the bright one brings a panel back;
- both closed: the same pair, and the history handle still opens the
whole workspace (it broadcasts, so the nav returns with it) while the
nav handle restores just the icon rail.
The header glyphs are gone: the top row keeps only its height (the drag
band and the traffic lights still own that strip), and the search field
gets its full width back. The nav's seam handle lives in a host beside
the rail, since the rail clips its own width animation.
* fix(desktop): reap the whole dev process tree on shell exit
Ctrl+C previously forwarded SIGTERM to Electron and, after a watchdog
window, SIGKILLed only the Electron main process. Python runs in its own
detached process group, so a hung or unresponsive shell could leave the
backend alive holding the database open. Builds before launch were not
supervised at all.
run-dev.sh now hands the build and the app to scripts/dev-process.mjs:
- the managed command runs in its own process group, so terminal signals
reach the supervisor instead of racing with the app;
- the tree is sampled from ps and tracked by PID plus start time, keeping
detached descendants after their parent is gone and rejecting reused
PIDs; a failed sample is skipped rather than stopping a healthy app;
- the first signal sends Electron exactly one SIGTERM so its own sidecar
shutdown runs, then cleans observed survivors even if Electron exits
normally or crashes; after 8s the rest are killed and confirmed within
2 more seconds, and a second signal skips the grace window;
- explicit stops exit 0, build/app failures keep their status, and
unconfirmed cleanup reports 1 instead of claiming success.
Option parsing stays ahead of the supervisor so --help and bad flags never
need a process table.
* fix(desktop): let a bare 'pnpm dev' reach the supervisor again
macOS ships bash 3.2, which reports "${ORIGINAL_ARGS[@]}" as an unbound
variable under 'set -u' when the array is empty. A plain 'pnpm dev' has no
arguments, so the re-exec line aborted with
scripts/run-dev.sh: line 53: ORIGINAL_ARGS[@]: unbound variable
and the shell exited before starting anything. Linux shells expand the empty
array silently, so CI would never have caught it.
Expand the array only when it has elements, and add a regression test that
runs the real script with no arguments under a trimmed PATH so it stops at
the pnpm check instead of building.
* feat(dashboard): fold all three columns from their seams
Give the two left columns one hover-triggered handle each, straddling the
divider they share with the next column, and take the copies back out of
the column headers.
Placement is derived, not measured: the host column is relative and the
capsule sits at `left: 100%` with `translate(-50%)`, so it lands on the
seam and follows it when the column folds — the arrow flips with the state
(chevron-left to fold, chevron-right to reopen) and the handle ends up on
the new edge with no second rule. Nothing about it lives in the content.
The 20x44 capsule is its own hit area and stays transparent until hovered
(opacity 0 is still hit-testable, so no invisible overlay sits on the
seam and the column's resize handle either side stays usable). Folded, the
handle stays painted: it is that column's only way back.
Both handles carry a small offset off the seam's vertical centre
(+/-SEAM_HANDLE_STEP) so that when the history rail is closed — its seam
collapses onto the nav's — they stack instead of overlapping, which also
removes the old per-state `stack` prop and the shared-seam bookkeeping in
Sidebar.
ChatSidebarPanel no longer owns a fold control at all, so its railToggle
test and the RailEdgeControl it rendered are gone; the broadcast constant
moves to chatRailEvents.ts, next to its consumer.
* refactor(dashboard): unify desktop chrome height and streamline drag regions
Updated the desktop chrome height to a consistent 58px across the application, ensuring alignment with native window controls. Removed unnecessary drag regions from various components, consolidating the drag functionality into a single bounded area. Adjusted styles and layout to maintain visual consistency and improve usability, particularly in fullscreen mode. Enhanced tests to validate the new layout behavior and ensure proper integration across platforms.
* feat(logging): implement desktop logging functionality
Introduced a new logging system for the desktop application, allowing for better tracking of events and errors. The logs are stored in `/logs/desktop.log`, providing a centralized location for diagnostics. Updated various components to utilize the new logging methods, replacing console outputs with structured log entries. Added tests to ensure the logging functionality works as expected, including log rotation and error handling.
* feat(authentication): implement local account claim flow for existing users
Added a new document outlining the implementation plan for claiming existing local accounts when `OCTOP_HOME` already contains users. This addresses the scenario where users with pre-existing data are directed to the login page after installing a new desktop version. The document specifies the necessary API endpoints and security measures, although the actual implementation is yet to be completed. Updated `DESKTOP_ARCHITECTURE.zh.md` to reference this new functionality.
* feat(docs): add integration and task check documents for Octop desktop
Created new documentation for Octop's Electron integration, detailing the embedding of the green portable zip and the necessary steps for setup and execution. Additionally, added a document outlining the implementation plan for a pre-quit task check, which prompts users if there are ongoing tasks before exiting the application. These documents enhance the understanding of the desktop architecture and improve user experience during application shutdown.
* refactor(logging): restructure desktop logging system and update documentation
Reorganized the desktop logging functionality to store logs in a dedicated directory: `/logs/desktop/desktop.log`. Enhanced log rotation to occur at local midnight and at 100 MiB, with older logs being gzipped and purged based on retention settings. Updated related documentation to reflect these changes, including paths in `README.md` and implementation details in `DESKTOP_ARCHITECTURE.zh.md` and `LOCAL_ACCOUNT_CLAIM.zh.md`. Added tests to ensure the new logging behavior works as intended.
* feat(dashboard): add DesktopWindowDragBand component for improved window dragging
Introduced the DesktopWindowDragBand component to enhance the window dragging experience across different platforms. This component conditionally renders a drag region based on the desktop chrome style and fullscreen state. Updated MainLayout to utilize the new drag band, ensuring it integrates seamlessly with existing layouts. Added comprehensive tests for the DesktopWindowDragBand to validate its behavior in various scenarios, including fullscreen mode and different operating systems.
* feat(authentication): implement local account functionality for desktop users
Enhanced the authentication flow to support local accounts in the desktop application. Introduced a mechanism to create and sign in to a local account named "local," which bypasses the login screen. Updated JWT handling to differentiate between local and password accounts, ensuring proper session management. Modified the setup process to allow the addition of a local account alongside existing users. Added relevant tests to validate the new functionality and updated localization files for user-facing strings related to local account actions.
* feat(dashboard): enhance theme handling and improve UI consistency
Updated the dashboard's theme management to prioritize desktop shell preferences over stored values, ensuring a seamless user experience. Introduced functions to read and remember theme preferences, allowing for dynamic adjustments based on URL parameters. Modified CSS styles for better visual consistency across light and dark themes, including background and text color adjustments. Updated splash and error pages to share a common theme script, ensuring consistent theming during initial loading. Enhanced tests to validate new theme behaviors and ensure proper integration with the desktop application.
* feat(dashboard): update logo assets and improve theme consistency
Replaced the favicon with a new cropped logo asset for both light and dark themes, ensuring a unified appearance across the dashboard. Adjusted CSS styles to remove unnecessary properties and enhance visual consistency. Updated tests to validate the new logo integration and confirm that the splash and error pages utilize the same logo asset. Additionally, refactored the renderer configuration to streamline the build process for the desktop application.
* feat(dashboard): introduce RailEdgeControl and SplitSeamHandle components for improved navigation
Added the RailEdgeControl component to manage the navigation rail's edge interactions, allowing for seamless expansion and collapse of the sidebar. Introduced the SplitSeamHandle component to provide distinct controls for collapsing the navigation and expanding the history rail, enhancing user experience. Updated styles for better visual consistency and integrated new components into the MainLayout. Removed the deprecated RailSeamHandle component and its associated tests, ensuring a cleaner codebase. Added tests for the new components to validate their functionality and interactions.
* refactor(dashboard): remove SplitSeamHandle and enhance RailEdgeControl functionality
Deleted the SplitSeamHandle component along with its styles and tests to streamline the codebase. Enhanced the RailEdgeControl component to manage sidebar interactions more effectively, including improved hover effects and pointer event handling. Updated styles for better visual consistency and integrated new chat rail toggle functionality within the Sidebar component. Adjusted tests to validate the new behavior and ensure proper integration across the application.
* feat(dashboard): enhance sidebar collapsed navigation and styling
Improved the sidebar's collapsed navigation by introducing new styles and components for better user interaction. Updated the Sidebar and SidebarCollapsedIconNav components to support a more visually appealing collapsed state, including refined button styles and hover effects. Adjusted the layout to ensure proper alignment of icons and badges within the collapsed view. Enhanced tests to validate the new functionality and ensure consistent behavior across different screen sizes.
* fix(dashboard): adjust brand mark positioning in sidebar collapsed state
Modified the transform property of the brand mark in the sidebar's collapsed state to improve alignment. This change ensures a more visually appealing presentation of the logo when the sidebar is minimized.
* feat(mac-privacy): implement macOS privacy usage descriptions and localization
Added functionality to manage macOS privacy usage descriptions for microphone, speech recognition, screen capture, and local network access. Introduced a new module for handling localization in English and Chinese, ensuring compliance with macOS requirements. Updated the Electron builder configuration to include privacy-related information and write localization files during the packaging process. Added tests to validate the new privacy features and localization functionality.
* feat(dashboard): implement desktop update confirmation and localization enhancements
Added a new confirmation dialog for desktop updates, allowing users to confirm installations directly from the settings page. Updated the localization files for English and Chinese to include new strings related to the update process. Refactored the update handling logic to ensure the renderer cannot specify package URLs, enhancing security. Introduced tests for the DesktopUpdatePanel component to validate the new confirmation flow and user interactions.
* feat(dashboard): integrate desktop shell update checks into useUpdateStatus hook
Enhanced the useUpdateStatus hook to include checks for updates via the desktop shell, allowing for a more streamlined update process. Added a new test case to validate the behavior when the desktop shell is present. Updated the DesktopUpdatePanel component to utilize the new hook for fetching update status, ensuring a consistent user experience. Adjusted related tests to reflect these changes and improve overall functionality.
* feat(supervisor): improve process cleanup and temp directory handling
Introduced a new `removeTemp` function to handle the removal of temporary directories more robustly, addressing potential issues with busy or locked files. Updated the `SidecarSupervisor` class to wait for process exit before attempting to delete directories on Windows, ensuring proper cleanup. Refactored tests to utilize the new cleanup function, enhancing reliability in test scenarios.
* refactor(dashboard): simplify RailEdgeControl styles and remove unused resizing logic
Removed unnecessary resizing styles and props from the RailEdgeControl component to streamline the codebase. Updated the associated LESS file to eliminate redundant hover effects and improve overall clarity in styling. This change enhances maintainability and reduces complexity in the component's implementation.
* chore(electron): update icon configuration and replace icon asset
Added a comment in the electron-builder configuration to clarify the use of full-bleed opaque icns. Updated the icon asset located in resources to enhance visual quality. This change ensures better compatibility with macOS Finder display requirements.
* feat(electron): enhance DMG configuration and improve symlink handling
Updated the electron-builder configuration to include a custom DMG background and icon settings for better macOS compatibility. Enhanced the runtime extraction process by implementing safe symlink target checks and restoring symlinks from the portable zip, ensuring proper executable permissions. Added tests to validate the new symlink handling functionality and improve overall reliability.
* refactor(dashboard): remove device login functionality and clean up localization files
Removed device login related strings from English and Chinese localization files to streamline the user interface. Updated the DesktopUpdatePanel component by eliminating the reset login functionality and associated tests, enhancing overall clarity and maintainability of the codebase.
* refactor(dashboard): simplify Chat background styling and enhance DesktopUpdatePanel layout
Removed the radial gradient background from the Chat component, reverting to a solid background for improved clarity. Updated the DesktopUpdatePanel to apply a constrained panel style, enhancing layout consistency across settings pages. Added a new panelConstrained class to manage maximum width, improving responsiveness.
* feat(update): enhance update status handling and introduce channel head logic
Updated the useUpdateStatus hook to accurately reflect the latest version available, including the channel head logic for stable and beta versions. Added a new test case to verify behavior when no updates are available. Refactored the update coordinator to fetch the update manifest and determine the highest tag based on user settings. Improved documentation for clarity on version handling.
* feat(runtime): enhance portable runtime handling and extraction process
Updated the workflow for managing the portable runtime in the Electron application. Improved the extraction logic to handle platform-specific requirements, ensuring that the runtime is correctly expanded and utilized based on the operating system. Enhanced documentation in the README and related files to clarify the runtime structure and installation paths. Added tests to validate the new runtime detection and extraction functionality, ensuring robust handling across Windows, macOS, and Linux environments.
* feat(installer): add custom checks for running processes and enhance portable runtime extraction
Implemented a custom check in the NSIS installer to prevent installation if the application is already running, providing user feedback in both English and Chinese. Added logic to extract the portable runtime during installation, ensuring proper handling of the runtime files. Updated the .gitignore to allow the build directory for the installer, improving build management.
* feat(installer): enhance installation process with taskbar pinning and desktop shortcut options
Updated the NSIS installer to include user options for pinning the application to the taskbar and creating a desktop shortcut during installation. The taskbar pinning option is presented before file copying, while the desktop shortcut creation is confirmed on the finish page. Silent installations will still create the desktop shortcut unless specified otherwise. Improved uninstall process to remove taskbar pins and shortcuts appropriately, ensuring a cleaner removal experience.
* feat(workflow): handle unsigned packaging for macOS in workflow_dispatch event
Updated the GitHub Actions workflow to package unsigned installers when the CSC_LINK secret is unset during a workflow_dispatch event. This change prevents build failures related to code signing and ensures a smoother packaging process. Additionally, added comments to clarify the logic for handling signing conditions.
* fix(desktop): keep manual package dispatches unsigned
Manual workflow_dispatch was still asking electron-builder to sign, which aborts on macOS when no certificate is configured. Branch dispatches now skip signing; a dispatch on a v* tag still signs.
Co-authored-by: Cursor
* fix(installer): declare the taskbar page with Page custom
MUI2 does not define MUI_PAGE_CUSTOM, so makensis aborted both Windows installers.
Co-authored-by: Cursor
* feat(tray): implement system tray functionality for Windows
Added support for a system tray icon on Windows, allowing users to access the application from the notification area. Implemented context menu options for showing the window and quitting the application. Enhanced the installation process to include checks for the tray icon and updated related logic to ensure proper behavior when the application is minimized or closed. Updated health check timeout to accommodate longer cold imports of the bundled runtime.
Co-authored-by: Cursor
* feat(installer): enhance Python bytecode compilation during installation
Updated the NSIS installer to compile Python bytecode into the designated cache directory during installation, improving the initial launch experience. The installer now handles potential compilation failures gracefully, allowing the application to function while ensuring bytecode is compiled on first launch if necessary. Additionally, clarified the retention of user data during uninstallation, preserving the cache directory along with other user configurations.
* fix(installer): update uninstallation process to remove bytecode cache
Modified the uninstallation logic in the NSIS installer to delete the Python bytecode cache directory (`OCTOP_HOME\pyc`) while retaining user data such as the database, workspace, and configuration files. This ensures a cleaner uninstallation process while allowing for bytecode recompilation on the next installation. Updated related documentation to reflect these changes.
* fix(installer): leave customFiles macros to electron-builder
The portable zip is a precompressed resource, so electron-builder already defines customFiles_. A second definition aborts makensis.
Co-authored-by: Cursor
* fix(installer): write install steps into the details list
textonly only updated the status line above the progress bar, so the details box stayed empty.
Co-authored-by: Cursor
* fix(desktop): put window controls on their own row and show error text
Windows keeps a full system title row and the standard menus, while macOS traffic lights stay at their usual size. User admin failures show the message instead of the raw JSON, and local sign-in copy says 本地账户.
Co-authored-by: Cursor
* fix(dashboard): keep extra tabs in the Tabs overflow menu
The tab row grew with its labels and the page clipped the tail, so the more menu never appeared.
Co-authored-by: Cursor
* fix(desktop): make the Windows title bar transparent and keep the tray icon
The opaque caption hid the page, the packaged app had no ico for the notification area, and About only showed the version.
Co-authored-by: Cursor
* fix(desktop): start the Windows dev dashboard past the boot screen
Node rejects spawn of vite.cmd, and pnpm does not expose dayjs, katex, or @ant-design/icons until they are direct dependencies.
Co-authored-by: Cursor
* feat(desktop): keep the Windows window and draw its menu in the page
The splash window loads the dashboard in place. File, Edit, View, and Help stay on that bar in fullscreen, while the native caption buttons hide and the loading and error pages can be dragged from the top strip.
Co-authored-by: Cursor
* fix(desktop): line the loading mark up with the wordmark
The red circle sits left in the mark, so both boot screens nudge it right onto the text below.
Co-authored-by: Cursor
* fix(desktop): satisfy the menu index typecheck
Indexing the menu tuple can be undefined under strict checks, which failed the desktop package build.
Co-authored-by: Cursor
* fix(desktop): drag Windows only from the caption bar
The page drag strip stays macOS-only, and the boot line says the app is opening.
Co-authored-by: Cursor
* refactor(tests): improve formatting and readability in test files
Updated test files to enhance code readability by adjusting formatting, including consistent indentation and line breaks. This includes changes in the WindowsAppMenu, SidebarCollapsedIconNav, and MainLayout tests, among others.
Co-authored-by: Cursor
* feat(desktop): enable dragging macOS windows from the drawer header
Added CSS rules to allow dragging of macOS windows specifically from the drawer header, ensuring that the title-bar drag strip remains functional. Updated tests to verify this behavior.
Co-authored-by: Cursor
* refactor(build): streamline Linux packaging by removing AppImage support
Updated the CI workflow and documentation to reflect the removal of AppImage from the Linux build targets, focusing on deb and rpm packages instead. Adjusted related scripts and tests to ensure consistency with the new packaging strategy.
* fix(desktop): hide the Windows loading-page menu and keep reload on client routes
The splash was showing the native menu bar, and reloading a frontend route such as /chat served an empty page.
Co-authored-by: Cursor
* fix(desktop): keep the Windows caption above drawers
Drawers mount on the body and were painting over the File / Edit / View / Help row.
Co-authored-by: Cursor
* refactor(build): optimize packaging by pruning unnecessary files and updating dashboard handling
Introduced a new script to remove bloat from the packaged site, including debug symbols and test directories. Updated the CI workflow to reflect changes in how the Dashboard is served, ensuring it is now sourced directly from the portable tree without duplication. Adjusted related configurations and documentation accordingly.
* feat(build): introduce dual packaging variants for desktop and portable applications
Added support for two packaging variants: 'lite' for public network access and 'full' for intranet use, which includes additional components like desktop, OCR, and local embedding. Updated CI workflows, scripts, and documentation to reflect these changes, ensuring proper naming conventions and asset handling for both variants. Enhanced tests to verify the correct prioritization of package names based on the selected variant.
* feat(portable): update macOS dependency overrides for onnxruntime and opencv-python
Enhanced the `_common.sh` script to pin `onnxruntime` to version 1.23.2 for macOS 13.0 compatibility and added `opencv-python` version 4.11.0.86 for Intel architecture. Updated README to reflect these changes and clarified platform-specific overrides. Adjusted unit tests to include `darwin-arm64` as an override platform.
* feat(dependencies): add shapely as a dependency for knowledge-ocr and update version to 2.2.0
Included shapely in the knowledge-ocr package dependencies to ensure compatibility with Windows ARM64. Updated the version to 2.2.0, which provides wheels for all portable targets. Adjusted packaging scripts to exclude opencv-python and pyclipper for Windows ARM64 due to the absence of available wheels. Updated related documentation and tests to reflect these changes.
* feat(desktop): unify caption overlay behavior for Windows and Linux
Updated the desktop application to treat Windows and Linux consistently regarding the caption overlay. Adjusted comments and documentation to reflect that both platforms share the same row for the menu and window buttons. Enhanced tests to verify the new behavior across both platforms, ensuring a cohesive user experience.
Co-authored-by: Cursor
* feat(auth): enhance device token generation with MFA and password versioning
Updated the device token generation logic to include Multi-Factor Authentication (MFA) and password versioning. The changes ensure that the generated token incorporates the user's MFA and password versions, improving security and user session management. This enhancement aligns with the overall goal of strengthening authentication processes within the application.
* refactor(chat): simplify padding and update comments in ChatTitleBar styles
Refactored the CSS for the ChatTitleBar by simplifying the padding properties and removing unnecessary complexity related to window controls. Updated comments for clarity regarding layout behavior. Adjusted tests to reflect these changes, ensuring consistency in style expectations.
* feat(desktop): implement desktop shortcut creation for Linux installations
Added scripts to create and manage desktop shortcuts for the Linux version of the application during installation and removal processes. The `after-install` and `after-remove` scripts ensure that shortcuts are placed on the user's desktop and removed appropriately, enhancing user accessibility. Updated documentation to reflect these changes and included tests to verify the functionality of the new shortcut management system.
* feat(desktop): implement flexible overlay layers for popups and menus
Introduced a new structure for managing overlay layers in the desktop application, allowing popups and menus to be positioned correctly without overlapping. Added `octop-chrome` and `octop-stage` elements to the HTML layout for better organization of UI components. Updated CSS to ensure proper flex behavior and positioning of elements. Enhanced tests to verify the new overlay functionality and layout adjustments.
* feat(desktop): add Linux window controls with square buttons
Implemented square caption buttons for Linux in the desktop application, allowing users to minimize, maximize, and close windows directly from the application interface. The buttons are styled to match the application's theme, with the close button turning red on hover. Updated the layout and styles to ensure proper integration with existing components. Added tests to verify functionality and appearance across different scenarios.
* feat(vscode): enhance .gitignore and add custom CSS data support
Updated .gitignore to exclude all files in the .vscode directory except for settings.json and css-custom-data.json. Added css-custom-data.json to provide custom data for CSS properties specific to Electron/Chromium. Created settings.json to reference the custom data files for CSS and LESS, improving development experience in VSCode.
* feat(desktop): migrate styles from CSS to LESS for improved modularity
Refactored the desktop application to replace CSS files with LESS modules for the splash and error pages, enhancing style encapsulation and maintainability. Updated the Linux window controls to utilize LESS for styling, ensuring consistency across components. Removed legacy CSS files and adjusted imports accordingly. Added tests to validate the new styling approach.
* refactor(desktop): streamline package naming and CI workflow for desktop installers
Updated the desktop packaging process to unify the naming convention for installers, removing the `-full` suffix for intranet packages. Adjusted CI workflows to reflect this change, ensuring that only the `browser` extra is included in the desktop installers while keeping desktop control, OCR, and local embedding in the Docker image. Enhanced documentation to clarify the new structure and updated tests to validate the changes in package naming and CI behavior.
* fix(tests): ensure LF line endings in Linux desktop shortcut tests
Updated the test file for Linux desktop shortcuts to read files with LF line endings, addressing issues caused by CRLF line endings on Windows. This change improves compatibility and ensures accurate test results across platforms.
* feat(desktop): enhance Linux window controls with icon components
Refactored the Linux window controls to utilize dedicated icon components for minimize, maximize, restore, and close actions, improving code modularity and readability. Introduced a new `WindowControlIcons` file to manage these icons and updated the styling to ensure consistent dimensions across the application. This change enhances the visual consistency and maintainability of the window control interface.
* fix(styles): adjust #root min-height to prevent clipping under caption row
Updated the CSS for the #root element to set min-height to 0, addressing layout issues caused by the boot splash height exceeding the visible area. This change ensures proper rendering of the application interface without clipping under the caption row. Added corresponding tests to validate the CSS adjustments.
* feat(loading): introduce BrandLoading component for unified loading experience
Replaced the Ant Design Spin component with a new BrandLoading component across the application, providing a consistent loading interface that features a horizontal logo and a status line. Updated styles for the loading indicators to enhance visual consistency and responsiveness. The new implementation includes a spinner that matches the branding and integrates seamlessly with both light and dark themes. Additionally, updated tests to validate the new loading behavior and ensure proper rendering in various scenarios.
* feat(assets): integrate SVGR for SVG icon management and add window control icons
Added the `vite-plugin-svgr` to streamline the handling of SVG icons in the application. Replaced the existing icon components for window controls with SVG imports, enhancing modularity and maintainability. Introduced new SVG assets for close, maximize, minimize, and restore actions, while removing the previous `WindowControlIcons` component. Updated relevant configurations and type definitions to support the new SVG integration.
* fix(build): increase memory limit for dashboard build process
Updated the Makefile to increase the Node.js memory limit from 2048MB to 4096MB during the dashboard build process. This change addresses out-of-memory issues encountered on GitHub runners, ensuring a successful build without interruptions.
* fix(build): update Linux maintainer scripts for desktop icon management
Refactored the Linux maintainer scripts to improve desktop icon handling during installation and removal processes. Updated the `linux-after-install.sh` and `linux-after-remove.sh` scripts to accommodate both deb and rpm package formats, ensuring proper desktop shortcut creation and removal. Adjusted test cases to reflect these changes and validate the new logic for icon management.
---------
Co-authored-by: Cursor
---
.github/workflows/octop-desktop.yml | 240 +-
.gitignore | 5 +-
.vscode/css-custom-data.json | 19 +
.vscode/settings.json | 4 +
Makefile | 3 +-
README.md | 2 +
README_CN.md | 2 +
dashboard/index.html | 249 +-
dashboard/package-lock.json | 357 +-
dashboard/package.json | 4 +
dashboard/public/logo_mark.svg | 55 +
dashboard/public/offline.html | 128 +-
dashboard/src/App.tsx | 18 +-
dashboard/src/api/config.ts | 7 +-
dashboard/src/api/desktopSession.ts | 114 +
dashboard/src/api/modules/auth.ts | 4 +
dashboard/src/api/modules/update.ts | 2 +-
dashboard/src/api/modules/wsChat.ts | 4 +-
.../src/api/request.desktopSession.test.ts | 157 +
dashboard/src/api/request.ts | 50 +-
.../src/assets/window-controls/close.svg | 3 +
.../src/assets/window-controls/maximize.svg | 3 +
.../src/assets/window-controls/minimize.svg | 3 +
.../src/assets/window-controls/restore.svg | 3 +
dashboard/src/components/AntdAppProvider.tsx | 6 +-
dashboard/src/components/AuthGuard.tsx | 16 +-
dashboard/src/components/AvatarDropdown.tsx | 7 +-
.../BrandLoading/BrandLoading.module.less | 69 +
.../src/components/BrandLoading/index.tsx | 48 +
.../ChatDockPanelShell.test.tsx | 41 +-
.../BrowserWorkspace/ChatDockPanelShell.tsx | 2 +-
.../DesktopWindowControls.module.less | 104 -
.../DesktopWindowControls.test.tsx | 44 -
.../DesktopWindowControls.tsx | 93 -
.../components/DesktopWindowControls/index.ts | 1 -
.../components/DesktopWindowDragBand.test.tsx | 63 +
.../src/components/DesktopWindowDragBand.tsx | 38 +
.../ErrorBoundary/ErrorFallback.module.less | 136 +
.../ErrorBoundary/ErrorFallback.tsx | 77 +
.../components/ErrorBoundary/index.test.tsx | 41 +
.../src/components/ErrorBoundary/index.tsx | 78 +-
.../components/LinuxWindowControls.test.tsx | 112 +
.../src/components/LinuxWindowControls.tsx | 88 +
.../OctopSpinner/OctopSpinner.module.less | 36 +-
.../src/components/OctopSpinner/index.tsx | 7 +-
.../src/components/PageLoading/index.tsx | 6 +-
.../PwaInstallPrompt/index.test.tsx | 10 +-
.../src/components/PwaInstallPrompt/index.tsx | 2 +-
.../components/RailEdgeControl.module.less | 72 +-
.../src/components/RailEdgeControl.test.tsx | 40 +
dashboard/src/components/RailEdgeControl.tsx | 47 +-
dashboard/src/components/TabLabel/TabBar.tsx | 30 +-
.../src/components/TabLabel/index.module.less | 50 +-
.../src/components/WindowsAppMenu.test.tsx | 137 +
dashboard/src/components/WindowsAppMenu.tsx | 191 +
dashboard/src/hooks/useBrowserStream.ts | 4 +-
.../hooks/useDashboardPushToast.module.less | 4 -
dashboard/src/hooks/useDesktopChrome.ts | 49 +-
dashboard/src/hooks/useDesktopStream.ts | 4 +-
dashboard/src/hooks/useMobileStream.ts | 4 +-
dashboard/src/hooks/useNativeWindowChrome.ts | 17 +
dashboard/src/hooks/useRailShortcuts.test.tsx | 68 +
dashboard/src/hooks/useRailShortcuts.ts | 43 +
dashboard/src/hooks/useUpdateStatus.test.ts | 43 +
dashboard/src/hooks/useUpdateStatus.ts | 36 +
dashboard/src/hooks/useWindowFullscreen.ts | 20 +
.../src/layouts/MainLayout/index.test.tsx | 277 ++
dashboard/src/layouts/MainLayout/index.tsx | 356 +-
.../layouts/MainLayout/seamHandle.test.tsx | 151 +
dashboard/src/layouts/PageShell.module.less | 4 +
dashboard/src/layouts/PageShell.tsx | 2 -
.../layouts/Sidebar.chatRailToggle.test.tsx | 133 -
dashboard/src/layouts/Sidebar.module.less | 165 +-
.../src/layouts/Sidebar.railCollapse.test.tsx | 107 +
dashboard/src/layouts/Sidebar.tsx | 235 +-
.../layouts/SidebarCollapsedIconNav.test.tsx | 100 +
.../src/layouts/SidebarCollapsedIconNav.tsx | 64 +-
dashboard/src/locales/en.json | 33 +-
dashboard/src/locales/zh.json | 33 +-
dashboard/src/main.tsx | 9 +-
.../src/pages/Admin/Users/UsersListPanel.tsx | 36 +-
.../Agent/Connectors/openAuthWindow.test.ts | 17 +-
.../pages/Agent/Connectors/openAuthWindow.ts | 8 +-
dashboard/src/pages/Chat/chatRailEvents.ts | 9 +
.../src/pages/Chat/chatSidebar.partial.less | 41 +-
.../Chat/chatThemeOverrides.partial.less | 36 +-
.../components/AgentNotReadyScreen.test.tsx | 91 +
.../Chat/components/AgentNotReadyScreen.tsx | 25 +-
.../components/ChatSidebarPanel.edge.test.tsx | 64 +
.../Chat/components/ChatSidebarPanel.tsx | 60 +-
.../Chat/components/ChatTitleBar.test.tsx | 265 +-
.../pages/Chat/components/ChatTitleBar.tsx | 61 +-
.../pages/Chat/components/MessageFileCard.tsx | 2 +-
.../SessionList.emptyAgents.test.tsx | 57 +
.../src/pages/Chat/components/SessionList.tsx | 52 +-
dashboard/src/pages/Chat/index.module.less | 75 +-
dashboard/src/pages/Chat/index.tsx | 42 +-
.../src/pages/Chat/utils/droppedFiles.ts | 2 +-
.../Control/RemoteAndroid/useAdbShell.ts | 6 +-
.../src/pages/Control/Terminal/useTerminal.ts | 8 +-
.../pages/Experts/components/AgentCard.tsx | 9 +-
.../src/pages/Experts/components/TeamCard.tsx | 9 +-
dashboard/src/pages/Login/index.tsx | 211 +-
.../DesktopUpdatePanel.test.tsx | 93 +
.../AdvancedSettings/DesktopUpdatePanel.tsx | 194 +
.../AdvancedSettings/UpdateConfig.module.less | 4 +
.../AdvancedSettings/UpdateConfig.tsx | 9 +
dashboard/src/pages/Setup/index.tsx | 30 +-
dashboard/src/pages/Setup/steps/AdminStep.tsx | 154 +-
.../src/pages/Setup/steps/FinishStep.tsx | 28 +-
dashboard/src/pages/Setup/wizardClient.ts | 3 +-
dashboard/src/styles/bootTheme.test.ts | 51 +-
dashboard/src/styles/layout.css | 265 +-
dashboard/src/styles/spin-override.css | 18 +-
dashboard/src/styles/theme-vars.css | 4 +-
dashboard/src/utils/agentError.test.ts | 37 +-
dashboard/src/utils/agentError.ts | 27 +
dashboard/src/utils/desktopBridge.ts | 151 +
dashboard/src/utils/desktopChrome.test.ts | 337 +-
dashboard/src/utils/desktopChrome.ts | 245 +-
.../src/utils/desktopExternalLinks.test.ts | 79 -
dashboard/src/utils/desktopExternalLinks.ts | 121 -
dashboard/src/utils/desktopWsUrl.test.ts | 70 +
dashboard/src/utils/desktopWsUrl.ts | 48 +
.../src/utils/nativeWindowChrome.test.ts | 68 +
dashboard/src/utils/nativeWindowChrome.ts | 42 +
dashboard/src/utils/overlayLayers.test.ts | 33 +
dashboard/src/utils/overlayLayers.ts | 25 +
dashboard/src/utils/railShortcuts.test.ts | 94 +
dashboard/src/utils/railShortcuts.ts | 91 +
dashboard/src/utils/saveBlobAsFile.test.ts | 82 +-
dashboard/src/utils/saveBlobAsFile.ts | 20 +-
dashboard/src/vite-env.d.ts | 1 +
dashboard/vite.config.ts | 2 +
dashboard/vitest.config.ts | 3 +-
desktop/README.md | 328 +-
.../AGENT_ELECTRON_INTEGRATION.md | 23 +-
desktop/docs/DESKTOP_ARCHITECTURE.zh.md | 647 +++
desktop/docs/LOCAL_ACCOUNT_CLAIM.zh.md | 135 +
desktop/docs/QUIT_TASK_CHECK.zh.md | 218 +
desktop/package-dev.sh | 75 -
desktop/package-release.sh | 117 -
desktop/portable/Makefile | 12 +-
desktop/portable/README.md | 21 +-
desktop/portable/_common.sh | 24 +
desktop/portable/package.sh | 20 +-
desktop/portable/prune_packages.py | 114 +
desktop/portable/vendor-wheels.sh | 1 +
desktop/src/.gitignore | 25 +-
desktop/src/.npmrc | 14 +
desktop/src/Taskfile.yml | 33 -
desktop/src/assets/index.html | 767 ----
desktop/src/assets/octop-mascot-peek.webp | Bin 249002 -> 0 bytes
desktop/src/assets/octop-mascot-type.webp | Bin 378064 -> 0 bytes
desktop/src/assets/tray-icon-template.png | Bin 1641 -> 0 bytes
desktop/src/assets/tray-icon.png | Bin 8025 -> 0 bytes
desktop/src/build/Taskfile.yml | 79 -
desktop/src/build/appicon-macos.png | Bin 433408 -> 0 bytes
desktop/src/build/config.yml | 47 -
desktop/src/build/darwin/Info.dev.plist | 35 -
desktop/src/build/darwin/Info.plist | 33 -
desktop/src/build/darwin/Taskfile.yml | 175 -
desktop/src/build/installer.nsh | 304 ++
desktop/src/build/linux-after-install.sh | 75 +
desktop/src/build/linux-after-remove.sh | 278 ++
desktop/src/build/linux-desktop-shortcut.sh | 238 +
desktop/src/build/linux/Taskfile.yml | 51 -
desktop/src/build/stamp_version.py | 168 -
desktop/src/build/windows/Taskfile.yml | 126 -
desktop/src/build/windows/info.json | 15 -
desktop/src/build/windows/nsis/project.nsi | 100 -
.../src/build/windows/nsis/wails_tools.nsh | 221 -
desktop/src/build/windows/wails.exe.manifest | 22 -
desktop/src/bundled/.gitkeep | 0
desktop/src/cmd/devserver/main.go | 21 -
desktop/src/desktop_copy.go | 108 -
desktop/src/desktop_copy_test.go | 25 -
desktop/src/dock_reopen.go | 30 -
desktop/src/dock_reopen_test.go | 67 -
desktop/src/download.go | 407 --
desktop/src/download_test.go | 697 ---
desktop/src/electron-builder.config.ts | 120 +
desktop/src/electron.vite.config.ts | 55 +
desktop/src/embed_portable.go | 8 -
desktop/src/embed_portable_embedded.go | 11 -
desktop/src/filedrop.go | 403 --
desktop/src/filedrop_test.go | 184 -
desktop/src/go.mod | 18 -
desktop/src/go.sum | 35 -
desktop/src/icons_darwin.go | 25 -
desktop/src/icons_other.go | 20 -
desktop/src/mac-privacy-plist.ts | 71 +
desktop/src/main.go | 468 --
desktop/src/main/app-version.test.ts | 61 +
desktop/src/main/app-version.ts | 41 +
.../src/main/dev/dashboard-dev-server.test.ts | 87 +
desktop/src/main/dev/dashboard-dev-server.ts | 144 +
desktop/src/main/index.ts | 1162 +++++
desktop/src/main/log/desktop-log.test.ts | 244 +
desktop/src/main/log/desktop-log.ts | 269 ++
desktop/src/main/mac-privacy-plist.test.ts | 39 +
desktop/src/main/protocol/static-handler.ts | 68 +
desktop/src/main/protocol/stream-proxy.ts | 43 +
desktop/src/main/protocol/ws-relay.test.ts | 279 ++
desktop/src/main/protocol/ws-relay.ts | 220 +
.../main/session/device-credential.test.ts | 256 ++
desktop/src/main/session/device-credential.ts | 195 +
.../src/main/session/device-session.test.ts | 212 +
desktop/src/main/session/device-session.ts | 117 +
.../src/main/session/safe-storage-cipher.ts | 63 +
desktop/src/main/storage/client-settings.ts | 67 +
desktop/src/main/supervisor/health.ts | 50 +
.../src/main/supervisor/process-tree.test.ts | 43 +
desktop/src/main/supervisor/process-tree.ts | 83 +
desktop/src/main/supervisor/random-port.ts | 29 +
.../main/supervisor/runtime-extractor.test.ts | 182 +
.../src/main/supervisor/runtime-extractor.ts | 194 +
desktop/src/main/supervisor/sha256.ts | 21 +
desktop/src/main/supervisor/shell-env.test.ts | 94 +
desktop/src/main/supervisor/shell-env.ts | 64 +
desktop/src/main/supervisor/sidecar.test.ts | 186 +
desktop/src/main/supervisor/sidecar.ts | 159 +
desktop/src/main/supervisor/version.test.ts | 27 +
desktop/src/main/supervisor/version.ts | 64 +
.../src/main/supervisor/zip-safety.test.ts | 25 +
desktop/src/main/update/download.test.ts | 88 +
desktop/src/main/update/download.ts | 53 +
desktop/src/main/update/installer.test.ts | 163 +
desktop/src/main/update/installer.ts | 164 +
.../main/update/update-coordinator.test.ts | 121 +
desktop/src/main/update/update-coordinator.ts | 140 +
desktop/src/main/windows/about-info.test.ts | 83 +
desktop/src/main/windows/about-info.ts | 75 +
desktop/src/main/windows/app-menu.test.ts | 93 +
desktop/src/main/windows/app-menu.ts | 149 +
desktop/src/main/windows/chrome.test.ts | 160 +
desktop/src/main/windows/chrome.ts | 232 +
desktop/src/main/windows/early-window.ts | 120 +
desktop/src/main/windows/main-window.ts | 100 +
desktop/src/main/windows/present.test.ts | 117 +
desktop/src/main/windows/present.ts | 73 +
desktop/src/main/windows/size.test.ts | 21 +
desktop/src/main/windows/size.ts | 11 +
desktop/src/main/windows/tray.test.ts | 75 +
desktop/src/main/windows/tray.ts | 65 +
desktop/src/mise.toml | 24 +
desktop/src/openurl.go | 170 -
desktop/src/openurl_test.go | 49 -
desktop/src/package.json | 52 +
desktop/src/pnpm-lock.yaml | 3995 +++++++++++++++++
desktop/src/pnpm-workspace.yaml | 23 +
desktop/src/portable_upgrade.go | 116 -
desktop/src/portable_upgrade_test.go | 73 -
desktop/src/preload/early.ts | 23 +
desktop/src/preload/index.ts | 146 +
desktop/src/preventsleep.go | 34 -
desktop/src/preventsleep_darwin.go | 21 -
desktop/src/preventsleep_linux.go | 47 -
desktop/src/preventsleep_other.go | 9 -
desktop/src/preventsleep_windows.go | 27 -
desktop/src/process.go | 272 --
desktop/src/process_test.go | 241 -
desktop/src/process_unix.go | 17 -
desktop/src/process_windows.go | 31 -
desktop/src/renderer/.gitattributes | 2 +
desktop/src/renderer/error.html | 25 +
desktop/src/renderer/splash.html | 30 +
.../src/assets/logo_horizontal_dark.png | Bin 0 -> 19005 bytes
.../src/assets/logo_horizontal_white.png | Bin 0 -> 15339 bytes
.../src/renderer/src/assets/octop-mark.svg | 55 +
desktop/src/renderer/src/base.less | 103 +
desktop/src/renderer/src/base.test.ts | 113 +
desktop/src/renderer/src/error.module.less | 266 ++
desktop/src/renderer/src/error.tsx | 172 +
.../src/linux-window-controls.module.less | 56 +
.../src/linux-window-controls.test.ts | 27 +
.../renderer/src/linux-window-controls.tsx | 83 +
desktop/src/renderer/src/mount.tsx | 12 +
desktop/src/renderer/src/splash.module.less | 155 +
desktop/src/renderer/src/splash.tsx | 52 +
desktop/src/renderer/src/vite-env.d.ts | 2 +
desktop/src/renderer/vite.config.ts | 49 +
.../darwin => resources}/dmg-background.jpeg | Bin
desktop/src/resources/dmg-background.png | Bin 0 -> 136060 bytes
desktop/src/resources/dmg-background@2x.png | Bin 0 -> 386721 bytes
desktop/src/resources/icon.icns | Bin 0 -> 781307 bytes
desktop/src/resources/icon.ico | Bin 0 -> 91700 bytes
.../{build/appicon.png => resources/icon.png} | Bin
desktop/src/scripts/dev-process.mjs | 226 +
desktop/src/scripts/dev-process.test.mjs | 462 ++
.../scripts/linux-desktop-shortcut.test.mjs | 367 ++
desktop/src/scripts/make-dev-runtime.sh | 48 +
.../src/scripts/register-extensionless-ts.mjs | 6 +
.../src/scripts/resolve-extensionless-ts.mjs | 12 +
desktop/src/scripts/run-dev.sh | 130 +
desktop/src/settings.go | 128 -
desktop/src/settings_test.go | 23 -
desktop/src/settings_window.go | 18 -
desktop/src/shared/early-ipc.ts | 16 +
desktop/src/shared/global.d.ts | 16 +
desktop/src/shared/ipc-contract.ts | 82 +
desktop/src/shared/shell-error.test.ts | 73 +
desktop/src/shared/shell-error.ts | 92 +
desktop/src/tray_click.go | 11 -
desktop/src/tray_click_test.go | 17 -
desktop/src/tray_menu.go | 18 -
desktop/src/tray_menu_test.go | 68 -
desktop/src/tsconfig.json | 28 +
desktop/src/version.go | 153 -
desktop/src/window_chrome.go | 88 -
desktop/src/window_chrome_test.go | 173 -
docs/configuration.md | 14 +
mise.toml | 11 +-
pyproject.toml | 1 +
scripts/release_download_links.py | 23 +-
src/octop/api/app.py | 2 +
src/octop/api/deps.py | 3 +
src/octop/api/routers/auth_device.py | 226 +
src/octop/api/routers/envs.py | 7 +
src/octop/api/routers/setup.py | 142 +-
src/octop/api/routers/update.py | 39 +
src/octop/cli/commands/update.py | 4 +
src/octop/i18n/zh.json | 8 +-
src/octop/infra/desktop.py | 56 +
src/octop/infra/knowledge/ocr.py | 7 +-
src/octop/infra/setup/self_update.py | 17 +-
src/octop/infra/utils/env_file.py | 15 +-
src/octop/launch.py | 8 +-
.../test_desktop_device_session.py | 208 +
tests/integration/test_setup_wizard.py | 100 +
tests/unit/desktop/test_stamp_version.py | 133 -
tests/unit/infra/setup/test_self_update.py | 39 +-
tests/unit/test_desktop_shell.py | 212 +
tests/unit/test_portable_prune.py | 96 +
tests/unit/test_release_download_links.py | 19 +-
tests/unit/test_vendor_wheels_argv.py | 41 +-
uv.lock | 102 +-
337 files changed, 24485 insertions(+), 8784 deletions(-)
create mode 100644 .vscode/css-custom-data.json
create mode 100644 .vscode/settings.json
create mode 100644 dashboard/public/logo_mark.svg
create mode 100644 dashboard/src/api/desktopSession.ts
create mode 100644 dashboard/src/api/request.desktopSession.test.ts
create mode 100644 dashboard/src/assets/window-controls/close.svg
create mode 100644 dashboard/src/assets/window-controls/maximize.svg
create mode 100644 dashboard/src/assets/window-controls/minimize.svg
create mode 100644 dashboard/src/assets/window-controls/restore.svg
create mode 100644 dashboard/src/components/BrandLoading/BrandLoading.module.less
create mode 100644 dashboard/src/components/BrandLoading/index.tsx
delete mode 100644 dashboard/src/components/DesktopWindowControls/DesktopWindowControls.module.less
delete mode 100644 dashboard/src/components/DesktopWindowControls/DesktopWindowControls.test.tsx
delete mode 100644 dashboard/src/components/DesktopWindowControls/DesktopWindowControls.tsx
delete mode 100644 dashboard/src/components/DesktopWindowControls/index.ts
create mode 100644 dashboard/src/components/DesktopWindowDragBand.test.tsx
create mode 100644 dashboard/src/components/DesktopWindowDragBand.tsx
create mode 100644 dashboard/src/components/ErrorBoundary/ErrorFallback.module.less
create mode 100644 dashboard/src/components/ErrorBoundary/ErrorFallback.tsx
create mode 100644 dashboard/src/components/LinuxWindowControls.test.tsx
create mode 100644 dashboard/src/components/LinuxWindowControls.tsx
create mode 100644 dashboard/src/components/RailEdgeControl.test.tsx
create mode 100644 dashboard/src/components/WindowsAppMenu.test.tsx
create mode 100644 dashboard/src/components/WindowsAppMenu.tsx
create mode 100644 dashboard/src/hooks/useNativeWindowChrome.ts
create mode 100644 dashboard/src/hooks/useRailShortcuts.test.tsx
create mode 100644 dashboard/src/hooks/useRailShortcuts.ts
create mode 100644 dashboard/src/hooks/useWindowFullscreen.ts
create mode 100644 dashboard/src/layouts/MainLayout/index.test.tsx
create mode 100644 dashboard/src/layouts/MainLayout/seamHandle.test.tsx
delete mode 100644 dashboard/src/layouts/Sidebar.chatRailToggle.test.tsx
create mode 100644 dashboard/src/layouts/Sidebar.railCollapse.test.tsx
create mode 100644 dashboard/src/layouts/SidebarCollapsedIconNav.test.tsx
create mode 100644 dashboard/src/pages/Chat/chatRailEvents.ts
create mode 100644 dashboard/src/pages/Chat/components/AgentNotReadyScreen.test.tsx
create mode 100644 dashboard/src/pages/Chat/components/ChatSidebarPanel.edge.test.tsx
create mode 100644 dashboard/src/pages/Chat/components/SessionList.emptyAgents.test.tsx
create mode 100644 dashboard/src/pages/Settings/AdvancedSettings/DesktopUpdatePanel.test.tsx
create mode 100644 dashboard/src/pages/Settings/AdvancedSettings/DesktopUpdatePanel.tsx
create mode 100644 dashboard/src/utils/desktopBridge.ts
delete mode 100644 dashboard/src/utils/desktopExternalLinks.test.ts
delete mode 100644 dashboard/src/utils/desktopExternalLinks.ts
create mode 100644 dashboard/src/utils/desktopWsUrl.test.ts
create mode 100644 dashboard/src/utils/desktopWsUrl.ts
create mode 100644 dashboard/src/utils/nativeWindowChrome.test.ts
create mode 100644 dashboard/src/utils/nativeWindowChrome.ts
create mode 100644 dashboard/src/utils/overlayLayers.test.ts
create mode 100644 dashboard/src/utils/overlayLayers.ts
create mode 100644 dashboard/src/utils/railShortcuts.test.ts
create mode 100644 dashboard/src/utils/railShortcuts.ts
rename desktop/{portable => docs}/AGENT_ELECTRON_INTEGRATION.md (80%)
create mode 100644 desktop/docs/DESKTOP_ARCHITECTURE.zh.md
create mode 100644 desktop/docs/LOCAL_ACCOUNT_CLAIM.zh.md
create mode 100644 desktop/docs/QUIT_TASK_CHECK.zh.md
delete mode 100644 desktop/package-dev.sh
delete mode 100755 desktop/package-release.sh
create mode 100644 desktop/portable/prune_packages.py
create mode 100644 desktop/src/.npmrc
delete mode 100644 desktop/src/Taskfile.yml
delete mode 100644 desktop/src/assets/index.html
delete mode 100644 desktop/src/assets/octop-mascot-peek.webp
delete mode 100644 desktop/src/assets/octop-mascot-type.webp
delete mode 100644 desktop/src/assets/tray-icon-template.png
delete mode 100644 desktop/src/assets/tray-icon.png
delete mode 100644 desktop/src/build/Taskfile.yml
delete mode 100644 desktop/src/build/appicon-macos.png
delete mode 100644 desktop/src/build/config.yml
delete mode 100644 desktop/src/build/darwin/Info.dev.plist
delete mode 100644 desktop/src/build/darwin/Info.plist
delete mode 100644 desktop/src/build/darwin/Taskfile.yml
create mode 100644 desktop/src/build/installer.nsh
create mode 100644 desktop/src/build/linux-after-install.sh
create mode 100644 desktop/src/build/linux-after-remove.sh
create mode 100644 desktop/src/build/linux-desktop-shortcut.sh
delete mode 100644 desktop/src/build/linux/Taskfile.yml
delete mode 100644 desktop/src/build/stamp_version.py
delete mode 100644 desktop/src/build/windows/Taskfile.yml
delete mode 100644 desktop/src/build/windows/info.json
delete mode 100644 desktop/src/build/windows/nsis/project.nsi
delete mode 100644 desktop/src/build/windows/nsis/wails_tools.nsh
delete mode 100644 desktop/src/build/windows/wails.exe.manifest
delete mode 100644 desktop/src/bundled/.gitkeep
delete mode 100644 desktop/src/cmd/devserver/main.go
delete mode 100644 desktop/src/desktop_copy.go
delete mode 100644 desktop/src/desktop_copy_test.go
delete mode 100644 desktop/src/dock_reopen.go
delete mode 100644 desktop/src/dock_reopen_test.go
delete mode 100644 desktop/src/download.go
delete mode 100644 desktop/src/download_test.go
create mode 100644 desktop/src/electron-builder.config.ts
create mode 100644 desktop/src/electron.vite.config.ts
delete mode 100644 desktop/src/embed_portable.go
delete mode 100644 desktop/src/embed_portable_embedded.go
delete mode 100644 desktop/src/filedrop.go
delete mode 100644 desktop/src/filedrop_test.go
delete mode 100644 desktop/src/go.mod
delete mode 100644 desktop/src/go.sum
delete mode 100644 desktop/src/icons_darwin.go
delete mode 100644 desktop/src/icons_other.go
create mode 100644 desktop/src/mac-privacy-plist.ts
delete mode 100644 desktop/src/main.go
create mode 100644 desktop/src/main/app-version.test.ts
create mode 100644 desktop/src/main/app-version.ts
create mode 100644 desktop/src/main/dev/dashboard-dev-server.test.ts
create mode 100644 desktop/src/main/dev/dashboard-dev-server.ts
create mode 100644 desktop/src/main/index.ts
create mode 100644 desktop/src/main/log/desktop-log.test.ts
create mode 100644 desktop/src/main/log/desktop-log.ts
create mode 100644 desktop/src/main/mac-privacy-plist.test.ts
create mode 100644 desktop/src/main/protocol/static-handler.ts
create mode 100644 desktop/src/main/protocol/stream-proxy.ts
create mode 100644 desktop/src/main/protocol/ws-relay.test.ts
create mode 100644 desktop/src/main/protocol/ws-relay.ts
create mode 100644 desktop/src/main/session/device-credential.test.ts
create mode 100644 desktop/src/main/session/device-credential.ts
create mode 100644 desktop/src/main/session/device-session.test.ts
create mode 100644 desktop/src/main/session/device-session.ts
create mode 100644 desktop/src/main/session/safe-storage-cipher.ts
create mode 100644 desktop/src/main/storage/client-settings.ts
create mode 100644 desktop/src/main/supervisor/health.ts
create mode 100644 desktop/src/main/supervisor/process-tree.test.ts
create mode 100644 desktop/src/main/supervisor/process-tree.ts
create mode 100644 desktop/src/main/supervisor/random-port.ts
create mode 100644 desktop/src/main/supervisor/runtime-extractor.test.ts
create mode 100644 desktop/src/main/supervisor/runtime-extractor.ts
create mode 100644 desktop/src/main/supervisor/sha256.ts
create mode 100644 desktop/src/main/supervisor/shell-env.test.ts
create mode 100644 desktop/src/main/supervisor/shell-env.ts
create mode 100644 desktop/src/main/supervisor/sidecar.test.ts
create mode 100644 desktop/src/main/supervisor/sidecar.ts
create mode 100644 desktop/src/main/supervisor/version.test.ts
create mode 100644 desktop/src/main/supervisor/version.ts
create mode 100644 desktop/src/main/supervisor/zip-safety.test.ts
create mode 100644 desktop/src/main/update/download.test.ts
create mode 100644 desktop/src/main/update/download.ts
create mode 100644 desktop/src/main/update/installer.test.ts
create mode 100644 desktop/src/main/update/installer.ts
create mode 100644 desktop/src/main/update/update-coordinator.test.ts
create mode 100644 desktop/src/main/update/update-coordinator.ts
create mode 100644 desktop/src/main/windows/about-info.test.ts
create mode 100644 desktop/src/main/windows/about-info.ts
create mode 100644 desktop/src/main/windows/app-menu.test.ts
create mode 100644 desktop/src/main/windows/app-menu.ts
create mode 100644 desktop/src/main/windows/chrome.test.ts
create mode 100644 desktop/src/main/windows/chrome.ts
create mode 100644 desktop/src/main/windows/early-window.ts
create mode 100644 desktop/src/main/windows/main-window.ts
create mode 100644 desktop/src/main/windows/present.test.ts
create mode 100644 desktop/src/main/windows/present.ts
create mode 100644 desktop/src/main/windows/size.test.ts
create mode 100644 desktop/src/main/windows/size.ts
create mode 100644 desktop/src/main/windows/tray.test.ts
create mode 100644 desktop/src/main/windows/tray.ts
create mode 100644 desktop/src/mise.toml
delete mode 100644 desktop/src/openurl.go
delete mode 100644 desktop/src/openurl_test.go
create mode 100644 desktop/src/package.json
create mode 100644 desktop/src/pnpm-lock.yaml
create mode 100644 desktop/src/pnpm-workspace.yaml
delete mode 100644 desktop/src/portable_upgrade.go
delete mode 100644 desktop/src/portable_upgrade_test.go
create mode 100644 desktop/src/preload/early.ts
create mode 100644 desktop/src/preload/index.ts
delete mode 100644 desktop/src/preventsleep.go
delete mode 100644 desktop/src/preventsleep_darwin.go
delete mode 100644 desktop/src/preventsleep_linux.go
delete mode 100644 desktop/src/preventsleep_other.go
delete mode 100644 desktop/src/preventsleep_windows.go
delete mode 100644 desktop/src/process.go
delete mode 100644 desktop/src/process_test.go
delete mode 100644 desktop/src/process_unix.go
delete mode 100644 desktop/src/process_windows.go
create mode 100644 desktop/src/renderer/.gitattributes
create mode 100644 desktop/src/renderer/error.html
create mode 100644 desktop/src/renderer/splash.html
create mode 100644 desktop/src/renderer/src/assets/logo_horizontal_dark.png
create mode 100644 desktop/src/renderer/src/assets/logo_horizontal_white.png
create mode 100644 desktop/src/renderer/src/assets/octop-mark.svg
create mode 100644 desktop/src/renderer/src/base.less
create mode 100644 desktop/src/renderer/src/base.test.ts
create mode 100644 desktop/src/renderer/src/error.module.less
create mode 100644 desktop/src/renderer/src/error.tsx
create mode 100644 desktop/src/renderer/src/linux-window-controls.module.less
create mode 100644 desktop/src/renderer/src/linux-window-controls.test.ts
create mode 100644 desktop/src/renderer/src/linux-window-controls.tsx
create mode 100644 desktop/src/renderer/src/mount.tsx
create mode 100644 desktop/src/renderer/src/splash.module.less
create mode 100644 desktop/src/renderer/src/splash.tsx
create mode 100644 desktop/src/renderer/src/vite-env.d.ts
create mode 100644 desktop/src/renderer/vite.config.ts
rename desktop/src/{build/darwin => resources}/dmg-background.jpeg (100%)
create mode 100644 desktop/src/resources/dmg-background.png
create mode 100644 desktop/src/resources/dmg-background@2x.png
create mode 100644 desktop/src/resources/icon.icns
create mode 100644 desktop/src/resources/icon.ico
rename desktop/src/{build/appicon.png => resources/icon.png} (100%)
create mode 100644 desktop/src/scripts/dev-process.mjs
create mode 100644 desktop/src/scripts/dev-process.test.mjs
create mode 100644 desktop/src/scripts/linux-desktop-shortcut.test.mjs
create mode 100755 desktop/src/scripts/make-dev-runtime.sh
create mode 100644 desktop/src/scripts/register-extensionless-ts.mjs
create mode 100644 desktop/src/scripts/resolve-extensionless-ts.mjs
create mode 100755 desktop/src/scripts/run-dev.sh
delete mode 100644 desktop/src/settings.go
delete mode 100644 desktop/src/settings_test.go
delete mode 100644 desktop/src/settings_window.go
create mode 100644 desktop/src/shared/early-ipc.ts
create mode 100644 desktop/src/shared/global.d.ts
create mode 100644 desktop/src/shared/ipc-contract.ts
create mode 100644 desktop/src/shared/shell-error.test.ts
create mode 100644 desktop/src/shared/shell-error.ts
delete mode 100644 desktop/src/tray_click.go
delete mode 100644 desktop/src/tray_click_test.go
delete mode 100644 desktop/src/tray_menu.go
delete mode 100644 desktop/src/tray_menu_test.go
create mode 100644 desktop/src/tsconfig.json
delete mode 100644 desktop/src/version.go
delete mode 100644 desktop/src/window_chrome.go
delete mode 100644 desktop/src/window_chrome_test.go
create mode 100644 src/octop/api/routers/auth_device.py
create mode 100644 src/octop/infra/desktop.py
create mode 100644 tests/integration/test_desktop_device_session.py
delete mode 100644 tests/unit/desktop/test_stamp_version.py
create mode 100644 tests/unit/test_desktop_shell.py
create mode 100644 tests/unit/test_portable_prune.py
diff --git a/.github/workflows/octop-desktop.yml b/.github/workflows/octop-desktop.yml
index 52fb362fc9..d325a36732 100644
--- a/.github/workflows/octop-desktop.yml
+++ b/.github/workflows/octop-desktop.yml
@@ -1,9 +1,18 @@
name: Octop Desktop Package
# 正式发版:Auto Tag 在打 v* 后与 Release / Docker Publish 一并 dispatch。
-# 产物 upsert 到同一 GitHub Release,再上传到 COS octop/release//。
+# 每个原生 runner 打便携 zip + Electron 安装包,upsert 到同一 GitHub Release,
+# 再上传到 COS octop/release//。
# 手工补包:workflow_dispatch + release_tag(不必跑在 v* ref 上)。
# attach_from_run 只挂已有 artifact、不重打。
+#
+# 镜像固定到 ubuntu-24.04 而不是 ubuntu-latest:`latest` 已经公告要迁到
+# 26.04,发版机器的底层镜像不该由 GitHub 的时间表决定。
+#
+# action 一律挑 `runs.using: node24` 的主版本(setup-uv@v7、
+# pnpm/action-setup@v6、action-gh-release@v3)。跑在 node20 上的版本会在
+# 每次运行里刷 "Node.js 20 is deprecated" 而不报错,属于会一直烂在那里的
+# 警告——升级时以 action.yml 里的 `runs.using` 为准,别看版本号大小猜。
on:
push:
@@ -59,13 +68,15 @@ jobs:
frontend:
name: Build dashboard
if: github.event_name != 'workflow_dispatch' || github.event.inputs.attach_from_run == ''
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
- node-version: "24"
+ # Dashboard stays on Node 20 (same as docker/Dockerfile + release.yml).
+ # Node 24 is a desktop/electron-only pin and nothing here builds it.
+ node-version: "20"
cache: npm
cache-dependency-path: dashboard/package-lock.json
@@ -84,7 +95,7 @@ jobs:
select-platforms:
name: Select platforms
if: github.event_name != 'workflow_dispatch' || github.event.inputs.attach_from_run == ''
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
outputs:
matrix: ${{ steps.set.outputs.matrix }}
steps:
@@ -99,7 +110,7 @@ jobs:
import os
all_plats = [
- {"plat": "linux-amd64", "arch": "amd64", "os": "ubuntu-latest"},
+ {"plat": "linux-amd64", "arch": "amd64", "os": "ubuntu-24.04"},
{"plat": "linux-arm64", "arch": "arm64", "os": "ubuntu-24.04-arm"},
{"plat": "darwin-arm64", "arch": "arm64", "os": "macos-15"},
{"plat": "darwin-amd64", "arch": "amd64", "os": "macos-15-intel"},
@@ -112,16 +123,16 @@ jobs:
sel = os.environ.get("PLATFORMS", "all").lower().replace(" ", "")
known = {row["plat"] for row in all_plats}
if sel == "all":
- include = all_plats
+ selected = all_plats
else:
wanted = {part for part in sel.split(",") if part}
unknown = wanted - known
if unknown:
raise SystemExit(f"unknown platform(s): {', '.join(sorted(unknown))}")
- include = [row for row in all_plats if row["plat"] in wanted]
- if not include:
+ selected = [row for row in all_plats if row["plat"] in wanted]
+ if not selected:
raise SystemExit(f"no platforms selected: {sel}")
- matrix = json.dumps({"include": include}, separators=(",", ":"))
+ matrix = json.dumps({"include": selected}, separators=(",", ":"))
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh:
fh.write(f"matrix={matrix}\n")
print(matrix)
@@ -133,6 +144,7 @@ jobs:
runs-on: ${{ matrix.os }}
# Matrix runners are native for each plat; pin host detection so x64 Git Bash
# on windows-11-arm does not mis-classify the job as windows-amd64 cross-build.
+ # Installers are unsigned and not notarized.
env:
GREEN_HOST_PLAT: ${{ matrix.plat }}
strategy:
@@ -156,7 +168,7 @@ jobs:
name: dashboard-dist
path: src/octop/dashboard
- - uses: astral-sh/setup-uv@v6
+ - uses: astral-sh/setup-uv@v7
with:
enable-cache: true
python-version: "3.12"
@@ -217,100 +229,150 @@ jobs:
verify_no_homebrew_dylibs "${staging}/packages" "${{ matrix.plat }}"
fi
- - uses: actions/setup-go@v6
+ # archive: false — upload the prebuilt zip as-is. Default archive=true would
+ # wrap it again, so Actions UI / "Download artifact" becomes zip-in-zip.
+ # With archive:false, artifact name is the filename (name: is ignored).
+ - uses: actions/upload-artifact@v7
with:
- go-version: "1.25.x"
- cache-dependency-path: desktop/src/go.sum
+ path: desktop/portable/release/Octop-portable-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip
+ archive: false
+ if-no-files-found: error
+ retention-days: 14
- - name: Install Linux desktop build dependencies
- if: runner.os == 'Linux'
+ - name: Stage Electron runtime
run: |
- sudo apt-get update
- sudo apt-get install -y libgtk-4-dev libwebkitgtk-6.0-dev
+ set -euo pipefail
+ plat="${{ matrix.plat }}"
+ zip="desktop/portable/release/Octop-portable-${plat}-${OCTOP_VERSION}.zip"
+ rm -rf desktop/src/resources/portable
+ mkdir -p desktop/src/resources/portable
+ # The shell serves packages/octop/dashboard from this tree. There is
+ # no second copy under resources/dashboard.
+ test -f "desktop/portable/release/Octop-${plat}/packages/octop/dashboard/index.html"
+ # Windows keeps one zip; NSIS extracts it with tar.exe. Packing the
+ # ~40k files into NSIS is slower. macOS (DMG) and Linux (deb/rpm)
+ # copy the tree package.sh already assembled. No zip in those apps.
+ if [[ "$plat" == windows-* ]]; then
+ cp "$zip" desktop/src/resources/portable/
+ else
+ inner="desktop/portable/release/Octop-${plat}"
+ if [[ ! -f "$inner/launch.py" ]]; then
+ echo "expanded portable tree has no launch.py under ${inner}" >&2
+ exit 1
+ fi
+ shopt -s dotglob
+ cp -a "$inner"/. desktop/src/resources/portable/
+ shopt -u dotglob
+ test -x desktop/src/resources/portable/runtime/bin/python3
+ test ! -e desktop/src/resources/portable/*.zip
+ fi
+ if [[ "$plat" == windows-* ]]; then py=python; else py=python3; fi
+ "$py" - "$zip" "$OCTOP_VERSION" <<'PY'
+ import hashlib
+ import json
+ import pathlib
+ import sys
+ import zipfile
+
+ path = pathlib.Path(sys.argv[1])
+ if not zipfile.is_zipfile(path):
+ raise SystemExit(f"not a portable zip: {path}")
+ manifest = {"version": sys.argv[2], "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
+ dest = pathlib.Path("desktop/src/resources/portable/portable-version.json")
+ dest.write_text(json.dumps(manifest) + "\n", encoding="utf-8")
+ print(f"Bundled {path.name} with SHA-256 {manifest['sha256']}")
+ PY
+ if [[ "$plat" != windows-* ]]; then
+ test -f desktop/src/resources/portable/packages/octop/dashboard/index.html
+ fi
+
+ - uses: actions/setup-node@v5
+ with:
+ node-version: "24"
- - name: Install Wails v3 CLI
- run: go install github.com/wailsapp/wails/v3/cmd/wails3@v3.0.0-beta.13
+ # v6 起改用 node24 运行时;`run_install` 仍存在,留着 false 是为了让
+ # 下一步那个显式的 `pnpm install --frozen-lockfile` 是唯一一次安装。
+ - uses: pnpm/action-setup@v6
+ with:
+ version: 12.15.0
+ run_install: false
- - name: Install NSIS
- if: runner.os == 'Windows'
- shell: pwsh
+ - name: Install and check Electron shell
+ working-directory: desktop/src
run: |
- $nsisDir = "${env:ProgramFiles(x86)}\NSIS"
- $makensis = Join-Path $nsisDir "makensis.exe"
- function Test-Makensis { Test-Path -LiteralPath $makensis }
-
- if (-not (Test-Makensis)) {
- $installed = $false
- for ($i = 1; $i -le 5; $i++) {
- Write-Host "choco install nsis (attempt $i/5)"
- try {
- choco install nsis --yes --no-progress --execution-timeout=600
- } catch {
- Write-Warning "choco attempt $i failed: $_"
- }
- if (Test-Makensis) { $installed = $true; break }
- Start-Sleep -Seconds ([Math]::Min(60, 10 * $i))
- }
-
- if (-not $installed) {
- Write-Host "Chocolatey unavailable; downloading NSIS setup from SourceForge"
- $setup = Join-Path $env:RUNNER_TEMP "nsis-setup.exe"
- $urls = @(
- "https://downloads.sourceforge.net/project/nsis/NSIS%203/3.11/nsis-3.11-setup.exe",
- "https://sourceforge.net/projects/nsis/files/NSIS%203/3.11/nsis-3.11-setup.exe/download"
- )
- $downloaded = $false
- foreach ($url in $urls) {
- try {
- Invoke-WebRequest -Uri $url -OutFile $setup -UseBasicParsing -TimeoutSec 180
- if ((Test-Path -LiteralPath $setup) -and ((Get-Item $setup).Length -gt 1MB)) {
- $downloaded = $true
- break
- }
- } catch {
- Write-Warning "NSIS download failed from $url : $_"
- }
- }
- if (-not $downloaded) {
- throw "NSIS install failed (Chocolatey and direct download)"
- }
- Start-Process -FilePath $setup -ArgumentList "/S" -Wait
- }
- }
-
- if (-not (Test-Makensis)) {
- throw "makensis.exe missing after NSIS install"
- }
- Add-Content -Path $env:GITHUB_PATH -Value $nsisDir
-
- - name: Package desktop app with bundled portable runtime
+ pnpm install --frozen-lockfile
+ pnpm run typecheck
+ pnpm run test
+
+ - name: Build native Electron installers
working-directory: desktop/src
- run: >-
- wails3 task package
- ARCH=${{ matrix.arch }}
- VERSION=${{ env.OCTOP_VERSION }}
- PORTABLE_ZIP=../portable/release/Octop-portable-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip
+ env:
+ OCTOP_PLATFORM: ${{ matrix.plat }}
+ # Empty, not omitted: a CSC_LINK in the runner environment overrides
+ # mac.identity: null and electron-builder tries to sign.
+ CSC_LINK: ""
+ CSC_KEY_PASSWORD: ""
+ WIN_CSC_LINK: ""
+ WIN_CSC_KEY_PASSWORD: ""
+ APPLE_ID: ""
+ APPLE_APP_SPECIFIC_PASSWORD: ""
+ APPLE_TEAM_ID: ""
+ run: |
+ set -euo pipefail
+ pnpm run build
+ case "${{ matrix.plat }}" in
+ darwin-*) target=--mac ;;
+ windows-*) target=--win ;;
+ linux-*) target=--linux ;;
+ *) echo "Unsupported Electron target: ${{ matrix.plat }}" >&2; exit 1 ;;
+ esac
+ if [[ "${{ matrix.arch }}" == amd64 ]]; then arch=--x64; else arch=--arm64; fi
+ pnpm exec electron-builder --config electron-builder.config.ts "$target" "$arch" --publish never
+
+ # archive:false preserves each installer; different formats must be uploaded
+ # separately (one file per artifact), not wrapped in an extra Actions zip.
+ - uses: actions/upload-artifact@v7
+ if: startsWith(matrix.plat, 'darwin-')
+ with:
+ path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.dmg
+ archive: false
+ if-no-files-found: error
+ retention-days: 14
- # archive: false — upload the prebuilt zip as-is. Default archive=true would
- # wrap it again, so Actions UI / "Download artifact" becomes zip-in-zip.
- # With archive:false, artifact name is the filename (name: is ignored).
- uses: actions/upload-artifact@v7
+ if: startsWith(matrix.plat, 'darwin-')
with:
- path: desktop/portable/release/Octop-portable-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip
+ path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.zip
archive: false
if-no-files-found: error
retention-days: 14
- - name: Upload bundled desktop package
- uses: actions/upload-artifact@v7
+ - uses: actions/upload-artifact@v7
+ if: startsWith(matrix.plat, 'windows-')
+ with:
+ path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.exe
+ archive: false
+ if-no-files-found: error
+ retention-days: 14
+
+ - uses: actions/upload-artifact@v7
+ if: startsWith(matrix.plat, 'linux-')
+ with:
+ path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.deb
+ archive: false
+ if-no-files-found: error
+ retention-days: 14
+
+ - uses: actions/upload-artifact@v7
+ if: startsWith(matrix.plat, 'linux-')
with:
- path: desktop/src/bin/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.*
+ path: desktop/src/release/Octop-desktop-${{ matrix.plat }}-${{ env.OCTOP_VERSION }}.rpm
archive: false
if-no-files-found: error
retention-days: 14
release:
- name: Attach zips to GitHub Release
+ name: Attach packages to GitHub Release
needs: package
outputs:
tag: ${{ steps.rel.outputs.tag }}
@@ -330,7 +392,7 @@ jobs:
(github.event_name == 'workflow_dispatch' &&
github.event.inputs.attach_release == 'true')))
)
- runs-on: ubuntu-latest
+ runs-on: ubuntu-24.04
permissions:
contents: write
actions: read
@@ -350,8 +412,8 @@ jobs:
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
# v8 required for archive:false artifacts. skip-decompress keeps the
- # uploaded .zip / .tar.gz / .dmg / .exe intact — default unzip turns portable
- # zips into directories, so files: release-assets/* would skip them.
+ # uploaded .zip / .dmg / .exe intact — default unzip turns portable zips
+ # into directories, so files: release-assets/* would skip them.
- uses: actions/download-artifact@v8
with:
pattern: Octop-*
@@ -373,7 +435,7 @@ jobs:
fi
- name: Upload to GitHub Release
- uses: softprops/action-gh-release@v2
+ uses: softprops/action-gh-release@v3
with:
tag_name: ${{ steps.rel.outputs.tag }}
files: release-assets/*
@@ -390,7 +452,7 @@ jobs:
uses: ./.github/workflows/upload-release-cos.yml
with:
tag: ${{ needs.release.outputs.tag }}
- patterns: "Octop-desktop-*,Octop-portable-*"
+ patterns: "Octop-portable-*,Octop-desktop-*"
secrets:
RELEASE_COS_SECRET_ID: ${{ secrets.RELEASE_COS_SECRET_ID }}
RELEASE_COS_SECRET_KEY: ${{ secrets.RELEASE_COS_SECRET_KEY }}
diff --git a/.gitignore b/.gitignore
index 9918065cd4..47ab4b023f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
# Build
build/
+# NSIS include lives here; the blanket build/ rule would hide it.
!desktop/src/build/
!desktop/src/build/**
dist/
@@ -53,7 +54,9 @@ coverage.xml
.hypothesis/
# IDE / editors
-.vscode/
+.vscode/*
+!.vscode/settings.json
+!.vscode/css-custom-data.json
.idea/
.codebuddy
*.swp
diff --git a/.vscode/css-custom-data.json b/.vscode/css-custom-data.json
new file mode 100644
index 0000000000..3dcaa52978
--- /dev/null
+++ b/.vscode/css-custom-data.json
@@ -0,0 +1,19 @@
+{
+ "version": 1.1,
+ "properties": [
+ {
+ "name": "app-region",
+ "status": "nonstandard",
+ "description": "Electron/Chromium window drag region. `drag` makes the element a window drag handle; `no-drag` keeps a control clickable inside a drag region.",
+ "syntax": "drag | no-drag",
+ "values": [{ "name": "drag" }, { "name": "no-drag" }]
+ },
+ {
+ "name": "-webkit-app-region",
+ "status": "nonstandard",
+ "description": "Vendor-prefixed form of `app-region`. Chromium uses this name for frameless-window dragging.",
+ "syntax": "drag | no-drag",
+ "values": [{ "name": "drag" }, { "name": "no-drag" }]
+ }
+ ]
+}
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000000..a8a0a1add5
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,4 @@
+{
+ "css.customData": [".vscode/css-custom-data.json"],
+ "less.customData": [".vscode/css-custom-data.json"]
+}
diff --git a/Makefile b/Makefile
index afc0a00f76..293e8dc509 100644
--- a/Makefile
+++ b/Makefile
@@ -97,7 +97,8 @@ build-frontend:
@echo "[build-frontend] Installing npm dependencies..."
cd $(DASHBOARD_DIR) && npm ci
@echo "[build-frontend] Building dashboard (output: $(DASHBOARD_DEST))..."
- cd $(DASHBOARD_DIR) && NODE_ENV=production NODE_OPTIONS="--max-old-space-size=2048" npm run build
+ # Render peaks above 2GB (Full GC, then OOM at 2048 on GitHub runners).
+ cd $(DASHBOARD_DIR) && NODE_ENV=production NODE_OPTIONS="--max-old-space-size=4096" npm run build
@echo "[build-frontend] Done."
.PHONY: build-wheel
diff --git a/README.md b/README.md
index 3508de536c..4cd789b4d4 100644
--- a/README.md
+++ b/README.md
@@ -231,6 +231,8 @@ See [scripts/README.md](scripts/README.md) for all install options (`--version`,
| Linux | `Octop-desktop-linux-amd64-.tar.gz` / `Octop-desktop-linux-arm64-.tar.gz` |
| FnOS NAS | `Octop-fnos-docker-lite-.fpk` (smaller image) / `Octop-fnos-docker-.fpk` (full: desktop, OCR, local models) / `Octop-fnos-native-amd64-.fpk` (x86_64, no Docker) / `Octop-fnos-native-arm64-.fpk` (ARM64 fallback if no Docker) — install via App Center |
+Desktop installers bundle the `browser` extra only. Desktop control, OCR, and local embedding stay on the Docker image tag `:-full`.
+
See [desktop/README.md](desktop/README.md) for the desktop shell and [fnos/README.md](fnos/README.md) for the FnOS packaging guide.
**Alternative — PyPI** (if you already manage Python yourself):
diff --git a/README_CN.md b/README_CN.md
index 4515284485..85ac6f5657 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -233,6 +233,8 @@ curl -fsSL https://download.octop.cloud/octop/scripts/install.sh | bash -s -- --
| Linux | `Octop-desktop-linux-amd64-.tar.gz` / `Octop-desktop-linux-arm64-.tar.gz` |
| 飞牛 NAS(FnOS) | `Octop-fnos-docker-lite-.fpk`(精简镜像)/ `Octop-fnos-docker-.fpk`(完整版:桌面、OCR、本地向量)/ `Octop-fnos-native-amd64-.fpk`(x86_64,无需 Docker)/ `Octop-fnos-native-arm64-.fpk`(ARM64,无 Docker 时再用)— 通过应用中心安装 |
+桌面安装包只带 `browser`。桌面控制、OCR 和本地向量留在 Docker 镜像标签 `:-full`。
+
桌面客户端说明见 [desktop/README.md](desktop/README.md),飞牛打包指南见 [fnos/README.md](fnos/README.md)。
**备选 — PyPI**(若你已自行管理 Python 环境):
diff --git a/dashboard/index.html b/dashboard/index.html
index 872fa7bc34..359ab10edd 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -35,6 +35,12 @@
the splash CSS keys off html[data-theme], not prefers-color-scheme,
so a stored "light" preference wins over an OS dark setting.
Storage shape matches appearanceStorage.ts (THEME_STORAGE_KEY = "theme").
+
+ The desktop shell loads this page with ?octopTheme=system|light|dark
+ (DASHBOARD_THEME_QUERY in desktop/src/main/windows/chrome.ts). That
+ device preference wins over localStorage and is written back, then the
+ query is removed so a later reload keeps the stored value. Browser
+ loads have no query and keep using localStorage alone.
-->
+
+
+ {/* macOS only: room for the traffic lights. Windows caption is a
+ separate full-width row above the shell, so no blank here. */}
+ {reserveTrafficLightBand ? (
+
+ ) : null}
+