Skip to content

Commit ce190b5

Browse files
authored
Merge pull request #10078 from loopx-project/codex/read-lark-material-disposition
Look up a captured Lark message’s committed disposition
2 parents 494239f + 52adf9a commit ce190b5

16 files changed

Lines changed: 1642 additions & 62 deletions

‎apps/presentation/dashboard/src/features/personal-workspace/goal-capability-settings.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { withReportScheduleTimezone } from "./periodic-report-schedule-field";
1818
import {PeriodicReportSessionField} from "./periodic-report-session-field";
1919
import { localizeCapability, localizedCapabilityFieldCopy } from "./capability-localization";
2020
import { orderCapabilitiesForPresentation, canEditCapability, CapabilityCatalogNavigation, CapabilityConfigurationSummary, CapabilityDetailHeader, CapabilityEditorStatus, CapabilityConfigurationHelp } from "./capability-workbench";
21+
import { LarkMaterialLookup } from "./lark-material-lookup";
2122
import { GoalAutoNotifyToggle } from "./notification-settings-panel";
2223
import { DecisionContextWorkbench } from "./decision-context-workbench";
2324
import { rewardMemoryBindingStatus, rewardMemoryScopeDraft, rewardMemoryWriteValue } from "./reward-memory-settings";
@@ -28,6 +29,7 @@ type CapabilityCatalogProps = Readonly<{
2829
callbacks: PersonalWorkspaceCallbacks;
2930
catalog: CapabilityConfigurationCatalog;
3031
goalId: string;
32+
registeredAgentIds: readonly string[];
3133
loading: boolean;
3234
readbackLoading: boolean;
3335
onApplied: () => Promise<void>;
@@ -297,7 +299,7 @@ function CapabilityMutationFeedback({ mutationError, onApplied, partialWrite, re
297299
);
298300
}
299301

300-
function CapabilityCatalog({ callbacks, catalog, goalId, loading, readbackLoading, notification, onApplied, onNotificationChanged }: CapabilityCatalogProps) {
302+
function CapabilityCatalog({ callbacks, catalog, goalId, registeredAgentIds, loading, readbackLoading, notification, onApplied, onNotificationChanged }: CapabilityCatalogProps) {
301303
const { locale, t } = useWorkspaceI18n();
302304
const orderedCapabilities = useMemo(
303305
() => orderCapabilitiesForPresentation(
@@ -433,6 +435,10 @@ function CapabilityCatalog({ callbacks, catalog, goalId, loading, readbackLoadin
433435
</section>
434436
) : null}
435437

438+
{selected.capability_id === "lark_event_inbox" && selected.current?.enabled === true && !loading ? (
439+
<LarkMaterialLookup key={goalId} goalId={goalId} agents={registeredAgentIds} />
440+
) : null}
441+
436442
{editorAvailable ? <>
437443
{editorMode === "json" || !localizedSelected.configuration_editor.fields.some((field) => field.key === "enabled" && field.input_kind === "boolean") || (selected.capability_id === "reward_memory" && !draft.agent_id) ? (
438444
<div className="personal-capability-editor-mode">
@@ -524,9 +530,10 @@ function CapabilityCatalog({ callbacks, catalog, goalId, loading, readbackLoadin
524530
);
525531
}
526532

527-
export function GoalCapabilitySettings({ callbacks, goalId, notification, onChanged }: Readonly<{
533+
export function GoalCapabilitySettings({ callbacks, goalId, registeredAgentIds = [], notification, onChanged }: Readonly<{
528534
callbacks: PersonalWorkspaceCallbacks;
529535
goalId?: string | null;
536+
registeredAgentIds?: readonly string[];
530537
notification?: WorkspaceGoalNotification;
531538
onChanged: () => void;
532539
}>) {
@@ -572,6 +579,7 @@ export function GoalCapabilitySettings({ callbacks, goalId, notification, onChan
572579
<CapabilityCatalog
573580
callbacks={callbacks}
574581
catalog={inspection.capability_catalog}
582+
registeredAgentIds={registeredAgentIds}
575583
goalId={goalId}
576584
loading={loading || Boolean(error)}
577585
readbackLoading={loading}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { useEffect, useRef, useState, type FormEvent } from "react";
2+
import { z } from "zod";
3+
import { ChatApiError, requestJson } from "../../data/chat";
4+
import { useWorkspaceI18n } from "./i18n";
5+
6+
const outcomes = {
7+
working_session_turn: ["已送入工作会话", "Sent to a working session"],
8+
todo_update: ["已更新任务", "Task updated"],
9+
authority_update: ["已更新权威记录", "Authority record updated"],
10+
design_update: ["已更新设计", "Design updated"],
11+
no_follow_up: ["无需跟进", "No follow-up"],
12+
} as const;
13+
const statuses = {
14+
pending: ["待处置", "Awaiting review"],
15+
not_captured: ["所选信源未收录此消息", "Message missing from the selected source"],
16+
ambiguous_route: ["多个信源收录了此消息,请指定信源路由", "Multiple sources captured this message. Enter a source route."],
17+
processed_without_receipt: ["消息已处理,缺少处置回执", "Message processed without a disposition receipt"],
18+
not_material_review: ["此消息不适用材料处置", "Material review does not apply to this message"],
19+
inbox_unavailable: ["收件箱不可用", "Inbox unavailable"],
20+
readback_unavailable: ["无法核实处置回执", "Disposition receipt could not be verified"],
21+
} as const;
22+
const lookupResult = z.discriminatedUnion("status", [
23+
z.object({status: z.literal("committed"), receipt: z.object({
24+
effect_kind: z.enum(Object.keys(outcomes) as [keyof typeof outcomes, ...(keyof typeof outcomes)[]]),
25+
effect_ref: z.string().regex(/^sha256:[0-9a-f]{24}$/),
26+
})}),
27+
z.object({status: z.enum(Object.keys(statuses) as [keyof typeof statuses, ...(keyof typeof statuses)[]])}),
28+
]);
29+
30+
export function LarkMaterialLookup({goalId, agents}: Readonly<{goalId: string; agents: readonly string[]}>) {
31+
const {locale} = useWorkspaceI18n();
32+
const zh = locale === "zh-CN";
33+
const [agent, setAgent] = useState("");
34+
const [message, setMessage] = useState("");
35+
const [route, setRoute] = useState("");
36+
const [result, setResult] = useState<z.infer<typeof lookupResult> | null>(null);
37+
const [error, setError] = useState<string | null>(null);
38+
const [busy, setBusy] = useState(false);
39+
const generation = useRef(0);
40+
useEffect(() => () => { generation.current++; }, []);
41+
function reset() {
42+
generation.current++;
43+
setBusy(false);
44+
setError(null);
45+
setResult(null);
46+
}
47+
async function lookup(event: FormEvent) {
48+
event.preventDefault();
49+
reset();
50+
const current = generation.current;
51+
setBusy(true);
52+
try {
53+
const value = lookupResult.parse(await requestJson<unknown>("/api/chat/lark/material-review/read", {
54+
method: "POST", body: JSON.stringify({
55+
goal_id: goalId, message_id: message.trim(), agent_id: agent || undefined, route_key: route.trim() || undefined,
56+
}),
57+
}));
58+
if (current === generation.current) setResult(value);
59+
} catch (cause) {
60+
const code = cause instanceof ChatApiError ? cause.payload.error_code : null;
61+
if (current === generation.current) setError(typeof code === "string" ? code : "unknown");
62+
} finally {
63+
if (current === generation.current) setBusy(false);
64+
}
65+
}
66+
return <details className="personal-capability-raw-values">
67+
<summary>{zh ? "查询消息处置" : "Look up a message disposition"}</summary>
68+
<form className="personal-capability-field-summary" onSubmit={lookup} onChange={reset}>
69+
<div className="personal-capability-fields">
70+
{agents.length > 0 && <label>{zh ? "收件箱" : "Inbox"} <select value={agent} onChange={e => setAgent(e.target.value)}>
71+
<option value="">{zh ? "目标默认收件箱" : "Goal default inbox"}</option>
72+
{agents.map(id => <option key={id} value={id}>{id}</option>)}
73+
</select></label>}
74+
<label>{zh ? "消息 ID" : "Message ID"} <input required value={message} onChange={e => setMessage(e.target.value)} /></label>
75+
<label>{zh ? "信源路由(可选)" : "Source route (optional)"} <input value={route} onChange={e => setRoute(e.target.value)} /></label>
76+
</div>
77+
<div className="personal-capability-actions"><button type="submit" disabled={busy || !message.trim()}>{zh ? "查询" : "Look up"}</button></div>
78+
<div role="status">{busy && (zh ? "查询中…" : "Looking up…")}
79+
{error === "extension_doctor_not_ready" ? <p>
80+
{zh ? "飞书扩展需要重新检查。在此目标的运行环境中执行 " : "Recheck the Lark extension in this goal’s runtime. Run "}
81+
<code>loopx extension doctor loopx-lark --execute</code>
82+
{zh ? ",然后重试。若使用自定义运行目录,请在 loopx 后加上相同的 --runtime-root 参数。" : ", then retry. For a custom runtime, include the same --runtime-root option after loopx."}
83+
</p> : error === "inbox_unavailable" ? (zh ? "所选收件箱不可用。请检查其绑定和扩展启用状态。" : "The selected inbox is unavailable. Check its binding and whether the extension is enabled.")
84+
: error === "invalid_inbox_lookup" ? (zh ? "请核对消息 ID 和信源路由后重试。" : "Check the message ID and source route, then retry.")
85+
: error && (zh ? "暂时无法查询,请重试。" : "Lookup unavailable. Please retry.")}
86+
{result && (result.status === "committed" ? <p>{outcomes[result.receipt.effect_kind][zh ? 0 : 1]} <code>{result.receipt.effect_ref}</code></p>
87+
: statuses[result.status][zh ? 0 : 1])}
88+
</div>
89+
</form>
90+
</details>;
91+
}

‎apps/presentation/dashboard/src/features/personal-workspace/workspace-settings-page.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ export function WorkspaceSettingsPage({
268268
{tab === "capabilities" && editableGoal ? <div className="personal-goal-capability-content" key={editableGoal.goalId}>
269269
<GoalRemoteAuthorityInspection goalId={editableGoal.goalId} />
270270
<GoalCapabilitySettings
271+
registeredAgentIds={editableGoal.registeredAgentIds}
271272
key={editableGoal.goalId}
272273
callbacks={callbacks}
273274
goalId={editableGoal.goalId}

‎docs/guides/personal-workspace-user-guide.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,14 @@ Async inbox 不要求活跃 Turn,适合后台 Agent 稍后处理。发送一
785785
loopx lark-inbox drain --goal-id <goal-id> --agent-id <agent-id>
786786
```
787787

788+
查询一条群材料的处置结果,可在「Goal 设置 → 能力 → 飞书事件收件箱 → 查询消息处置」选择收件箱并输入原消息 ID。命令行也可读取同一份回执。
789+
790+
```bash
791+
loopx lark-inbox material-read --goal-id <goal-id> --agent-id <agent-id> --message-id <message-id>
792+
```
793+
794+
已提交的回执会显示处置类型和引用。多个信源收录了同一 ID 时,用 `--route-key <route>` 指定来源。
795+
788796
要停用该 Goal 的话题入站,在 Connections 中选择 **Disconnect**。断开只移除这个
789797
Goal 的 Topic 路由,不删除 Goal、Agent Session、历史 Todo 或其他 Goal 的连接。
790798

‎loopx/chat/lark_api.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,72 @@ def observation_runner(args: list[str], cwd: Path | None, timeout: float | None)
509509
}
510510
)
511511

512+
def _lark_material_read(self) -> None:
513+
from ..control_plane.runtime.goal_project_route import resolve_goal_project_route
514+
from ..extensions.lark import (
515+
LARK_EXTENSION_ID,
516+
LARK_INBOX_READ_PERMISSION,
517+
goal_inbox_config,
518+
)
519+
from ..extensions.lark.routed_inbox import (
520+
LarkInboxConfigUnavailableError,
521+
read_routed_material_review,
522+
)
523+
from ..extensions.runtime import (
524+
ExtensionDoctorNotReadyError,
525+
default_extension_state_file,
526+
resolve_extension_activation,
527+
)
528+
from ..status_server import is_loopback_host
529+
530+
if not is_loopback_host(str(self.server.server_address[0])):
531+
self._send_error("Inbox lookup requires a local server.", status=403)
532+
return
533+
try:
534+
body = self._read_json()
535+
if (
536+
set(body) - {"goal_id", "message_id", "agent_id", "route_key"}
537+
or not {"goal_id", "message_id"} <= body.keys()
538+
or any(not isinstance(v, str) or not v.strip() for v in body.values())
539+
):
540+
raise ValueError("invalid lookup")
541+
except ValueError:
542+
self._send_error("Invalid inbox lookup fields.", status=400)
543+
return
544+
try:
545+
goal, project, route = resolve_goal_project_route(
546+
registry_path=self.server.registry_path, goal_id=body["goal_id"]
547+
)
548+
config = goal_inbox_config(goal, agent_id=body.get("agent_id"))
549+
if config is None:
550+
raise ValueError("unconfigured inbox")
551+
runtime_root = route["source_runtime_root"]
552+
if Path(route["source_registry"]).resolve() == self.server.registry_path.resolve():
553+
runtime_root = self.server.runtime_root_override or runtime_root
554+
resolve_extension_activation(
555+
LARK_EXTENSION_ID,
556+
state_file=default_extension_state_file(runtime_root),
557+
required_permissions=(LARK_INBOX_READ_PERMISSION,),
558+
)
559+
except ExtensionDoctorNotReadyError as exc:
560+
self._send_error(str(exc), status=409, error_code=exc.error_code)
561+
return
562+
except (ValueError, OSError):
563+
self._send_error("The selected inbox is unavailable.", status=409, error_code="inbox_unavailable")
564+
return
565+
try:
566+
result = read_routed_material_review(
567+
project=project, config_path=config, message_id=body["message_id"],
568+
route_key=body.get("route_key"),
569+
)
570+
except (LarkInboxConfigUnavailableError, OSError):
571+
self._send_error("The selected inbox is unavailable.", status=409, error_code="inbox_unavailable")
572+
return
573+
except ValueError:
574+
self._send_error("Check the message ID and configured route.", status=400, error_code="invalid_inbox_lookup")
575+
return
576+
self._send_json(result)
577+
512578
def _lark_setup_start(self) -> None:
513579
try:
514580
body = self._read_json()

‎loopx/chat_server.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1614,6 +1614,7 @@ def do_POST(self) -> None:
16141614
CHAT_GOAL_CHANNEL_CONFIGURE_PATH: self._goal_channel_configure,
16151615
CHAT_LARK_APP_SETUPS_PATH: self._lark_setup_start,
16161616
CHAT_LARK_CONNECTIONS_PATH: self._lark_connect,
1617+
"/api/chat/lark/material-review/read": self._lark_material_read,
16171618
PRIVATE_CONVERSATIONS_PATH: self._private_conversation_connect,
16181619
"/api/chat/app-steward": self._select_app_steward,
16191620
PRIVATE_CONVERSATIONS_PATH + "/agent-targets": self._private_conversation_agent_target,

0 commit comments

Comments
 (0)