Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
22 changes: 9 additions & 13 deletions apps/mobile/src/features/cloud/cloudDebugLog.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import { createDebugLogger } from "../../lib/debugLog";

const logger = createDebugLogger("cloud", {
enabledInDev: true,
legacyGlobalFlag: "__T3_CLOUD_DEBUG__",
});

export function isCloudDebugEnabled(): boolean {
return (
(typeof __DEV__ !== "undefined" && __DEV__) ||
(typeof globalThis !== "undefined" &&
(globalThis as { __T3_CLOUD_DEBUG__?: boolean }).__T3_CLOUD_DEBUG__ === true)
);
return logger.isEnabled();
}

export function cloudDebugLog(event: string, data?: Record<string, unknown>): void {
if (!isCloudDebugEnabled()) {
return;
}
if (data) {
console.log(`[t3-cloud] ${event}`, data);
} else {
console.log(`[t3-cloud] ${event}`);
}
logger.log(event, data);
}
27 changes: 12 additions & 15 deletions apps/mobile/src/features/terminal/terminalDebugLog.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import { createDebugLogger } from "../../lib/debugLog";

/**
* Debug logging for the mobile terminal pipeline. Prefix: `[t3-terminal]`.
*
* Enabled when `__DEV__` is true, or set `globalThis.__T3_TERMINAL_DEBUG__ = true` in a JS
* debugger / Metro console to trace release/TestFlight builds.
* Enabled when `__DEV__` is true, or set `globalThis.__T3_TERMINAL_DEBUG__`
* (or the shared `globalThis.__T3_DEBUG__` filter) in a JS debugger / Metro
* console to trace release/TestFlight builds.
*/
const logger = createDebugLogger("terminal", {
enabledInDev: true,
legacyGlobalFlag: "__T3_TERMINAL_DEBUG__",
});

export function isTerminalDebugEnabled(): boolean {
return (
(typeof __DEV__ !== "undefined" && __DEV__) ||
(typeof globalThis !== "undefined" &&
(globalThis as { __T3_TERMINAL_DEBUG__?: boolean }).__T3_TERMINAL_DEBUG__ === true)
);
return logger.isEnabled();
}

export function terminalDebugLog(message: string, data?: Record<string, unknown>): void {
if (!isTerminalDebugEnabled()) {
return;
}
if (data !== undefined) {
console.log(`[t3-terminal] ${message}`, data);
} else {
console.log(`[t3-terminal] ${message}`);
}
logger.log(message, data);
}
70 changes: 70 additions & 0 deletions apps/mobile/src/lib/debugLog.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";

import { createDebugLogger } from "./debugLog";

describe("createDebugLogger", () => {
let logSpy: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
vi.stubGlobal("__DEV__", false);
vi.stubGlobal("__T3_DEBUG__", undefined);
vi.stubGlobal("__T3_CLOUD_DEBUG__", undefined);
logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
});

afterEach(() => {
vi.unstubAllGlobals();
logSpy.mockRestore();
});

function setDebugFilter(filter: unknown): void {
vi.stubGlobal("__T3_DEBUG__", filter);
}

it("is silent by default, including in development builds", () => {
vi.stubGlobal("__DEV__", true);
const trace = createDebugLogger("thread-outbox");
trace.log("queued message delivery failed");
expect(trace.isEnabled()).toBe(false);
expect(logSpy).not.toHaveBeenCalled();
});

it("logs with the [t3-<namespace>] prefix when the global filter is true", () => {
setDebugFilter(true);
const trace = createDebugLogger("thread-outbox");
trace.log("attachment upload failed", { messageId: "m1" });
expect(trace.isEnabled()).toBe(true);
expect(logSpy).toHaveBeenCalledWith("[t3-thread-outbox] attachment upload failed", {
messageId: "m1",
});
});

it("filters per namespace when the global filter is a list", () => {
setDebugFilter(["cloud"]);
createDebugLogger("thread-outbox").log("delivery failed");
createDebugLogger("cloud").log("relay connected");
expect(logSpy.mock.calls).toEqual([["[t3-cloud] relay connected"]]);
});

it("logs without data as a single prefixed line", () => {
setDebugFilter(true);
createDebugLogger("thread-outbox").log("delivery failed");
expect(logSpy).toHaveBeenCalledWith("[t3-thread-outbox] delivery failed");
});

