diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index 79bbd8946f..ed9ebf8896 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -3131,12 +3131,16 @@ export async function updateGoalOwnership(body: { goal_id: string; mode: Executi const privateAgentSessionSchema = z.object({session_id: z.string(), goal_id: z.string(), agent_id: z.string(), executor_endpoint_id: z.string()}); const privateAgentTargetSchema = privateAgentSessionSchema.extend({target_ref: z.string(), host_ref: z.string(), goal_instance_id: z.string().nullable()}); -const privateConversationSchema = z.object({ +const privateConversationSettingsRowSchema = z.object({ binding_id: z.string(), app_ref: z.string(), context_kind: z.enum(["project", "steward"]), project_ref: z.string(), project_title: z.string(), context_available: z.boolean(), executor_endpoint_id: z.string(), - grant: z.enum(["workspace_read", "workspace_write", "portfolio_read"]), goal_count: z.number().int().default(0), listener_status: z.string(), + grant: z.enum(["workspace_read", "workspace_write", "portfolio_read"]), goal_count: z.number().int().default(0), goal_scope: z.enum(["all_registered", "selected"]).nullable().optional(), audience: z.enum(["owner", "group"]).default("owner"), group_count: z.number().int().default(0), + agent_targets: z.array(privateAgentTargetSchema).default([]), +}); +const privateConversationDiagnosticsRowSchema = z.object({ + binding_id: z.string(), listener_status: z.string(), pending_count: z.number().int(), recovery_count: z.number().int(), ingress: z.object({status: z.enum(["unobserved", "verified", "gap", "unavailable"]), last_checked_at: z.number().nullable(), last_complete_at: z.number().nullable(), @@ -3169,14 +3173,21 @@ const privateConversationSchema = z.object({ z.object({available: z.literal(false), error_code: z.string(), execution_available: z.boolean().optional(), execution_error_code: z.string().optional()}), ]).optional(), - agent_candidates: z.array(privateAgentSessionSchema).default([]), agent_targets: z.array(privateAgentTargetSchema).default([]), + agent_candidates: z.array(privateAgentSessionSchema).default([]), }); +const privateConversationSchema = privateConversationSettingsRowSchema.extend(privateConversationDiagnosticsRowSchema.shape); const privateConversationStopRecoverySchema = z.object({binding_id: z.string(), project_ref: z.string(), project_title: z.string(), pending_count: z.number().int().positive()}); export type PrivateConversationStopRecovery = z.infer; -const privateConversationsSchema = z.object({ok: z.literal(true), revision: z.number().int(), +const privateConversationSettingsSchema = z.object({ok: z.literal(true), revision: z.number().int(), app_steward_binding_id: z.string().regex(/^[a-f0-9]{24}$/).nullable().default(null), + connections: z.array(privateConversationSettingsRowSchema)}); +const privateConversationDiagnosticsSchema = z.object({ok: z.literal(true), revision: z.number().int(), + connections: z.array(privateConversationDiagnosticsRowSchema), stop_recoveries: z.array(privateConversationStopRecoverySchema)}); +const privateConversationsSchema = privateConversationSettingsSchema.extend({ connections: z.array(privateConversationSchema), stop_recoveries: z.array(privateConversationStopRecoverySchema).default([])}); +export type PrivateConversationSettings = z.infer; +export type PrivateConversationDiagnostics = z.infer; export type PrivateConversation = z.infer; const boundConversationSourceSchema = privateConversationSchema.pick({ binding_id: true, app_ref: true, context_kind: true, project_title: true, executor_endpoint_id: true, @@ -3199,6 +3210,23 @@ export async function resolveBoundConversation(target: BoundConversationTarget, export async function fetchPrivateConversations(signal?: AbortSignal) { return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { signal })); } + +export async function fetchPrivateConversationSettings(signal: AbortSignal) { + return privateConversationSettingsSchema.parse( + await requestJson("/api/chat/lark/private-conversations?view=settings", {signal})); +} + +export async function fetchPrivateConversationDiagnostics(settings: PrivateConversationSettings, signal: AbortSignal) { + const diagnostics = privateConversationDiagnosticsSchema.parse(await requestJson( + `/api/chat/lark/private-conversations?view=diagnostics&revision=${settings.revision}`, {signal})); + const observedBindingIds = new Set(diagnostics.connections.map(row => row.binding_id)); + if (diagnostics.revision !== settings.revision || diagnostics.connections.length !== settings.connections.length + || observedBindingIds.size !== diagnostics.connections.length + || !settings.connections.every(row => observedBindingIds.has(row.binding_id))) { + throw new Error("Conversation bindings changed during the read"); + } + return diagnostics; +} const appStewardTargetSchema = z.union([ z.object({ok: z.literal(true), binding_id: z.null(), session_id: z.null()}), z.object({ok: z.literal(true), binding_id: z.string().regex(/^[a-f0-9]{24}$/), @@ -3216,7 +3244,7 @@ export async function selectAppSteward(bindingId: string | null, revision: numbe return result; } export async function connectPrivateConversation(appRef: string, projectRef: string, executor: string, contextKind: "project" | "steward" = "project", projectGrant: "workspace_read" | "workspace_write" = "workspace_write", groupIds?: string[]) { - return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { + return z.object({ok: z.literal(true)}).parse(await requestJson("/api/chat/lark/private-conversations?response=minimal", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({app_ref: appRef, project_ref: projectRef, executor_endpoint_id: executor, context_kind: contextKind, project_grant: projectGrant, ...(contextKind === "steward" ? {goal_scope: "all_registered"} : {}), @@ -3224,7 +3252,7 @@ export async function connectPrivateConversation(appRef: string, projectRef: str })); } export async function disconnectPrivateConversation(bindingId: string, revision: number) { - return privateConversationsSchema.parse(await requestJson("/api/chat/lark/private-conversations", { + return z.object({ok: z.literal(true)}).parse(await requestJson("/api/chat/lark/private-conversations?response=minimal", { method: "DELETE", headers: {"Content-Type": "application/json"}, body: JSON.stringify({binding_id: bindingId, revision}), })); } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx index a895b0b681..43549a1332 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx @@ -116,12 +116,10 @@ export const ChannelTimeline = memo(function ChannelTimeline({ useLayoutEffect(() => { if (!findMessageId) return; readMessage(); - const frame = requestAnimationFrame(() => { - const row = Array.from(timeline.current?.querySelectorAll("[data-timeline-id]") ?? []) - .find(node => node.dataset.timelineId === findMessageId); - row?.scrollIntoView({block: "start"}); - }); - return () => cancelAnimationFrame(frame); + // Keep the scroll with the selection so a later user scroll stays put. + const row = Array.from(timeline.current?.querySelectorAll("[data-timeline-id]") ?? []) + .find(node => node.dataset.timelineId === findMessageId); + row?.scrollIntoView({block: "start"}); }, [findMessageId, findNavigation]); const presentedItems = items.filter(item => { // The visible draft already owns this confirmation and recovery entry. diff --git a/apps/presentation/dashboard/src/features/personal-workspace/private-conversation-panel.tsx b/apps/presentation/dashboard/src/features/personal-workspace/private-conversation-panel.tsx index 94bbc9314c..8a3d9603bf 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/private-conversation-panel.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/private-conversation-panel.tsx @@ -1,10 +1,10 @@ import {MessageSquareText, RefreshCw} from "lucide-react"; import {ContextHelp} from "./context-help"; import {useEffect, useRef, useState} from "react"; -import {connectPrivateConversation, disconnectPrivateConversation, fetchPrivateConversations, +import {ChatApiError, connectPrivateConversation, disconnectPrivateConversation, fetchPrivateConversationSettings, fetchPrivateConversationDiagnostics, changePrivateAgentTarget, changeOwnerNotifications, prepareManagedSteward, configureStewardMonitor, configureStewardReport, fetchChatProjects, fetchChatCapabilities, fetchLarkGroupChats, type PrivateConversation, discoverBoundChatSession, selectAppSteward, type BoundConversationTarget, - type ChatProject, type LarkApp, type PrivateConversationStopRecovery} from "../../data/chat"; + type ChatProject, type LarkApp, type PrivateConversationSettings, type PrivateConversationDiagnostics} from "../../data/chat"; import {useWorkspaceI18n} from "./i18n"; import {StewardManagedMode} from "./steward-managed-mode"; import "./private-conversation.css"; @@ -14,11 +14,17 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[ const zh = locale === "zh-CN"; const [projects, setProjects] = useState([]); const [executors, setExecutors] = useState([]); - const [rows, setRows] = useState([]); - const [connectionsLoading, setConnectionsLoading] = useState(true); - const [recoveries, setRecoveries] = useState([]); - const [revision, setRevision] = useState(0); - const [appStewardBindingId, setAppStewardBindingId] = useState(null); + const [settings, setSettings] = useState(null); + const [diagnostics, setDiagnostics] = useState(null); + const [settingsUnavailable, setSettingsUnavailable] = useState(false); + const [diagnosticsUnavailable, setDiagnosticsUnavailable] = useState(false); + const [refreshAfterMutation, setRefreshAfterMutation] = useState(0); + const currentDiagnostics = diagnostics?.revision === settings?.revision ? diagnostics : null; + const observed = new Map(currentDiagnostics?.connections.map(row => [row.binding_id, row])); + const rows = (settings?.connections ?? []).map(row => ({...row, ...observed.get(row.binding_id)})); + const recoveries = currentDiagnostics?.stop_recoveries ?? []; + const revision = settings?.revision ?? 0; + const appStewardBindingId = settings?.app_steward_binding_id ?? null; const [app, setApp] = useState(""); const [project, setProject] = useState(""); const [executor, setExecutor] = useState(""); @@ -34,6 +40,7 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[ const [busy, setBusy] = useState(false); const [opening, setOpening] = useState(null); const openController = useRef(null); + const connectionRead = useRef<{cancel: () => void; refresh: () => void} | null>(null); useEffect(() => () => openController.current?.abort(), []); async function openOriginal(bindingId: string) { setOpening(bindingId); setError(""); @@ -47,11 +54,6 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[ finally { if (!controller.signal.aborted) setOpening(null); } } - async function refresh() { - const state = await fetchPrivateConversations(); - setRows(state.connections); setRecoveries(state.stop_recoveries); setRevision(state.revision); - setAppStewardBindingId(state.app_steward_binding_id); - } useEffect(() => { let active = true; const failed = (error: unknown) => {if (active) setError(String(error));}; @@ -64,18 +66,87 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[ const choices = (capabilities.adapters ?? []).filter(row => row.available).map(row => row.agent_id); setExecutors(choices); setExecutor(choices.includes("codex") ? "codex" : choices[0] ?? ""); }}).catch(failed); - let timer: ReturnType; - async function readConnections() { + return () => {active = false;}; + }, []); + + useEffect(() => { + if (busy) return; + let active = true; + let settingsRequest: AbortController | undefined; + let diagnosticsRequest: {controller: AbortController; revision: number} | undefined; + let timer: ReturnType | undefined; + function cancel() { + active = false; + clearTimeout(timer); + settingsRequest?.abort(); + diagnosticsRequest?.controller.abort(); + } + function scheduleSettings(delayMs: number) { + clearTimeout(timer); + timer = setTimeout(() => void readSettings(), delayMs); + } + function bindingChanged(cause: unknown) { + return cause instanceof ChatApiError && cause.payload.http_status === 409; + } + async function readDiagnostics(current: PrivateConversationSettings) { + const controller = new AbortController(); + diagnosticsRequest = {controller, revision: current.revision}; + const {signal} = controller; + setDiagnosticsUnavailable(false); try { - const state = await fetchPrivateConversations(AbortSignal.timeout(5000)); - if (active) {setRows(state.connections); setRecoveries(state.stop_recoveries); setRevision(state.revision); - setAppStewardBindingId(state.app_steward_binding_id);} - } catch (error) {failed(error);} - finally {if (active) {setConnectionsLoading(false); timer = setTimeout(() => void readConnections(), 5000);}} + const fresh = await fetchPrivateConversationDiagnostics(current, AbortSignal.any([signal, AbortSignal.timeout(30000)])); + if (!signal.aborted) setDiagnostics(fresh); + } catch (cause) { + if (signal.aborted) return; + setDiagnostics(null); + if (bindingChanged(cause)) { + settingsRequest?.abort(); + setSettings(null); + setSettingsUnavailable(false); + scheduleSettings(500); + } else { + setDiagnosticsUnavailable(true); + } + } finally { + if (diagnosticsRequest?.controller === controller) diagnosticsRequest = undefined; + } } - void readConnections(); - return () => {active = false; clearTimeout(timer);}; - }, []); + async function readSettings(refreshDiagnostics = false) { + if (!active) return; + clearTimeout(timer); + settingsRequest?.abort(); + if (refreshDiagnostics) diagnosticsRequest?.controller.abort(); + const request = new AbortController(); + settingsRequest = request; + const {signal} = request; + let nextReadMs = 5000; + try { + const current = await fetchPrivateConversationSettings(AbortSignal.any([signal, AbortSignal.timeout(5000)])); + if (signal.aborted) return; + setSettings(current); + setSettingsUnavailable(false); + // Keep polling authorization while a single diagnostics read for this revision is in flight. + if (refreshDiagnostics || diagnosticsRequest?.revision !== current.revision) { + diagnosticsRequest?.controller.abort(); + void readDiagnostics(current); + } + } catch (cause) { + if (signal.aborted) return; + diagnosticsRequest?.controller.abort(); + diagnosticsRequest = undefined; + setDiagnostics(null); + setSettings(null); + const changed = bindingChanged(cause); + setSettingsUnavailable(!changed); + if (changed) nextReadMs = 500; + } finally { + if (!signal.aborted) scheduleSettings(nextReadMs); + } + } + connectionRead.current = {cancel, refresh: () => void readSettings(true)}; + void readSettings(); + return () => {cancel(); connectionRead.current = null;}; + }, [busy, refreshAfterMutation]); useEffect(() => { let active = true; @@ -101,12 +172,15 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[ } async function act(operation: () => Promise) { + connectionRead.current?.cancel(); + setDiagnostics(null); setBusy(true); setError(""); try {await operation();} catch (error) {setError(String(error));} finally { // A failed stop may follow a committed revocation. Read its current // revision and exact recovery target even when the mutation returned 400. - try {await refresh();} catch (error) {setError(String(error));} + setSettings(null); + setRefreshAfterMutation(value => value + 1); setBusy(false); } } @@ -127,8 +201,13 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[

{zh ? "发送文字、图片或图文消息开始;后续消息进入原会话队列。/status 查看工作区、角色与持久排队状态,/help 查看用法与解绑入口,/stop 停止当前聊天执行,/new 开启新会话。文件、音视频、附在控制命令或已选择 Agent 上的图片会明确提示暂不支持。" : "Send text, images or image/text posts to begin; follow-ups queue in the same Session. /status shows the workspace, role and durable queue, /help explains commands and where to unbind, /stop stops the current Chat Turn, /new starts a new conversation. Files, audio/video, and images sent with control commands or to a selected attached Agent receive an explicit unsupported response."}

{audience === "owner" ?

{zh ? "管家新委托:/delegate --tokens N 具体目标。先读预览,再用原私聊的完整 /confirm 命令确认;15 分钟过期。原生执行保持只读,总 token 上限可能被运行中的请求超过;没有默认定时调度。回执提供 /stop-commission 停止和 /resume-commission 恢复命令;恢复保留原线程及累计用量。" : "Steward commission: /delegate --tokens N objective. Read the preview, then use its full /confirm command in the original private Chat within 15 minutes. Native execution remains read-only; in-flight requests can exceed the total token allowance. No default schedule. Receipts provide /stop-commission and /resume-commission commands; recovery retains the original thread and cumulative usage."}

: null} - + + {settings && !currentDiagnostics ?

{diagnosticsUnavailable + ? (zh ? "监听、送达和停止状态暂不可用。可刷新重试。" : "Listener, delivery and stop status are unavailable. Refresh to retry.") + : (zh ? "正在读取监听、送达和停止状态…" : "Reading listener, delivery and stop status…")}

: null} {appStewardBindingId !== null && !rows.some(row => row.binding_id === appStewardBindingId) ?

{zh ? "已选的 App 对话来源已失效。" : "The selected App Conversation source is unavailable."}

)} - {rows.length === 0 ?

{connectionsLoading ? (zh ? "正在读取已有连接…" : "Reading existing connections…") - : error ? (zh ? "连接读取暂不可用,请刷新重试。" : "Connections unavailable. Refresh to retry.") - : (zh ? "尚未连接助手。" : "No assistant connected.")}

: null} -
+ {settingsUnavailable ?

{zh ? "连接读取暂不可用,请刷新重试。" : "Connections unavailable. Refresh to retry."}

+ : settings === null ?

{zh ? "正在读取已有连接…" : "Reading existing connections…"}

+ : rows.length === 0 ?

{zh ? "尚未连接助手。" : "No assistant connected."}

: null} +
{zh ? "连接助手" : "Connect an assistant"}
@@ -261,20 +341,24 @@ export function PrivateConversationPanel({apps, onOpenOriginal}: {apps: LarkApp[ ; } -function PrivateAgentTargets({row, revision, zh, busy, act}: {row: PrivateConversation; revision: number; zh: boolean; +function PrivateAgentTargets({row, revision, zh, busy, act}: { + row: PrivateConversationSettings["connections"][number] & Partial>; + revision: number; zh: boolean; busy: boolean; act: (operation: () => Promise) => Promise}) { const [session, setSession] = useState(""); - const candidates = row.agent_candidates.filter(item => !row.agent_targets.some(target => target.session_id === item.session_id)); + const candidates = row.agent_candidates?.filter(item => !row.agent_targets.some(target => target.session_id === item.session_id)); return

{zh ? "直连注册 Agent:只授权确切的已有 attached Session。消息进入原宿主队列;此处不创建 Agent、不继承其它目标或提高宿主权限。一个 Session 的 App 受众固定,撤销后也不能换给另一 App。" : "Direct registered Agent: grant an exact existing attached Session. Messages enter its original host queue; this creates no Agent, inherits no other Goals and raises no host permission. The Session audience remains fixed even after revocation."}

{row.agent_targets.map(target =>

{target.agent_id} · {target.goal_id}
/agent {target.target_ref}

)} + {candidates !== undefined ? <> - {row.agent_candidates.length === 0 ?

{zh ? "暂无此工作区的可用 attached Agent 会话。请先在原宿主完成注册和 attached-session-bind;普通聊天仍可直接使用,不需要创建 Goal。" : "No eligible attached Agent Session in this workspace. Register and bind it in its original host first; ordinary Chat remains available without a Goal."}

: null} + {row.agent_candidates?.length === 0 ?

{zh ? "暂无此工作区的可用 attached Agent 会话。请先在原宿主完成注册和 attached-session-bind;普通聊天仍可直接使用,不需要创建 Goal。" : "No eligible attached Agent Session in this workspace. Register and bind it in its original host first; ordinary Chat remains available without a Goal."}

: null} + : null}

{zh ? "私聊 /agents 查看当前可用授权,复制完整 /agent 命令选择;/project 返回原项目对话。实时停止或新建 Agent 会话请在原宿主处理。" : "Use /agents to list usable grants, select with the full /agent command, and /project to return to project Chat. Stop or create Agent Sessions in their original host."}

; } diff --git a/examples/personal-workspace-browser/private-steward-scope.mjs b/examples/personal-workspace-browser/private-steward-scope.mjs index fe5a85e44b..2a725c9d47 100644 --- a/examples/personal-workspace-browser/private-steward-scope.mjs +++ b/examples/personal-workspace-browser/private-steward-scope.mjs @@ -15,7 +15,7 @@ export const privateStewardScopeScenario = { beforeGoto: async (_api, page) => { await page.route("**/api/chat/projects", route => route.fulfill({json: projectsAvailable ? {ok: true, projects: [{project_ref: row.project_ref, title: row.project_title, grant: "workspace_write"}]} : {ok: true}})); - await page.route("**/api/chat/lark/private-conversations", async route => { + await page.route(url => url.pathname === "/api/chat/lark/private-conversations", async route => { if (route.request().method() === "POST") { const body = route.request().postDataJSON(); if (body.app_ref !== row.app_ref || body.project_ref !== row.project_ref @@ -29,7 +29,19 @@ export const privateStewardScopeScenario = { } Object.assign(row, {goal_scope: "all_registered", goal_count: 150}); } - await route.fulfill({json: {ok: true, revision: writes.length + 1, connections: hasConnection ? [row, ...extraRows] : []}}); + const revision = writes.length + 1; + const connections = hasConnection ? [row, ...extraRows] : []; + const query = new URL(route.request().url()).searchParams; + if (query.get("view") === "diagnostics") { + if (query.get("revision") !== String(revision)) { + throw new Error("Diagnostics did not use the displayed authorization revision"); + } + const diagnostics = connections.map(({binding_id, listener_status, pending_count, recovery_count, ingress, owner_attention}) => + ({binding_id, listener_status, pending_count, recovery_count, ingress, owner_attention})); + await route.fulfill({json: {ok: true, revision, connections: diagnostics, stop_recoveries: []}}); + return; + } + await route.fulfill({json: {ok: true, revision, connections}}); }); }, }); diff --git a/loopx/extensions/lark/private_conversation_api.py b/loopx/extensions/lark/private_conversation_api.py index 1030245ccd..54231b66bf 100644 --- a/loopx/extensions/lark/private_conversation_api.py +++ b/loopx/extensions/lark/private_conversation_api.py @@ -33,61 +33,101 @@ def _private_listener_status(self, transport_ref: str, lark_health: Mapping[str, return status if isinstance(status, str) and status in ("starting", "listening", "retrying", "stopped", "standby", "inactive") else "unknown" def _private_conversations(self) -> None: + args = parse_qs(urlsplit(getattr(self, "path", "")).query, keep_blank_values=True) + view = args.get("view") if getattr(self, "command", "GET") == "GET" else None + if view is not None and view not in (["authorization"], ["settings"], ["diagnostics"]): + self._send_error("Unknown private conversation view", status=400) + return + bindings = self.server.runtime_controller.project_contexts.conversation_bindings current = bindings.read() - titles = {row["project_ref"]: Path(row["workspace_path"]).name - for row in self.server.runtime_controller.project_contexts.available()} - # Source adapters revalidate this projection before publication. They - # need current grants, not listener probes or historical delivery scans. - # This read grants nothing; the caller retains its own identity, Turn, - # revocation, publication fence and compare-and-swap checks. - view = parse_qs(urlsplit(getattr(self, "path", "")).query, keep_blank_values=True).get("view") - if view is not None: - if view != ["authorization"]: - self._send_error("Unknown private conversation view", status=400) + revision = current["revision"] + diagnostic_read = view == ["diagnostics"] + if diagnostic_read: + requested = args.get("revision", []) + if len(requested) != 1 or not requested[0].isascii() or not requested[0].isdecimal(): + self._send_error("A binding revision is required for private conversation diagnostics", status=400) return - if bindings.read() != current: + if requested != [str(revision)]: self._send_error("Conversation bindings changed during the read", status=409) return - self._send_json({"ok": True, "revision": current["revision"], "connections": [ - {"binding_id": row["binding_id"], "app_ref": row["transport_ref"], - "context_kind": row["context_kind"], "project_ref": row["project_ref"], - "context_available": row["project_ref"] in titles, - "executor_endpoint_id": row["executor_endpoint_id"], "grant": row["grant"], - "audience": row.get("audience", "owner")} - for row in current["bindings"]]}) + titles = {row["project_ref"]: Path(row["workspace_path"]).name + for row in self.server.runtime_controller.project_contexts.available()} + + def changed() -> bool: + if view is not None and bindings.read() != current: + self._send_error("Conversation bindings changed during the read", status=409) + return True + return False + + def send(payload: dict[str, Any]) -> None: + if not changed(): + self._send_json({"ok": True, "revision": revision, **payload}) + + def grant(row: dict[str, Any]) -> dict[str, Any]: + return {"binding_id": row["binding_id"], "app_ref": row["transport_ref"], + "context_kind": row["context_kind"], "project_ref": row["project_ref"], + "context_available": row["project_ref"] in titles, + "executor_endpoint_id": row["executor_endpoint_id"], "grant": row["grant"], + "audience": row.get("audience", "owner")} + + # Source adapters receive a current projection for their own checks. + if view == ["authorization"]: + send({"connections": [grant(row) for row in current["bindings"]]}) return + + def settings(row: dict[str, Any]) -> dict[str, Any]: + return {**grant(row), "project_title": titles.get(row["project_ref"], "Unavailable workspace"), + "group_count": len(row.get("group_refs", [])), + "goal_count": len(bindings.goal_scope_ids(row)), + "goal_scope": row.get("goal_scope", "selected") if row["context_kind"] == "steward" else None, + "agent_targets": row.get("agent_targets", [])} + + selection = {"app_steward_binding_id": current.get("app_steward_binding_id")} + if view == ["settings"]: + send({**selection, "connections": [settings(row) for row in current["bindings"]]}) + return + health = self.server.lark_goal_topic_runtime.health_snapshot() composed = getattr(self.server, "conversation_transports", None) lark_profiles = set(health) - set(composed.transports if composed is not None else {}) deliveries = self.server.lark_private_conversations.health() - self._send_json({"ok": True, "revision": current["revision"], - "app_steward_binding_id": current.get("app_steward_binding_id"), "connections": [ - {"binding_id": row["binding_id"], "app_ref": row["transport_ref"], "context_kind": row["context_kind"], - "project_ref": row["project_ref"], "context_available": row["project_ref"] in titles, "project_title": titles.get(row["project_ref"], "Unavailable workspace"), - "executor_endpoint_id": row["executor_endpoint_id"], "grant": row["grant"], - "audience": row.get("audience", "owner"), "group_count": len(row.get("group_refs", [])), - "goal_count": len(bindings.goal_scope_ids(row)), - "goal_scope": row.get("goal_scope", "selected") if row["context_kind"] == "steward" else None, - "agent_candidates": [{key: item.get(key) for key in ["session_id", "goal_id", "agent_id", "executor_endpoint_id"]} - for item in bindings.agent_candidates(row["binding_id"])], - "agent_targets": row.get("agent_targets", []), - "listener_status": self._private_listener_status(row["transport_ref"], health), - **({"ingress": self.server.lark_private_conversations.ingress.health(row["binding_id"])} - if row.get("audience", "owner") == "owner" - and row["transport_ref"] in lark_profiles - and hasattr(self.server.lark_private_conversations, "ingress") else {}), - **({"owner_attention": self.server.lark_private_conversations.owner_attention.health(row["binding_id"])} - if row["context_kind"] == "steward" and row.get("audience", "owner") == "owner" else {}), - **({"managed_steward": self.server.lark_private_conversations.managed_steward.health(row["binding_id"])} - if row["context_kind"] == "steward" and row.get("audience", "owner") == "owner" - and (row["executor_endpoint_id"] == "codex" or row.get("managed_actor")) - and hasattr(self.server.lark_private_conversations, "managed_steward") else {}), - **deliveries.get(row["binding_id"], {"pending_count": 0, "recovery_count": 0})} - for row in current["bindings"]], + if diagnostic_read and changed(): + return + + def diagnostics(row: dict[str, Any]) -> dict[str, Any]: + transport = self.server.lark_private_conversations + binding_id = row["binding_id"] + owner = row.get("audience", "owner") == "owner" + steward = owner and row["context_kind"] == "steward" + return {"binding_id": binding_id, + "agent_candidates": [{key: item.get(key) for key in ["session_id", "goal_id", "agent_id", "executor_endpoint_id"]} + for item in bindings.agent_candidates(binding_id)], + "listener_status": self._private_listener_status(row["transport_ref"], health), + **({"ingress": transport.ingress.health(binding_id)} + if owner and row["transport_ref"] in lark_profiles and hasattr(transport, "ingress") else {}), + **({"owner_attention": transport.owner_attention.health(binding_id)} if steward else {}), + **({"managed_steward": transport.managed_steward.health(binding_id)} + if steward and (row["executor_endpoint_id"] == "codex" or row.get("managed_actor")) + and hasattr(transport, "managed_steward") else {}), + **deliveries.get(binding_id, {"pending_count": 0, "recovery_count": 0})} + + try: + rows = [diagnostics(row) if diagnostic_read else {**settings(row), **diagnostics(row)} + for row in current["bindings"]] + except StopIteration: + # Agent candidate discovery can lose the binding to a concurrent + # revocation after the delivery scan. + if diagnostic_read and changed(): + return + raise + payload = { + "connections": rows, "stop_recoveries": [{**row, "project_title": titles.get(row["project_ref"], "Unavailable workspace")} - for row in bindings.stop_recoveries(current)]}) + for row in bindings.stop_recoveries(current)], + } + send(payload if diagnostic_read else {**selection, **payload}) def _app_steward(self) -> None: from .conversation_identity import LarkOwnerIdentityUnavailable @@ -118,6 +158,9 @@ def _private_conversation_connect(self) -> None: from .goal_topic_runtime import _active_profile_configs from ...chat_lark_api import build_lark_goal_topic_runtime_snapshot try: + response = parse_qs(urlsplit(getattr(self, "path", "")).query, keep_blank_values=True).get("response") + if response is not None and response != ["minimal"]: + raise ValueError("Unknown private conversation connect response") body = self._read_json() if set(body) - {"context_kind", "project_grant", "goal_scope", "audience", "group_ids"} != {"app_ref", "project_ref", "executor_endpoint_id"}: raise ValueError("select an App, authorized workspace and executor") @@ -185,10 +228,17 @@ def _private_conversation_connect(self) -> None: except (ValueError, OSError, KeyError) as exc: self._send_error(str(exc), status=400) return + if response == ["minimal"]: + # Settings reads back the verified grant and its diagnostics separately. + self._send_json({"ok": True}) + return self._private_conversations() def _private_conversation_disconnect(self) -> None: try: + response = parse_qs(urlsplit(getattr(self, "path", "")).query, keep_blank_values=True).get("response") + if response is not None and response != ["minimal"]: + raise ValueError("Unknown private conversation disconnect response") body = self._read_json() if set(body) != {"binding_id", "revision"}: raise ValueError("disconnect the exact current binding revision") @@ -198,6 +248,11 @@ def _private_conversation_disconnect(self) -> None: except (ValueError, OSError, KeyError) as exc: self._send_error(str(exc), status=400) return + if response == ["minimal"]: + # The caller reads the new settings separately. A diagnostics scan + # must not hold the acknowledgement of an already verified revoke. + self._send_json({"ok": True}) + return self._private_conversations() def _private_conversation_managed_steward(self) -> None: diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py index 1c9d0c59bf..ba52b9bb35 100644 --- a/tests/test_lark_private_conversations.py +++ b/tests/test_lark_private_conversations.py @@ -5236,7 +5236,10 @@ def test_group_status_and_recipient_commands_cannot_expose_private_sessions(ordi @pytest.mark.parametrize("owner_ready", [True, False]) -def test_http_group_setup_observes_membership_reads_back_selection_and_rejects_widening(ordinary, monkeypatch, owner_ready): # noqa: F811 +@pytest.mark.parametrize("response_form", ["legacy", "minimal"]) +def test_http_group_setup_observes_membership_reads_back_selection_and_rejects_widening( + ordinary, monkeypatch, owner_ready, response_form, # noqa: F811 +): from loopx.chat_server import ChatHTTPServer, ChatRequestHandler from loopx.extensions.lark.cli_resolution import LarkCliResolution import loopx.chat_lark_api as api @@ -5266,6 +5269,7 @@ def request(path, body=None): connection.close() path = "/api/chat/lark/private-conversations" + connect_path = f"{path}?response=minimal" if response_form == "minimal" else path body = {"app_ref": "notes-app", "project_ref": runtime.project_contexts.available()[0]["project_ref"], "executor_endpoint_id": "codex", "audience": "group", "group_ids": ["oc_community"]} provider.owner_ready = owner_ready @@ -5274,22 +5278,45 @@ def request(path, body=None): for bad in [{"group_ids": ["oc_not_selected"]}, {"group_ids": []}, {"group_ids": ["oc_community", "oc_community"]}, {"context_kind": "steward"}, {"executor_endpoint_id": "claude-code"}]: - assert request(path, {**body, **bad})[0] == 400 + assert request(connect_path, {**body, **bad})[0] == 400 assert transport.bindings.read() == original and not refreshes - status, response = request(path, body) + health_reads = [] + read_health = transport.health + + def observe_health(): + health_reads.append(True) + return read_health() + + monkeypatch.setattr(transport, "health", observe_health) + status, response = request(connect_path, body) assert status == 200, response + if response_form == "minimal": + assert response == {"ok": True} + assert not health_reads + status, response = request(path) + assert status == 200 + assert health_reads == [True] saved = next(row for row in response["connections"] if row["app_ref"] == "notes-app") assert saved["audience"] == "group" and saved["group_count"] == 1 assert saved["agent_candidates"] == saved["agent_targets"] == [] assert str(ordinary[-1]) not in json.dumps(response) selected = request("/api/chat/lark/chats?app_ref=notes-app")[1]["chats"] assert [(row["chat_id"], row["selected"]) for row in selected] == [("oc_community", True), ("oc_second", False)] - assert request(path, body)[1]["revision"] == response["revision"] + status, retry = request(connect_path, body) + assert status == 200 + if response_form == "minimal": + assert retry == {"ok": True} and health_reads == [True] + else: + assert retry["revision"] == response["revision"] + assert transport.bindings.read()["revision"] == response["revision"] + for malformed in ("", "legacy", "minimal&response=minimal"): + assert request(f"{path}?response={malformed}", body)[0] == 400 + assert transport.bindings.read()["revision"] == response["revision"] assert refreshes == [True, True] assert not store.list_sessions() and not provider.writes if not owner_ready: frozen = transport.bindings.read() - assert request(path, {key: value for key, value in body.items() if key not in {"audience", "group_ids"}})[0] == 400 + assert request(connect_path, {key: value for key, value in body.items() if key not in {"audience", "group_ids"}})[0] == 400 assert transport.bindings.read() == frozen finally: server.shutdown() @@ -5298,7 +5325,8 @@ def request(path, body=None): runtime.close() -def test_http_stop_recovery_reuses_source_revision_without_reusing_turn_state(ordinary, monkeypatch): # noqa: F811 +@pytest.mark.parametrize("progressive_read", [False, True]) +def test_http_stop_recovery_reuses_source_revision_without_reusing_turn_state(ordinary, monkeypatch, progressive_read): # noqa: F811 from loopx.chat_server import ChatHTTPServer, ChatRequestHandler from loopx.control_plane import chat_turn_acceptance, effect_runtime @@ -5350,13 +5378,16 @@ def read_queue(turns, *args, **kwargs): server.lark_goal_topic_runtime = SimpleNamespace(health_snapshot=lambda: {}, close=lambda: None) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() + path = "/api/chat/lark/private-conversations" + if progressive_read: + path += f"?view=diagnostics&revision={transport.bindings.read()['revision']}" def snapshot(): revision_reads.clear() queue_selections.clear() connection = http.client.HTTPConnection(*server.server_address, timeout=15) try: - connection.request("GET", "/api/chat/lark/private-conversations") + connection.request("GET", path) response = connection.getresponse() assert response.status == 200 result = json.loads(response.read()) @@ -6732,6 +6763,96 @@ def changed_during_read(): runtime.close() +def test_http_settings_load_while_delivery_is_slow_and_reject_revoked_diagnostics(ordinary, monkeypatch): # noqa: F811 + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + + store, runtime, provider, transport = connect(ordinary) + bindings = transport.bindings + before = bindings.read() + revision = before["revision"] + removed = before["bindings"][0]["binding_id"] + sessions = store.list_sessions() + entered, release = threading.Event(), threading.Event() + health = transport.health + refreshes = [] + + def slow_health(): + entered.set() + assert release.wait(10) + return health() + + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.chat_store, server.runtime_controller, server.verbose = store, runtime, False + server.lark_private_conversations = transport + server.lark_goal_topic_runtime = SimpleNamespace( + health_snapshot=lambda: {}, refresh=lambda: refreshes.append(True), close=lambda: None) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + def read(query, *, method="GET", body=None): + connection = http.client.HTTPConnection(*server.server_address, timeout=15) + try: + connection.request(method, "/api/chat/lark/private-conversations" + query, + body=json.dumps(body) if body is not None else None, + headers={"Content-Type": "application/json"} if body is not None else {}) + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + detail_url = f"?view=diagnostics&revision={revision}" + try: + assert read("?view=diagnostics")[0] == 400 + assert read(f"{detail_url}&revision={revision}")[0] == 400 + legacy_status, legacy = read("") + status, diagnostics = read(detail_url) + assert legacy_status == status == 200 + assert legacy["stop_recoveries"] == diagnostics["stop_recoveries"] + monkeypatch.setattr(transport, "health", slow_health) + with ThreadPoolExecutor(max_workers=2) as executor: + delayed = executor.submit(read, detail_url) + try: + assert entered.wait(5) + status, settings = read("?view=settings") + assert status == 200 and not delayed.done() + assert settings["revision"] == revision + assert settings["app_steward_binding_id"] == legacy["app_steward_binding_id"] + assert "stop_recoveries" not in settings + assert all("pending_count" not in row and "agent_candidates" not in row for row in settings["connections"]) + combined = [{**row, **details} for row, details in zip( + settings["connections"], diagnostics["connections"], strict=True)] + assert combined == legacy["connections"] + + body = {"binding_id": removed, "revision": revision} + mutation = executor.submit(read, "?response=minimal", method="DELETE", body=body) + assert mutation.result(timeout=4) == (200, {"ok": True}) + assert not delayed.done() + status, after = read("?view=settings") + assert status == 200 and after["revision"] > revision + assert removed not in {row["binding_id"] for row in after["connections"]} + assert read(detail_url)[0] == 409 # A stale caller never waits for the scan. + assert read("?response=minimal", method="DELETE", body=body)[0] == 400 + finally: + release.set() + status, late = delayed.result(timeout=12) + assert status == 409 and "connections" not in late + remaining, = after["connections"] + body = {"binding_id": remaining["binding_id"], "revision": after["revision"]} + invalid_status, _ = read("?response=minimal&response=legacy", method="DELETE", body=body) + assert invalid_status == 400 and read("?view=settings")[1] == after + status, legacy_disconnect = read("", method="DELETE", body=body) + assert status == 200 and legacy_disconnect["revision"] > after["revision"] + assert legacy_disconnect["connections"] == [] and "stop_recoveries" in legacy_disconnect + assert refreshes == [True, True] + assert store.list_sessions() == sessions + assert not provider.writes + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + runtime.close() + + def test_rendered_cli_text_is_preserved_and_source_type_must_agree(ordinary): # noqa: F811 store, runtime, provider, transport = connect(ordinary) try: