Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,9 @@ jobs:
- name: Test desktop settings publication
run: cargo test --manifest-path apps/src-tauri/Cargo.toml commands::settings::ui::tests -- --test-threads=1

- name: Test desktop request log pagination
run: cargo test --locked --manifest-path apps/src-tauri/Cargo.toml --lib requestlog_detail_forwards_desktop_paging_and_legacy_defaults

- name: Build Tauri app bundle
uses: ./.github/actions/build-tauri-with-retry
with:
Expand Down
6 changes: 6 additions & 0 deletions apps/src-tauri/src/commands/requestlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,16 @@ pub async fn service_requestlog_detail(
addr: Option<String>,
trace_id: Option<String>,
stage: Option<String>,
item_offset: Option<usize>,
item_limit: Option<usize>,
field_limit: Option<usize>,
) -> Result<serde_json::Value, String> {
let params = serde_json::json!({
"traceId": trace_id,
"stage": stage,
"itemOffset": item_offset.unwrap_or_default(),
"itemLimit": item_limit.unwrap_or_default(),
"fieldLimit": field_limit.unwrap_or_default(),
});
rpc_call_in_background("requestlog/detail", addr, Some(params)).await
}
Expand Down
5 changes: 5 additions & 0 deletions apps/src-tauri/src/rpc_client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use super::retry_policy::{rpc_replay_safety, RpcReplaySafety};

const RPC_CONNECT_TIMEOUT: Duration = Duration::from_millis(400);
const RPC_DEFAULT_IO_TIMEOUT: Duration = Duration::from_secs(10);
const RPC_REQUEST_LOG_DETAIL_IO_TIMEOUT: Duration = Duration::from_secs(120);
const RPC_MANAGED_MODEL_PRICE_SYNC_IO_TIMEOUT: Duration = Duration::from_secs(60);
const RPC_BULK_USAGE_REFRESH_IO_TIMEOUT: Duration = Duration::from_secs(600);
const RPC_ACCOUNT_IMPORT_IO_TIMEOUT: Duration = Duration::from_secs(600);
Expand Down Expand Up @@ -78,6 +79,10 @@ fn validate_http_status(response: &str) -> Result<(), RpcAttemptError> {
/// # 返回
/// 返回函数执行结果
fn rpc_io_timeout(method: &str, params: Option<&serde_json::Value>) -> Duration {
if method == "requestlog/detail" {
return RPC_REQUEST_LOG_DETAIL_IO_TIMEOUT;
}

if method == "account/import" {
return RPC_ACCOUNT_IMPORT_IO_TIMEOUT;
}
Expand Down
45 changes: 45 additions & 0 deletions apps/src-tauri/src/rpc_client/transport_retry_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,51 @@ fn assert_no_pending_connection(listener: &TcpListener) {
}
}

#[test]
fn requestlog_detail_forwards_desktop_paging_and_legacy_defaults() {
use serde_json::json;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap().to_string();
for (offset, limit, field_limit) in [
(Some(1), Some(2), Some(4)),
(Some(1), Some(2), Some(0)),
(None, None, None),
] {
let socket = listener.try_clone().unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = socket.accept().unwrap();
let request = read_rpc_request(&mut stream);
assert_eq!(request["method"], "requestlog/detail");
let reply = json!({"result": request["params"]});
stream
.write_all(response(&reply.to_string()).as_bytes())
.unwrap();
});
let reply =
tauri::async_runtime::block_on(crate::commands::requestlog::service_requestlog_detail(
Some(addr.clone()),
Some("trace".into()),
Some("upstream".into()),
offset,
limit,
field_limit,
))
.unwrap();
server.join().unwrap();
assert_eq!(
reply["result"],
json!({
"traceId": "trace", "stage": "upstream", "itemOffset": offset.unwrap_or(0),
"itemLimit": limit.unwrap_or(0), "fieldLimit": field_limit.unwrap_or(0)
})
);
}
assert_eq!(
rpc_io_timeout("requestlog/detail", None),
Duration::from_secs(120)
);
}