it("honors enabledInDev with __DEV__", () => {
vi.stubGlobal("__DEV__", true);
const trace = createDebugLogger("terminal", { enabledInDev: true });
trace.log("buffer replay");
expect(trace.isEnabled()).toBe(true);
expect(logSpy).toHaveBeenCalledWith("[t3-terminal] buffer replay");
});

it("honors a legacy subsystem-specific global flag", () => {
vi.stubGlobal("__T3_CLOUD_DEBUG__", true);
const trace = createDebugLogger("cloud", { legacyGlobalFlag: "__T3_CLOUD_DEBUG__" });
trace.log("relay state changed");
expect(trace.isEnabled()).toBe(true);
expect(logSpy).toHaveBeenCalledWith("[t3-cloud] relay state changed");
});
});
64 changes: 64 additions & 0 deletions apps/mobile/src/lib/debugLog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Namespaced, filterable debug logging shared by mobile subsystems.
*
* Ordinary, expected conditions — a queued send failing while the device is
* offline, for example — go through a debug logger instead of `console.warn`
* so warning output stays reserved for failures someone can act on. Output
* uses `console.log` with a `[t3-<namespace>]` prefix, matching the existing
* cloud and terminal debug logs. (client-runtime cannot host this: its
* tooling bans `console.*` in favor of Effect logging.)
*
* A logger is silent in every build, including development, unless enabled.
* Toggle it from a JS debugger or the Metro console, including on release/TestFlight builds:
* - `globalThis.__T3_DEBUG__ = true` enables every namespace;
* - `globalThis.__T3_DEBUG__ = ["thread-outbox"]` enables only listed ones.
*
* Subsystems whose traces are useful by default in development (`__DEV__`)
* opt in with `enabledInDev`; `legacyGlobalFlag` keeps an older
* subsystem-specific global (e.g. `__T3_CLOUD_DEBUG__`) working.
*/

export interface DebugLogger {
readonly isEnabled: () => boolean;
readonly log: (event: string, data?: Record<string, unknown>) => void;
}

export interface DebugLoggerOptions {
/** Log whenever `__DEV__` is true, without the global filter. Defaults to false. */
readonly enabledInDev?: boolean;
/** Name of a legacy subsystem-specific global boolean, e.g. `"__T3_CLOUD_DEBUG__"`. */
readonly legacyGlobalFlag?: string;
}

function globalValue(name: string): unknown {
return typeof globalThis === "undefined"
? undefined
: (globalThis as Record<string, unknown>)[name];
}

