feat: add thread status documents and safe thread reply handling

This commit is contained in:
kris
2026-04-04 11:50:46 +08:00
parent 010d8eda2d
commit 4d9b8e2976
10 changed files with 487 additions and 57 deletions

View File

@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { requireRequestSession } from "@/lib/boss-auth";
import { readState } from "@/lib/boss-data";
import { getProjectDetailView } from "@/lib/boss-projections";
export async function GET(
request: NextRequest,
@@ -13,8 +14,8 @@ export async function GET(
const { projectId } = await context.params;
const state = await readState();
const project = state.projects.find((item) => item.id === projectId);
if (!project) {
const detail = getProjectDetailView(state, projectId, session.account);
if (!detail) {
return NextResponse.json({ ok: false, message: "PROJECT_NOT_FOUND" }, { status: 404 });
}

View File

@@ -0,0 +1,161 @@
import { notFound } from "next/navigation";
import { AppShell, PageNav, StatusBar } from "@/components/app-ui";
import { requirePageSession } from "@/lib/boss-auth";
import { readState } from "@/lib/boss-data";
import { getProjectDetailView } from "@/lib/boss-projections";
import { formatTimestampLabel } from "@/lib/boss-projections";
export const dynamic = "force-dynamic";
function renderMetadataLine(parts: Array<string | undefined>) {
return parts.filter((part) => part && part.trim()).join(" · ");
}
function renderFallback(value: string | undefined, fallback: string) {
return value && value.trim() ? value : fallback;
}
export default async function ThreadStatusPage({
params,
}: {
params: Promise<{ projectId: string }>;
}) {
const session = await requirePageSession();
const { projectId } = await params;
const state = await readState();
const detail = getProjectDetailView(state, projectId, session.account);
if (!detail) notFound();
const threadStatusDocument =
state.threadStatusDocuments.find((item) => item.projectId === projectId) ?? null;
const recentProgressEvents = state.threadProgressEvents
.filter((item) => item.projectId === projectId)
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
.slice(0, 5);
const subtitle = threadStatusDocument?.folderName?.trim()
? `${threadStatusDocument.folderName} · 只读`
: "只读状态文档";
return (
<AppShell bottomNav={false}>
<StatusBar />
<PageNav title="线程状态" backHref={`/conversations/${projectId}`} />
<div className="space-y-3 px-[18px] pb-6">
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[18px] font-semibold text-[#111111]">{detail.project.name}</div>
<div className="mt-1 text-[13px] text-[#8C8C8C]">{subtitle}</div>
<div className="mt-3 text-[12px] leading-6 text-[#57606A]">
{threadStatusDocument
? renderMetadataLine([
threadStatusDocument.threadId,
threadStatusDocument.deviceId,
`更新于 ${formatTimestampLabel(threadStatusDocument.updatedAt)}`,
])
: "当前还没有线程状态文档。"}
</div>
</div>
{threadStatusDocument ? (
<>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{renderFallback(threadStatusDocument.projectGoal, "暂无目标")}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{renderFallback(threadStatusDocument.currentPhase, "暂无阶段")}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{renderFallback(threadStatusDocument.currentProgress, "暂无进度")}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{renderFallback(threadStatusDocument.technicalArchitecture, "暂无架构")}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{renderFallback(threadStatusDocument.currentBlockers, "暂无阻塞")}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{renderFallback(threadStatusDocument.recommendedNextStep, "暂无建议")}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{threadStatusDocument.keyFiles.length
? threadStatusDocument.keyFiles.join("\n")
: "暂无关键文件"}
</div>
</div>
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="mt-2 whitespace-pre-wrap text-[13px] leading-6 text-[#57606A]">
{threadStatusDocument.keyCommands.length
? threadStatusDocument.keyCommands.join("\n")
: "暂无关键命令"}
</div>
</div>
</>
) : (
<div className="rounded-2xl border border-dashed border-[#D9D9D9] bg-white px-4 py-5 text-[13px] leading-6 text-[#57606A]">
线 Agent 线
</div>
)}
<div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
<div className="flex items-center justify-between gap-3">
<div className="text-[14px] font-semibold text-[#111111]"></div>
<div className="text-[12px] text-[#8C8C8C]">
{recentProgressEvents.length ? `最近 ${recentProgressEvents.length}` : "暂无事件"}
</div>
</div>
<div className="mt-3 space-y-3">
{recentProgressEvents.length ? (
recentProgressEvents.map((event) => (
<div key={event.eventId} className="rounded-2xl bg-[#F7F8FA] px-3 py-3">
<div className="flex items-center justify-between gap-3 text-[12px] text-[#8C8C8C]">
<span>{renderFallback(event.phase, event.eventType)}</span>
<span>{formatTimestampLabel(event.createdAt)}</span>
</div>
<div className="mt-2 text-[13px] leading-6 text-[#111111]">{event.summary}</div>
<div className="mt-1 text-[12px] leading-5 text-[#57606A]">
{renderMetadataLine([event.threadDisplayName, event.deviceId])}
</div>
{event.blockerDelta ? (
<div className="mt-1 text-[12px] leading-5 text-[#A15C00]">
{event.blockerDelta}
</div>
) : null}
{event.nextStepDelta ? (
<div className="mt-1 text-[12px] leading-5 text-[#215B39]">
{event.nextStepDelta}
</div>
) : null}
</div>
))
) : (
<div className="rounded-2xl bg-[#F7F8FA] px-3 py-3 text-[12px] leading-6 text-[#57606A]">
线
</div>
)}
</div>
</div>
</div>
</AppShell>
);
}

View File

@@ -782,9 +782,7 @@ export function ProjectHeaderActions({ projectId }: { projectId: string }) {
</Link>
<Link
href={`/api/v1/projects/${projectId}/thread-status`}
target="_blank"
rel="noreferrer"
href={`/conversations/${projectId}/thread-status`}
className="flex h-11 items-center justify-center rounded-2xl bg-white text-[14px] font-semibold text-[#111111]"
>
线

View File

@@ -2882,6 +2882,8 @@ function appendThreadProgressEventInState(
return event;
}
const THREAD_STATUS_FULL_SYNC_INTERVAL_MS = 15 * 60_000;
function normalizeState(raw: Partial<BossState> | undefined): BossState {
const base = cloneInitialState();
if (!raw) return syncDerivedState(base);
@@ -5962,6 +5964,7 @@ function appendDispatchExecutionResultInState(
targetThreadDisplayName?: string;
rawThreadReply?: string;
masterSummary?: string;
failureReason?: string;
},
) {
const execution = state.dispatchExecutions.find(
@@ -6047,7 +6050,9 @@ function appendDispatchExecutionResultInState(
masterSummary = pushProjectLedgerMessage(state, payload.groupProjectId, {
sender: "ops",
senderLabel: "主 Agent Relay",
body: `${threadTitle} 执行失败,请稍后重试。`,
body: payload.failureReason?.trim()
? `${threadTitle} 执行失败:${payload.failureReason.trim()}`
: `${threadTitle} 执行失败,请稍后重试。`,
kind: "text",
});
}
@@ -6321,6 +6326,7 @@ export async function completeMasterAgentTask(payload: {
targetThreadDisplayName: task.targetThreadDisplayName,
rawThreadReply: payload.rawThreadReply?.trim() || task.replyBody,
masterSummary: payload.replyBody?.trim(),
failureReason: payload.errorMessage?.trim(),
});
} else if (!attachmentProjectId && payload.status === "completed" && task.replyBody) {
const isDeviceImportUnderstanding =
@@ -7133,20 +7139,28 @@ export async function upsertDeviceHeartbeat(payload: {
if (!matchingProject) {
continue;
}
const previousObservedAt = matchingProject.threadMeta.lastObservedCodexActivityAt;
matchingProject.threadMeta.lastObservedCodexActivityAt = latestIsoTimestamp(
matchingProject.threadMeta.lastObservedCodexActivityAt,
previousObservedAt,
candidate.lastActiveAt,
) ?? candidate.lastActiveAt;
appendThreadProgressEventInState(state, {
projectId: matchingProject.id,
threadId: matchingProject.threadMeta.threadId,
threadDisplayName: matchingProject.threadMeta.threadDisplayName,
deviceId: matchingProject.deviceIds[0] ?? payload.deviceId,
eventType: "progress_updated",
summary: buildHeartbeatProgressSummary(candidate.threadDisplayName),
createdAt: candidate.lastActiveAt,
sourceTaskId: `heartbeat-${candidate.candidateId}`,
});
const previousObservedTs = Date.parse(previousObservedAt ?? "1970-01-01T00:00:00.000Z");
const nextObservedTs = Date.parse(candidate.lastActiveAt);
const hasNewObservedActivity =
Number.isFinite(nextObservedTs) &&
(!Number.isFinite(previousObservedTs) || nextObservedTs > previousObservedTs);
if (hasNewObservedActivity) {
appendThreadProgressEventInState(state, {
projectId: matchingProject.id,
threadId: matchingProject.threadMeta.threadId,
threadDisplayName: matchingProject.threadMeta.threadDisplayName,
deviceId: matchingProject.deviceIds[0] ?? payload.deviceId,
eventType: "progress_updated",
summary: buildHeartbeatProgressSummary(candidate.threadDisplayName),
createdAt: candidate.lastActiveAt,
sourceTaskId: `heartbeat-${candidate.candidateId}`,
});
}
if (shouldQueueProjectUnderstandingSync(matchingProject, candidate.lastActiveAt, state)) {
projectUnderstandingSyncRequests.push({
projectId: matchingProject.id,
@@ -7608,7 +7622,21 @@ function shouldQueueProjectUnderstandingSync(project: Project, observedActivityA
(item) => item.projectId === project.id && item.threadId === project.threadMeta.threadId,
);
if (project.projectUnderstanding && hasThreadStatusDocument) {
return false;
const lastSyncedTs = Date.parse(
project.threadMeta.lastProjectUnderstandingSyncedAt ??
project.projectUnderstanding.updatedAt ??
"1970-01-01T00:00:00.000Z",
);
const understandingLooksThin =
!project.projectUnderstanding.currentProgress?.trim() ||
!project.projectUnderstanding.recommendedNextStep?.trim();
if (
!understandingLooksThin &&
Number.isFinite(lastSyncedTs) &&
observedTs - lastSyncedTs < THREAD_STATUS_FULL_SYNC_INTERVAL_MS
) {
return false;
}
}
return !state.masterAgentTasks.some(
(task) =>
@@ -8571,7 +8599,8 @@ export async function appendProjectMessage(payload: {
project.preview = message.body;
const shouldTrackThreadProgress =
payload.sender !== "user" &&
payload.sender === "device" &&
(payload.kind ?? "text") === "text" &&
isDispatchableThreadProject(project) &&
Boolean(project.threadMeta.codexThreadRef?.trim());
if (shouldTrackThreadProgress) {

View File

@@ -25,17 +25,66 @@ function trimToDefined(value: string | undefined) {
return trimmed ? trimmed : undefined;
}
function looksLikeThreadEnvironmentDiagnostic(value: string | undefined) {
const text = trimToDefined(value);
if (!text) {
return false;
}
const primarySignals = [
"当前会话环境从只读改回可写",
"当前会话环境只读",
"不能直接把当前会话环境",
"cwd 我可以在命令里指向",
"文件系统read-only",
];
const secondarySignals = [
"只读权限",
"切回可写",
"不能继续开发",
"不能写文件",
"不能提交",
];
const primaryMatchCount = primarySignals.filter((fragment) => text.includes(fragment)).length;
const secondaryMatchCount = secondarySignals.filter((fragment) => text.includes(fragment)).length;
return primaryMatchCount >= 2 || (primaryMatchCount >= 1 && secondaryMatchCount >= 1);
}
function buildThreadEnvironmentErrorMessage() {
return "THREAD_ENVIRONMENT_INVALID: 线程返回了内部环境提示,已拦截,请检查线程绑定或工作目录。";
}
export function normalizeRemoteExecutionResult(
input: RemoteExecutionResultInput,
): NormalizedRemoteExecutionResult {
const rawThreadReply = trimToDefined(input.rawThreadReply);
const replyBody = trimToDefined(input.replyBody);
const errorMessage = trimToDefined(input.errorMessage);
const hasEnvironmentDiagnostic =
looksLikeThreadEnvironmentDiagnostic(rawThreadReply) ||
looksLikeThreadEnvironmentDiagnostic(replyBody);
if (hasEnvironmentDiagnostic) {
return {
status: "failed",
dispatchExecutionId: trimToDefined(input.dispatchExecutionId),
targetProjectId: trimToDefined(input.targetProjectId),
targetThreadId: trimToDefined(input.targetThreadId),
errorMessage: errorMessage || buildThreadEnvironmentErrorMessage(),
requestId: trimToDefined(input.requestId),
};
}
return {
status: input.status === "failed" ? "failed" : "completed",
dispatchExecutionId: trimToDefined(input.dispatchExecutionId),
targetProjectId: trimToDefined(input.targetProjectId),
targetThreadId: trimToDefined(input.targetThreadId),
rawThreadReply: trimToDefined(input.rawThreadReply),
replyBody: trimToDefined(input.replyBody),
errorMessage: trimToDefined(input.errorMessage),
rawThreadReply,
replyBody,
errorMessage,
requestId: trimToDefined(input.requestId),
};
}