#[test]
fn managed_model_price_sync_uses_a_dedicated_timeout() {
assert_eq!(
Expand Down
67 changes: 62 additions & 5 deletions apps/src/app/logs/request-detail-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ import {

const RAW_BODY_FIELD = "$body";
const SUMMARY_MAX_CHARS = 160;
/// Detail bodies can reach several megabytes; the modal transfers them in
/// item windows and previews oversized first-level fields instead of asking
/// the service for the whole thing on every open.
const DETAIL_ITEM_PAGE_SIZE = 200;
const DETAIL_FIELD_PREVIEW_BYTES = 64 * 1024;

type DetailRow =
| { kind: "header"; key: string; label: string; tone: "normal" | "muted" | "warning" }
Expand Down Expand Up @@ -379,17 +384,28 @@ export function RequestDetailModal({
const { t } = useI18n();
const traceId = log?.traceId?.trim() || "";
const [stage, setStage] = useState<RequestLogDetailStage | null>(null);
const [itemLimit, setItemLimit] = useState(DETAIL_ITEM_PAGE_SIZE);
const [fieldLimit, setFieldLimit] = useState(DETAIL_FIELD_PREVIEW_BYTES);

// A new trace starts from the default stage again.
// A new trace starts from the default stage and the first payload window.
useEffect(() => {
setStage(null);
setItemLimit(DETAIL_ITEM_PAGE_SIZE);
setFieldLimit(DETAIL_FIELD_PREVIEW_BYTES);
}, [traceId, open]);

const { data: detail, isLoading } = useQuery({
queryKey: ["logs", "detail", serviceAddr, traceId, stage],
queryKey: ["logs", "detail", serviceAddr, traceId, stage, itemLimit, fieldLimit],
queryFn: ({ signal }) =>
serviceClient.requestLogDetail(
{ traceId, stage, addr: serviceAddr },
{
traceId,
stage,
itemOffset: 0,
itemLimit,
fieldLimit,
addr: serviceAddr,
},
{ signal }
),
enabled: open && traceId.length > 0,
Expand All @@ -416,12 +432,20 @@ export function RequestDetailModal({
const copyFullRequest = useCallback(async () => {
if (!detail) return;
try {
await navigator.clipboard.writeText(buildFullRequestJson(detail));
const needsFullBody = detail.hasMore || detail.fields.some((field) => field.truncated);
const fullDetail = needsFullBody
? await serviceClient.requestLogDetail({
traceId: detail.traceId,
stage: detail.stage,
addr: serviceAddr,
})
: detail;
await navigator.clipboard.writeText(buildFullRequestJson(fullDetail));
toast.success(t("已复制完整请求内容"));
} catch {
toast.error(t("复制失败"));
}
}, [detail, t]);
}, [detail, serviceAddr, t]);

return (
<Dialog open={open} onOpenChange={onOpenChange}>
Expand Down Expand Up @@ -546,6 +570,39 @@ export function RequestDetailModal({
</div>
) : null}
<DetailEntries key={`${detail.traceId}-${detail.stage}`} detail={detail} t={t} />
{detail.hasMore ? (
<div className="flex items-center justify-between gap-2 rounded-md border px-3 py-2 text-[11px] text-muted-foreground">
<span>
{t("已加载 {shown}/{total} 条,请求体较大时可继续加载。", {
shown: detail.items.length,
total: detail.itemTotal,
})}
</span>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-[11px]"
onClick={() => setItemLimit((prev) => prev + DETAIL_ITEM_PAGE_SIZE)}
>
{t("加载更多条目")}
</Button>
</div>
) : null}
{detail.fields.some((field) => field.truncated) ? (
<div className="flex items-center justify-between gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-600 dark:text-amber-400">
<span>{t("部分字段内容过大,已截断显示。")}</span>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-[11px]"
onClick={() => setFieldLimit(0)}
>
{t("展开全部字段")}
</Button>
</div>
) : null}
</>
) : dropReason ? (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-6 text-center text-xs text-amber-700 dark:text-amber-400">
Expand Down
11 changes: 10 additions & 1 deletion apps/src/lib/api/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1672,9 +1672,18 @@ export function normalizeRequestLogDetail(payload: unknown): RequestLogDetail {
complete: asBoolean(source.complete, true),
fields: asArray(source.fields).map((item) => {
const field = asObject(item);
return { name: asString(field.name), value: asRawText(field.value) };
return {
name: asString(field.name),
value: asRawText(field.value),
bytes: asInteger(field.bytes, 0, 0),
truncated: asBoolean(field.truncated, false),
};
}),
items: asRawTextArray(source.items),
itemTotal: asInteger(source.itemTotal ?? source.item_total, 0, 0),
itemOffset: asInteger(source.itemOffset ?? source.item_offset, 0, 0),
itemLimit: asInteger(source.itemLimit ?? source.item_limit, 0, 0),
hasMore: asBoolean(source.hasMore ?? source.has_more, false),
inheritedItemCount: asInteger(
source.inheritedItemCount ?? source.inherited_item_count,
0,
Expand Down
17 changes: 16 additions & 1 deletion apps/src/lib/api/rpc-retry-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,27 @@ export function rpcAllowsReplay(method: string): boolean {
return getRpcRetryKind(method) !== "non-idempotent-write";
}

/// Payload detail responses can reach several megabytes; the default 10s
/// transfer budget makes slow remote links abort and surface a misleading
/// "no payload record" state, so large reads get their own deadline.
const RPC_METHOD_TIMEOUT_MS: Record<string, number> = {
"requestlog/detail": 120_000,
};

export function rpcRequestOptions(
method: string,
options: RequestOptions,
): RequestOptions {
const methodTimeout = RPC_METHOD_TIMEOUT_MS[method];
const withTimeout =
methodTimeout === undefined
? options
: {
...options,
timeoutMs: Math.max(options.timeoutMs ?? 0, methodTimeout),
};
// Apply the safety cap after caller options, including at the outer IPC layer.
return rpcAllowsReplay(method) ? options : { ...options, retries: 0 };
return rpcAllowsReplay(method) ? withTimeout : { ...withTimeout, retries: 0 };
}

export function rpcResultUnknown(method: string, detail: string, cause?: unknown): Error {
Expand Down
12 changes: 11 additions & 1 deletion apps/src/lib/api/service-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,24 @@ export const serviceClient = {
return normalizeRequestLogListWithSummaryResult(result);
},
async requestLogDetail(
params: { traceId: string; stage?: RequestLogDetailStage | null; addr?: string | null },
params: {
traceId: string;
stage?: RequestLogDetailStage | null;
itemOffset?: number;
itemLimit?: number;
fieldLimit?: number;
addr?: string | null;
},
options?: RequestOptions,
): Promise<RequestLogDetail> {
const result = await invoke<unknown>(
"service_requestlog_detail",
withAddr({
traceId: params.traceId,
...(params.stage ? { stage: params.stage } : {}),
...(params.itemOffset === undefined ? {} : { itemOffset: params.itemOffset }),
...(params.itemLimit === undefined ? {} : { itemLimit: params.itemLimit }),
...(params.fieldLimit === undefined ? {} : { fieldLimit: params.fieldLimit }),
...(params.addr === undefined ? {} : { addr: params.addr || null }),
}),
options
Expand Down
4 changes: 4 additions & 0 deletions apps/src/lib/i18n/messages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,10 @@ export const EN_MESSAGES: MessageCatalog = {
"The request payload exceeds the storage cap; only the first 16 KB preview is kept.",
"未找到该请求的内容记录;日志可能产生于旧版本,或已被清理。":
"No payload record found for this request; the log may predate this feature or have been cleared.",
"已加载 {shown}/{total} 条,请求体较大时可继续加载。": "Showing {shown}/{total} items. Load more when the request body is large.",
"加载更多条目": "Load more items",
"部分字段内容过大,已截断显示。": "Some field values are truncated because they are very large.",
"展开全部字段": "Expand all fields",
"有 {count} 条请求内容因磁盘空间不足等原因未记录": "{count} request bodies were not recorded (low disk space or similar)",
"此请求内容因{reason}未记录": "This request body was not recorded: {reason}",
"磁盘空间不足": "low disk space",
Expand Down
4 changes: 4 additions & 0 deletions apps/src/lib/i18n/messages/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,10 @@ export const KO_MESSAGES: MessageCatalog = {
"요청 본문이 저장 한도를 초과하여 처음 16 KB 미리보기만 보관됩니다.",
"未找到该请求的内容记录;日志可能产生于旧版本,或已被清理。":
"이 요청의 본문 기록을 찾을 수 없습니다. 해당 기능 이전의 로그이거나 이미 정리되었을 수 있습니다.",
"已加载 {shown}/{total} 条,请求体较大时可继续加载。": "{shown}/{total}개 항목 표시 중입니다. 요청 본문이 크면 더 불러올 수 있습니다.",
"加载更多条目": "항목 더 불러오기",
"部分字段内容过大,已截断显示。": "일부 필드 값이 너무 커서 잘려서 표시됩니다.",
"展开全部字段": "모든 필드 펼치기",
"有 {count} 条请求内容因磁盘空间不足等原因未记录": "디스크 공간 부족 등의 이유로 요청 본문 {count}건이 기록되지 않았습니다",
"此请求内容因{reason}未记录": "이 요청 본문은 다음 이유로 기록되지 않았습니다: {reason}",
"磁盘空间不足": "디스크 공간 부족",
Expand Down
4 changes: 4 additions & 0 deletions apps/src/lib/i18n/messages/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,10 @@ export const RU_MESSAGES: MessageCatalog = {
"Тело запроса превышает лимит хранения; сохранён только предпросмотр первых 16 КБ.",
"未找到该请求的内容记录;日志可能产生于旧版本,或已被清理。":
"Запись тела запроса не найдена; журнал мог появиться до внедрения функции или уже был очищен.",
"已加载 {shown}/{total} 条,请求体较大时可继续加载。": "Показано {shown}/{total} элементов. При большом теле запроса можно загрузить ещё.",
"加载更多条目": "Загрузить ещё элементы",
"部分字段内容过大,已截断显示。": "Некоторые значения полей обрезаны из-за большого размера.",
"展开全部字段": "Развернуть все поля",
"有 {count} 条请求内容因磁盘空间不足等原因未记录": "Тела запросов не сохранены: {count} (нехватка места на диске и т. п.)",
"此请求内容因{reason}未记录": "Тело этого запроса не сохранено: {reason}",
"磁盘空间不足": "недостаточно места на диске",
Expand Down
14 changes: 13 additions & 1 deletion apps/src/types/request-log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ export interface RequestLogDetailField {
name: string;
/** JSON text of the field value (raw text for non-JSON bodies). */
value: string;
/** Stored length of the value in bytes before any truncation. */
bytes: number;
/** Set when the value was cut down to the requested field limit. */
truncated: boolean;
}

export interface RequestLogDetailContextSegment {
Expand Down Expand Up @@ -122,8 +126,16 @@ export interface RequestLogDetail {
listField: string | null;
complete: boolean;
fields: RequestLogDetailField[];
/** JSON text of each list item, in request order. */
/** Items of the requested window, in request order. */
items: string[];
/** Number of list items stored for this payload. */
itemTotal: number;
/** Offset the returned items start at. */
itemOffset: number;
/** Requested item limit; 0 means "everything after itemOffset". */
itemLimit: number;
/** Set when stored items remain after the returned window. */
hasMore: boolean;
/** Number of leading items shared with the parent request of the conversation. */
inheritedItemCount: number;
parentTraceId: string | null;
Expand Down
44 changes: 44 additions & 0 deletions apps/tests/request-logs-duration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,50 @@ test("timeline expands request metadata without fetching the payload until reque
expect(state.detailTraces).toEqual(["trace-duration-1"]);
});

test("paged payloads load on demand and copy the full captured stage", async ({ page }) => {
await mockLogs(page);
const items = Array.from({ length: 201 }, (_, i) => i);
const note = "x".repeat(65_537);
const field = JSON.stringify(note);
const requests: Record<string, unknown>[] = [];
let copied = "";
await page.exposeFunction("captureRequestCopy", (text: string) => { copied = text; });
await page.addInitScript(() => {
Object.defineProperty(navigator, "clipboard", {
value: { writeText: Reflect.get(window, "captureRequestCopy") },
});
});
await page.route("**/api/rpc*", async (route) => {
const { id, method, params } = route.request().postDataJSON();
if (method !== "requestlog/detail") return route.fallback();
requests.push(params);
const shown = items.slice(0, params.itemLimit || items.length);
const value = field.slice(0, params.fieldLimit || field.length);
return route.fulfill({ json: { id, result: {
traceId: params.traceId, stage: "client", stages: ["client"], storageMode: "full",
bodyKind: "json_list", listField: "input", complete: true,
fields: [{ name: "note", value, truncated: value !== field, bytes: field.length }],
itemTotal: items.length, items: shown.map(String), hasMore: shown.length < items.length,
} } });
});
await page.goto("/logs/");
const entry = page.getByTestId("request-log-entry-trace-duration-1");
await entry.locator("summary").click();
await entry.getByRole("button", { name: "查看请求内容" }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toContainText("200/201");
expect(requests[0]).toMatchObject({ itemOffset: 0, itemLimit: 200, fieldLimit: 65_536 });
await dialog.getByRole("button", { name: "复制完整请求" }).click();
await expect.poll(() => copied.length).toBeGreaterThan(0);
expect(JSON.parse(copied)).toEqual({ note, input: items });
expect(requests[1].stage).toBe("client");
await dialog.getByRole("button", { name: "加载更多条目" }).click();
await expect(dialog.getByRole("button", { name: "加载更多条目" })).toHaveCount(0);
await dialog.getByRole("button", { name: "展开全部字段" }).click();
await expect.poll(() => requests.at(-1)?.fieldLimit).toBe(0);
await expect(dialog.getByRole("button", { name: "展开全部字段" })).toHaveCount(0);
});

test("timeline displays explicit upstream errors as failures even with HTTP 200", async ({ page }) => {
await mockLogs(page, { log: { status_code: 200, error: "upstream stream closed before completion" } });
await page.goto("/logs/");
Expand Down
Loading
Loading