export function createDebugLogger(
namespace: string,
options: DebugLoggerOptions = {},
): DebugLogger {
const isEnabled = () => {
if (options.enabledInDev === true && typeof __DEV__ !== "undefined" && __DEV__) {
return true;
}
if (options.legacyGlobalFlag !== undefined && globalValue(options.legacyGlobalFlag) === true) {
return true;
}
const filter = globalValue("__T3_DEBUG__");
return filter === true || (Array.isArray(filter) && filter.includes(namespace));
};
const log = (event: string, data?: Record<string, unknown>) => {
if (!isEnabled()) {
return;
}
if (data === undefined) {
console.log(`[t3-${namespace}] ${event}`);
} else {
console.log(`[t3-${namespace}] ${event}`, data);
}
};
return { isEnabled, log };
}
139 changes: 138 additions & 1 deletion apps/mobile/src/state/use-thread-outbox-drain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ import { recoverFailedThreadDraft } from "./recover-failed-thread-draft";
import { editingQueuedMessageIdsAtom } from "./use-thread-outbox";
import {
completeQueuedMessageDelivery,
logThreadOutboxDeliveryFailure,
logThreadOutboxUploadFailure,
prepareQueuedMessageAttachments,
recoverEditedCreationAfterDelivery,
removeAcknowledgedExistingThreadMessage,
Expand Down Expand Up @@ -426,7 +428,16 @@ describe("thread outbox drain delivery cleanup", () => {
const edited = { ...message, text: "edited while the turn delivered" };
await harness.manager.update(edited);

await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");
// Losing the cleanup race to an edit is expected; it must not warn.
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
let outcome: "edited" | "failed" | "removed";
try {
outcome = await completeQueuedMessageDelivery(message, deliveryRevision);
} finally {
warn.mockRestore();
}
expect(outcome).toBe("edited");
expect(warn).not.toHaveBeenCalled();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

expect(remainingMessages()).toEqual([edited]);
expect(harness.removePersistedFile).not.toHaveBeenCalled();
Expand Down Expand Up @@ -763,3 +774,129 @@ describe("thread outbox recovery rollback", () => {
expect(harness.setPendingConnectionError).toHaveBeenCalledWith("too large");
});
});

describe("thread outbox failure logging", () => {
// Tagged errors match shouldRetryThreadOutboxDelivery's transport tags, so
// the assertions cover the real failure classification, not a
// predetermined action argument.
const transportError = { _tag: "RpcClientError" };
const serverDecidedError = { _tag: "OrchestrationDispatchCommandError" };

function failureLogging(input: Parameters<typeof logThreadOutboxDeliveryFailure>[0]): {
readonly action: string;
readonly warnCalls: ReadonlyArray<unknown[]>;
readonly logCalls: ReadonlyArray<unknown[]>;
} {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const log = vi.spyOn(console, "log").mockImplementation(() => {});
try {
return {
action: logThreadOutboxDeliveryFailure(input),
warnCalls: [...warn.mock.calls],
logCalls: [...log.mock.calls],
};
} finally {
warn.mockRestore();
log.mockRestore();
}
}

it("keeps offline transport retries silent by default at both stages", () => {
for (const stage of ["settings-sync", "start-turn"] as const) {
const { action, warnCalls, logCalls } = failureLogging({
stage,
error: transportError,
interrupted: false,
context: { messageId: "m1" },
});
expect(action).toBe("retry");
expect(warnCalls).toEqual([]);
expect(logCalls).toEqual([]);
}
});

it("surfaces transport retry details when the thread-outbox debug filter is enabled", () => {
vi.stubGlobal("__T3_DEBUG__", ["thread-outbox"]);
const log = vi.spyOn(console, "log").mockImplementation(() => {});
try {
logThreadOutboxDeliveryFailure({
stage: "start-turn",
error: transportError,
interrupted: false,
context: { messageId: "m1" },
});
expect(log).toHaveBeenCalledWith(
"[t3-thread-outbox] queued message delivery failed",
expect.objectContaining({ messageId: "m1", action: "retry" }),
);
} finally {
log.mockRestore();
vi.unstubAllGlobals();
}
});

it("warns when the server decided the message must be restored", () => {
const { action, warnCalls } = failureLogging({
stage: "start-turn",
error: serverDecidedError,
interrupted: false,
context: { messageId: "m2" },
});
expect(action).toBe("restore");
expect(warnCalls).toEqual([
[
"[thread-outbox] queued message delivery failed",
expect.objectContaining({ messageId: "m2", action: "restore" }),
],
]);
});

it("warns on a nontransport settings-sync failure even though it resolves to a retry", () => {
const { action, warnCalls } = failureLogging({
stage: "settings-sync",
error: serverDecidedError,
interrupted: false,
context: { messageId: "m3" },
});
expect(action).toBe("retry");
expect(warnCalls).toEqual([
[
"[thread-outbox] queued message delivery failed",
expect.objectContaining({ stage: "settings-sync", action: "retry" }),
],
]);
});

it("routes retryable attachment-upload failures to the debug log and warns on the rest", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const log = vi.spyOn(console, "log").mockImplementation(() => {});
try {
logThreadOutboxUploadFailure(transportError);
expect(warn).not.toHaveBeenCalled();
expect(log).not.toHaveBeenCalled();

logThreadOutboxUploadFailure(serverDecidedError);
expect(warn).toHaveBeenCalledWith(
"[thread-outbox] failed to upload attachments",
serverDecidedError,
);
} finally {
warn.mockRestore();
log.mockRestore();
}
});

it("logs retryable attachment-upload failures when the debug filter is enabled", () => {
vi.stubGlobal("__T3_DEBUG__", ["thread-outbox"]);
const log = vi.spyOn(console, "log").mockImplementation(() => {});
try {
logThreadOutboxUploadFailure(transportError);
expect(log).toHaveBeenCalledWith("[t3-thread-outbox] attachment upload failed; retrying", {
error: transportError,
});
} finally {
log.mockRestore();
vi.unstubAllGlobals();
}
});
});
Loading
Loading