-
+ {featured ? (
+
+
+
+
+
+ ) : null}
+
{
+ it("edits a config file in a textarea", () => {
+ render(
+ {}}
+ onSaved={() => {}}
+ onLocalSave={() => {}}
+ />,
+ );
+
+ const box = screen.getByRole("textbox");
+ expect(box.tagName).toBe("TEXTAREA");
+ expect(box).toHaveValue("# Agents\nkeep this");
+ });
+});
diff --git a/dashboard/src/pages/Experts/components/FileEditModal.tsx b/dashboard/src/pages/Experts/components/FileEditModal.tsx
index ade8584382..7a9204fd12 100644
--- a/dashboard/src/pages/Experts/components/FileEditModal.tsx
+++ b/dashboard/src/pages/Experts/components/FileEditModal.tsx
@@ -1,14 +1,12 @@
// dashboard/src/pages/Experts/components/FileEditModal.tsx
-import { lazy, Suspense, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button, Drawer, Spin } from "antd";
import { message } from "@/utils/antdMessage";
import { request } from "../../../api/request";
-import { useTheme } from "../../../context/ThemeContext";
import { withFromWorkspace } from "../../../utils/fromWorkspace";
-
-const MonacoEditor = lazy(() => import("@/components/monaco"));
+import styles from "./FileEditModal.module.less";
interface FileEditModalProps {
open: boolean;
@@ -37,7 +35,6 @@ export default function FileEditModal({
onLocalSave,
}: FileEditModalProps) {
const { t } = useTranslation();
- const { isDark } = useTheme();
const [value, setValue] = useState("");
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
@@ -163,39 +160,14 @@ export default function FileEditModal({
) : (
-
-
-
- }
- >
-
- setValue(v ?? "")}
- options={{
- minimap: { enabled: false },
- wordWrap: "on",
- fontSize: 13,
- lineNumbers: "on",
- scrollBeyondLastLine: false,
- }}
- />
-
-
+
diff --git a/dashboard/src/pages/Settings/Models/components/modals/ProviderConfigModal.tsx b/dashboard/src/pages/Settings/Models/components/modals/ProviderConfigModal.tsx
index f0c846b296..7691883d48 100644
--- a/dashboard/src/pages/Settings/Models/components/modals/ProviderConfigModal.tsx
+++ b/dashboard/src/pages/Settings/Models/components/modals/ProviderConfigModal.tsx
@@ -657,17 +657,18 @@ export function ProviderConfigModal({
if (!open) return;
// Only hydrate when the modal opens (or provider id changes), so
// background refreshes / local model toggles do not reset the form.
- const currentDefaultModel = provider.models?.length
- ? provider.models[0].id
- : "";
+ const savedModel = (provider.model ?? "").trim();
form.setFieldsValue({
kind: provider.kind,
base_url: provider.base_url ?? "",
api_key: undefined,
- model: currentDefaultModel,
note: provider.note ?? "",
stream_usage: provider.stream_usage !== false,
});
+ // undefined is skipped by setFieldsValue, so an empty default has to be
+ // reset or the previous provider's model stays selected.
+ if (savedModel) form.setFieldValue("model", savedModel);
+ else form.resetFields(["model"]);
setDraftModels(
(provider.models ?? []).map((m) => ({
...m,
@@ -705,10 +706,8 @@ export function ProviderConfigModal({
payload.stream_usage = Boolean(values.stream_usage);
}
// default model
- const existingDefault = provider.models?.length
- ? provider.models[0].id
- : "";
- if ((values.model ?? "") !== existingDefault)
+ const existingDefault = (provider.model ?? "").trim();
+ if ((values.model ?? "").trim() !== existingDefault)
payload.model = values.model?.trim() || null;
const modelsForSave =
@@ -1001,6 +1000,25 @@ export function ProviderConfigModal({
}
};
+ const savedDefaultModel = (provider.model ?? "").trim();
+ const defaultModelOptions = useMemo(() => {
+ const source =
+ isOllama || isOnnx
+ ? draftModels.filter((m) => downloadedIds.includes(m.id))
+ : draftModels;
+ const options = source.map((m) => ({
+ value: m.id,
+ label: m.name !== m.id ? `${m.name} (${m.id})` : m.id,
+ }));
+ if (
+ savedDefaultModel &&
+ !options.some((option) => option.value === savedDefaultModel)
+ ) {
+ options.unshift({ value: savedDefaultModel, label: savedDefaultModel });
+ }
+ return options;
+ }, [draftModels, downloadedIds, isOllama, isOnnx, savedDefaultModel]);
+
return (
downloadedIds.includes(m.id))
- : draftModels
- ).map((m) => ({
- value: m.id,
- label: m.name !== m.id ? `${m.name} (${m.id})` : m.id,
- }))}
+ options={defaultModelOptions}
notFoundContent={
isOllama || isOnnx
? t("models.defaultModelNeedDownload")
diff --git a/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx b/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx
index bdc329fc2c..5543627fcb 100644
--- a/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx
+++ b/dashboard/src/pages/Settings/Models/components/sections/ActiveModelPool.tsx
@@ -85,17 +85,20 @@ export function ActiveModelPool({
const isAlready =
m.provider_name === activeModel.provider_name &&
m.model === activeModel.model;
- if (isAlready) return;
-
const key = `${m.provider_name}/${m.model}`;
setSetting(key);
try {
- await preferencesApi.patch({ preferred_model: key });
- message.success(
- t("models.preferredModelSet", {
- model: modelOptionLabel(m),
- }),
- );
+ if (isAlready) {
+ await preferencesApi.patch({ preferred_model: null });
+ message.success(t("models.preferredModelCleared"));
+ } else {
+ await preferencesApi.patch({ preferred_model: key });
+ message.success(
+ t("models.preferredModelSet", {
+ model: modelOptionLabel(m),
+ }),
+ );
+ }
await onSaved();
} catch (err) {
message.error(
@@ -328,7 +331,7 @@ export function ActiveModelPool({
@@ -351,11 +354,18 @@ export function ActiveModelPool({
-
- {modelOptionLabel(m)}
+
+
+ {modelOptionLabel(m)}
+
+ {isPreferred ? (
+
+ {t("models.preferredBadge")}
+
+ ) : null}
diff --git a/dashboard/src/pages/Settings/Models/index.module.less b/dashboard/src/pages/Settings/Models/index.module.less
index c01daae272..cb07e6d453 100644
--- a/dashboard/src/pages/Settings/Models/index.module.less
+++ b/dashboard/src/pages/Settings/Models/index.module.less
@@ -1173,6 +1173,20 @@
white-space: nowrap;
}
+.poolModelNameRow {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+}
+
+.preferredBadge {
+ flex: none;
+ margin-inline-end: 0;
+ font-size: 11px;
+ line-height: 18px;
+}
+
.poolModelName {
font-size: 14px;
font-weight: 500;
@@ -1180,6 +1194,7 @@
line-height: 1.4;
word-break: break-word;
overflow-wrap: anywhere;
+ min-width: 0;
@media (max-width: 767px) {
font-size: 14px;
diff --git a/dashboard/src/pages/Settings/Models/useProviders.ts b/dashboard/src/pages/Settings/Models/useProviders.ts
index ee42b656b6..7f02ad5112 100644
--- a/dashboard/src/pages/Settings/Models/useProviders.ts
+++ b/dashboard/src/pages/Settings/Models/useProviders.ts
@@ -79,6 +79,8 @@ export interface ProviderRow {
models: ProviderModel[];
note: string | null;
enabled: boolean;
+ /** Saved connection-test model. Empty means the form stays blank. */
+ model?: string | null;
/** Resolved: custom defaults off, bundled presets default on. */
stream_usage?: boolean;
/** UI lane: embedding providers are managed on the embedding Models tab. */
@@ -133,9 +135,6 @@ export function useProviders(): UseProvidersResult {
request("/admin/providers"),
request("/providers/presets"),
providerApi.listResolvedModels(),
- request<{ provider_name: string; model: string }>(
- "/providers/active-model",
- ),
preferencesApi.get(),
]);
const rows =
@@ -150,10 +149,8 @@ export function useProviders(): UseProvidersResult {
settled[2].status === "fulfilled" && Array.isArray(settled[2].value)
? settled[2].value
: [];
- const active =
- settled[3].status === "fulfilled" ? settled[3].value : null;
const preferences =
- settled[4].status === "fulfilled" ? settled[4].value : null;
+ settled[3].status === "fulfilled" ? settled[3].value : null;
if (
settled[0].status === "rejected" &&
@@ -171,6 +168,8 @@ export function useProviders(): UseProvidersResult {
setProviders(normalized);
setPresets(presetList);
setResolvedModels(resolved);
+ // Only an explicit per-user preference is starred. The global active
+ // model is a separate fallback and must not look selected here.
const preferredParts = (preferences?.preferred_model || "").split("/");
setActiveModel(
preferredParts.length > 1
@@ -178,11 +177,6 @@ export function useProviders(): UseProvidersResult {
provider_name: preferredParts[0],
model: preferredParts.slice(1).join("/"),
}
- : active && typeof active === "object"
- ? {
- provider_name: active.provider_name ?? "",
- model: active.model ?? "",
- }
: { provider_name: "", model: "" },
);
setModelReasoning(preferences?.model_reasoning || {});
diff --git a/dashboard/src/pwa.ts b/dashboard/src/pwa.ts
index 9225cb1a54..a67f23d9e1 100644
--- a/dashboard/src/pwa.ts
+++ b/dashboard/src/pwa.ts
@@ -12,3 +12,9 @@ export async function applyUpdate(): Promise {
const { applyUpdate: apply } = await import("./sw-register");
await apply();
}
+
+/** Whether a newer frontend is already waiting. Survives a missed event. */
+export async function hasPendingAppUpdate(): Promise {
+ const { hasPendingAppUpdate: pending } = await import("./sw-register");
+ return pending();
+}
diff --git a/dashboard/src/styles/appearanceStorage.test.ts b/dashboard/src/styles/appearanceStorage.test.ts
index c46a87adc1..f392404c91 100644
--- a/dashboard/src/styles/appearanceStorage.test.ts
+++ b/dashboard/src/styles/appearanceStorage.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import {
loadAppearanceOnBoot,
readStoredAppearance,
+ userAppearanceStorageKey,
writeStoredAppearance,
} from "./appearanceStorage";
import {
@@ -14,6 +15,9 @@ import {
afterEach(() => {
localStorage.removeItem(THEME_STORAGE_KEY);
localStorage.removeItem(LEGACY_PALETTE_STORAGE_KEY);
+ localStorage.removeItem(userAppearanceStorageKey(1));
+ localStorage.removeItem(userAppearanceStorageKey(2));
+ localStorage.removeItem(userAppearanceStorageKey(3));
});
describe("appearanceStorage", () => {
@@ -115,4 +119,32 @@ describe("appearanceStorage", () => {
expect(readStoredAppearance().preference).toBe("system");
expect(readStoredAppearance().palette).toBe(DEFAULT_PALETTE);
});
+
+ it("keeps each user's palette separate from the shared boot key", () => {
+ writeStoredAppearance(
+ {
+ preference: "dark",
+ palette: "violet",
+ customColor: DEFAULT_CUSTOM_COLOR,
+ },
+ 1,
+ );
+ writeStoredAppearance(
+ {
+ preference: "light",
+ palette: "indigo",
+ customColor: DEFAULT_CUSTOM_COLOR,
+ },
+ 2,
+ );
+ localStorage.setItem(
+ THEME_STORAGE_KEY,
+ JSON.stringify({ preference: "dark", palette: "tech" }),
+ );
+
+ expect(readStoredAppearance(1).palette).toBe("violet");
+ expect(readStoredAppearance(2).palette).toBe("indigo");
+ expect(readStoredAppearance(3).palette).toBe(DEFAULT_PALETTE);
+ expect(readStoredAppearance().palette).toBe("tech");
+ });
});
diff --git a/dashboard/src/styles/appearanceStorage.ts b/dashboard/src/styles/appearanceStorage.ts
index 3aebc7659c..d8fd85b05b 100644
--- a/dashboard/src/styles/appearanceStorage.ts
+++ b/dashboard/src/styles/appearanceStorage.ts
@@ -42,7 +42,12 @@ function readLegacyPalette(): ThemePalette {
* Read light/dark preference + brand palette from the shared `theme` key.
* Migrates legacy plain-string `theme` and `octop:ui-palette` values.
*/
-export function readStoredAppearance(): StoredAppearance {
+export function readStoredAppearance(userId?: number | null): StoredAppearance {
+ if (typeof userId === "number") {
+ const own = localStorage.getItem(userAppearanceStorageKey(userId));
+ if (!own) return defaultAppearance();
+ return parseUserAppearance(own);
+ }
const raw = localStorage.getItem(THEME_STORAGE_KEY);
if (!raw) {
return {
@@ -86,10 +91,50 @@ export function readStoredAppearance(): StoredAppearance {
};
}
-/** Persist both fields under the same `theme` key; drop legacy palette key. */
-export function writeStoredAppearance(appearance: StoredAppearance): void {
+function parseUserAppearance(raw: string): StoredAppearance {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (parsed && typeof parsed === "object") {
+ const obj = parsed as Record;
+ return {
+ preference: isPreference(obj.preference) ? obj.preference : "system",
+ palette: isPalette(obj.palette) ? obj.palette : DEFAULT_PALETTE,
+ customColor:
+ normalizeHexColor(obj.customColor as string) ?? DEFAULT_CUSTOM_COLOR,
+ };
+ }
+ } catch {
+ // fall through
+ }
+ return defaultAppearance();
+}
+
+export function defaultAppearance(): StoredAppearance {
+ return {
+ preference: "system",
+ palette: DEFAULT_PALETTE,
+ customColor: DEFAULT_CUSTOM_COLOR,
+ };
+}
+
+/** Per-user key so two accounts on one browser do not share a palette. */
+export function userAppearanceStorageKey(userId: number): string {
+ return `${THEME_STORAGE_KEY}:user:${userId}`;
+}
+
+function appearanceStorageKey(userId?: number | null): string {
+ return typeof userId === "number"
+ ? userAppearanceStorageKey(userId)
+ : THEME_STORAGE_KEY;
+}
+
+/** Persist both fields. A user id writes that account's key, not the shared boot key. */
+export function writeStoredAppearance(
+ appearance: StoredAppearance,
+ userId?: number | null,
+): void {
localStorage.setItem(
- THEME_STORAGE_KEY,
+ appearanceStorageKey(userId),
JSON.stringify({
preference: appearance.preference,
palette: appearance.palette,
@@ -97,7 +142,9 @@ export function writeStoredAppearance(appearance: StoredAppearance): void {
normalizeHexColor(appearance.customColor ?? "") ?? DEFAULT_CUSTOM_COLOR,
}),
);
- localStorage.removeItem(LEGACY_PALETTE_STORAGE_KEY);
+ if (typeof userId !== "number") {
+ localStorage.removeItem(LEGACY_PALETTE_STORAGE_KEY);
+ }
}
/** One-shot boot read + migrate for ThemeProvider initial state. */
diff --git a/dashboard/src/sw-register.test.ts b/dashboard/src/sw-register.test.ts
index 285ebc2b83..6e81ced051 100644
--- a/dashboard/src/sw-register.test.ts
+++ b/dashboard/src/sw-register.test.ts
@@ -104,6 +104,18 @@ describe("registerProductionSW", () => {
expect(waiting.postMessage).not.toHaveBeenCalled();
expect(onReady).toHaveBeenCalledOnce();
+
+ const { hasPendingAppUpdate } = await import("./sw-register");
+ expect(hasPendingAppUpdate()).toBe(true);
+ });
+
+ it("reports no pending update when nothing is waiting", async () => {
+ mockRegistration({ waiting: null, controller: null });
+ const { registerProductionSW, hasPendingAppUpdate } = await import(
+ "./sw-register"
+ );
+ await registerProductionSW();
+ expect(hasPendingAppUpdate()).toBe(false);
});
});
diff --git a/dashboard/src/sw-register.ts b/dashboard/src/sw-register.ts
index cd67e5544d..c265ba8cec 100644
--- a/dashboard/src/sw-register.ts
+++ b/dashboard/src/sw-register.ts
@@ -35,6 +35,11 @@ function notifyUpdateReady(): void {
window.dispatchEvent(new CustomEvent("pwa:update-ready"));
}
+/** True when a newer worker is waiting and the page is still on the old one. */
+export function hasPendingAppUpdate(): boolean {
+ return pendingRegistration?.waiting != null;
+}
+
async function unregisterAllServiceWorkers(): Promise {
const regs = await navigator.serviceWorker.getRegistrations();
await Promise.all(regs.map((r) => r.unregister()));
diff --git a/dashboard/src/utils/modelOptions.test.ts b/dashboard/src/utils/modelOptions.test.ts
new file mode 100644
index 0000000000..cea271de96
--- /dev/null
+++ b/dashboard/src/utils/modelOptions.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { modelRefLabel } from "./modelOptions";
+
+describe("modelRefLabel", () => {
+ it("uses the picker label so two vendors of the same model stay distinct", () => {
+ const models = [
+ { provider_name: "Huawei", model: "deepseek-v3", name: "DeepSeek V3" },
+ { provider_name: "Tencent", model: "deepseek-v3", name: "DeepSeek V3" },
+ ];
+ expect(modelRefLabel("Huawei/deepseek-v3", models)).toBe(
+ "Huawei / DeepSeek V3",
+ );
+ expect(modelRefLabel("Tencent/deepseek-v3", models)).toBe(
+ "Tencent / DeepSeek V3",
+ );
+ });
+
+ it("keeps the provider when the catalog entry is missing", () => {
+ expect(modelRefLabel("Huawei/deepseek-v3")).toBe("Huawei / deepseek-v3");
+ });
+});
diff --git a/dashboard/src/utils/modelOptions.ts b/dashboard/src/utils/modelOptions.ts
index 74d7c4ce93..60030e9d5a 100644
--- a/dashboard/src/utils/modelOptions.ts
+++ b/dashboard/src/utils/modelOptions.ts
@@ -52,3 +52,17 @@ export function modelShortLabel(modelRefValue: string): string {
if (slash < 0) return modelRefValue;
return modelRefValue.slice(slash + 1);
}
+
+/** Same text as the model picker, so the chat chip can tell two vendors apart. */
+export function modelRefLabel(
+ modelRefValue: string,
+ models?: readonly ModelPickerOption[] | null,
+): string {
+ const ref = modelRefValue.trim();
+ if (!ref) return "";
+ const match = models?.find((item) => modelOptionValue(item) === ref);
+ if (match) return modelOptionLabel(match);
+ const slash = ref.indexOf("/");
+ if (slash <= 0 || slash === ref.length - 1) return ref;
+ return `${ref.slice(0, slash)} / ${ref.slice(slash + 1)}`;
+}
diff --git a/docker/Dockerfile b/docker/Dockerfile
index ec5ab44a4d..a4aae85d7d 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -104,6 +104,7 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
libglib2.0-0 \
curl \
git \
+ postgresql-client \
ripgrep \
&& rm -rf /var/lib/apt/lists/*
diff --git a/docs/api.md b/docs/api.md
index ad75d94bc2..131dd4fa7c 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -393,6 +393,7 @@ Bundled experts live in `src/octop/infra/agents/experts/library/`
| `GET` | `/agents/{aid}/heartbeat-config` | owner | read heartbeat YAML |
| `PUT` | `/agents/{aid}/heartbeat-config` | owner | write heartbeat YAML |
| `GET` | `/agents/{aid}/memory/daily` | owner | list daily memory files |
+| `GET`/`PUT` | `/agents/{aid}/memory/extract-config` | owner/admin | Read/update memory runtime and extraction options; omitted fields retain their stored values |
| `GET`/`PUT` | `/agents/{aid}/memory/strong` | owner | read/edit user-maintained MEMORY.md, including for stopped agents; new sessions snapshot full content once, existing sessions keep their snapshot |
| `GET`/`PUT` | `/agents/{aid}/memory/user` | owner | read/edit user-maintained USER.md with the same session snapshot policy; distinct from the derived profile |
| `GET` | `/agents/{aid}/memory/manual-review` | owner | read persisted reconciliation status against current documents; no model call or memory mutation |
@@ -401,6 +402,13 @@ Bundled experts live in `src/octop/infra/agents/experts/library/`
| `DELETE` | `/agents/{aid}/memory/daily/{filename}` | owner | delete one daily memory |
| `GET`/`POST` | `/memory/...` | user | memory API (dashboard memory tab) |
+The extraction-config API accepts independent `memory_capture_enabled` and
+`memory_recall_inject_enabled` booleans. Both default to `true`: set the first to
+`false` to stop automatic conversation-event capture, or the second to `false` to
+stop automatically injecting recalled memory into model context. These switches
+do not disable explicit memory tools. Check `supported_call_options` before using
+them with an older harness; unsupported options are not forwarded to its config.
+
### Manual document reconciliation
The manual editors save files first, then request reconciliation. The response reports
diff --git a/docs/projects.md b/docs/projects.md
new file mode 100644
index 0000000000..353b3345b3
--- /dev/null
+++ b/docs/projects.md
@@ -0,0 +1,103 @@
+# 项目模式设计
+
+项目是一种专家。它自己完成任务,需要时把别的专家当作工具调用。任务是这个项目下的对话。能打开项目的人看到全部任务,并可以继续问。
+
+本文是设计,尚未实现。专家上的「共享会话」已经单独落地:会话默认私有,主人可以再把某一条开放出去。那不是项目。
+
+## 区别和联系
+
+专家、团队、项目都是 `agents` 里的一行。工作区、记忆、对话都挂在这一行上。差别在谁干活、别人怎么进来、上下文怎么带。
+
+| | 专家 `kind=expert` | 团队 `kind=team` | 项目 `kind=project` |
+|---|---|---|---|
+| 是什么 | 一个人可用的专家 | 主持人加至少两名成员 | 一块共享的工作,本身也是专家 |
+| 谁干活 | 自己 | 主持人只调度,成员干活 | 自己做完;需要时再调用专家 |
+| 工具 | 干活的全套,含技能 | 只有 `agent_list`、异步 `ask_agent`、记忆、时间 | 和专家同一套 |
+| 调用专家 | 可以同步调用 | 异步派工,编制写在 `.octop/manifest.json` | 同步调用,名单写在项目配置里,可以为空 |
+| 谁能打开 | 仅自己、全部或指定分组 | 当前不能分享,只有创建者 | 和专家一样:仅自己、全部或指定分组 |
+| 对话谁能看 | 默认只有自己;主人可再共享某一条 | 只有创建者 | 能打开项目的人看到全部任务 |
+| 知识库、连接器 | 选进专家的,按当前发消息的人再滤一遍 | 主持人不挂 | 项目默认按主人调用;对话里另选的按当前用户的授权 |
+| 技能 | 挂在专家上,主人管理 | 主持人不挂技能 | 和专家一样,挂在项目上 |
+| 制品 | 专家工作区 | 各写各的工作区 | 项目工作区 |
+
+联系:
+
+- 项目和专家共用同一套技能、知识库、连接器、工作区和记忆。团队主持人是调度壳,这些能力在成员专家上。
+- 三者的准入都不是点名用户。专家和项目用「仅自己 / 全部 / 指定分组」。团队仍保持不分享。
+- 任务不另建表。专家的会话、团队房间、项目任务都是 `threads`。
+- 可调用的专家仍是普通专家。项目调用他们是一次工具返回,不是团队那种上墙派工。
+
+## 谁能用
+
+创建和编辑项目时选择可见范围,复用专家现在的「仅自己 / 全部 / 指定分组」。不单独点名用户。
+
+被选中的人可以打开项目、看到全部任务、继续追问、处理待审批。改名称、可见范围、默认知识库、默认连接器、技能和可调用专家,只有主人可以。
+
+## 知识库和连接器
+
+分成两层。
+
+项目上选中的默认知识库和默认连接器,每次任务都带上,按项目主人的身份调用。别人不用先拥有这些资源,也不会在自己的列表里看到它们,不能拿到别的专家上用。凭证仍是主人的,只在这个项目里生效。对话里不能拿掉这层默认。
+
+发消息时还可以再选。可选的只包括当前这个人自己的,以及别人已经共享给他的。这一层按该用户自己的授权调用,加在项目默认之上。
+
+因此一次任务里可以同时有两套:项目默认走主人,对话里勾上的走当前用户。
+
+今天的专家还不是这样。别人发消息时,专家上选的知识库和连接器会按这个人自己的可见范围再滤一遍。项目按上面的两层做。专家是否改成同样的默认层,不在这一版里。
+
+## 技能
+
+技能跟专家一样管理:挂在这个项目上,主人启用或停用。谁来聊都用这一份,不按用户再授权一次。
+
+## 任务
+
+一条任务就是这个项目下的一条对话。能打开项目的人默认都能看见,不必再逐条点共享。
+
+状态从这一轮运行情况读出来,不另做工单:
+
+- **进行中**:这一轮还在跑。有人追问后,从已完成回到进行中。
+- **待审批**:停在工具确认上。能看这条任务的人都可以处理。
+- **已完成**:这一轮正常结束。
+- **失败**:这一轮出错结束。现有接口若还没有失败标记,第一版先不画这个图标。
+
+创建人记在对话上。改名、置顶、删除、分叉,以及模型和审批设置,只有创建人可以。其他人可以发消息。调用专家产生的内部会话不出现在任务列表里。
+
+记忆是这个项目专家的一份,房间里的人共用。按人隔开放到后面。
+
+## 页面
+
+左侧导航增加「项目」,路径 `/projects`。
+
+列表是卡片:名称、简介、进行中和待审批的数量。主人可以新建、编辑、删除。
+
+详情列出当前绑定,主人可改,其他人只读:
+
+- 知识库
+- 连接器
+- 技能
+- 可调用的专家
+
+页头有「打开任务」,进入聊天里的这个项目。
+
+聊天侧栏的分页改为「专家 / 团队 / 项目」,用「项目」换掉「云端」。对端专家仍在「专家」里,对端团队仍在「团队」里,云端协同页面留在原入口。
+
+「项目」下展开的是任务。进行中和待审批排在前面,可筛「全部 / 进行中 / 待审批」。按钮写「新任务」。每一行有标题、状态、发起人头像,名字在悬停时出现。
+
+任务页仍是现在的聊天。顶栏标「项目」,下面一行只读摘要链到项目详情。制品在右侧文件栏,读这个项目的工作区。
+
+## 实现时沿用的结构
+
+不新建项目表,也不新建任务表。
+
+- `agents.kind` 增加 `project`。现在只接受 `expert` 和 `team`。
+- 可调用专家写在该专家配置里的一份 id 列表,不用团队清单。
+- 运行时走专家装配,不套主持人的工具白名单。`ask_agent` 用专家现有的同步调用,名单之外的专家调不到;名单为空就不提供这项工具。
+- 项目线程对能打开该项目的人全部可见。追问、作者和待审批走已经做好的共享会话路径。共享专家上的逐条共享保持不变。
+- `TEAM_NOT_SHAREABLE` 继续只拦团队。
+
+## 不做
+
+- 不把项目做成共享团队,不放开团队分享。
+- 不点名用户,不用第二张成员表。
+- 不做看板、项目动态、关闭后锁定的工单。
+- 不把项目默认的知识库和连接器复制进每个用户自己的库。
diff --git a/fnos/docker/Dockerfile b/fnos/docker/Dockerfile
index b51aba6856..072226a2f7 100644
--- a/fnos/docker/Dockerfile
+++ b/fnos/docker/Dockerfile
@@ -80,6 +80,7 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
libglib2.0-0 \
curl \
git \
+ postgresql-client \
ripgrep \
&& rm -rf /var/lib/apt/lists/*
diff --git a/pyproject.toml b/pyproject.toml
index 429eabe344..02dc6ccca4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -30,6 +30,10 @@ dependencies = [
"edge-tts>=6.1",
"segno>=1.6",
"websockets>=13.0",
+ # websockets raises "python-socks is required to use a SOCKS proxy" when
+ # the host has a SOCKS proxy env and this package is absent — the browser
+ # host's CDP connection then fails to attach.
+ "python-socks>=2.4",
"acme>=5.6.0",
"josepy>=2.2.0",
"boto3>=1.40.61",
diff --git a/src/octop/api/middleware/bridge_proxy.py b/src/octop/api/middleware/bridge_proxy.py
index 9927dc9426..772cfd5acf 100644
--- a/src/octop/api/middleware/bridge_proxy.py
+++ b/src/octop/api/middleware/bridge_proxy.py
@@ -203,6 +203,21 @@ def _forward_headers(request: Request, remote_agent_id: str) -> dict[str, str]:
return headers
+def _is_websocket_upgrade(headers: Any) -> bool:
+ """True only for a real WebSocket handshake.
+
+ A reverse proxy often sets ``Connection: upgrade`` on every request
+ (``proxy_set_header Connection "upgrade"``) and leaves ``Upgrade`` empty.
+ Those requests must still be tunneled. ``Connection`` may also be a list.
+ """
+ connection = headers.get("connection") or ""
+ tokens = {part.strip().lower() for part in str(connection).split(",") if part.strip()}
+ if "upgrade" not in tokens:
+ return False
+ upgrade = headers.get("upgrade") or ""
+ return "websocket" in {part.strip().lower() for part in str(upgrade).split(",") if part.strip()}
+
+
def install(app: Any, server: Any) -> None:
if getattr(app, _INSTALL_ATTR, False):
return
@@ -220,8 +235,8 @@ async def _bridge_proxy(
)
if target is None:
return await call_next(request)
- # WebSocket upgrades are handled by the chat/bridge routers.
- if (request.headers.get("connection") or "").lower() == "upgrade":
+ # Real WebSocket upgrades are handled by the chat/bridge routers.
+ if _is_websocket_upgrade(request.headers):
return await call_next(request)
user = getattr(request.state, "octop_user", None)
diff --git a/src/octop/api/routers/chat/history.py b/src/octop/api/routers/chat/history.py
index 764cdd7441..1f76333f41 100644
--- a/src/octop/api/routers/chat/history.py
+++ b/src/octop/api/routers/chat/history.py
@@ -11,7 +11,7 @@
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import JSONResponse, Response
-from octop.api.common.agent import require_agent_row
+from octop.api.common.agent import agent_is_shared, require_agent_row
from octop.api.common.agent_workspace import resolve_agent_workspace_dir
from octop.api.deps import current_user, get_server
from octop.api.routers.chat.models import ForkThreadBody, RebindSessionBody, RenameThreadBody
@@ -29,7 +29,7 @@
from octop.infra.agents.workspace.dir import agent_facing_workspace_dir_from_config
from octop.infra.errors import ErrorCode, OctopError
from octop.infra.gateway.hitl.coordinator import pending_hitl_payload
-from octop.infra.gateway.threads import ThreadRegistry, thread_row_has_messages
+from octop.infra.gateway.threads import ThreadRegistry, thread_row_has_messages, thread_visible_to
from octop.infra.history.service import HistoryArchive
from octop.infra.history.trajectory.service import TrajectoryService
from octop.infra.utils.locale import resolve_request_locale
@@ -47,6 +47,67 @@ def _hitl_policy_payload(row: Any) -> dict[str, Any]:
return parse_hitl_session_policy(getattr(row, "hitl_policy", None)).to_dict()
+def _message_author_profile(server: Any, user_id: int) -> dict[str, Any] | None:
+ """Name and portrait for one sender. Skips mocks and missing accounts."""
+ repo = getattr(getattr(server, "services", None), "user_repo", None)
+ get = getattr(repo, "get", None)
+ if not callable(get):
+ return None
+ row = get(user_id)
+ username = getattr(row, "username", None)
+ if not isinstance(username, str) or not username:
+ return None
+ from octop.infra.users.profile_avatar import profile_avatar_url # noqa: PLC0415
+
+ avatars = getattr(getattr(server, "services", None), "avatars", None)
+ avatar_url = None
+ if callable(avatars):
+ avatar_url = profile_avatar_url(
+ avatars("user"),
+ str(user_id),
+ f"/api/users/{user_id}/avatar",
+ )
+ display_name = getattr(row, "display_name", None)
+ icon = getattr(row, "avatar_icon", None)
+ return {
+ "user_id": user_id,
+ "display_name": display_name if isinstance(display_name, str) else "",
+ "username": username,
+ "avatar_icon": icon if isinstance(icon, str) and icon else None,
+ "avatar_url": avatar_url,
+ }
+
+
+def _attach_message_authors(
+ server: Any, messages: list[dict[str, Any]], *, owner_user_id: int
+) -> None:
+ """Fill each user turn with who asked it.
+
+ Turns written before this stamp belong to the thread owner. Later turns
+ keep the person who actually sent them, so a shared conversation can show
+ a different head for each person.
+ """
+ if not isinstance(owner_user_id, int) or owner_user_id <= 0:
+ return
+ needed: set[int] = set()
+ for item in messages:
+ if item.get("role") != "user":
+ continue
+ author_id = item.get("author_user_id")
+ if not isinstance(author_id, int) or author_id <= 0:
+ author_id = owner_user_id
+ item["author_user_id"] = author_id
+ needed.add(author_id)
+ profiles = {user_id: _message_author_profile(server, user_id) for user_id in needed}
+ for item in messages:
+ if item.get("role") != "user":
+ continue
+ raw_author = item.get("author_user_id")
+ profile = profiles.get(raw_author) if isinstance(raw_author, int) else None
+ if profile is not None:
+ item["author"] = profile
+
+
def _history_migration_payload(server: Any, *, agent_id: str, user_id: int) -> dict[str, Any]:
repo = server.services.thread_message_repo
summary = repo.migration_summary(
@@ -87,14 +148,28 @@ def _agent_facing_workspace_dir(server: Any, agent_id: str) -> Path:
def _require_thread(
- server: Any, agent_id: str, thread_id: str, user: Any, as_user: int | None
+ server: Any,
+ agent_id: str,
+ thread_id: str,
+ user: Any,
+ as_user: int | None,
+ *,
+ write: bool = False,
) -> Any:
+ """Load a thread the caller may open.
+
+ ``write`` is the owner's management actions (rename, delete, fork, contribute).
+ A contributed thread stays readable and continuable by anyone who can open the expert.
+ """
require_agent_row(agent_id, user=user, as_user=as_user, server=server)
row = server.app_runtime.gateway.thread_registry.get_thread(thread_id)
if row is None or row.agent_id != agent_id:
raise OctopError(ErrorCode.AGENT_NOT_FOUND, f"thread {thread_id!r} not found")
effective_uid = as_user if as_user is not None else user.id
- if row.user_id != effective_uid:
+ if write:
+ if row.user_id != effective_uid:
+ raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
+ elif not thread_visible_to(row, effective_uid):
raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
return row
@@ -115,19 +190,24 @@ async def list_threads(
require_agent_row(agent_id, user=user, as_user=as_user, server=server)
thread_registry = server.app_runtime.gateway.thread_registry
effective_uid = as_user if as_user is not None else user.id
- rows = thread_registry.list_threads(agent_id=agent_id, user_id=effective_uid, limit=limit)
+ rows = thread_registry.list_visible_threads(
+ agent_id=agent_id, user_id=effective_uid, limit=limit
+ )
bound = thread_registry.get_bound_thread_id(
ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=effective_uid)
)
workspace_dir = _agent_facing_workspace_dir(server, agent_id)
hub = server.app_runtime.gateway.ws_hub
- awaiting_ids = server.app_runtime.gateway.processor.hitl_coordinator.store.pending_thread_ids(
- agent_id=agent_id, user_id=effective_uid
+ hitl_store = server.app_runtime.gateway.processor.hitl_coordinator.store
+ awaiting_ids = hitl_store.pending_thread_ids(agent_id=agent_id, user_id=effective_uid)
+ shared_awaiting_ids = hitl_store.pending_thread_ids(
+ agent_id=agent_id, user_id=effective_uid, any_user=True
)
# title / last_active 只能说明「建过会话」,不能说明「有内容」:
# 有些 thread 有标题但从未落过消息,点开就是空白。这里补一次真实计数。
message_repo = server.services.thread_message_repo
ids_with_messages = message_repo.threads_with_messages([r.thread_id for r in rows])
+ unread = thread_registry.unread_counts_for_threads([r.thread_id for r in rows])
def _has_messages(row: Any) -> bool:
if not thread_row_has_messages(row):
@@ -148,6 +228,9 @@ def _has_messages(row: Any) -> bool:
"is_active": r.thread_id == bound,
"has_messages": _has_messages(r),
"pinned": r.pinned,
+ "unread_count": int(unread.get(r.thread_id, 0)),
+ "contributed": bool(r.contributed),
+ "owned": r.user_id == effective_uid,
"model_ref": r.model_ref,
"reasoning_mode": r.reasoning_mode,
"reasoning_effort": r.reasoning_effort,
@@ -155,7 +238,8 @@ def _has_messages(row: Any) -> bool:
"pending_plan_path": r.pending_plan_path,
"hitl_policy": _hitl_policy_payload(r),
"turn_active": hub.is_turn_active(r.thread_id),
- "awaiting_user": r.thread_id in awaiting_ids,
+ "awaiting_user": r.thread_id
+ in (shared_awaiting_ids if r.contributed else awaiting_ids),
**thread_artifacts_payload(
r.artifacts,
workspace_dir,
@@ -409,11 +493,12 @@ async def _work() -> None:
user=user,
)
effective_uid = as_user if as_user is not None else user.id
+ _attach_message_authors(server, messages, owner_user_id=row.user_id)
hitl_pending = pending_hitl_payload(
server.app_runtime.gateway.processor.hitl_coordinator.store,
thread_id=thread_id,
agent_id=agent_id,
- user_id=effective_uid,
+ user_id=None if row.contributed else effective_uid,
)
workspace_dir = _agent_facing_workspace_dir(server, agent_id)
return {
@@ -453,7 +538,8 @@ async def mark_thread_read(
) -> None:
"""Clear unread message count for a thread (e.g. when the user opens it in the dashboard)."""
_require_thread(server, agent_id, thread_id, user, as_user)
- server.app_runtime.gateway.thread_registry.mark_thread_read(thread_id)
+ effective_uid = as_user if as_user is not None else user.id
+ server.app_runtime.gateway.thread_registry.mark_thread_read_for_user(thread_id, effective_uid)
@router.post(
@@ -512,7 +598,7 @@ async def fork_thread(
ErrorCode.SLASH_BAD_ARGS,
"message_id or assistant_turns_from_end is required",
)
- row = _require_thread(server, agent_id, thread_id, user, as_user)
+ row = _require_thread(server, agent_id, thread_id, user, as_user, write=True)
effective_uid = as_user if as_user is not None else user.id
harness = server.app_runtime.agent_registry.get_agent(agent_id)
return await fork_dashboard_thread(
@@ -540,7 +626,10 @@ async def rebind_session(
_require_thread(server, agent_id, body.thread_id, user, as_user=None)
sk = ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=user.id)
await server.app_runtime.gateway.thread_registry.rebind(
- session_key=sk, thread_id=body.thread_id, agent_id=agent_id
+ session_key=sk,
+ thread_id=body.thread_id,
+ agent_id=agent_id,
+ acting_user_id=user.id,
)
return {"session_key": sk, "thread_id": body.thread_id}
@@ -591,6 +680,7 @@ async def patch_thread(
) -> dict[str, Any]:
"""Update sidebar metadata or sticky composer settings for a thread."""
row = _require_thread(server, agent_id, thread_id, user, as_user)
+ effective_uid = as_user if as_user is not None else user.id
composer_fields = {
"model_ref",
"reasoning_mode",
@@ -598,15 +688,21 @@ async def patch_thread(
"conversation_mode",
"hitl_policy",
}
+ managing = bool(body.model_fields_set)
+ if managing and row.user_id != effective_uid:
+ raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
if (
body.title is None
and body.pinned is None
+ and "contributed" not in body.model_fields_set
and not body.model_fields_set.intersection(composer_fields)
):
return {
"thread_id": thread_id,
"title": row.title,
"pinned": row.pinned,
+ "contributed": bool(row.contributed),
+ "owned": row.user_id == effective_uid,
"model_ref": row.model_ref,
"reasoning_mode": row.reasoning_mode,
"reasoning_effort": row.reasoning_effort,
@@ -615,6 +711,15 @@ async def patch_thread(
"hitl_policy": _hitl_policy_payload(row),
}
registry = server.app_runtime.gateway.thread_registry
+ if "contributed" in body.model_fields_set:
+ if body.contributed:
+ agent_row = require_agent_row(agent_id, user=user, as_user=as_user, server=server)
+ if not agent_is_shared(agent_row):
+ raise OctopError(
+ ErrorCode.THREAD_CONTRIBUTE_REQUIRES_SHARE,
+ "only a shared expert can accept a contributed conversation",
+ )
+ registry.set_contributed(thread_id, bool(body.contributed))
if body.title is not None:
registry.update_title(thread_id, body.title)
if body.pinned is not None:
@@ -670,6 +775,8 @@ async def patch_thread(
"thread_id": thread_id,
"title": updated.title,
"pinned": updated.pinned,
+ "contributed": bool(updated.contributed),
+ "owned": updated.user_id == effective_uid,
"model_ref": updated.model_ref,
"reasoning_mode": updated.reasoning_mode,
"reasoning_effort": updated.reasoning_effort,
@@ -700,7 +807,7 @@ async def delete_thread(
maintenance reclaims the free space later, once the freelist is large
enough. Omitting ``compact`` keeps the previous empty 204.
"""
- _require_thread(server, agent_id, thread_id, user, as_user)
+ _require_thread(server, agent_id, thread_id, user, as_user, write=True)
if server.app_runtime.gateway.ws_hub.is_turn_active(thread_id):
raise OctopError(
ErrorCode.THREAD_TURN_ACTIVE,
diff --git a/src/octop/api/routers/chat/models.py b/src/octop/api/routers/chat/models.py
index d5b7482145..e221151c5f 100644
--- a/src/octop/api/routers/chat/models.py
+++ b/src/octop/api/routers/chat/models.py
@@ -194,6 +194,10 @@ class ForkThreadBody(BaseModel):
class RenameThreadBody(BaseModel):
title: str | None = None
pinned: bool | None = None
+ contributed: bool | None = Field(
+ default=None,
+ description="Share this conversation with other users of the expert.",
+ )
model_ref: str | None = None
reasoning_mode: Literal["auto", "enabled", "disabled"] | None = None
reasoning_effort: str | None = None
diff --git a/src/octop/api/routers/chat/routes.py b/src/octop/api/routers/chat/routes.py
index 4bf975af48..fac5fa96bb 100644
--- a/src/octop/api/routers/chat/routes.py
+++ b/src/octop/api/routers/chat/routes.py
@@ -13,7 +13,6 @@
from octop.api.deps import current_user, get_server
from octop.api.routers.chat.models import HitlResumeBody, PolishBody
from octop.api.routers.chat.sse import format_sse
-from octop.i18n.domains.stream import format_stream_error
from octop.infra.agents.experts.catalog import (
default_welcome_payload,
display_task_examples_for_agent,
@@ -25,6 +24,7 @@
from octop.infra.agents.settings.profile import welcome_from_row
from octop.infra.agents.teams import is_team_agent
from octop.infra.agents.teams.welcome import team_host_welcome_payload
+from octop.infra.errors import stream_error
from octop.infra.gateway.hitl.coordinator import (
HitlChannelCoordinator,
HitlStreamContext,
@@ -202,10 +202,11 @@ async def iter_dashboard_hitl_resume_sse(
# leave the record looking like a successful approve/reject.
if pending is not None:
hitl_coordinator.store.mark_resolved(pending.pending_id, "expired")
- yield format_sse(
- "chunk",
- {"type": "error", "message": format_stream_error(exc, locale)},
- )
+ error_message, error_code = stream_error(exc, locale)
+ payload: dict[str, Any] = {"type": "error", "message": error_message}
+ if error_code:
+ payload["error_code"] = error_code
+ yield format_sse("chunk", payload)
def _dashboard_hitl_stream_context(
@@ -233,14 +234,16 @@ async def resume_hitl(
server: Any = Depends(get_server),
) -> StreamingResponse:
"""Resume a paused human-in-the-loop tool approval and stream subsequent chunks."""
- assert_agent_access(server, agent_id, user)
+ from octop.api.routers.chat.history import _require_thread # noqa: PLC0415
+
+ thread_row = _require_thread(server, agent_id, body.thread_id, user, None)
processor = server.app_runtime.gateway.processor
hitl_coordinator = processor.hitl_coordinator
requested_id = (body.pending_id or "").strip()
pending = hitl_coordinator.store.resolve_pending_for_thread(
body.thread_id,
agent_id=agent_id,
- user_id=user.id,
+ user_id=None if thread_row.contributed else user.id,
pending_id=requested_id or None,
)
if requested_id and pending is None:
@@ -268,7 +271,7 @@ async def missing() -> AsyncIterator[str]:
if reason is not None:
raise HTTPException(status_code=400, detail=reason)
- if body.hitl_policy is not None:
+ if body.hitl_policy is not None and thread_row.user_id == user.id:
hitl_coordinator.session_policies.set(body.thread_id, body.hitl_policy.model_dump())
async def gen() -> AsyncIterator[str]:
diff --git a/src/octop/api/routers/chat/serialize.py b/src/octop/api/routers/chat/serialize.py
index d1b69a798e..ddfec14bc9 100644
--- a/src/octop/api/routers/chat/serialize.py
+++ b/src/octop/api/routers/chat/serialize.py
@@ -18,6 +18,7 @@
from octop.i18n.domains.attachment import attachment_empty_image
from octop.infra.agents.threads.context_breakdown import usage_dict_from_message
from octop.infra.gateway.process.message_keys import (
+ AUTHOR_USER_ID_KEY,
CHECKPOINT_TS_KEY,
COMPOSER_CTX_KEY,
INBOUND_ATTACHMENTS_KEY,
@@ -918,6 +919,17 @@ def _split_string_thinking(text: str) -> list[dict[str, Any]]:
return blocks
+def _author_user_id(raw: Any) -> int | None:
+ if isinstance(raw, bool):
+ return None
+ if isinstance(raw, int) and raw > 0:
+ return raw
+ if isinstance(raw, str) and raw.isdigit():
+ value = int(raw)
+ return value if value > 0 else None
+ return None
+
+
def _serialize_history_message(
msg: Any,
*,
@@ -1012,6 +1024,9 @@ def _serialize_history_message(
entry["composer_context"] = raw_ctx
if has_user_attachments:
entry["inbound_attachments"] = raw_att
+ author_id = _author_user_id(additional_kwargs.get(AUTHOR_USER_ID_KEY))
+ if author_id is not None:
+ entry["author_user_id"] = author_id
if additional_kwargs.get(STREAM_ERROR_FLAG):
entry["status"] = "error"
code = additional_kwargs.get(STREAM_ERROR_CODE_KEY)
diff --git a/src/octop/api/routers/chat/turn.py b/src/octop/api/routers/chat/turn.py
index d033f49d17..82d1fc74f8 100644
--- a/src/octop/api/routers/chat/turn.py
+++ b/src/octop/api/routers/chat/turn.py
@@ -31,7 +31,7 @@
build_composer_context,
)
from octop.infra.gateway.process.usage_record import extract_usage_from_chunk
-from octop.infra.gateway.threads import ThreadRegistry
+from octop.infra.gateway.threads import ThreadRegistry, thread_visible_to
from octop.infra.gateway.ws import WS_CHANNEL_ID
__all__ = [
@@ -71,9 +71,14 @@ async def resolve_thread_id(
row = thread_registry.get_thread(thread_id)
if row is None or row.agent_id != agent_id:
raise OctopError(ErrorCode.AGENT_NOT_FOUND, f"thread {thread_id!r} not found")
- if row.user_id != user_id:
+ if not thread_visible_to(row, user_id):
raise OctopError(ErrorCode.FORBIDDEN, "thread not owned by user")
- await thread_registry.rebind(session_key=sk, thread_id=thread_id, agent_id=agent_id)
+ await thread_registry.rebind(
+ session_key=sk,
+ thread_id=thread_id,
+ agent_id=agent_id,
+ acting_user_id=user_id,
+ )
return thread_id, sk
bound = thread_registry.get_bound_thread_id(sk)
if bound:
diff --git a/src/octop/api/routers/chat/ws.py b/src/octop/api/routers/chat/ws.py
index 410ac67e9e..0460a85ab5 100644
--- a/src/octop/api/routers/chat/ws.py
+++ b/src/octop/api/routers/chat/ws.py
@@ -27,6 +27,7 @@
from octop.infra.errors import OctopError
from octop.infra.gateway.steer import SteerAdmitOk, SteerAdmitReject, SteerCoordinator
from octop.infra.gateway.steer.types import preview_text
+from octop.infra.gateway.threads import thread_visible_to
from octop.infra.gateway.ws import WS_CHANNEL_ID
logger = logging.getLogger(__name__)
@@ -34,6 +35,10 @@
router = APIRouter()
+def _ws_thread_visible(row: Any, agent_id: str, user_id: int) -> bool:
+ return row is not None and row.agent_id == agent_id and thread_visible_to(row, user_id)
+
+
@router.websocket("/agents/{agent_id}/chat/ws")
async def dashboard_chat_ws(
websocket: WebSocket,
@@ -108,7 +113,7 @@ async def send_frame(frame: dict[str, Any]) -> None:
await send_frame({"type": "error", "message": "subscribe requires thread_id"})
continue
row = gateway.thread_registry.get_thread(thread_id)
- if row is None or row.agent_id != agent_id or row.user_id != user.id:
+ if not _ws_thread_visible(row, agent_id, user.id):
await send_frame(
{"type": "error", "message": f"thread {thread_id!r} not found"},
)
@@ -153,7 +158,7 @@ def _subscribe(tid: str = thread_id, cid: str = connection_id) -> None:
await send_frame({"type": "error", "message": "cancel requires thread_id"})
continue
row = gateway.thread_registry.get_thread(thread_id)
- if row is None or row.agent_id != agent_id or row.user_id != user.id:
+ if not _ws_thread_visible(row, agent_id, user.id):
await send_frame(
{"type": "error", "message": f"thread {thread_id!r} not found"},
)
@@ -754,7 +759,7 @@ async def _handle_steer_remove(
)
return
row = gateway.thread_registry.get_thread(thread_id)
- if row is None or row.agent_id != agent_id or row.user_id != user_id:
+ if not _ws_thread_visible(row, agent_id, user_id):
await send_frame(
{
"type": "steer.ack",
diff --git a/src/octop/api/routers/experts.py b/src/octop/api/routers/experts.py
index 65390f1eb0..46902a36c5 100644
--- a/src/octop/api/routers/experts.py
+++ b/src/octop/api/routers/experts.py
@@ -34,6 +34,7 @@
apply_workspace_quick_prompts,
build_create_spec_from_expert,
discover_seed_paths,
+ featured_expert_template_ids,
preview_file_paths,
preview_paths_from_expert_dir,
read_text_file_contents,
@@ -311,7 +312,12 @@ def _portal_prompts(value: Any) -> list[dict[str, Any]]:
return prompts
-def _portal_hub_item(item: dict[str, Any], *, include_content: bool) -> dict[str, Any]:
+def _portal_hub_item(
+ item: dict[str, Any],
+ *,
+ include_content: bool,
+ featured_ids: frozenset[str] | None = None,
+) -> dict[str, Any]:
raw_slugs = item.get("skill_slugs")
slugs = (
[slug for slug in raw_slugs if isinstance(slug, str)] if isinstance(raw_slugs, list) else []
@@ -329,6 +335,7 @@ def _portal_hub_item(item: dict[str, Any], *, include_content: bool) -> dict[str
"skill_slugs": slugs,
"skill_count": int(item.get("skill_count") or 0),
"source": str(item.get("source") or "portal"),
+ "featured": str(item.get("slug") or item.get("id") or "") in (featured_ids or frozenset()),
"task_examples": _portal_task_examples(item.get("task_examples")),
}
if include_content:
@@ -390,6 +397,7 @@ class ExpertHubItemResponse(BaseModel):
skill_slugs: list[str] = Field(default_factory=list)
skill_count: int = 0
source: str = "portal"
+ featured: bool = False
content: LocalizedTextResponse | None = None
quick_prompts: list[QuickPromptResponse] | None = None
task_examples: dict[str, list[str]] | None = None
@@ -820,6 +828,7 @@ async def list_expert_hub(
"""List experts published on the octop.cloud market."""
try:
portal_items, portal_scenes = await asyncio.to_thread(list_market_experts, q, scene)
+ featured_ids = featured_expert_template_ids()
except PortalMarketError as exc:
logger.warning("remote expert market unavailable: %s", exc)
network_error = local_network_error(exc)
@@ -831,7 +840,10 @@ async def list_expert_hub(
details={"reason": "upstream request failed"},
) from exc
return {
- "items": [_portal_hub_item(item, include_content=False) for item in portal_items],
+ "items": [
+ _portal_hub_item(item, include_content=False, featured_ids=featured_ids)
+ for item in portal_items
+ ],
"scenes": portal_scenes,
}
@@ -848,6 +860,7 @@ async def get_expert_hub_item(
"""Expert detail from the octop.cloud market."""
try:
portal_item = await asyncio.to_thread(get_market_expert, slug)
+ featured_ids = featured_expert_template_ids()
except PortalMarketError as exc:
logger.warning("remote expert market unavailable: %s", exc)
network_error = local_network_error(exc)
@@ -860,7 +873,7 @@ async def get_expert_hub_item(
) from exc
if portal_item is None:
raise OctopError(ErrorCode.NOT_FOUND, "expert not found")
- return _portal_hub_item(portal_item, include_content=True)
+ return _portal_hub_item(portal_item, include_content=True, featured_ids=featured_ids)
@router.post(
diff --git a/src/octop/api/routers/memory.py b/src/octop/api/routers/memory.py
index ddf345bcff..f44cae665a 100644
--- a/src/octop/api/routers/memory.py
+++ b/src/octop/api/routers/memory.py
@@ -57,6 +57,8 @@
# back when constructing the agent.
_EXTRACT_DEFAULTS: dict[str, Any] = {
"memory_enabled": True,
+ "memory_capture_enabled": True,
+ "memory_recall_inject_enabled": True,
"extract_on_session_end": True,
"extract_trigger_mode": "idle",
"extract_idle_seconds": 300.0,
@@ -193,6 +195,12 @@ class _ExtractConfigBody(BaseModel):
"""
memory_enabled: bool | None = None
+ memory_capture_enabled: bool | None = Field(
+ default=None, description="Automatically record conversation events in memory"
+ )
+ memory_recall_inject_enabled: bool | None = Field(
+ default=None, description="Automatically inject recalled memory into the agent context"
+ )
extract_on_session_end: bool | None = None
extract_trigger_mode: str | None = Field(default=None, description="idle / interval")
extract_idle_seconds: float | None = Field(
@@ -922,8 +930,9 @@ async def put_extract_config(
merged = _read_extract_config(row)
patch = body.model_dump(exclude_none=True)
- if "memory_enabled" in patch:
- merged["memory_enabled"] = bool(patch["memory_enabled"])
+ for key in ("memory_enabled", "memory_capture_enabled", "memory_recall_inject_enabled"):
+ if key in patch:
+ merged[key] = bool(patch[key])
if "extract_on_session_end" in patch:
merged["extract_on_session_end"] = bool(patch["extract_on_session_end"])
if "extract_trigger_mode" in patch:
diff --git a/src/octop/api/routers/providers.py b/src/octop/api/routers/providers.py
index aec8d645b9..aaadde8eb3 100644
--- a/src/octop/api/routers/providers.py
+++ b/src/octop/api/routers/providers.py
@@ -38,6 +38,7 @@
from octop.infra.agents.providers.resolved import list_resolved_models as _list_resolved_models
from octop.infra.agents.providers.store import (
clear_stale_pins_for_provider,
+ merge_default_model_extra,
merge_provider_purpose_extra,
merge_stream_usage_extra,
resolve_provider_purpose,
@@ -76,6 +77,8 @@ class ProviderPatchBody(BaseModel):
models: list[dict[str, Any]] | None = None
note: str | None = None
enabled: bool | None = None
+ # Model id used by "test connection". Null clears a previously saved choice.
+ model: str | None = None
# Fields that affect harness factory / agent runtime when patched.
@@ -169,9 +172,9 @@ def _provider_patch_updates(
sends ``{"api_key": null}``; treating that the same as "field absent" left
the key in place and the provider still looked authorized.
- ``stream_usage`` / ``purpose`` are stored inside ``extra_json``. A patch
- that only sets those flags rewrites the current blob and must not clear
- the API key.
+ ``stream_usage`` / ``purpose`` / ``model`` are stored inside ``extra_json``.
+ A patch that only sets those flags rewrites the current blob and must not
+ clear the API key. ``model`` is the connection-test default; ``null`` clears it.
"""
fields = body.model_fields_set
updates: dict[str, Any] = {}
@@ -181,12 +184,19 @@ def _provider_patch_updates(
updates["base_url"] = _blank_to_none(body.base_url)
if "api_key" in fields:
updates["api_key"] = _blank_to_none(body.api_key)
- if "extra_json" in fields or "stream_usage" in fields or "purpose" in fields:
+ if (
+ "extra_json" in fields
+ or "stream_usage" in fields
+ or "purpose" in fields
+ or "model" in fields
+ ):
base = body.extra_json if "extra_json" in fields else current_extra_json
if "stream_usage" in fields:
base = merge_stream_usage_extra(base, body.stream_usage)
if "purpose" in fields:
base = merge_provider_purpose_extra(base, body.purpose)
+ if "model" in fields:
+ base = merge_default_model_extra(base, body.model)
updates["extra_json"] = base
if "models" in fields:
models = body.models
@@ -257,6 +267,14 @@ async def _maybe_refresh_codex_row(server: Any, row: Any) -> Any:
return row
+def _saved_default_model(extra: dict[str, Any]) -> str | None:
+ raw = extra.get("default_model")
+ if not isinstance(raw, str):
+ return None
+ cleaned = raw.strip()
+ return cleaned or None
+
+
def _row_to_dict(r: Any) -> dict[str, Any]:
models: list[dict[str, Any]] = []
for stored in r.get_models():
@@ -276,6 +294,7 @@ def _row_to_dict(r: Any) -> dict[str, Any]:
"models": models,
"note": r.note,
"enabled": bool(r.enabled),
+ "model": _saved_default_model(extra),
"stream_usage": resolve_provider_stream_usage(provider_name=r.name, extra=extra),
"purpose": resolve_provider_purpose(
provider_name=r.name,
@@ -380,6 +399,11 @@ async def admin_create_provider(
models_json = _json.dumps(models) if models is not None else None
extra_json = merge_stream_usage_extra(body.extra_json, body.stream_usage)
extra_json = merge_provider_purpose_extra(extra_json, body.purpose)
+ if server.services.provider_repo.get_by_name(body.name) is not None:
+ raise OctopError(
+ ErrorCode.PROVIDER_NAME_TAKEN,
+ f"provider {body.name!r} already exists",
+ )
pid = server.services.provider_repo.create(
name=body.name,
kind=body.kind,
diff --git a/src/octop/api/routers/users.py b/src/octop/api/routers/users.py
index d7ec7a6f14..5ebf5aa149 100644
--- a/src/octop/api/routers/users.py
+++ b/src/octop/api/routers/users.py
@@ -16,7 +16,6 @@
from octop.infra.users.identity import Role, User
from octop.infra.users.permissions import (
PERMISSIONS,
- effective_permissions,
expand_permission_grants,
)
from octop.infra.users.resource_policy import (
@@ -688,11 +687,10 @@ async def upload_user_avatar(
@router.get("/{user_id}/avatar")
async def get_user_avatar(
user_id: int,
- actor: Any = Depends(current_user),
+ _: Any = Depends(current_user),
server: Any = Depends(get_server),
) -> Any:
- if actor.id != user_id and "users" not in effective_permissions(actor):
- raise OctopError(ErrorCode.FORBIDDEN, "not allowed to read this avatar")
+ """Portrait for any signed-in user. Shared conversations show each sender."""
from octop.infra.users.profile_avatar import avatar_response
if server.user_manager.get_row(user_id) is None:
diff --git a/src/octop/cli/commands/backup.py b/src/octop/cli/commands/backup.py
index b90ddb4034..a0496b888d 100644
--- a/src/octop/cli/commands/backup.py
+++ b/src/octop/cli/commands/backup.py
@@ -9,7 +9,7 @@
from octop.config import load_config
from octop.infra.backup.auto import create_and_store_auto_backup
-from octop.infra.backup.store import place_backup_file
+from octop.infra.backup.store import move_file_replace, place_backup_file
from octop.infra.backup.system_archive import create_system_backup, restore_system_backup
from octop.infra.db.factory import open_database
from octop.infra.db.migrate import run_migrations
@@ -78,8 +78,7 @@ def create(
size = entry.size
else:
dest = output
- dest.parent.mkdir(parents=True, exist_ok=True)
- tmp_path.replace(dest)
+ move_file_replace(tmp_path, dest)
size = dest.stat().st_size
finally:
db.close()
diff --git a/src/octop/i18n/en.json b/src/octop/i18n/en.json
index 58a34b0ef4..7fce5ee306 100644
--- a/src/octop/i18n/en.json
+++ b/src/octop/i18n/en.json
@@ -400,6 +400,7 @@
"BACKUP_DRIVER_MISMATCH": "This backup was made with a different database engine (SQLite vs PostgreSQL). Switch the runtime to match the backup, or create a new backup on the current engine. Cross-engine restore is not supported.",
"BACKUP_SCHEMA_INCOMPATIBLE": "This backup uses database schema version {archive_schema_version}, which cannot be restored by this Octop version (maximum supported: {runtime_schema_version}).",
"BACKUP_IN_PROGRESS": "A backup or restore is already in progress. Try again shortly.",
+ "BACKUP_CLIENT_MISSING": "PostgreSQL backup needs {tool}, which is not installed. Install the PostgreSQL client tools where Octop runs, then try again.",
"FORBIDDEN": "Permission denied.",
"UPDATE_TARGET_NOT_NEWER": "Target version {target} must be newer than installed version {current}. Reinstalling or downgrading is not supported.",
"NOT_FOUND": "Not found.",
@@ -420,6 +421,7 @@
"AGENT_NOT_RUNNING": "This expert is not enabled.",
"CHECKPOINT_DELETE_FAILED": "Conversation data was not deleted. The thread is still here; try again.",
"THREAD_TURN_ACTIVE": "A reply is still in progress. Stop it, then delete this conversation.",
+ "THREAD_CONTRIBUTE_REQUIRES_SHARE": "Only a shared expert can share a conversation with other users.",
"AGENT_FAILED": "Agent failed to start.",
"AGENT_BUSY": "Agent is busy.",
"AGENT_NAME_TAKEN": "This name is already in use. Please choose another.",
@@ -459,6 +461,8 @@
"BRIDGE_CONNECTION_LIMIT": "At most {limit} cloud collab connections per user. Delete one to add another.",
"BRIDGE_SELF_CONNECT": "Cannot add this Octop instance as a peer of itself.",
"BRIDGE_INBOUND_PASSIVE": "This link was opened by the peer. This side cannot change the address or dial out. After disconnect, the peer must reopen it.",
+ "BRIDGE_PEER_FORBIDDEN": "The account you signed in with on the peer does not have Cloud collab permission. This is not limited to admins — grant that account Cloud collab on the peer, or sign in with an account that already has it.",
+ "BRIDGE_PEER_CONNECTION_OWNED": "The peer already registered this cloud collab link to another user, so this account cannot take it over. Ask that user to delete it, or sign in with the same peer account. If the address actually points at this Octop, use the peer's real address instead.",
"CRON_TRIGGER_INVALID": "Invalid cron trigger.",
"CRON_ALREADY_RUNNING": "This task is already running on another instance.",
"SLASH_UNKNOWN": "Unknown slash command.",
diff --git a/src/octop/i18n/zh.json b/src/octop/i18n/zh.json
index ccea23761f..565381bfba 100644
--- a/src/octop/i18n/zh.json
+++ b/src/octop/i18n/zh.json
@@ -400,6 +400,7 @@
"BACKUP_DRIVER_MISMATCH": "该备份与当前数据库引擎不一致(SQLite 与 PostgreSQL 不能互恢)。请将运行时切回备份所用引擎后再恢复,或在当前引擎上重新备份。暂不支持跨引擎恢复。",
"BACKUP_SCHEMA_INCOMPATIBLE": "该备份使用数据库结构版本 {archive_schema_version},当前 Octop 版本无法恢复(最高支持版本:{runtime_schema_version})。",
"BACKUP_IN_PROGRESS": "已有备份或恢复任务正在进行,请稍后再试。",
+ "BACKUP_CLIENT_MISSING": "当前环境找不到 {tool},无法备份或恢复 PostgreSQL。请在运行 Octop 的环境中安装 PostgreSQL 客户端后再试。",
"FORBIDDEN": "没有权限。",
"UPDATE_TARGET_NOT_NEWER": "目标版本 {target} 必须高于已安装版本 {current},不支持重装同版本或降级。",
"NOT_FOUND": "未找到。",
@@ -420,6 +421,7 @@
"AGENT_NOT_RUNNING": "此专家未启用。",
"CHECKPOINT_DELETE_FAILED": "对话数据没有删除,会话已保留,请重试。",
"THREAD_TURN_ACTIVE": "回复进行中,请先停止再删除。",
+ "THREAD_CONTRIBUTE_REQUIRES_SHARE": "只有共享专家上的会话可以共享给其他用户。",
"AGENT_FAILED": "Agent 启动失败。",
"AGENT_BUSY": "Agent 正忙。",
"AGENT_NAME_TAKEN": "该名称已被使用,请换一个名称。",
@@ -459,6 +461,8 @@
"BRIDGE_CONNECTION_LIMIT": "每用户最多 {limit} 条云端协同,请先删除不用的连接。",
"BRIDGE_SELF_CONNECT": "不能把本机 Octop 添加为自己的对端。",
"BRIDGE_INBOUND_PASSIVE": "这是对端主动接入的连接,本侧无法改地址或主动拨号。断开后需对端重新打开。",
+ "BRIDGE_PEER_FORBIDDEN": "对端登录账号没有「云端协同」权限。这项功能不限于管理员:请在对端为该账号打开云端协同权限,或改用已有该权限的账号。",
+ "BRIDGE_PEER_CONNECTION_OWNED": "对端已把这条云端协同登记在另一个用户名下,当前账号无法接管。请让原用户删除那条连接,或改用同一个对端账号。如果填写的地址其实指向本机,请改成对端的真实地址。",
"CRON_TRIGGER_INVALID": "无效的定时触发器。",
"CRON_ALREADY_RUNNING": "该任务已在其他实例上运行。",
"SLASH_UNKNOWN": "未知的斜杠指令。",
diff --git a/src/octop/infra/agents/experts/catalog.py b/src/octop/infra/agents/experts/catalog.py
index a760e84aae..660cc26f01 100644
--- a/src/octop/infra/agents/experts/catalog.py
+++ b/src/octop/infra/agents/experts/catalog.py
@@ -883,6 +883,42 @@ def default_library_root() -> Path:
return Path(__file__).parent / "library"
+# Templates listed in the built-in library before the expert market replaced
+# that tab (22 cards; the blank ``default`` seed was never shown). Matching is
+# by id, not by whatever still happens to live under ``library/``.
+FEATURED_EXPERT_TEMPLATE_IDS = frozenset(
+ {
+ "ai-coding-coach",
+ "ai-safety-guardian",
+ "business-operations",
+ "clinical-learning-subscription",
+ "cowork-plugin-management",
+ "cvm-ai-doctor",
+ "cvm-cluster-doctor",
+ "design",
+ "engineering",
+ "general-assistant",
+ "karpathy-knowledge-base",
+ "meituan-living-assistant",
+ "multi-agent-orchestrator",
+ "news-trend",
+ "office-automation",
+ "ops-engineer",
+ "parenting-companion",
+ "productivity",
+ "stock-assistant",
+ "superpowers-methodology",
+ "tencentcloud-api",
+ "wechat-ops",
+ }
+)
+
+
+def featured_expert_template_ids() -> frozenset[str]:
+ """Ids of the expert templates that shipped before the remote market."""
+ return FEATURED_EXPERT_TEMPLATE_IDS
+
+
def resolve_expert_agent_name(
expert: Expert,
expert_id: str,
diff --git a/src/octop/infra/agents/manager.py b/src/octop/infra/agents/manager.py
index aa4263cffa..ae944e4e39 100644
--- a/src/octop/infra/agents/manager.py
+++ b/src/octop/infra/agents/manager.py
@@ -224,6 +224,8 @@ def _memory_aux_model_settings(
def memory_extract_supported_options() -> list[str]:
"""Call options supported by the installed harness, for the settings UI."""
fields = {
+ "memory_capture_enabled": "memory_capture_enabled",
+ "memory_recall_inject_enabled": "memory_recall_inject_enabled",
"extract_max_tokens": "memory_extract_max_tokens",
"extract_light_timeout_s": "memory_aux_light_timeout_s",
"extract_heavy_timeout_s": "memory_aux_heavy_timeout_s",
@@ -252,8 +254,9 @@ def _memory_extract_settings(
if not isinstance(mem, dict):
return {}
out: dict[str, Any] = _memory_aux_model_settings(mem, supported_fields, is_ref_usable)
- if "memory_enabled" in supported_fields and isinstance(mem.get("memory_enabled"), bool):
- out["memory_enabled"] = mem["memory_enabled"]
+ for key in ("memory_enabled", "memory_capture_enabled", "memory_recall_inject_enabled"):
+ if key in supported_fields and isinstance(mem.get(key), bool):
+ out[key] = mem[key]
if "memory_extract_on_session_end" in supported_fields and isinstance(
mem.get("extract_on_session_end"), bool
):
@@ -559,6 +562,7 @@ def __init__(
self._reclaim_pending: set[str] = set()
self._reclaim_holds: dict[str, asyncio.Event] = {}
self._reclaim_task: asyncio.Task[None] | None = None
+ self._reclaim_sweep_task: asyncio.Task[None] | None = None
self._reclaim_wake: asyncio.Event | None = None
self._reload_dirty: set[str] = set()
self._reload_worker_running: dict[str, bool] = {}
@@ -718,7 +722,23 @@ async def boot(self) -> None:
)
async def shutdown(self) -> None:
+ # The idle sweep reads the control-plane DB on a worker thread. Wait for
+ # that read to finish before the caller closes the shared connection.
+ sweep = self._reclaim_sweep_task
+ self._reclaim_sweep_task = None
+ if sweep is not None and not sweep.done():
+ try:
+ await sweep
+ except Exception:
+ logger.warning("idle reclaim sweep failed during shutdown", exc_info=True)
self._reclaim_pending.clear()
+ # The idle sweep runs list_all on a worker thread. Cancelling that
+ # task does not stop the thread, so wait until the scan returns before
+ # the caller closes the control-plane connection.
+ sweep_task = self._reclaim_sweep_task
+ self._reclaim_sweep_task = None
+ if sweep_task is not None and not sweep_task.done():
+ await sweep_task
reclaim_task = self._reclaim_task
self._reclaim_task = None
if reclaim_task is not None and not reclaim_task.done():
@@ -1766,11 +1786,15 @@ def schedule_store_reclaim(self, agent_id: str) -> None:
def schedule_idle_reclaim_sweep(self) -> None:
"""Queue loaded stores whose freelist is already large enough to compact."""
try:
- asyncio.get_running_loop().create_task(
- self._sweep_bloated_stores(), name="store-reclaim-sweep"
- )
+ loop = asyncio.get_running_loop()
except RuntimeError:
return
+ current = self._reclaim_sweep_task
+ if current is not None and not current.done():
+ return
+ self._reclaim_sweep_task = loop.create_task(
+ self._sweep_bloated_stores(), name="store-reclaim-sweep"
+ )
async def compact_agent_database(self, agent_id: str, *, wait_s: float = 60) -> bool:
"""Rebuild the database now. False means it was deferred until idle."""
@@ -1824,9 +1848,14 @@ def _ensure_reclaim_task(self) -> None:
self._reclaim_task = loop.create_task(self._reclaim_pending_loop(), name="store-reclaim")
async def _sweep_bloated_stores(self) -> None:
- queued = await asyncio.to_thread(self._queue_bloated_sqlite_stores)
- if queued:
- self._ensure_reclaim_task()
+ try:
+ queued = await asyncio.to_thread(self._queue_bloated_sqlite_stores)
+ if queued:
+ self._ensure_reclaim_task()
+ finally:
+ current = asyncio.current_task()
+ if self._reclaim_sweep_task is current:
+ self._reclaim_sweep_task = None
def _queue_bloated_sqlite_stores(self) -> int:
from octop.infra.agents.memory.thread_cleanup import ( # noqa: PLC0415
@@ -2989,7 +3018,11 @@ def _backend_supports_host_skill_packages(
root_dir = str(spec.get("root_dir") or "").strip()
if not root_dir:
return False
- if root_dir == "/":
+ from octop.infra.agents.workspace.dir import is_explicit_host_root # noqa: PLC0415
+
+ # ``/`` on POSIX, or a drive root (``C:/``) on Windows. Both can see the
+ # host path of a global skill package.
+ if is_explicit_host_root(root_dir):
return True
if workspace_dir is None:
return False
diff --git a/src/octop/infra/agents/providers/store.py b/src/octop/infra/agents/providers/store.py
index 6036b73907..8ca03bb504 100644
--- a/src/octop/infra/agents/providers/store.py
+++ b/src/octop/infra/agents/providers/store.py
@@ -85,6 +85,28 @@ def merge_stream_usage_extra(
return json.dumps(extra)
+def merge_default_model_extra(extra_json: str | None, model: str | None) -> str | None:
+ """Write or clear the connection-test model inside *extra_json*.
+
+ A blank value removes ``default_model`` so the settings form can stay empty.
+ Other keys in the blob are left in place.
+ """
+ extra: dict[str, Any] = {}
+ if extra_json:
+ try:
+ parsed = json.loads(extra_json)
+ if isinstance(parsed, dict):
+ extra = dict(parsed)
+ except json.JSONDecodeError:
+ extra = {}
+ cleaned = (model or "").strip()
+ if cleaned:
+ extra["default_model"] = cleaned
+ else:
+ extra.pop("default_model", None)
+ return json.dumps(extra) if extra else None
+
+
def merge_provider_purpose_extra(
extra_json: str | None,
purpose: str | None,
diff --git a/src/octop/infra/agents/workspace/dir.py b/src/octop/infra/agents/workspace/dir.py
index c80448fa13..b1600b1b17 100644
--- a/src/octop/infra/agents/workspace/dir.py
+++ b/src/octop/infra/agents/workspace/dir.py
@@ -45,6 +45,18 @@ def _running_on_windows() -> bool:
return os.name == "nt"
+def is_explicit_host_root(root: str) -> bool:
+ """True for POSIX ``/`` and a Windows drive root such as ``C:/``.
+
+ Empty strings are not a host root. A path below the drive (``C:/data``)
+ is a scoped jail.
+ """
+ text = root.strip()
+ if text in {"/", "\\"}:
+ return True
+ return bool(_WINDOWS_DRIVE_ROOT_RE.match(text))
+
+
def _is_host_root_sentinel(root: str | Path | None) -> bool:
"""True when *root* means the whole host filesystem (not a jail).
diff --git a/src/octop/infra/backup/pg_dump.py b/src/octop/infra/backup/pg_dump.py
index 6eae78958f..f6ace83ce9 100644
--- a/src/octop/infra/backup/pg_dump.py
+++ b/src/octop/infra/backup/pg_dump.py
@@ -14,8 +14,9 @@ def _require_tool(name: str) -> str:
path = shutil.which(name)
if not path:
raise OctopError(
- ErrorCode.INTERNAL_ERROR,
+ ErrorCode.BACKUP_CLIENT_MISSING,
f"{name} not found on PATH; required for PostgreSQL backup/restore",
+ details={"tool": name},
)
return path
diff --git a/src/octop/infra/backup/store.py b/src/octop/infra/backup/store.py
index 556251816c..9deff127c4 100644
--- a/src/octop/infra/backup/store.py
+++ b/src/octop/infra/backup/store.py
@@ -184,6 +184,21 @@ def write_backup_file(paths: PathLayout, filename: str, data: bytes) -> BackupFi
return backup_file_info(dest)
+def move_file_replace(src: Path, dest: Path) -> None:
+ """Move *src* onto *dest*.
+
+ ``Path.replace`` raises ``EXDEV`` when the paths are on different filesystems.
+ Copy and then delete so a backup written under the system temp dir can land
+ on another disk.
+ """
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ src.replace(dest)
+ except OSError:
+ shutil.copy2(src, dest)
+ src.unlink(missing_ok=True)
+
+
def place_backup_file(paths: PathLayout, filename: str, src: Path) -> BackupFileInfo:
"""Move *src* into ``backups_dir`` under *filename* (atomic replace when possible)."""
paths.ensure_backups_dir()
@@ -192,12 +207,7 @@ def place_backup_file(paths: PathLayout, filename: str, src: Path) -> BackupFile
src = Path(src)
if src.resolve() == dest.resolve():
return backup_file_info(dest)
- dest.parent.mkdir(parents=True, exist_ok=True)
- try:
- src.replace(dest)
- except OSError:
- shutil.copy2(src, dest)
- src.unlink(missing_ok=True)
+ move_file_replace(src, dest)
return backup_file_info(dest)
diff --git a/src/octop/infra/bridge/manager.py b/src/octop/infra/bridge/manager.py
index 474d0d1ef4..d23d64a35d 100644
--- a/src/octop/infra/bridge/manager.py
+++ b/src/octop/infra/bridge/manager.py
@@ -7,8 +7,8 @@
import json
import logging
from contextlib import suppress
-from typing import Any
-from urllib.parse import urljoin, urlparse, urlsplit
+from typing import Any, NoReturn
+from urllib.parse import parse_qsl, urlencode, urljoin, urlparse, urlsplit
import httpx
import websockets
@@ -62,12 +62,106 @@ def _handshake_http_status(exc: BaseException) -> int | None:
return status if isinstance(status, int) else None
+def _close_frame(exc: BaseException) -> Any:
+ return getattr(exc, "rcvd", None) or getattr(exc, "sent", None)
+
+
def _close_code(exc: BaseException) -> int | None:
- rcvd = getattr(exc, "rcvd", None)
- code = getattr(rcvd, "code", None)
+ frame = _close_frame(exc)
+ code = getattr(frame, "code", None)
return code if isinstance(code, int) else None
+def _close_reason(exc: BaseException) -> str:
+ frame = _close_frame(exc)
+ reason = getattr(frame, "reason", None)
+ if isinstance(reason, bytes):
+ reason = reason.decode("utf-8", errors="replace")
+ return str(reason or "").strip()
+
+
+_DIAL_ERROR_PREFIX = "octop:apiErrors."
+# The peer will reject these the same way on every retry. Fail the dial at once
+# and keep the readable error; do not spend the auto-reconnect budget on them.
+_PERMANENT_DIAL_CODES = frozenset(
+ {
+ ErrorCode.BRIDGE_SELF_CONNECT,
+ ErrorCode.BRIDGE_PEER_FORBIDDEN,
+ ErrorCode.BRIDGE_PEER_CONNECTION_OWNED,
+ ErrorCode.BRIDGE_CONNECTION_LIMIT,
+ ErrorCode.BRIDGE_AUTH_FAILED,
+ }
+)
+
+
+def bridge_failure_from_dial(exc: BaseException) -> OctopError:
+ """Map a peer WebSocket close into a user-facing bridge error.
+
+ The raw ``websockets`` text (``received 4003 (private use) ...``) is not
+ something to show in the dashboard.
+ """
+ reason = _close_reason(exc).lower()
+ code = _close_code(exc)
+ if code == 4004 or "self connect" in reason:
+ return OctopError(
+ ErrorCode.BRIDGE_SELF_CONNECT,
+ "cannot link this Octop instance to itself",
+ )
+ if code == 4003 and "permission" in reason:
+ return OctopError(
+ ErrorCode.BRIDGE_PEER_FORBIDDEN,
+ "peer account lacks cloud collab permission",
+ )
+ if code == 4003 and "owned by another" in reason:
+ return OctopError(
+ ErrorCode.BRIDGE_PEER_CONNECTION_OWNED,
+ "connection owned by another user on the peer",
+ )
+ if code == 4008 or "connection limit" in reason:
+ return OctopError(
+ ErrorCode.BRIDGE_CONNECTION_LIMIT,
+ f"at most {MAX_CONNECTIONS_PER_USER} cloud collab connections",
+ details={"limit": MAX_CONNECTIONS_PER_USER},
+ )
+ if code == 4001:
+ return OctopError(ErrorCode.BRIDGE_AUTH_FAILED, "peer rejected credentials")
+ return OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, _annotate_bridge_dial_error(exc))
+
+
+def dial_error_note(exc: BaseException) -> str:
+ """Persist a bridge dial failure. Known cases use an ``octop:`` i18n key.
+
+ Interpolation values (for example the connection ``limit``) ride in the
+ query so the dashboard and the API toast can format the same sentence.
+ """
+ failure = bridge_failure_from_dial(exc)
+ if failure.code is not ErrorCode.BRIDGE_PEER_UNREACHABLE:
+ note = f"{_DIAL_ERROR_PREFIX}{failure.code.value}"
+ if failure.details:
+ note = f"{note}?{urlencode(failure.details)}"
+ return note
+ reason = _close_reason(exc)
+ if reason:
+ return reason
+ return _annotate_bridge_dial_error(exc)
+
+
+def error_from_dial_note(note: str | None) -> OctopError | None:
+ text = (note or "").strip()
+ if not text.startswith(_DIAL_ERROR_PREFIX):
+ return None
+ body = text[len(_DIAL_ERROR_PREFIX) :]
+ name, _, query = body.partition("?")
+ try:
+ code = ErrorCode(name)
+ except ValueError:
+ return None
+ details: dict[str, Any] = {}
+ for key, value in parse_qsl(query, keep_blank_values=False):
+ details[key] = int(value) if key == "limit" and value.isdigit() else value
+ return OctopError(code, name, details=details)
+
+
def _should_refresh_peer_token(exc: BaseException) -> bool:
"""True when the peer refused the socket before hello — usually a bad token.
@@ -661,15 +755,26 @@ async def connect(self, connection_id: str, *, owner_user_id: int) -> BridgeConn
self._reconnect_failures[connection_id] = 0
return self._repo.get(connection_id) or row
if task.done():
- exc = task.exception() if not task.cancelled() else None
- msg = str(exc) if exc else "bridge connect failed"
- latest = self._repo.get(connection_id)
- if latest is not None and latest.status != "error":
- self._repo.update_status(connection_id, status="error", last_error=msg[:500])
- raise OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, msg)
+ self._raise_dial_failure(connection_id)
await asyncio.sleep(0.1)
- self._repo.update_status(connection_id, status="error", last_error="bridge connect timeout")
- raise OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, "bridge connect timeout")
+ self._raise_dial_failure(connection_id, fallback="bridge connect timeout")
+
+ def _raise_dial_failure(
+ self, connection_id: str, *, fallback: str = "bridge connect failed"
+ ) -> NoReturn:
+ latest = self._repo.get(connection_id)
+ note = latest.last_error if latest is not None else None
+ known = error_from_dial_note(note)
+ if known is not None:
+ if latest is not None and latest.status != "error":
+ self._repo.update_status(
+ connection_id, status="error", last_error=(note or "")[:500]
+ )
+ raise known
+ detail = (note or fallback)[:500]
+ if latest is not None and latest.status != "error":
+ self._repo.update_status(connection_id, status="error", last_error=detail)
+ raise OctopError(ErrorCode.BRIDGE_PEER_UNREACHABLE, detail)
async def disconnect(self, connection_id: str) -> None:
self._user_stopped.add(connection_id)
@@ -888,7 +993,17 @@ async def _outbound_supervisor(self, connection_id: str) -> None:
)
continue
retried_auth = False
- detail = _annotate_bridge_dial_error(exc)
+ detail = dial_error_note(exc)
+ if bridge_failure_from_dial(exc).code in _PERMANENT_DIAL_CODES:
+ if self._repo.get(connection_id) is not None:
+ self._repo.update_status(
+ connection_id, status="error", last_error=detail[:500]
+ )
+ # Leave auto-reconnect enabled, but stop this supervisor so a
+ # rejected login does not wait out the backoff or overwrite
+ # the readable error with the English disable line.
+ self._user_stopped.add(connection_id)
+ return
failures = self._reconnect_failures.get(connection_id, 0) + 1
self._reconnect_failures[connection_id] = failures
if self._repo.get(connection_id) is not None:
@@ -1128,6 +1243,13 @@ async def close_transport() -> None:
return
existing = self._repo.get(connection_id)
+ # An outbound row (we stored the peer password) only exists on the
+ # instance that allocated this connection id. A hello for that id means
+ # the dial reached this same Octop — often because the typed URL does
+ # not match the advertised address, so the earlier self-check missed it.
+ if existing is not None and bool(existing.credential_blob):
+ await websocket.close(code=4004, reason="self connect")
+ return
if existing is not None and int(existing.owner_user_id) != int(user.id):
await websocket.close(code=4003, reason="connection owned by another user")
return
diff --git a/src/octop/infra/db/migrate.py b/src/octop/infra/db/migrate.py
index 8a7e1087c4..f5b815bc0d 100644
--- a/src/octop/infra/db/migrate.py
+++ b/src/octop/infra/db/migrate.py
@@ -1676,6 +1676,13 @@ def _ensure_control_blobs_schema(db: DatabasePool) -> None:
)
+def _ensure_thread_contributed_schema(db: DatabasePool) -> None:
+ """``threads.contributed`` (v25). Idempotent for SQLite, which skips the SQL file."""
+ if not _table_exists(db, "threads"):
+ return
+ _ensure_column(db, "threads", "contributed", "INTEGER NOT NULL DEFAULT 0")
+
+
def _ensure_user_mfa_schema(db: DatabasePool) -> None:
"""MFA tables + users.mfa_* / password_version columns (v25). Idempotent."""
if not _table_exists(db, "users"):
@@ -1922,6 +1929,7 @@ def _repair_legacy_schema(db: DatabasePool) -> None:
_ensure_column(db, "threads", "reasoning_mode", "TEXT")
_ensure_column(db, "threads", "reasoning_effort", "TEXT")
_ensure_column(db, "threads", "artifacts", "TEXT NOT NULL DEFAULT '[]'")
+ _ensure_column(db, "threads", "contributed", "INTEGER NOT NULL DEFAULT 0")
_ensure_thread_conversation_mode_schema(db)
if _table_exists(db, "agents"):
_ensure_column(db, "agents", "is_shared", "INTEGER NOT NULL DEFAULT 0")
@@ -2225,6 +2233,7 @@ def _apply_sqlite_migration(db: DatabasePool, version: int, path: Path) -> None:
if version == 25:
_ensure_user_mfa_schema(db)
_ensure_instance_lease_schema(db)
+ _ensure_thread_contributed_schema(db)
with db.connect() as conn:
conn.execute("UPDATE _schema_version SET version = ?", (version,))
return
@@ -2483,6 +2492,7 @@ def run_migrations(db: DatabasePool) -> None:
_ensure_user_mfa_schema(db)
_ensure_instance_lease_schema(db)
_ensure_control_blobs_schema(db)
+ _ensure_thread_contributed_schema(db)
_grant_default_nav_permissions(db)
_grant_personalization_tab_permissions(db)
_grant_bridge_permission(db)
diff --git a/src/octop/infra/db/migrations/025_user_mfa.pg.sql b/src/octop/infra/db/migrations/025_user_mfa.pg.sql
index afd670e42f..23cea7d46e 100644
--- a/src/octop/infra/db/migrations/025_user_mfa.pg.sql
+++ b/src/octop/infra/db/migrations/025_user_mfa.pg.sql
@@ -72,6 +72,8 @@ ALTER TABLE channels ADD COLUMN IF NOT EXISTS runtime_lease_token TEXT;
ALTER TABLE channels ADD COLUMN IF NOT EXISTS runtime_lease_until BIGINT;
ALTER TABLE channels ADD COLUMN IF NOT EXISTS runtime_generation INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE threads ADD COLUMN IF NOT EXISTS contributed INTEGER NOT NULL DEFAULT 0;
+
CREATE TABLE IF NOT EXISTS profile_avatars (
owner_kind TEXT NOT NULL,
owner_id TEXT NOT NULL,
diff --git a/src/octop/infra/db/migrations/025_user_mfa.sql b/src/octop/infra/db/migrations/025_user_mfa.sql
index 42647bc7fb..5707b10425 100644
--- a/src/octop/infra/db/migrations/025_user_mfa.sql
+++ b/src/octop/infra/db/migrations/025_user_mfa.sql
@@ -73,6 +73,8 @@ ALTER TABLE channels ADD COLUMN runtime_lease_token TEXT;
ALTER TABLE channels ADD COLUMN runtime_lease_until INTEGER;
ALTER TABLE channels ADD COLUMN runtime_generation INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE threads ADD COLUMN contributed INTEGER NOT NULL DEFAULT 0;
+
CREATE TABLE IF NOT EXISTS profile_avatars (
owner_kind TEXT NOT NULL,
owner_id TEXT NOT NULL,
diff --git a/src/octop/infra/db/pool.py b/src/octop/infra/db/pool.py
index 84f44cded9..aefb1c5cab 100644
--- a/src/octop/infra/db/pool.py
+++ b/src/octop/infra/db/pool.py
@@ -39,29 +39,36 @@ def __init__(self, path: Path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
first_create = not self.path.exists()
- self._conn = sqlite3.connect(
+ conn = sqlite3.connect(
str(self.path),
check_same_thread=False,
isolation_level=None,
)
- self._conn.row_factory = sqlite3.Row
- self._conn.execute("PRAGMA foreign_keys = ON")
- self._conn.execute("PRAGMA journal_mode = WAL")
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA foreign_keys = ON")
+ conn.execute("PRAGMA journal_mode = WAL")
# WAL + FULL fsyncs every autocommit statement. On Windows that is
# FlushFileBuffers and dominates pytest (and the app), so only Windows
# drops to NORMAL (SQLite's recommended WAL setting): an OS crash can
# drop the last transaction, an application crash cannot corrupt the
# file. Other platforms keep the default FULL.
if os.name == "nt":
- self._conn.execute("PRAGMA synchronous = NORMAL")
+ conn.execute("PRAGMA synchronous = NORMAL")
+ self._conn: sqlite3.Connection | None = conn
self._lock = threading.RLock()
if first_create and os.name == "posix":
os.chmod(self.path, 0o600)
+ def _live_connection(self) -> sqlite3.Connection:
+ conn = self._conn
+ if conn is None:
+ raise sqlite3.ProgrammingError("sqlite pool is closed")
+ return conn
+
@contextmanager
def connect(self) -> Iterator[sqlite3.Connection]:
with self._lock:
- yield self._conn
+ yield self._live_connection()
@contextmanager
def transaction(self) -> Iterator[sqlite3.Connection]:
@@ -73,16 +80,23 @@ def transaction(self) -> Iterator[sqlite3.Connection]:
# SQLITE_BUSY_SNAPSHOT ("database is locked") *immediately*; the 5s busy timeout
# cannot wait that out. Taking the write lock up front makes the competing writer
# wait instead of aborting us.
- self._conn.execute("BEGIN IMMEDIATE")
+ conn = self._live_connection()
+ conn.execute("BEGIN IMMEDIATE")
try:
- yield self._conn
- self._conn.execute("COMMIT")
+ yield conn
+ conn.execute("COMMIT")
except Exception:
- self._conn.execute("ROLLBACK")
+ conn.execute("ROLLBACK")
raise
def close(self) -> None:
- self._conn.close()
+ # Wait for an in-flight query. Closing the shared connection underneath
+ # another thread is an access violation on Windows.
+ with self._lock:
+ conn = self._conn
+ self._conn = None
+ if conn is not None:
+ conn.close()
class _CompatRow(Mapping[str, Any]):
diff --git a/src/octop/infra/db/repos/sessions.py b/src/octop/infra/db/repos/sessions.py
index f2c28e46f1..0341d227e1 100644
--- a/src/octop/infra/db/repos/sessions.py
+++ b/src/octop/infra/db/repos/sessions.py
@@ -251,6 +251,13 @@ def clear_unread_for_thread(self, thread_id: str) -> None:
(thread_id,),
)
+ def clear_unread_for_user_thread(self, thread_id: str, user_id: int) -> None:
+ with self._db.transaction() as conn:
+ conn.execute(
+ "UPDATE sessions SET unread_count = 0 WHERE thread_id = ? AND user_id = ?",
+ (thread_id, user_id),
+ )
+
def clear_unread_for_agent(self, agent_id: str, user_id: int) -> None:
with self._db.transaction() as conn:
conn.execute(
diff --git a/src/octop/infra/db/repos/threads.py b/src/octop/infra/db/repos/threads.py
index 0f6649cf9b..d76aa31479 100644
--- a/src/octop/infra/db/repos/threads.py
+++ b/src/octop/infra/db/repos/threads.py
@@ -47,6 +47,7 @@ class ThreadRow:
conversation_mode: str | None = None
pending_plan_path: str | None = None
hitl_policy: str | None = None
+ contributed: bool = False
@classmethod
def from_row(cls, r: DbRow) -> ThreadRow:
@@ -66,6 +67,10 @@ def from_row(cls, r: DbRow) -> ThreadRow:
hitl_policy = r["hitl_policy"]
except (KeyError, IndexError):
hitl_policy = None
+ try:
+ contributed = bool(r["contributed"])
+ except (KeyError, IndexError):
+ contributed = False
return cls(
id=r["id"],
thread_id=r["thread_id"],
@@ -84,6 +89,7 @@ def from_row(cls, r: DbRow) -> ThreadRow:
conversation_mode=str(conversation_mode) if conversation_mode else None,
pending_plan_path=str(pending_plan_path) if pending_plan_path else None,
hitl_policy=str(hitl_policy) if hitl_policy else None,
+ contributed=contributed,
)
@@ -251,6 +257,26 @@ def list_by_agent_user(
).fetchall()
return map_rows(rows, ThreadRow)
+ def list_visible(self, *, agent_id: str, user_id: int, limit: int = 50) -> list[ThreadRow]:
+ """Own threads plus conversations contributed to this shared expert."""
+ with self._db.connect() as conn:
+ rows = conn.execute(
+ "SELECT * FROM threads WHERE agent_id = ? "
+ "AND (user_id = ? OR contributed = 1) "
+ "ORDER BY pinned DESC, "
+ "CASE WHEN last_active > 0 THEN last_active ELSE created_at END DESC, "
+ "thread_id DESC LIMIT ?",
+ (agent_id, user_id, limit),
+ ).fetchall()
+ return map_rows(rows, ThreadRow)
+
+ def set_contributed(self, thread_id: str, contributed: bool) -> None:
+ with self._db.transaction() as conn:
+ conn.execute(
+ "UPDATE threads SET contributed = ? WHERE thread_id = ?",
+ (bool_int(contributed), thread_id),
+ )
+
def list_by_session(self, *, session_key: str, limit: int = 50) -> list[ThreadRow]:
with self._db.connect() as conn:
rows = conn.execute(
diff --git a/src/octop/infra/errors.py b/src/octop/infra/errors.py
index b8c74ce52a..cc88cf8d7d 100644
--- a/src/octop/infra/errors.py
+++ b/src/octop/infra/errors.py
@@ -7,6 +7,7 @@
from typing import Any
from octop.i18n import error_message as i18n_error_message
+from octop.i18n.domains.stream import format_stream_error
from octop.infra.utils.locale import Locale, normalize_locale
@@ -18,6 +19,7 @@ class ErrorCode(StrEnum):
BACKUP_DRIVER_MISMATCH = "BACKUP_DRIVER_MISMATCH"
BACKUP_SCHEMA_INCOMPATIBLE = "BACKUP_SCHEMA_INCOMPATIBLE"
BACKUP_IN_PROGRESS = "BACKUP_IN_PROGRESS"
+ BACKUP_CLIENT_MISSING = "BACKUP_CLIENT_MISSING"
FORBIDDEN = "FORBIDDEN"
UPDATE_TARGET_NOT_NEWER = "UPDATE_TARGET_NOT_NEWER"
NOT_FOUND = "NOT_FOUND"
@@ -38,6 +40,7 @@ class ErrorCode(StrEnum):
AGENT_NOT_RUNNING = "AGENT_NOT_RUNNING"
CHECKPOINT_DELETE_FAILED = "CHECKPOINT_DELETE_FAILED"
THREAD_TURN_ACTIVE = "THREAD_TURN_ACTIVE"
+ THREAD_CONTRIBUTE_REQUIRES_SHARE = "THREAD_CONTRIBUTE_REQUIRES_SHARE"
AGENT_FAILED = "AGENT_FAILED"
AGENT_BUSY = "AGENT_BUSY"
AGENT_NAME_TAKEN = "AGENT_NAME_TAKEN"
@@ -77,6 +80,8 @@ class ErrorCode(StrEnum):
BRIDGE_CONNECTION_LIMIT = "BRIDGE_CONNECTION_LIMIT"
BRIDGE_SELF_CONNECT = "BRIDGE_SELF_CONNECT"
BRIDGE_INBOUND_PASSIVE = "BRIDGE_INBOUND_PASSIVE"
+ BRIDGE_PEER_FORBIDDEN = "BRIDGE_PEER_FORBIDDEN"
+ BRIDGE_PEER_CONNECTION_OWNED = "BRIDGE_PEER_CONNECTION_OWNED"
CRON_TRIGGER_INVALID = "CRON_TRIGGER_INVALID"
CRON_ALREADY_RUNNING = "CRON_ALREADY_RUNNING"
SLASH_UNKNOWN = "SLASH_UNKNOWN"
@@ -177,6 +182,7 @@ class ErrorCode(StrEnum):
ErrorCode.BACKUP_DRIVER_MISMATCH: 400,
ErrorCode.BACKUP_SCHEMA_INCOMPATIBLE: 400,
ErrorCode.BACKUP_IN_PROGRESS: 409,
+ ErrorCode.BACKUP_CLIENT_MISSING: 503,
ErrorCode.FORBIDDEN: 403,
ErrorCode.UPDATE_TARGET_NOT_NEWER: 400,
ErrorCode.NOT_FOUND: 404,
@@ -197,6 +203,7 @@ class ErrorCode(StrEnum):
ErrorCode.AGENT_NOT_RUNNING: 409,
ErrorCode.CHECKPOINT_DELETE_FAILED: 409,
ErrorCode.THREAD_TURN_ACTIVE: 409,
+ ErrorCode.THREAD_CONTRIBUTE_REQUIRES_SHARE: 400,
ErrorCode.AGENT_FAILED: 500,
ErrorCode.AGENT_BUSY: 409,
ErrorCode.AGENT_NAME_TAKEN: 409,
@@ -238,6 +245,8 @@ class ErrorCode(StrEnum):
ErrorCode.BRIDGE_CONNECTION_LIMIT: 400,
ErrorCode.BRIDGE_SELF_CONNECT: 400,
ErrorCode.BRIDGE_INBOUND_PASSIVE: 400,
+ ErrorCode.BRIDGE_PEER_FORBIDDEN: 403,
+ ErrorCode.BRIDGE_PEER_CONNECTION_OWNED: 409,
ErrorCode.CRON_TRIGGER_INVALID: 400,
ErrorCode.CRON_ALREADY_RUNNING: 409,
ErrorCode.SLASH_UNKNOWN: 400,
@@ -379,6 +388,18 @@ def to_envelope(self, *, locale: str | Locale | None = None) -> dict[str, Any]:
}
+def stream_error(exc: Exception, locale: str) -> tuple[str, str | None]:
+ """Message and error code for a failed stream/turn.
+
+ ``OctopError`` keeps its localized ``errors.`` text and code so
+ channels can surface machine-readable failures; everything else falls back
+ to the generic stream-error formatting without a code.
+ """
+ if isinstance(exc, OctopError):
+ return exc.localized_message(locale), exc.code.value
+ return format_stream_error(exc, locale), None
+
+
def corrupt_config_error(path: object, detail: str) -> OctopError:
"""``OctopError`` for a config file that exists but cannot be parsed.
diff --git a/src/octop/infra/gateway/cli/cli_channel.py b/src/octop/infra/gateway/cli/cli_channel.py
index b13eced510..aa907002b8 100644
--- a/src/octop/infra/gateway/cli/cli_channel.py
+++ b/src/octop/infra/gateway/cli/cli_channel.py
@@ -19,7 +19,7 @@
VideoContent,
)
-from octop.i18n.domains.stream import format_stream_error
+from octop.infra.errors import stream_error
from octop.infra.gateway.threads import ThreadRegistry
from octop.infra.gateway.ws.ws_hub import WebSocketHub
from octop.infra.utils.locale import resolve_locale
@@ -119,10 +119,11 @@ async def handle_inbound(self, raw_payload: Any) -> None:
channel_type=str(getattr(message, "channel_type", "") or ""),
metadata=meta,
)
- await self._hub.push(
- conn_id,
- {"type": "error", "message": format_stream_error(exc, locale)},
- )
+ error_message, error_code = stream_error(exc, locale)
+ frame: dict[str, object] = {"type": "error", "message": error_message}
+ if error_code:
+ frame["error_code"] = error_code
+ await self._hub.push(conn_id, frame)
await self._hub.push(conn_id, {"type": "done"})
async def _send_text(self, subject: ChannelSubject, text: str) -> None:
diff --git a/src/octop/infra/gateway/hitl/coordinator.py b/src/octop/infra/gateway/hitl/coordinator.py
index 1337709389..9f0d76c5b8 100644
--- a/src/octop/infra/gateway/hitl/coordinator.py
+++ b/src/octop/infra/gateway/hitl/coordinator.py
@@ -203,7 +203,7 @@ def pending_hitl_payload(
*,
thread_id: str,
agent_id: str,
- user_id: int,
+ user_id: int | None,
) -> dict[str, Any] | None:
record = store.resolve_pending_for_thread(
thread_id,
diff --git a/src/octop/infra/gateway/hitl/store.py b/src/octop/infra/gateway/hitl/store.py
index 5102070230..671dfa3eeb 100644
--- a/src/octop/infra/gateway/hitl/store.py
+++ b/src/octop/infra/gateway/hitl/store.py
@@ -17,10 +17,19 @@ def _same_pause_slot(
existing: HitlPendingRecord,
*,
session_key: str,
+ thread_id: str,
resume_agent_id: str | None,
) -> bool:
+ """True when *existing* occupies the slot a new pause would replace.
+
+ Dashboard chats for one user and agent share a ``session_key``. The slot
+ is that key plus the thread, so a pause in chat B does not expire chat A.
+ Team members that share a room thread stay distinct via ``resume_agent_id``.
+ """
if existing.session_key != session_key or existing.status != "pending":
return False
+ if (existing.thread_id or "") != (thread_id or ""):
+ return False
if resume_agent_id:
return existing.resume_agent_id == resume_agent_id
return not existing.resume_agent_id
@@ -77,12 +86,14 @@ def register(
self._gc()
# A new pause replaces only the same slot. Two team members share the
# room session, so one member's card must not expire the other's.
+ # Dashboard threads also share a session key; thread_id keeps them apart.
# The same interrupt is often projected twice; reuse that pending id
# so an automatic resume of the first frame is not already expired.
for existing in list(self._records.values()):
if not _same_pause_slot(
existing,
session_key=session_key,
+ thread_id=thread_id,
resume_agent_id=resume_agent_id,
):
continue
@@ -92,6 +103,7 @@ def register(
if not _same_pause_slot(
existing,
session_key=session_key,
+ thread_id=thread_id,
resume_agent_id=resume_agent_id,
):
continue
@@ -251,15 +263,25 @@ def list_pending_for_session(
rows.sort(key=lambda r: r.created_at, reverse=True)
return rows
- def pending_thread_ids(self, *, agent_id: str, user_id: int) -> frozenset[str]:
- """Thread ids with a still-pending HITL pause for this agent/user."""
+ def pending_thread_ids(
+ self,
+ *,
+ agent_id: str,
+ user_id: int,
+ any_user: bool = False,
+ ) -> frozenset[str]:
+ """Thread ids with a still-pending HITL pause for this agent.
+
+ ``any_user`` includes pauses opened by someone else. Callers use that
+ only for conversations that were shared with the current user.
+ """
self._gc()
now = time.time()
out: set[str] = set()
for record in self._records.values():
if record.status != "pending":
continue
- if record.user_id != user_id:
+ if not any_user and record.user_id != user_id:
continue
if now - record.created_at > self.ttl_seconds:
continue
diff --git a/src/octop/infra/gateway/process/harness_request.py b/src/octop/infra/gateway/process/harness_request.py
index abcbc512b0..6dcaec811f 100644
--- a/src/octop/infra/gateway/process/harness_request.py
+++ b/src/octop/infra/gateway/process/harness_request.py
@@ -331,7 +331,11 @@ def build_harness_request(
payload = content if content is not None else build_content(text=text, images=images)
stored_id = (message_id or "").strip() or None
+ from octop.infra.gateway.process.message_keys import AUTHOR_USER_ID_KEY # noqa: PLC0415
+
kwargs = dict(message_kwargs or {})
+ if user_id > 0:
+ kwargs[AUTHOR_USER_ID_KEY] = user_id
if isinstance(payload, list) or kwargs or stored_id:
from langchain_core.messages import HumanMessage # noqa: PLC0415
diff --git a/src/octop/infra/gateway/process/message_keys.py b/src/octop/infra/gateway/process/message_keys.py
index e039e42cf4..6a3bc5e68f 100644
--- a/src/octop/infra/gateway/process/message_keys.py
+++ b/src/octop/infra/gateway/process/message_keys.py
@@ -13,6 +13,8 @@
# Persisted on HumanMessage.additional_kwargs for dashboard history UI.
COMPOSER_CTX_KEY = "octop_composer_context"
INBOUND_ATTACHMENTS_KEY = "octop_inbound_attachments"
+# Who sent this user turn. Shared conversations render a different portrait per person.
+AUTHOR_USER_ID_KEY = "octop_author_user_id"
# Must match octop_harness.messages.CHECKPOINT_TS_KEY (epoch-ms).
CHECKPOINT_TS_KEY = "checkpoint_ts"
# Persisted on AIMessage.additional_kwargs when a stream fails mid-turn.
diff --git a/src/octop/infra/gateway/process/processor.py b/src/octop/infra/gateway/process/processor.py
index 1676b8678e..9c426873ca 100644
--- a/src/octop/infra/gateway/process/processor.py
+++ b/src/octop/infra/gateway/process/processor.py
@@ -22,7 +22,6 @@
from octop_harness.teams.processor import ReplyEvent
from octop_harness.teams.util import PeerCall, PeerSession
-from octop.i18n.domains.stream import format_stream_error
from octop.infra.agents.providers.reasoning import reasoning_request_parameters
from octop.infra.agents.settings.profile import parse_config_json
from octop.infra.agents.teams import is_team_agent
@@ -32,7 +31,7 @@
from octop.infra.agents.teams.team_manager import (
stamp_team_host_chunk as _maybe_stamp_team_host,
)
-from octop.infra.errors import OctopError
+from octop.infra.errors import OctopError, stream_error
from octop.infra.gateway.cli.events import message_event_to_cli_chunks
from octop.infra.gateway.hitl.coordinator import (
HitlAnswerOutcome,
@@ -117,12 +116,6 @@ def _inbound_thread_id(msg: InboundMessage) -> str | None:
return None
-def _stream_error(exc: Exception, locale: str) -> tuple[str, str | None]:
- if isinstance(exc, OctopError):
- return exc.localized_message(locale), exc.code.value
- return format_stream_error(exc, locale), None
-
-
def _overwrite_last_user_text(request: dict[str, Any], text: str) -> None:
"""Replace the latest user-turn body without rebuilding the harness request."""
messages = request.get("messages")
@@ -1165,7 +1158,7 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]:
await self._record_stream_error(
user_id=user_id, agent_id=agent_id, thread_id=thread_id, exc=exc
)
- message, error_code = _stream_error(exc, locale)
+ message, error_code = stream_error(exc, locale)
if error_code:
message = f"[{error_code}] {message}"
history_tracker.observe(
@@ -1410,6 +1403,7 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
thread_id=thread_id,
command=msg.text,
response_lines=slash_lines,
+ user_id=user_id,
)
self._hitl.expire_pending_for_thread(thread_id, agent_id=agent_id, user_id=user_id)
self.teams.cancel_member_hitl(thread_id)
@@ -1566,7 +1560,7 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
await self._record_stream_error(
user_id=user_id, agent_id=agent_id, thread_id=thread_id, exc=exc
)
- message, error_code = _stream_error(exc, locale)
+ message, error_code = stream_error(exc, locale)
payload: dict[str, Any] = {"type": "error", "message": message}
if error_code:
payload["error_code"] = error_code
@@ -1665,7 +1659,7 @@ async def iter_hitl_resume_chunks(
user_id=user_id,
channel_type="dashboard",
)
- message, error_code = _stream_error(exc, locale)
+ message, error_code = stream_error(exc, locale)
payload: dict[str, Any] = {"type": "error", "message": message}
if error_code:
payload["error_code"] = error_code
@@ -1970,7 +1964,7 @@ async def _resolve_turn_mcp_servers(
flaky connector does not abort the whole message turn.
"""
from octop.infra.agents.teams import is_team_agent # noqa: PLC0415
- from octop.infra.errors import ErrorCode, OctopError # noqa: PLC0415
+ from octop.infra.errors import ErrorCode # noqa: PLC0415
# Team hosts only dispatch — never attach MCP tools.
row = self._agent_manager.get_row(agent_id)
@@ -2227,12 +2221,20 @@ async def _append_slash_checkpoint(
thread_id: str,
command: str,
response_lines: list[str],
+ user_id: int = 0,
) -> None:
"""Save slash history, honoring the command's checkpoint persistence policy."""
+ from octop.infra.gateway.process.message_keys import AUTHOR_USER_ID_KEY # noqa: PLC0415
+
turn_id = new_ulid()
response = "\n".join(response_lines).strip()
+ kwargs = {AUTHOR_USER_ID_KEY: user_id} if user_id > 0 else {}
canonical: list[HumanMessage | AIMessage] = [
- HumanMessage(content=command, id=f"slash:{turn_id}:human"),
+ HumanMessage(
+ content=command,
+ id=f"slash:{turn_id}:human",
+ additional_kwargs=kwargs,
+ ),
]
if response:
canonical.append(AIMessage(content=response, id=f"slash:{turn_id}:assistant"))
diff --git a/src/octop/infra/gateway/threads.py b/src/octop/infra/gateway/threads.py
index c2991a4e60..cc70d46e35 100644
--- a/src/octop/infra/gateway/threads.py
+++ b/src/octop/infra/gateway/threads.py
@@ -270,7 +270,14 @@ def im_sessions_for_thread(self, thread_id: str) -> list[SessionRow]:
"""IM sessions bound to *thread_id* (excludes dashboard / CLI)."""
return [row for row in self.sessions_for_thread(thread_id) if self.is_im_session(row)]
- async def rebind(self, *, session_key: str, thread_id: str, agent_id: str) -> None:
+ async def rebind(
+ self,
+ *,
+ session_key: str,
+ thread_id: str,
+ agent_id: str,
+ acting_user_id: int | None = None,
+ ) -> None:
row = self._threads.get(thread_id)
if row is None:
msg = f"thread {thread_id!r} not found"
@@ -296,10 +303,14 @@ async def rebind(self, *, session_key: str, thread_id: str, agent_id: str) -> No
metadata = {"channel_type": row.channel_type, "user_id": row.user_id}
channel_id = None
if session is None:
+ session_user_id = acting_user_id if acting_user_id is not None else row.user_id
+ if acting_user_id is not None:
+ subject_id = str(acting_user_id)
+ metadata = {"channel_type": channel_type, "user_id": acting_user_id}
self._sessions.upsert(
session_key=session_key,
agent_id=agent_id,
- user_id=row.user_id,
+ user_id=session_user_id,
channel_type=channel_type,
chat_type=chat_type,
thread_id=thread_id,
@@ -436,6 +447,15 @@ def get_thread(self, thread_id: str) -> ThreadRow | None:
def list_threads(self, *, agent_id: str, user_id: int, limit: int = 50) -> list[ThreadRow]:
return self._threads.list_by_agent_user(agent_id=agent_id, user_id=user_id, limit=limit)
+ def list_visible_threads(
+ self, *, agent_id: str, user_id: int, limit: int = 50
+ ) -> list[ThreadRow]:
+ """Threads this user owns, plus ones contributed on the same expert."""
+ return self._threads.list_visible(agent_id=agent_id, user_id=user_id, limit=limit)
+
+ def set_contributed(self, thread_id: str, contributed: bool) -> None:
+ self._threads.set_contributed(thread_id, contributed)
+
def list_threads_for_session(self, *, session_key: str, limit: int = 50) -> list[ThreadRow]:
return self._threads.list_by_session(session_key=session_key, limit=limit)
@@ -495,6 +515,9 @@ def increment_unread(self, session_key: str, *, delta: int = 1) -> None:
def mark_thread_read(self, thread_id: str) -> None:
self._sessions.clear_unread_for_thread(thread_id)
+ def mark_thread_read_for_user(self, thread_id: str, user_id: int) -> None:
+ self._sessions.clear_unread_for_user_thread(thread_id, user_id)
+
def mark_agent_read(self, agent_id: str, user_id: int) -> None:
self._sessions.clear_unread_for_agent(agent_id, user_id)
@@ -509,6 +532,15 @@ def _new_thread_id() -> str:
return f"thr_{new_ulid()}"
+def thread_visible_to(row: ThreadRow, user_id: int) -> bool:
+ """Owner, or anyone who can open an expert that this thread was contributed to.
+
+ Rows that predate the column, and test fakes, have no ``contributed`` flag.
+ Those stay private to the owner.
+ """
+ return row.user_id == user_id or bool(getattr(row, "contributed", False))
+
+
def thread_row_has_messages(row: ThreadRow) -> bool:
"""Infer conversation activity from thread metadata (no checkpoint I/O).
diff --git a/src/octop/infra/gateway/ws/ws_channel.py b/src/octop/infra/gateway/ws/ws_channel.py
index e67c3c6752..66c47f9e5e 100644
--- a/src/octop/infra/gateway/ws/ws_channel.py
+++ b/src/octop/infra/gateway/ws/ws_channel.py
@@ -20,12 +20,15 @@
)
from octop_gateway.utils import close_event_stream
-from octop.i18n.domains.stream import format_stream_error
+from octop.infra.errors import stream_error
from octop.infra.gateway.media.attachment_hints import (
inbound_attachments_from_parts,
is_vision_attachment,
)
-from octop.infra.gateway.process.message_keys import INBOUND_ATTACHMENTS_KEY
+from octop.infra.gateway.process.message_keys import (
+ INBOUND_ATTACHMENTS_KEY,
+ resolve_user_id_for_message,
+)
from octop.infra.gateway.steer import DiscardBundle, DrainBundle, SteerCoordinator
from octop.infra.gateway.threads import ThreadRegistry
from octop.infra.gateway.ws.ws_hub import WebSocketHub
@@ -176,6 +179,10 @@ async def handle_inbound(self, raw_payload: Any) -> None:
"thread_id": thread_id,
},
)
+ await self._hub.push_to_thread(
+ thread_id,
+ _turn_user_frame(message, thread_id, processor),
+ )
current = message
while True:
saw_tool_result = False
@@ -298,10 +305,11 @@ async def handle_inbound(self, raw_payload: Any) -> None:
metadata=err_meta,
)
try:
- await self._hub.push_to_thread(
- thread_id,
- {"type": "error", "message": format_stream_error(exc, locale)},
- )
+ error_message, error_code = stream_error(exc, locale)
+ frame: dict[str, object] = {"type": "error", "message": error_message}
+ if error_code:
+ frame["error_code"] = error_code
+ await self._hub.push_to_thread(thread_id, frame)
await self._hub.push_to_thread(thread_id, {"type": "done"})
except Exception:
logger.exception("websocket failed to deliver error frame thread=%s", thread_id)
@@ -391,6 +399,48 @@ async def _send_media(self, subject: ChannelSubject, media: ContentPart) -> None
await self._hub.push(conn_id, frame)
+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 {}
+ frame: dict[str, Any] = {
+ "type": "user",
+ "content": message.text or "",
+ "thread_id": thread_id,
+ }
+ message_id = meta.get("client_message_id")
+ if isinstance(message_id, str) and message_id.strip():
+ frame["message_id"] = message_id.strip()
+ user_id = resolve_user_id_for_message(message, agent_owner_id=None)
+ if user_id > 0:
+ author: dict[str, Any] = {
+ "user_id": user_id,
+ "display_name": "",
+ "username": "",
+ "avatar_icon": None,
+ "avatar_url": f"/api/users/{user_id}/avatar",
+ }
+ repo = getattr(processor, "_user_repo", None)
+ get = getattr(repo, "get", None)
+ if callable(get):
+ row = get(user_id)
+ username = getattr(row, "username", None)
+ if isinstance(username, str):
+ author["username"] = username
+ display_name = getattr(row, "display_name", None)
+ if isinstance(display_name, str):
+ author["display_name"] = display_name
+ icon = getattr(row, "avatar_icon", None)
+ if isinstance(icon, str) and icon.strip():
+ author["avatar_icon"] = icon.strip()
+ frame["author"] = author
+ attachments = meta.get(INBOUND_ATTACHMENTS_KEY)
+ if not isinstance(attachments, list) or not attachments:
+ attachments = inbound_attachments_from_parts(message.content)
+ if attachments:
+ frame["attachments"] = attachments
+ return frame
+
+
def _push_discarded_frame(thread_id: str, bundle: DiscardBundle) -> dict[str, Any]:
return {
"type": "steer.discarded",
diff --git a/src/octop/infra/knowledge/retrieve.py b/src/octop/infra/knowledge/retrieve.py
index 8421ef6bad..81b1286f6a 100644
--- a/src/octop/infra/knowledge/retrieve.py
+++ b/src/octop/infra/knowledge/retrieve.py
@@ -110,6 +110,7 @@ def _format_context(
ranked: Sequence[tuple[Any, Hit, Any]], *, char_budget: int, locale: str
) -> str:
sections: list[str] = []
+ included: list[tuple[Any, Hit, Any]] = []
remaining = char_budget
for base, hit, document in ranked:
citation = tr(
@@ -126,8 +127,9 @@ def _format_context(
continue
section = f"{citation}{text}"
sections.append(section)
+ included.append((base, hit, document))
remaining -= len(section)
if not sections:
return ""
body = tr("knowledge.retrieval.preamble", locale) + "\n\n" + "\n\n".join(sections)
- return append_citations_marker(body, citations_from_ranked(ranked))
+ return append_citations_marker(body, citations_from_ranked(included))
diff --git a/src/octop/infra/utils/env_file.py b/src/octop/infra/utils/env_file.py
index 2eea3451b5..740f059664 100644
--- a/src/octop/infra/utils/env_file.py
+++ b/src/octop/infra/utils/env_file.py
@@ -38,6 +38,19 @@ def env_file_path(root: Path) -> Path:
return root / "env"
+def _looks_like_assignment(line: str) -> bool:
+ """True when *line* is a new ``KEY=`` entry, not a quoted continuation."""
+ raw = line.strip()
+ if not raw or raw.startswith("#"):
+ return False
+ if raw.startswith("export "):
+ raw = raw[7:].strip()
+ if "=" not in raw:
+ return False
+ key, _, _ = raw.partition("=")
+ return bool(_KEY_RE.match(key.strip()))
+
+
def parse_env_text(text: str) -> dict[str, str]:
out: dict[str, str] = {}
lines = text.splitlines()
@@ -59,11 +72,13 @@ def parse_env_text(text: str) -> dict[str, str]:
# ``format_env_file`` quotes any value containing whitespace and leaves embedded line
# breaks raw, so a multi-line value has to be read back across lines. Only a value with
# an *unterminated* quote continues onto the next line; a value that already contains a
- # closing quote (or no quote at all) is left alone, so a malformed entry cannot swallow
- # the rest of the file.
+ # closing quote (or no quote at all) is left alone. A later ``KEY=`` line ends the
+ # continuation, so a missing closing quote cannot swallow the rest of the file.
if value[:1] in {'"', "'"} and value[0] not in value[1:]:
quote = value[0]
while index < len(lines) and quote not in value[1:]:
+ if _looks_like_assignment(lines[index]):
+ break
value = f"{value}\n{lines[index]}"
index += 1
value = value.strip()
diff --git a/tests/integration/test_memory_api.py b/tests/integration/test_memory_api.py
index 5789750582..33a8a4e7d3 100644
--- a/tests/integration/test_memory_api.py
+++ b/tests/integration/test_memory_api.py
@@ -384,6 +384,42 @@ async def test_extract_config_defaults_then_update(env_with_main_agent) -> None:
assert r3.json()["memory_enabled"] is False
+@pytest.mark.asyncio
+@pytest.mark.parametrize("key", ["memory_capture_enabled", "memory_recall_inject_enabled"])
+async def test_extract_config_memory_switch_roundtrip(env_with_main_agent, key: str) -> None:
+ import json
+
+ client, srv, auth, aid = env_with_main_agent
+ url = f"/api/agents/{aid}/memory/extract-config"
+ registry = srv.app_runtime.agent_registry
+
+ initial = await client.get(url, headers=auth)
+ assert initial.status_code == 200, initial.text
+ assert initial.json()[key] is True
+ assert key in initial.json()["supported_call_options"]
+
+ for enabled in (False, True):
+ updated = await client.put(url, headers=auth, json={key: enabled})
+ assert updated.status_code == 200, updated.text
+ assert updated.json()[key] is enabled
+ row = registry.get_row(aid)
+ assert json.loads(row.config_json)["memory"][key] is enabled
+ assert getattr(registry._build_harness_config(row), key) is enabled
+
+ # Updating extraction timing must preserve the independent runtime switch.
+ timing = await client.put(url, headers=auth, json={"extract_idle_seconds": 600})
+ assert timing.status_code == 200, timing.text
+ reread = await client.get(url, headers=auth)
+ assert reread.json()[key] is enabled
+ assert reread.json()["memory_enabled"] is True
+ other = (
+ "memory_recall_inject_enabled"
+ if key == "memory_capture_enabled"
+ else "memory_capture_enabled"
+ )
+ assert reread.json()[other] is True
+
+
@pytest.mark.asyncio
async def test_extract_config_aux_model_roundtrip(env_with_main_agent) -> None:
from tests.support.auth import create_provider
diff --git a/tests/integration/test_providers_api.py b/tests/integration/test_providers_api.py
index f2f9cc1229..d8a4e3a989 100644
--- a/tests/integration/test_providers_api.py
+++ b/tests/integration/test_providers_api.py
@@ -32,6 +32,18 @@ async def test_admin_creates_provider(env):
assert "user_id" not in body
+async def test_duplicate_provider_name_is_conflict(env):
+ """POST /admin/providers with a taken name is 409, not an unhandled 500."""
+ c, _, auth = env
+ body = {"name": "taken-name", "kind": "openai", "api_key": "k"}
+ created = await c.post("/api/admin/providers", headers=auth, json=body)
+ assert created.status_code == 201
+
+ again = await c.post("/api/admin/providers", headers=auth, json=body)
+ assert again.status_code == 409
+ assert again.json()["error"]["code"] == "PROVIDER_NAME_TAKEN"
+
+
async def test_regular_user_cannot_create_provider(env):
"""POST /admin/providers is admin-only."""
c, _, admin_auth = env
diff --git a/tests/unit/agents/test_agent_manager.py b/tests/unit/agents/test_agent_manager.py
index 3ff9950648..10a4c5d6ec 100644
--- a/tests/unit/agents/test_agent_manager.py
+++ b/tests/unit/agents/test_agent_manager.py
@@ -628,6 +628,39 @@ def test_format_agent_start_error_unknown_passthrough() -> None:
assert format_agent_start_error(exc) == "disk full"
+@pytest.mark.parametrize("key", ["memory_capture_enabled", "memory_recall_inject_enabled"])
+@pytest.mark.parametrize("enabled", [False, True])
+def test_memory_runtime_switches_reach_harness_config(
+ manager: AgentManager, key: str, enabled: bool
+) -> None:
+ memory = {key: enabled}
+ assert _memory_extract_settings({"memory": memory}) == memory
+ cfg = manager._build_harness_config(_row(config_json=json.dumps({"memory": memory})))
+ assert getattr(cfg, key) is enabled
+
+
+@pytest.mark.parametrize("key", ["memory_capture_enabled", "memory_recall_inject_enabled"])
+@pytest.mark.parametrize("value", [None, "false", 0, 1])
+def test_memory_runtime_switches_ignore_non_booleans(key: str, value: Any) -> None:
+ assert _memory_extract_settings({"memory": {key: value}}) == {}
+
+
+def test_memory_runtime_switches_skip_unsupported_harness_fields() -> None:
+ memory = {"memory_capture_enabled": False, "memory_recall_inject_enabled": False}
+ assert _memory_extract_settings({"memory": memory}, supported_fields=frozenset()) == {}
+
+
+def test_memory_runtime_switches_advertise_only_supported_options(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from octop.infra.agents import manager as module
+
+ monkeypatch.setattr(
+ module, "_HARNESS_AGENT_CONFIG_FIELDS", frozenset({"memory_capture_enabled"})
+ )
+ assert module.memory_extract_supported_options() == ["memory_capture_enabled"]
+
+
def test_memory_extract_settings_supports_legacy_harness(caplog: pytest.LogCaptureFixture) -> None:
settings = _memory_extract_settings(
{
@@ -980,6 +1013,34 @@ def pending_operation() -> None:
await asyncio.to_thread(conn._thread.join, 5)
+@pytest.mark.asyncio
+async def test_shutdown_waits_for_idle_reclaim_sweep(manager: AgentManager) -> None:
+ """The freelist scan uses the control-plane connection from a worker thread."""
+ entered, release = threading.Event(), threading.Event()
+
+ def slow_scan() -> int:
+ entered.set()
+ assert release.wait(5)
+ return 0
+
+ manager._queue_bloated_sqlite_stores = slow_scan # type: ignore[method-assign]
+ manager.schedule_idle_reclaim_sweep()
+ closing = None
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ closing = asyncio.create_task(manager.shutdown())
+ await asyncio.sleep(0.05)
+ assert not closing.done()
+ release.set()
+ await asyncio.wait_for(closing, timeout=5)
+ finally:
+ release.set()
+ if closing is not None:
+ await closing
+ else:
+ await manager.shutdown()
+
+
def test_build_harness_config_enables_bootstrap_for_expert_template(manager: AgentManager) -> None:
from dataclasses import replace
diff --git a/tests/unit/agents/test_agent_skill_packages.py b/tests/unit/agents/test_agent_skill_packages.py
index a984115318..9210cf7e92 100644
--- a/tests/unit/agents/test_agent_skill_packages.py
+++ b/tests/unit/agents/test_agent_skill_packages.py
@@ -105,6 +105,17 @@ def test_assert_backend_supports_skill_packages_accepts_host_root(
)
+def test_assert_backend_supports_skill_packages_accepts_windows_drive_root(
+ manager: AgentManager,
+) -> None:
+ manager.assert_backend_supports_skill_packages(
+ {"type": "local_shell", "root_dir": "C:/", "virtual_mode": True}
+ )
+ manager.assert_backend_supports_skill_packages(
+ {"type": "filesystem", "root_dir": "D:\\", "virtual_mode": True}
+ )
+
+
def test_assert_backend_supports_skill_packages_accepts_workspace_scoped_default(
manager: AgentManager,
tmp_path: Path,
diff --git a/tests/unit/agents/test_expert_catalog.py b/tests/unit/agents/test_expert_catalog.py
index a913f59200..7d030c020a 100644
--- a/tests/unit/agents/test_expert_catalog.py
+++ b/tests/unit/agents/test_expert_catalog.py
@@ -387,3 +387,16 @@ async def test_apply_workspace_quick_prompts_refuses_invalid_json() -> None:
with pytest.raises(OctopError) as exc:
await apply_workspace_quick_prompts(workspace, [])
assert exc.value.code is ErrorCode.SLASH_BAD_ARGS
+
+
+def test_featured_expert_template_ids_are_the_pre_market_library() -> None:
+ from octop.infra.agents.experts.catalog import featured_expert_template_ids
+
+ ids = featured_expert_template_ids()
+
+ assert len(ids) == 22
+ assert "general-assistant" in ids
+ assert "ops-engineer" in ids
+ assert "wechat-ops" in ids
+ assert "default" not in ids
+ assert "tencent-cvm-ops" not in ids
diff --git a/tests/unit/agents/test_memory_slim.py b/tests/unit/agents/test_memory_slim.py
index a05e3dd5f4..4c7aada22e 100644
--- a/tests/unit/agents/test_memory_slim.py
+++ b/tests/unit/agents/test_memory_slim.py
@@ -37,6 +37,7 @@ def make_manager(tmp_path):
registry._reclaim_pending = set()
registry._reclaim_holds = {}
registry._reclaim_task = None
+ registry._reclaim_sweep_task = None
registry._reclaim_wake = None
registry.get_agent = lambda _: agent
registry.memory_slim = MemorySlimCoordinator(registry)
diff --git a/tests/unit/api/test_chat_history.py b/tests/unit/api/test_chat_history.py
index 83bac3f2e2..079ccfe8c1 100644
--- a/tests/unit/api/test_chat_history.py
+++ b/tests/unit/api/test_chat_history.py
@@ -209,8 +209,9 @@ async def test_list_threads_derives_has_messages_from_db() -> None:
),
]
thread_registry = MagicMock()
- thread_registry.list_threads.return_value = rows
+ thread_registry.list_visible_threads.return_value = rows
thread_registry.get_bound_thread_id.return_value = None
+ thread_registry.unread_counts_for_threads.return_value = {"thr_used": 3}
server = MagicMock()
agent_row = MagicMock(user_id=1)
@@ -235,6 +236,8 @@ async def test_list_threads_derives_has_messages_from_db() -> None:
assert out[1]["has_messages"] is True
assert out[1]["turn_active"] is True
assert out[1]["awaiting_user"] is False
+ assert out[0]["unread_count"] == 0
+ assert out[1]["unread_count"] == 3
@pytest.mark.asyncio
@@ -534,3 +537,97 @@ async def _capture(_frame: dict[str, Any]) -> None:
server.app_runtime.agent_registry.delete_thread_checkpoint.assert_awaited_once_with(
"agt_1", "thr_1"
)
+
+
+@pytest.mark.asyncio
+async def test_non_owner_cannot_change_shared_thread_settings(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from octop.api.routers.chat.models import RenameThreadBody
+
+ monkeypatch.setattr(history_mod, "require_agent_row", lambda *_a, **_k: MagicMock())
+ server = MagicMock()
+ server.app_runtime.gateway.thread_registry.get_thread.return_value = MagicMock(
+ agent_id="agt_1",
+ user_id=1,
+ contributed=True,
+ )
+ body = RenameThreadBody(model_ref="prov/model")
+
+ with pytest.raises(OctopError) as exc:
+ await history_mod.patch_thread(
+ "agt_1",
+ "thr",
+ body,
+ user=MagicMock(id=2, is_admin=False),
+ server=server,
+ )
+
+ assert exc.value.code == ErrorCode.FORBIDDEN
+
+
+def test_history_authors_keep_the_sender() -> None:
+ class _User:
+ def __init__(self, username: str, display_name: str, avatar_icon: str | None) -> None:
+ self.username = username
+ self.display_name = display_name
+ self.avatar_icon = avatar_icon
+
+ users = {
+ 1: _User("ada", "Ada", None),
+ 2: _User("bob", "Bob", "doctor"),
+ }
+ server = MagicMock()
+ server.services.user_repo.get.side_effect = users.get
+ server.services.avatars.return_value.url.return_value = "/api/users/x/avatar?v=1"
+ messages: list[dict[str, Any]] = [
+ {"role": "user", "content": "old"},
+ {"role": "user", "content": "new", "author_user_id": 2},
+ {"role": "assistant", "content": "ok"},
+ ]
+
+ history_mod._attach_message_authors(server, messages, owner_user_id=1)
+
+ assert messages[0]["author"]["username"] == "ada"
+ assert messages[1]["author"]["username"] == "bob"
+ assert messages[1]["author"]["avatar_icon"] == "doctor"
+ assert "author" not in messages[2]
+
+
+@pytest.mark.asyncio
+async def test_shared_thread_hitl_resume_skips_user_filter(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from octop.api.routers.chat import routes as routes_mod
+ from octop.api.routers.chat.models import HitlResumeBody
+
+ row = MagicMock(contributed=True, user_id=1)
+ monkeypatch.setattr(history_mod, "_require_thread", lambda *_a, **_k: row)
+ server = MagicMock()
+ store = server.app_runtime.gateway.processor.hitl_coordinator.store
+ store.resolve_pending_for_thread.return_value = None
+ body = HitlResumeBody(
+ thread_id="thr",
+ decisions=[{"type": "approve"}],
+ pending_id="pend",
+ )
+
+ await routes_mod.resume_hitl(
+ "agt_1",
+ body,
+ MagicMock(),
+ user=MagicMock(id=2),
+ server=server,
+ )
+
+ assert store.resolve_pending_for_thread.call_args.kwargs["user_id"] is None
+
+ row.contributed = False
+ await routes_mod.resume_hitl(
+ "agt_1",
+ body,
+ MagicMock(),
+ user=MagicMock(id=2),
+ server=server,
+ )
+ assert store.resolve_pending_for_thread.call_args.kwargs["user_id"] == 2
diff --git a/tests/unit/api/test_openapi_meta.py b/tests/unit/api/test_openapi_meta.py
index 4b9a598d97..d409b2e281 100644
--- a/tests/unit/api/test_openapi_meta.py
+++ b/tests/unit/api/test_openapi_meta.py
@@ -27,5 +27,11 @@ async def test_openapi_has_bearer_security_and_descriptions(tmp_octop_home: Path
me = spec["paths"]["/api/auth/me"]["get"]
assert "BearerAuth" in me["security"][0]
assert "security" not in spec["paths"]["/api/setup/status"]["get"]
+ extraction = spec["paths"]["/api/agents/{agent_id}/memory/extract-config"]["put"]
+ ref = extraction["requestBody"]["content"]["application/json"]["schema"]["$ref"]
+ properties = spec["components"]["schemas"][ref.rsplit("/", 1)[-1]]["properties"]
+ for key in ("memory_capture_enabled", "memory_recall_inject_enabled"):
+ assert {"type": "boolean"} in properties[key]["anyOf"]
+ assert properties[key]["description"]
finally:
await srv.stop()
diff --git a/tests/unit/api/test_provider_patch_rehydrate.py b/tests/unit/api/test_provider_patch_rehydrate.py
index 61f8a2f8cc..7aa56d609e 100644
--- a/tests/unit/api/test_provider_patch_rehydrate.py
+++ b/tests/unit/api/test_provider_patch_rehydrate.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import json
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -10,6 +12,7 @@
ProviderPatchBody,
_patch_requires_provider_rehydrate,
_provider_patch_updates,
+ _row_to_dict,
admin_patch_provider,
)
@@ -38,6 +41,41 @@ def test_stream_usage_patch_rewrites_extra_without_clearing_api_key() -> None:
}
+def test_default_model_patch_is_stored_and_can_be_cleared() -> None:
+ body = ProviderPatchBody.model_validate({"model": "deepseek-v3"})
+ updates = _provider_patch_updates(body, current_extra_json='{"headers": {"X-A": "1"}}')
+ extra = json.loads(updates["extra_json"])
+ assert extra["default_model"] == "deepseek-v3"
+ assert extra["headers"] == {"X-A": "1"}
+ assert "api_key" not in updates
+ assert _patch_requires_provider_rehydrate(body) is False
+
+ cleared = ProviderPatchBody.model_validate({"model": None})
+ cleared_extra = json.loads(
+ _provider_patch_updates(cleared, current_extra_json=updates["extra_json"])["extra_json"]
+ )
+ assert "default_model" not in cleared_extra
+ assert cleared_extra["headers"] == {"X-A": "1"}
+
+
+def test_row_to_dict_uses_saved_default_model_not_the_first_model() -> None:
+ row = SimpleNamespace(
+ id=1,
+ name="custom",
+ kind="openai",
+ base_url="https://example.invalid",
+ api_key="sk",
+ note=None,
+ enabled=1,
+ extra_json=None,
+ get_models=lambda: [{"id": "first", "name": "First"}],
+ )
+ assert _row_to_dict(row)["model"] is None
+
+ row.extra_json = '{"default_model": "deepseek-v3"}'
+ assert _row_to_dict(row)["model"] == "deepseek-v3"
+
+
def test_patch_note_only_does_not_require_rehydrate() -> None:
body = ProviderPatchBody.model_validate({"note": "ops memo"})
assert _patch_requires_provider_rehydrate(body) is False
diff --git a/tests/unit/backup/test_move_file_replace.py b/tests/unit/backup/test_move_file_replace.py
new file mode 100644
index 0000000000..b3e2ad3e04
--- /dev/null
+++ b/tests/unit/backup/test_move_file_replace.py
@@ -0,0 +1,24 @@
+"""Cross-device backup moves fall back to copy."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from octop.infra.backup.store import move_file_replace
+
+
+def test_move_file_replace_copies_when_rename_fails(tmp_path: Path, monkeypatch) -> None:
+ src = tmp_path / "tmp" / "backup.tar.gz"
+ src.parent.mkdir()
+ src.write_bytes(b"archive")
+ dest = tmp_path / "other" / "backup.tar.gz"
+
+ def _explode(self: Path, _target: Path) -> Path:
+ raise OSError(18, "Invalid cross-device link")
+
+ monkeypatch.setattr(Path, "replace", _explode)
+
+ move_file_replace(src, dest)
+
+ assert dest.read_bytes() == b"archive"
+ assert not src.exists()
diff --git a/tests/unit/backup/test_pg_dump_helpers.py b/tests/unit/backup/test_pg_dump_helpers.py
index 9de1a8115f..1704f2f4b2 100644
--- a/tests/unit/backup/test_pg_dump_helpers.py
+++ b/tests/unit/backup/test_pg_dump_helpers.py
@@ -5,13 +5,16 @@
import pytest
from octop.infra.backup import pg_dump
-from octop.infra.errors import OctopError
+from octop.infra.errors import ErrorCode, OctopError
def test_require_tool_missing(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(pg_dump.shutil, "which", lambda _name: None)
- with pytest.raises(OctopError, match="pg_dump not found"):
+ with pytest.raises(OctopError, match="pg_dump not found") as raised:
pg_dump._require_tool("pg_dump")
+ assert raised.value.code is ErrorCode.BACKUP_CLIENT_MISSING
+ assert raised.value.details["tool"] == "pg_dump"
+ assert raised.value.status == 503
def test_dump_postgres_can_exclude_chat_table_data(
diff --git a/tests/unit/bridge/test_bridge_proxy_local.py b/tests/unit/bridge/test_bridge_proxy_local.py
index f22d67097d..3a65da4d55 100644
--- a/tests/unit/bridge/test_bridge_proxy_local.py
+++ b/tests/unit/bridge/test_bridge_proxy_local.py
@@ -7,6 +7,7 @@
import pytest
from octop.api.middleware.bridge_proxy import (
+ _is_websocket_upgrade,
_local_bridge_shadow_response,
resolve_tunnel_target,
)
@@ -54,6 +55,16 @@ def test_other_paths_pass_through() -> None:
)
+def test_constant_connection_upgrade_is_not_a_websocket() -> None:
+ """nginx ``Connection "upgrade"`` without ``Upgrade: websocket`` must still tunnel."""
+ assert _is_websocket_upgrade({"connection": "upgrade"}) is False
+ assert _is_websocket_upgrade({"connection": "keep-alive, upgrade"}) is False
+ assert _is_websocket_upgrade({"connection": "Upgrade", "upgrade": "websocket"}) is True
+ assert (
+ _is_websocket_upgrade({"connection": "keep-alive, Upgrade", "upgrade": "WebSocket"}) is True
+ )
+
+
def test_resolve_upload_path() -> None:
target = resolve_tunnel_target("/api/agents/bridge:cid1:aid1/upload")
assert target is not None
@@ -117,3 +128,60 @@ def test_resolve_ignores_local_header_and_unscoped_paths() -> None:
assert resolve_tunnel_target("/api/mbti/current", "01LOCAL") is None
assert resolve_tunnel_target("/api/users", "bridge:cid1:aid1") is None
assert resolve_tunnel_target("/api/plugins/install", "bridge:cid1:aid1") is None
+
+
+@pytest.mark.asyncio
+async def test_proxy_still_tunnels_when_connection_upgrade_is_not_websocket() -> None:
+ import httpx
+ from fastapi import FastAPI
+ from fastapi.responses import JSONResponse
+
+ from octop.api.middleware.bridge_proxy import install
+
+ app = FastAPI()
+ seen: dict[str, object] = {}
+
+ class _User:
+ id = 7
+
+ class _Mgr:
+ async def tunnel_http(self, **kwargs: object) -> httpx.Response:
+ seen.update(kwargs)
+ return httpx.Response(200, json={"ok": True})
+
+ class _Server:
+ class _Runtime:
+ bridge_manager = _Mgr()
+
+ app_runtime = _Runtime()
+
+ install(app, _Server())
+
+ @app.middleware("http")
+ async def _user(request, call_next): # type: ignore[no-untyped-def]
+ request.state.octop_user = _User()
+ return await call_next(request)
+
+ @app.get("/api/agents/{agent_id}/threads")
+ async def _local(agent_id: str) -> JSONResponse:
+ return JSONResponse(
+ {"error": {"code": "AGENT_NOT_FOUND", "message": agent_id}},
+ status_code=404,
+ )
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ proxied = await client.get(
+ "/api/agents/bridge:cid1:aid1/threads",
+ headers={"connection": "upgrade"},
+ )
+ skipped = await client.get(
+ "/api/agents/bridge:cid1:aid1/threads",
+ headers={"connection": "upgrade", "upgrade": "websocket"},
+ )
+
+ assert proxied.status_code == 200
+ assert proxied.json()["ok"] is True
+ assert seen["path"] == "/api/agents/aid1/threads"
+ assert skipped.status_code == 404
+ assert skipped.json()["error"]["code"] == "AGENT_NOT_FOUND"
diff --git a/tests/unit/bridge/test_inbound_identity.py b/tests/unit/bridge/test_inbound_identity.py
index 8a8d3925ee..67d3f24d40 100644
--- a/tests/unit/bridge/test_inbound_identity.py
+++ b/tests/unit/bridge/test_inbound_identity.py
@@ -171,6 +171,52 @@ async def test_same_loopback_advertise_accepts_remote_peer(tmp_path: Path) -> No
await task
+@pytest.mark.asyncio
+async def test_hello_for_local_outbound_row_is_self_connect(tmp_path: Path) -> None:
+ """A dial that lands on this instance is self-connect, even as another user.
+
+ The typed URL often does not match the advertised address, so the outbound
+ row already exists when the hello arrives. That used to close with
+ "connection owned by another user".
+ """
+ mgr, owner, uid = _manager(tmp_path, advertise_base_url="http://127.0.0.1:8088")
+ member_id = mgr._users.create(username="member", password_hash="x", role="user")
+ mgr._repo.create(
+ connection_id="CIDOUT",
+ owner_user_id=uid,
+ peer_base_url="https://peer.example",
+ peer_username="member",
+ display_name="peer",
+ credential_blob=b"secret",
+ )
+ member = SimpleNamespace(id=member_id, username="member")
+ sock = _HoldSocket(_hello("CIDOUT", display_name="对端"), client_host="203.0.113.8")
+ await mgr.accept_inbound(websocket=sock, user=member)
+ assert sock.close_code == 4004
+ assert mgr._sessions.get("CIDOUT") is None
+
+ own = _HoldSocket(_hello("CIDOUT", display_name="自己"), client_host="203.0.113.9")
+ await mgr.accept_inbound(websocket=own, user=owner)
+ assert own.close_code == 4004
+
+
+@pytest.mark.asyncio
+async def test_inbound_id_owned_by_another_user_stays_rejected(tmp_path: Path) -> None:
+ mgr, _owner, uid = _manager(tmp_path, advertise_base_url="http://127.0.0.1:8088")
+ member_id = mgr._users.create(username="member", password_hash="x", role="user")
+ mgr._repo.create(
+ connection_id="CIDIN",
+ owner_user_id=uid,
+ peer_base_url="http://203.0.113.8:8088",
+ peer_username="someone",
+ display_name="inbound",
+ )
+ sock = _HoldSocket(_hello("CIDIN", display_name="对端"), client_host="203.0.113.8")
+ member = SimpleNamespace(id=member_id, username="member")
+ await mgr.accept_inbound(websocket=sock, user=member)
+ assert sock.close_code == 4003
+
+
@pytest.mark.asyncio
async def test_matching_public_advertise_is_self_connect(tmp_path: Path) -> None:
mgr, owner, _uid = _manager(tmp_path, advertise_base_url="http://203.0.113.10:8088")
diff --git a/tests/unit/bridge/test_list_remote_agents.py b/tests/unit/bridge/test_list_remote_agents.py
index a479ca8ede..cd11b447d2 100644
--- a/tests/unit/bridge/test_list_remote_agents.py
+++ b/tests/unit/bridge/test_list_remote_agents.py
@@ -103,6 +103,7 @@ def json(self) -> list[dict[str, Any]]:
"name": "别人共享",
"is_owner": False,
"is_shared": True,
+ "default_model": "prov/shared-default",
},
]
@@ -113,6 +114,7 @@ def json(self) -> list[dict[str, Any]]:
assert by_remote["mine"]["is_shared"] is False
assert by_remote["shared"]["is_owner"] is False
assert by_remote["shared"]["is_shared"] is True
+ assert by_remote["shared"]["default_model"] == "prov/shared-default"
assert by_remote["mine"]["state"] == "stopped"
assert by_remote["shared"]["state"] == "stopped"
diff --git a/tests/unit/bridge/test_peer_auth.py b/tests/unit/bridge/test_peer_auth.py
index 29d5d68692..9f12139165 100644
--- a/tests/unit/bridge/test_peer_auth.py
+++ b/tests/unit/bridge/test_peer_auth.py
@@ -2,11 +2,18 @@
from __future__ import annotations
+import asyncio
+from unittest.mock import AsyncMock, MagicMock
+
import pytest
+from octop.i18n import error_message
from octop.infra.bridge.manager import (
_annotate_bridge_dial_error,
_should_refresh_peer_token,
+ bridge_failure_from_dial,
+ dial_error_note,
+ error_from_dial_note,
)
from octop.infra.bridge.peer_auth import (
is_self_peer_url,
@@ -58,6 +65,102 @@ def __init__(self) -> None:
assert "needs Octop with /api/bridge/ws" not in text
+class _Close:
+ def __init__(self, code: int, reason: str) -> None:
+ self.code = code
+ self.reason = reason
+
+ def __str__(self) -> str:
+ return f"{self.code} (private use) {self.reason}"
+
+
+class _Closed(Exception):
+ def __init__(self, code: int, reason: str) -> None:
+ frame = _Close(code, reason)
+ self.rcvd = frame
+ self.sent = frame
+ super().__init__(f"received {frame}; then sent {frame}")
+
+
+def test_dial_close_owned_by_another_user_is_readable() -> None:
+ exc = _Closed(4003, "connection owned by another user")
+ err = bridge_failure_from_dial(exc)
+ assert err.code == ErrorCode.BRIDGE_PEER_CONNECTION_OWNED
+ assert "4003" not in dial_error_note(exc)
+ assert dial_error_note(exc) == "octop:apiErrors.BRIDGE_PEER_CONNECTION_OWNED"
+
+
+def test_dial_close_permission_required_is_not_admin_only() -> None:
+ exc = _Closed(4003, "permission required")
+ err = bridge_failure_from_dial(exc)
+ assert err.code == ErrorCode.BRIDGE_PEER_FORBIDDEN
+ text = error_message(err.code.value, "zh")
+ assert "权限" in text
+ assert "管理员" in text
+
+
+def test_connection_limit_note_keeps_the_limit() -> None:
+ exc = _Closed(4008, "connection limit")
+ note = dial_error_note(exc)
+ err = error_from_dial_note(note)
+ assert err is not None
+ assert err.code == ErrorCode.BRIDGE_CONNECTION_LIMIT
+ assert err.details["limit"] == 10
+ text = error_message(err.code.value, "zh", **err.details)
+ assert "10" in text
+ assert "{limit}" not in text
+
+
+@pytest.mark.asyncio
+async def test_permanent_dial_stops_without_reconnect_backoff() -> None:
+ from octop.infra.bridge.manager import BridgeManager
+ from octop.infra.db.repos.bridge_connections import BridgeConnectionRow
+
+ row = BridgeConnectionRow(
+ pk=1,
+ connection_id="cid1",
+ owner_user_id=1,
+ peer_base_url="https://peer.example",
+ peer_username="alice",
+ display_name="云端",
+ notes=None,
+ icon_name=None,
+ credential_blob=b"enc",
+ access_token_blob=b"tok",
+ token_expires_at=None,
+ status="connecting",
+ last_error=None,
+ last_seen_at=None,
+ auto_reconnect=True,
+ created_at=1,
+ updated_at=1,
+ )
+ repo = MagicMock()
+ repo.get.return_value = row
+ mgr = BridgeManager(
+ bridge_repo=repo,
+ secret_repo=MagicMock(),
+ user_repo=MagicMock(),
+ advertise_base_url="http://local.test",
+ )
+ mgr._ensure_peer_token = AsyncMock(return_value="tok") # type: ignore[method-assign]
+
+ async def reject(*_args: object, **_kwargs: object) -> None:
+ raise _Closed(4003, "permission required")
+
+ mgr._run_outbound_client = reject # type: ignore[method-assign]
+ started = asyncio.get_running_loop().time()
+ await asyncio.wait_for(mgr._outbound_supervisor("cid1"), timeout=1.0)
+ assert asyncio.get_running_loop().time() - started < 0.5
+ assert "cid1" in mgr._user_stopped
+ repo.set_auto_reconnect.assert_not_called()
+ repo.update_status.assert_any_call(
+ "cid1",
+ status="error",
+ last_error="octop:apiErrors.BRIDGE_PEER_FORBIDDEN",
+ )
+
+
def test_is_self_peer_url_matches_loopback_aliases() -> None:
assert is_self_peer_url("http://localhost:8787", "http://127.0.0.1:8787")
assert not is_self_peer_url("https://peer.example", "http://127.0.0.1:8787")
diff --git a/tests/unit/bridge/test_session_liveness.py b/tests/unit/bridge/test_session_liveness.py
index 021ca0d7fb..83d9ad4ab1 100644
--- a/tests/unit/bridge/test_session_liveness.py
+++ b/tests/unit/bridge/test_session_liveness.py
@@ -397,9 +397,12 @@ async def send_json(payload: dict[str, Any]) -> None:
sess.send_json = send_json # type: ignore[method-assign]
frames: list[dict[str, Any]] = []
+ forwarded = asyncio.Event()
async def on_frame(frame: dict[str, Any]) -> None:
frames.append(frame)
+ if len(frames) >= 2:
+ forwarded.set()
task = asyncio.create_task(
mgr.relay_user_listen(
@@ -411,7 +414,7 @@ async def on_frame(frame: dict[str, Any]) -> None:
)
)
await asyncio.wait_for(started.wait(), timeout=1.0)
- await asyncio.sleep(0.05)
+ await asyncio.wait_for(forwarded.wait(), timeout=1.0)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
diff --git a/tests/unit/db/test_db_pool.py b/tests/unit/db/test_db_pool.py
index 4a4e03c6f0..adf1ebf605 100644
--- a/tests/unit/db/test_db_pool.py
+++ b/tests/unit/db/test_db_pool.py
@@ -21,6 +21,28 @@ def db(tmp_path: Path) -> SqlitePool:
return pool
+def test_close_waits_for_in_flight_query(tmp_path: Path) -> None:
+ pool = SqlitePool(tmp_path / "octop.db")
+ entered = threading.Event()
+ result: dict[str, int] = {}
+
+ def query() -> None:
+ with pool.connect() as conn:
+ entered.set()
+ time.sleep(0.2)
+ result["row"] = int(conn.execute("SELECT 1").fetchone()[0])
+
+ worker = threading.Thread(target=query)
+ worker.start()
+ assert entered.wait(2)
+ pool.close()
+ worker.join(2)
+ assert not worker.is_alive()
+ assert result["row"] == 1
+ with pytest.raises(sqlite3.ProgrammingError), pool.connect():
+ pass
+
+
def test_db_pool_creates_file(tmp_path: Path):
db_path = tmp_path / "octop.db"
SqlitePool(db_path)
@@ -35,6 +57,31 @@ def test_db_pool_file_is_0600(tmp_path: Path):
assert mode == 0o600
+def test_close_waits_for_in_flight_connection(db: SqlitePool) -> None:
+ """Closing must not free the connection while another thread is inside it."""
+ started = threading.Event()
+ release = threading.Event()
+
+ def hold() -> None:
+ with db.connect() as conn:
+ started.set()
+ assert release.wait(timeout=5)
+ conn.execute("SELECT 1").fetchone()
+
+ holder = threading.Thread(target=hold)
+ holder.start()
+ assert started.wait(timeout=5)
+ closer = threading.Thread(target=db.close)
+ closer.start()
+ closer.join(timeout=0.2)
+ assert closer.is_alive()
+ release.set()
+ closer.join(timeout=5)
+ holder.join(timeout=5)
+ assert not closer.is_alive()
+ assert not holder.is_alive()
+
+
def test_run_migrations_creates_tables(db: SqlitePool):
with db.connect() as conn:
rows = conn.execute(
diff --git a/tests/unit/db/test_repo_sessions_threads.py b/tests/unit/db/test_repo_sessions_threads.py
index fa5eba6294..949b91f869 100644
--- a/tests/unit/db/test_repo_sessions_threads.py
+++ b/tests/unit/db/test_repo_sessions_threads.py
@@ -305,3 +305,36 @@ def test_threads_hitl_policy_roundtrip(repos):
row = threads.get("thr_hitl")
assert row is not None
assert row.hitl_policy == '{"mode":"allow_all"}'
+
+
+def test_contributed_thread_is_listed_for_other_users(repos):
+ _sessions, threads = repos
+ UserRepo(threads._db).create(username="other", password_hash="h", role="user")
+ sk = ThreadRegistry.dashboard_key(agent_id="a1", user_id=1)
+ threads.insert(
+ thread_id="thr_private",
+ agent_id="a1",
+ user_id=1,
+ channel_type="dashboard",
+ session_key=sk,
+ title="mine",
+ last_active=10,
+ )
+ threads.insert(
+ thread_id="thr_shared",
+ agent_id="a1",
+ user_id=1,
+ channel_type="dashboard",
+ session_key=sk,
+ title="shared",
+ last_active=20,
+ )
+ threads.set_contributed("thr_shared", True)
+ visible = threads.list_visible(agent_id="a1", user_id=2, limit=10)
+ assert [row.thread_id for row in visible] == ["thr_shared"]
+ assert visible[0].contributed is True
+ assert threads.list_by_agent_user(agent_id="a1", user_id=2, limit=10) == []
+ owner_ids = {row.thread_id for row in threads.list_visible(agent_id="a1", user_id=1, limit=10)}
+ assert owner_ids == {"thr_private", "thr_shared"}
+ threads.set_contributed("thr_shared", False)
+ assert threads.list_visible(agent_id="a1", user_id=2, limit=10) == []
diff --git a/tests/unit/gateway/test_dashboard_ws.py b/tests/unit/gateway/test_dashboard_ws.py
index 12205df385..bc48b3a201 100644
--- a/tests/unit/gateway/test_dashboard_ws.py
+++ b/tests/unit/gateway/test_dashboard_ws.py
@@ -19,6 +19,21 @@ def _token(content: str, thread_id: str) -> dict[str, Any]:
return {"type": "token", "content": content, "thread_id": thread_id}
+def _user(content: str, thread_id: str, user_id: int = 7) -> dict[str, Any]:
+ return {
+ "type": "user",
+ "content": content,
+ "thread_id": thread_id,
+ "author": {
+ "user_id": user_id,
+ "display_name": "",
+ "username": "",
+ "avatar_icon": None,
+ "avatar_url": f"/api/users/{user_id}/avatar",
+ },
+ }
+
+
_STEER_PROTOCOL_TYPES = frozenset(
{
"turn.started",
@@ -240,6 +255,7 @@ 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
assert frames[-1]["type"] == "turn.ended"
@@ -291,7 +307,10 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
if a_frames:
break
await asyncio.sleep(0.01)
- assert _stream_frames(a_frames) == [_token("first", "thread-1")]
+ assert _stream_frames(a_frames) == [
+ _user("hi", "thread-1"),
+ _token("first", "thread-1"),
+ ]
assert hub.is_turn_active("thread-1") is True
hub.unsubscribe_connection("a")
@@ -350,13 +369,17 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str,
if a_frames:
break
await asyncio.sleep(0.01)
- assert _stream_frames(a_frames) == [_token("first", "thread-1")]
+ assert _stream_frames(a_frames) == [
+ _user("hi", "thread-1"),
+ _token("first", "thread-1"),
+ ]
hub.subscribe("thread-1", "b")
gate.set()
await task
assert _stream_frames(a_frames) == [
+ _user("hi", "thread-1"),
_token("first", "thread-1"),
_token("second", "thread-1"),
{"type": "done", "thread_id": "thread-1"},
diff --git a/tests/unit/gateway/test_hitl_channel.py b/tests/unit/gateway/test_hitl_channel.py
index 7dc00cba9c..bb1e0a59d2 100644
--- a/tests/unit/gateway/test_hitl_channel.py
+++ b/tests/unit/gateway/test_hitl_channel.py
@@ -403,6 +403,37 @@ def test_hitl_store_resolve_pending_for_thread() -> None:
assert store.resolve_pending_for_thread("thr-a", agent_id="agent1", user_id=2) is None
assert store.pending_thread_ids(agent_id="agent1", user_id=1) == frozenset({"thr-a", "thr-b"})
assert store.pending_thread_ids(agent_id="agent1", user_id=2) == frozenset()
+ assert store.pending_thread_ids(agent_id="agent1", user_id=2, any_user=True) == frozenset(
+ {"thr-a", "thr-b"}
+ )
+ assert store.resolve_pending_for_thread("thr-a", agent_id="agent1", user_id=None) is pending
+
+
+def test_hitl_store_other_thread_does_not_expire_pending() -> None:
+ """Same dashboard session_key, different threads, stay pending together."""
+ store = HitlPendingStore()
+ ask_a = [{"name": "ask_user_question", "args": {"questions": [{"question": "A?"}]}}]
+ ask_b = [{"name": "ask_user_question", "args": {"questions": [{"question": "B?"}]}}]
+ first = store.register(
+ thread_id="thr-a",
+ agent_id="agent1",
+ user_id=1,
+ session_key="dash:1:agent1",
+ channel_type="dashboard",
+ action_requests=ask_a,
+ review_configs=None,
+ )
+ second = store.register(
+ thread_id="thr-b",
+ agent_id="agent1",
+ user_id=1,
+ session_key="dash:1:agent1",
+ channel_type="dashboard",
+ action_requests=ask_b,
+ review_configs=None,
+ )
+ assert store.get(first.pending_id).status == "pending" # type: ignore[union-attr]
+ assert store.get(second.pending_id).status == "pending" # type: ignore[union-attr]
def test_hitl_store_reuses_equivalent_pending() -> None:
diff --git a/tests/unit/gateway/test_message_build.py b/tests/unit/gateway/test_message_build.py
index 3ccd3ba793..45e1d27fec 100644
--- a/tests/unit/gateway/test_message_build.py
+++ b/tests/unit/gateway/test_message_build.py
@@ -103,6 +103,7 @@ def test_build_harness_request_stores_dashboard_message_id() -> None:
assert isinstance(message, HumanMessage)
assert message.id == "1710000000000-ab12cd"
assert message.content == "画一张图"
+ assert message.additional_kwargs["octop_author_user_id"] == 1
def test_overwrite_last_user_text_keeps_message_id() -> None:
diff --git a/tests/unit/gateway/test_processor_conversation_mode.py b/tests/unit/gateway/test_processor_conversation_mode.py
index 671974c419..0625044b39 100644
--- a/tests/unit/gateway/test_processor_conversation_mode.py
+++ b/tests/unit/gateway/test_processor_conversation_mode.py
@@ -80,7 +80,7 @@ async def test_dashboard_execute_overwrites_user_text() -> None:
thread_id="thr",
meta={},
)
- assert request["messages"][0]["content"] == "请按 plans/foo.md 执行"
+ assert request["messages"][0].content == "请按 plans/foo.md 执行"
assert request["conversation_mode"] == "craft"
processor._thread_registry.update_composer.assert_called_once_with(
"thr",
@@ -114,7 +114,7 @@ async def test_dashboard_mode_switch_keeps_pending_plan() -> None:
thread_id="thr",
meta={"conversation_mode": "ask"},
)
- assert request["messages"][0]["content"] == "先问一句"
+ assert request["messages"][0].content == "先问一句"
assert request["conversation_mode"] == "ask"
processor._thread_registry.update_composer.assert_called_once_with(
"thr",
diff --git a/tests/unit/gateway/test_processor_default_open.py b/tests/unit/gateway/test_processor_default_open.py
index f51c9cb400..7bda1b8fa1 100644
--- a/tests/unit/gateway/test_processor_default_open.py
+++ b/tests/unit/gateway/test_processor_default_open.py
@@ -291,7 +291,7 @@ async def test_dashboard_request_attaches_knowledge_base_ids_without_prepending(
meta=msg.metadata or {},
)
- content = request["messages"][0]["content"]
+ content = request["messages"][0].content
assert content == "question"
configurable = request.get("configurable") or {}
assert configurable["knowledge_base_ids"] == ["kb-1"]
diff --git a/tests/unit/gateway/test_processor_resource_errors.py b/tests/unit/gateway/test_processor_resource_errors.py
index 41aaba7dea..86839b868a 100644
--- a/tests/unit/gateway/test_processor_resource_errors.py
+++ b/tests/unit/gateway/test_processor_resource_errors.py
@@ -12,7 +12,7 @@
from octop_gateway.models import ChannelSubject, InboundMessage, TextContent
from octop.infra.errors import ErrorCode, OctopError
-from octop.infra.gateway.process.processor import GlobalProcessor, _stream_error
+from octop.infra.gateway.process.processor import GlobalProcessor, stream_error
from octop.infra.gateway.slash.dispatcher import SlashDispatcher
from octop.infra.gateway.ws import WS_CHANNEL_ID
from octop.infra.history.projection import _wire_text
@@ -66,7 +66,7 @@ def test_stream_error_preserves_resource_error_code() -> None:
details={"used": 12, "quota": 10},
)
- message, code = _stream_error(error, "zh")
+ message, code = stream_error(error, "zh")
assert code == "TOKEN_QUOTA_EXCEEDED"
assert "12/10" in message
diff --git a/tests/unit/knowledge/test_retrieve.py b/tests/unit/knowledge/test_retrieve.py
index 8102ab3258..d2f7299381 100644
--- a/tests/unit/knowledge/test_retrieve.py
+++ b/tests/unit/knowledge/test_retrieve.py
@@ -79,3 +79,21 @@ def test_retrieve_context_skips_empty_non_text_turn() -> None:
)
assert context == ""
+
+
+def test_format_context_cites_only_documents_inside_the_budget() -> None:
+ base = SimpleNamespace(id="kb", name="KB")
+ doc_a = SimpleNamespace(id="a", filename="a.md", path="a.md")
+ doc_b = SimpleNamespace(id="b", filename="b.md", path="b.md")
+ hit_a = SimpleNamespace(text="alpha " * 40, ordinal=0)
+ hit_b = SimpleNamespace(text="beta " * 40, ordinal=0)
+
+ text = retrieve_module._format_context(
+ [(base, hit_a, doc_a), (base, hit_b, doc_b)],
+ char_budget=80,
+ locale="en",
+ )
+
+ marker = text.split(CITATIONS_MARKER_PREFIX, 1)[1]
+ assert "a.md" in marker
+ assert "b.md" not in marker
diff --git a/tests/unit/test_env_file.py b/tests/unit/test_env_file.py
index cfcfbf53c2..de3792c15a 100644
--- a/tests/unit/test_env_file.py
+++ b/tests/unit/test_env_file.py
@@ -124,6 +124,16 @@ def test_multiline_value_survives_roundtrip() -> None:
}
+def test_unclosed_quote_does_not_swallow_following_assignments() -> None:
+ text = 'BROKEN="no-close\nNEXT=1\nOK=2\n'
+
+ parsed = parse_env_text(text)
+
+ assert parsed["NEXT"] == "1"
+ assert parsed["OK"] == "2"
+ assert "NEXT" not in parsed["BROKEN"]
+
+
def test_quoted_value_with_inner_quote_does_not_swallow_following_lines() -> None:
"""Only an unterminated quote continues onto the next line."""
text = 'MALFORMED="abc"def\nNEXT=1\n'
diff --git a/uv.lock b/uv.lock
index a5df8e909d..42f0236364 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2621,6 +2621,7 @@ dependencies = [
{ name = "pypinyin" },
{ name = "python-docx" },
{ name = "python-pptx" },
+ { name = "python-socks" },
{ name = "questionary" },
{ name = "rich" },
{ name = "scalar-fastapi" },
@@ -2726,6 +2727,7 @@ requires-dist = [
{ name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6" },
{ name = "python-docx", specifier = ">=1.2.0" },
{ name = "python-pptx", specifier = ">=1.0" },
+ { name = "python-socks", specifier = ">=2.4" },
{ name = "questionary", specifier = ">=2.0" },
{ name = "rapidocr", marker = "extra == 'knowledge-ocr'", specifier = ">=3.4,<4" },
{ name = "rich", specifier = ">=13.7" },
@@ -4115,6 +4117,15 @@ asyncio-client = [
{ name = "aiohttp" },
]
+[[package]]
+name = "python-socks"
+version = "3.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bb/5d/57f4f34cba6cd33dabc557096225487bfd977f8831d789b2b81a885f9ed3/python_socks-3.2.1.tar.gz", hash = "sha256:d21618ae6c6734d357be83263b3791666d12af59480ace8f48f2b5fcc8edc987", size = 39934, upload-time = "2026-10-31T11:56:08.117Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/a6/175dbba852d77cf184dd6095a23dd0fe654898be74fb9dc6bfa16e89088f/python_socks-3.2.1-py3-none-any.whl", hash = "sha256:db2c37d4f7aeebfbba91d2d7670718b2d516061b34296fa8498c6f671e87c504", size = 49553, upload-time = "2026-10-31T11:56:06.54Z" },
+]
+
[[package]]
name = "python-telegram-bot"
version = "22.8"