The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 16:00 UTC
fix(clients): live working timers count on the host's clock (#36420)
Julius Marminge committed
Nov 13, 2026 at 15:54 UTC
2d80cb6bc75fe85b187d92c4322099b17e7f912e
17 files changed
+190
-28
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+5
-1
@@ -829,7 +829,11 @@ function ThreadDetailBody(
829
return { kind: "compacting" };
830
}
831
if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") {
832
- return { kind: "working", startedAt: props.activeWorkStartedAt };
832
+ return {
833
+ kind: "working",
834
+ environmentId: props.environmentId,
835
+ startedAt: props.activeWorkStartedAt,
836
+ };
837
}
838
if (pendingBackgroundWork !== null && contentPresentationKind === "ready") {
839
return {
apps/mobile/src/features/threads/floating-working-control.tsx
+15
-4
@@ -1,4 +1,6 @@
1
+import { toServerClock } from "@t3tools/client-runtime/clock";
2
import type { SubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents";
3
+import type { EnvironmentId } from "@t3tools/contracts";
4
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
5
import { GlassContainer, GlassView } from "expo-glass-effect";
6
import { type ReactNode, useEffect, useRef, useState } from "react";
@@ -597,7 +599,12 @@ function FloatingStatusLabel(props: {
599
);
600
}
601
return (
600
- <WorkingDuration key="working" startedAt={props.status.startedAt} onLayout={props.onLayout} />
602
+ <WorkingDuration
603
+ key="working"
604
+ environmentId={props.status.environmentId}
605
+ startedAt={props.status.startedAt}
606
+ onLayout={props.onLayout}
607
+ />
608
);
609
}
610
@@ -638,17 +645,21 @@ function StatusLabelRow(props: {
645
}
646
647
function WorkingDuration(props: {
648
+ readonly environmentId: EnvironmentId;
649
readonly startedAt: string;
650
readonly onLayout: (event: LayoutChangeEvent) => void;
651
}) {
652
return (
653
<StatusLabelRow onLayout={props.onLayout}>
646
- <WorkingTimer startedAt={props.startedAt} />
654
+ <WorkingTimer environmentId={props.environmentId} startedAt={props.startedAt} />
655
</StatusLabelRow>
656
);
657
}
658
651
-function WorkingTimer(props: { readonly startedAt: string }) {
659
+function WorkingTimer(props: {
660
+ readonly environmentId: EnvironmentId;
661
+ readonly startedAt: string;
662
+}) {
663
const nowMs = useVisibleSecondClock(true);
664
return (
665
<SystemText
@@ -656,7 +667,7 @@ function WorkingTimer(props: { readonly startedAt: string }) {
667
numberOfLines={1}
668
style={{ fontVariant: ["tabular-nums"], fontWeight: "500" }}
669
>
659
- Working {formatWorkingDuration(props.startedAt, nowMs)}
670
+ Working {formatWorkingDuration(props.startedAt, toServerClock(props.environmentId, nowMs))}
671
</SystemText>
672
);
673
}
apps/mobile/src/features/threads/floating-working-status.ts
+2
-1
@@ -1,4 +1,5 @@
1
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2
+import type { EnvironmentId } from "@t3tools/contracts";
3
4
export interface FloatingStatusAction {
5
readonly label: string;
@@ -8,7 +9,7 @@ export interface FloatingStatusAction {
9
}
10
11
export type FloatingWorkingStatus =
11
- | { readonly kind: "working"; readonly startedAt: string }
12
+ | { readonly kind: "working"; readonly environmentId: EnvironmentId; readonly startedAt: string }
13
| { readonly kind: "syncing"; readonly label: string }
14
| { readonly kind: "compacting" }
15
| {
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+10
-2
@@ -25,7 +25,12 @@ import {
25
formatWorkingDurationLabel,
26
resolveThreadWorkingStartedAt,
27
} from "@t3tools/client-runtime/state/models";
28
-import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts";
28
+import {
29
+ AuthOrchestrationOperateScope,
30
+ type EnvironmentId,
31
+ type EnvironmentMachineKind,
32
+} from "@t3tools/contracts";
33
+import { toServerClock } from "@t3tools/client-runtime/clock";
34
import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
35
import { canSnooze } from "@t3tools/client-runtime/state/thread-settled";
36
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
@@ -153,6 +158,7 @@ const TABULAR_DURATION_STYLE = {
158
} as const;
159
160
function ThreadListV2Duration(props: {
161
+ readonly environmentId: EnvironmentId;
162
readonly startedAt: string | null;
163
readonly leadingSpace: boolean;
164
}) {
@@ -163,7 +169,7 @@ function ThreadListV2Duration(props: {
169
<>
170
{props.leadingSpace ? " " : null}
171
<RNText style={TABULAR_DURATION_STYLE}>
166
- {formatWorkingDurationLabel(nowMs - startedAtMs)}
172
+ {formatWorkingDurationLabel(toServerClock(props.environmentId, nowMs) - startedAtMs)}
173
</RNText>
174
</>
175
);
@@ -1254,11 +1260,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
1260
{statusLabel.label}
1261
{status === "working" ? (
1262
<ThreadListV2Duration
1263
+ environmentId={thread.environmentId}
1264
startedAt={resolveThreadWorkingStartedAt(thread)}
1265
leadingSpace={statusLabel.label !== null}
1266
/>
1267
) : status === "waiting" ? (
1268
<ThreadListV2Duration
1269
+ environmentId={thread.environmentId}
1270
startedAt={thread.latestRun?.completedAt ?? null}
1271
leadingSpace={statusLabel.label !== null}
1272
/>
apps/server/src/ws.ts
+1
@@ -1885,6 +1885,7 @@ export const layerWsRpc = (
1885
}),
1886
newProjectsRoot: managedFolders.namedProjectsRoot,
1887
...(lastEventLoopStall === undefined ? {} : { lastEventLoopStall }),
1888
+ serverTime: DateTime.formatIso(yield* DateTime.now),
1889
};
1890
});
1891
apps/web/src/components/ChatView.logic.ts
+6
-1
@@ -1,3 +1,4 @@
1
+import { toServerClock } from "@t3tools/client-runtime/clock";
2
import { type OrchestrationV2ProviderTurn, type RunAttemptId } from "@t3tools/contracts";
3
import {
4
deriveLatestThreadRun,
@@ -979,15 +980,19 @@ export interface LocalDispatchSnapshot {
980
export function createLocalDispatchSnapshot(
981
activeThread: Thread | undefined,
982
options?: {
983
+ environmentId?: EnvironmentId;
984
preparingWorktree?: boolean;
985
latestUserMessageId?: ChatMessage["id"] | null;
986
submissionIntent?: ComposerSubmissionIntent;
987
},
988
): LocalDispatchSnapshot {
989
+ const environmentId = options?.environmentId ?? activeThread?.environmentId;
990
const latestRun = activeThread?.latestRun ?? null;
991
const runtime = activeThread?.runtime ?? null;
992
return {
990
- startedAt: new Date().toISOString(),
993
+ startedAt: new Date(
994
+ environmentId === undefined ? Date.now() : toServerClock(environmentId, Date.now()),
995
+ ).toISOString(),
996
preparingWorktree: Boolean(options?.preparingWorktree),
997
submissionIntent: options?.submissionIntent ?? "foreground",
998
latestUserMessageId: options?.latestUserMessageId ?? null,
apps/web/src/components/ChatView.tsx
+1
@@ -1441,6 +1441,7 @@ export default function ChatView(props: ChatViewProps) {
1441
isSendBusy,
1442
backgroundSubmissionPending,
1443
} = useLocalDispatchState({
1444
+ environmentId,
1445
activeThread,
1446
activeLatestRun,
1447
latestUserMessageId:
apps/web/src/components/chat/TimelineWorkGroupRows.logic.ts
+9
-9
@@ -1,20 +1,20 @@
1
+import { toServerClock } from "@t3tools/client-runtime/clock";
2
+import type { EnvironmentId } from "@t3tools/contracts";
3
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
4
3
-function formatWorkingTimer(startIso: string, endIso: string): string | null {
5
+export function formatWorkingTimerNow(startIso: string, environmentId: EnvironmentId): string {
6
const startedAtMs = Date.parse(startIso);
5
- const endedAtMs = Date.parse(endIso);
6
- if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
7
- return null;
7
+ if (!Number.isFinite(startedAtMs)) {
8
+ return "0s";
9
}
10
10
- const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
11
+ const elapsedSeconds = Math.max(
12
+ 0,
13
+ Math.floor((toServerClock(environmentId, Date.now()) - startedAtMs) / 1000),
14
+ );
15
if (elapsedSeconds < 60) {
16
return `${elapsedSeconds}s`;
17
}
18
19
return formatDuration(elapsedSeconds * 1_000);
20
}
17
-
18
-export function formatWorkingTimerNow(startIso: string): string {
19
- return formatWorkingTimer(startIso, new Date().toISOString()) ?? "0s";
20
-}
apps/web/src/components/chat/TimelineWorkGroupRows.tsx
+2
-1
@@ -127,9 +127,10 @@ export const WorkGroupSection = memo(function WorkGroupSection({
127
});
128
129
function WorkingTimer({ createdAt }: { createdAt: string }) {
130
+ const { activeThreadEnvironmentId } = use(TimelineRowCtx);
131
return (
132
<span
132
- ref={tickTextContent(() => formatWorkingTimerNow(createdAt), true)}
133
+ ref={tickTextContent(() => formatWorkingTimerNow(createdAt, activeThreadEnvironmentId), true)}
134
className="tabular-nums"
135
/>
136
);
apps/web/src/components/chat/useLocalDispatchState.ts
+3
-1
@@ -1,4 +1,4 @@
1
-import { type MessageId, type RuntimeRequestId } from "@t3tools/contracts";
1
+import { type EnvironmentId, type MessageId, type RuntimeRequestId } from "@t3tools/contracts";
2
import { useState } from "react";
3
import { type ComposerSubmissionIntent } from "../../composer-logic";
4
import { type SessionPhase, type Thread } from "../../types";
@@ -9,6 +9,7 @@ import {
9
} from "../ChatView.logic";
10
11
export function useLocalDispatchState(input: {
12
+ environmentId: EnvironmentId;
13
activeThread: Thread | undefined;
14
activeLatestRun: Thread["latestRun"] | null;
15
latestUserMessageId: MessageId | null;
@@ -50,6 +51,7 @@ export function useLocalDispatchState(input: {
51
}
52
return createLocalDispatchSnapshot(input.activeThread, {
53
...options,
54
+ environmentId: input.environmentId,
55
latestUserMessageId: input.latestUserMessageId,
56
});
57
});
apps/web/src/components/sidebar/SidebarThreadRow.tsx
+15
-6
@@ -26,6 +26,7 @@ import {
26
resolveThreadProviderStack,
27
} from "@t3tools/client-runtime/state/models";
28
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
29
+import { toServerClock } from "@t3tools/client-runtime/clock";
30
import {
31
AuthOrchestrationOperateScope,
32
type EnvironmentId,
@@ -163,18 +164,20 @@ function JumpHintBadge(props: { label: string }) {
164
const JUMP_HINT_SLOT_CLASS_NAME =
165
"[&>:not([data-jump-hint])]:invisible [&>:not([data-jump-hint])]:absolute";
166
166
-function WorkingDuration(props: { startedAt: string | null }) {
167
+function WorkingDuration(props: { environmentId: EnvironmentId; startedAt: string | null }) {
168
const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN;
169
if (Number.isNaN(startedMs)) return null;
169
- return <WorkingDurationLabel startedMs={startedMs} />;
170
+ return <WorkingDurationLabel environmentId={props.environmentId} startedMs={startedMs} />;
171
}
172
173
// Self-ticking so only this span re-renders each second, not the whole row;
174
// the shared tick lands every working row's update in the same frame.
174
-function WorkingDurationLabel(props: { startedMs: number }) {
175
+function WorkingDurationLabel(props: { environmentId: EnvironmentId; startedMs: number }) {
176
const nowMs = useNowSecond();
177
return (
177
- <span className="tabular-nums">{formatWorkingDurationLabel(nowMs - props.startedMs)}</span>
178
+ <span className="tabular-nums">
179
+ {formatWorkingDurationLabel(toServerClock(props.environmentId, nowMs) - props.startedMs)}
180
+ </span>
181
);
182
}
183
@@ -1524,11 +1527,17 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
1527
{topStatus.label}
1528
{status === "preparing" || status === "working" ? (
1529
<span aria-hidden>
1527
- <WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
1530
+ <WorkingDuration
1531
+ environmentId={thread.environmentId}
1532
+ startedAt={resolveWorkingStartedAt(thread)}
1533
+ />
1534
</span>
1535
) : status === "waiting" ? (
1536
<span aria-hidden>
1531
- <WorkingDuration startedAt={thread.latestRun?.completedAt ?? null} />
1537
+ <WorkingDuration
1538
+ environmentId={thread.environmentId}
1539
+ startedAt={thread.latestRun?.completedAt ?? null}
1540
+ />
1541
</span>
1542
) : null}
1543
</span>
packages/client-runtime/src/clock.test.ts
+36
-1
@@ -1,5 +1,6 @@
1
+import { EnvironmentId } from "@t3tools/contracts";
2
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
-import { deadlineStore, secondTick } from "./clock.ts";
3
+import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts";
4
5
describe("deadlineStore", () => {
6
afterEach(() => {
@@ -138,3 +139,37 @@ describe("secondTick", () => {
139
expect(vi.getTimerCount()).toBe(0);
140
});
141
});
142
+
143
+describe("server clock", () => {
144
+ const HOUR = 3_600_000;
145
+
146
+ it("counts from a host clock running ahead, minus only the reply's latency", () => {
147
+ const environmentId = EnvironmentId.make("ahead");
148
+ recordServerClock(environmentId, {
149
+ serverTimeMs: HOUR + 1_000,
150
+ requestedAtMs: 900,
151
+ receivedAtMs: 1_050,
152
+ });
153
+ expect(toServerClock(environmentId, 2_050)).toBe(HOUR + 2_000);
154
+ });
155
+
156
+ it("counts from a host clock running behind, minus only the request's latency", () => {
157
+ const environmentId = EnvironmentId.make("behind");
158
+ recordServerClock(environmentId, {
159
+ serverTimeMs: 1_000,
160
+ requestedAtMs: HOUR + 900,
161
+ receivedAtMs: HOUR + 1_050,
162
+ });
163
+ expect(toServerClock(environmentId, HOUR + 1_900)).toBe(2_000);
164
+ });
165
+
166
+ it("leaves clocks that agree within the round trip unshifted", () => {
167
+ const environmentId = EnvironmentId.make("synced");
168
+ recordServerClock(environmentId, {
169
+ serverTimeMs: 5_000,
170
+ requestedAtMs: 1_000,
171
+ receivedAtMs: 9_000,
172
+ });
173
+ expect(toServerClock(environmentId, 12_345)).toBe(12_345);
174
+ });
175
+});
packages/client-runtime/src/clock.ts
+39
@@ -1,5 +1,7 @@
1
// @effect-diagnostics globalTimers:off globalDate:off - Render clocks for React hooks, outside an Effect runtime.
2
3
+import type { EnvironmentId } from "@t3tools/contracts";
4
+
5
/**
6
* A `useSyncExternalStore`-shaped clock. Snapshots stay cached between
7
* notifications while subscribed, as `useSyncExternalStore` requires.
@@ -70,6 +72,43 @@ export const minuteTick: ClockStore<string> = makeTickStore(
72
60_000,
73
);
74
75
+// How far each environment's clock runs ahead of this one. Timers read it on
76
+// every tick, so a reconnect's new reading lands without a re-render.
77
+const serverClockOffsets = new Map<EnvironmentId, number>();
78
+
79
+/**
80
+ * The host stamped `serverTimeMs` between the request and its reply, so the
81
+ * offset lies within that window. Keep the one nearest 0, so clocks that agree
82
+ * read as 0 instead of shifting every timer by network latency.
83
+ */
84
+export function recordServerClock(
85
+ environmentId: EnvironmentId,
86
+ sample: {
87
+ readonly serverTimeMs: number | undefined;
88
+ readonly requestedAtMs: number;
89
+ readonly receivedAtMs: number;
90
+ },
91
+): void {
92
+ const { serverTimeMs, requestedAtMs, receivedAtMs } = sample;
93
+ if (serverTimeMs === undefined || !Number.isFinite(serverTimeMs)) {
94
+ serverClockOffsets.delete(environmentId);
95
+ return;
96
+ }
97
+ serverClockOffsets.set(
98
+ environmentId,
99
+ serverTimeMs > receivedAtMs
100
+ ? serverTimeMs - receivedAtMs
101
+ : serverTimeMs < requestedAtMs
102
+ ? serverTimeMs - requestedAtMs
103
+ : 0,
104
+ );
105
+}
106
+
107
+/** Converts client epoch milliseconds to the environment's clock. */
108
+export function toServerClock(environmentId: EnvironmentId, clientMs: number): number {
109
+ return clientMs + (serverClockOffsets.get(environmentId) ?? 0);
110
+}
111
+
112
export interface DeadlineStore extends ClockStore<boolean> {
113
/**
114
* Re-checks `Date.now()` and notifies if the deadline has passed. For callers
packages/client-runtime/src/rpc/session.test.ts
+24
@@ -35,6 +35,7 @@ import {
35
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
36
import * as Persistence from "../platform/persistence.ts";
37
import * as RpcSession from "./session.ts";
38
+import { toServerClock } from "../clock.ts";
39
import { makeEnvironmentServerConfigState } from "../state/server.ts";
40
import { applyServerConfigProjection } from "../state/serverConfigProjection.ts";
41
@@ -1048,6 +1049,29 @@ describe("RpcSessionFactory", () => {
1049
}),
1050
);
1051
1052
+ it.effect("reads the host clock from each connection's config, dropping it when absent", () =>
1053
+ Effect.gen(function* () {
1054
+ const { factory, sockets } = yield* makeFactory();
1055
+ const connectWith = (config: unknown) =>
1056
+ Effect.scoped(
1057
+ Effect.gen(function* () {
1058
+ const socketIndex = sockets.length;
1059
+ const session = yield* factory.connect(PREPARED);
1060
+ const ready = yield* Effect.forkChild(session.ready);
1061
+ const socket = yield* awaitSocket(sockets, socketIndex);
1062
+ socket.open();
1063
+ yield* completeInitialConfig(socket, config);
1064
+ yield* Fiber.join(ready);
1065
+ }),
1066
+ );
1067
+
1068
+ yield* connectWith({ ...ENCODED_SERVER_CONFIG, serverTime: "1970-01-01T01:00:00.000Z" });
1069
+ expect(toServerClock(PREPARED.environmentId, 0)).toBe(3_600_000);
1070
+ yield* connectWith(ENCODED_SERVER_CONFIG);
1071
+ expect(toServerClock(PREPARED.environmentId, 0)).toBe(0);
1072
+ }),
1073
+ );
1074
+
1075
it.effect("reaches ready when a newer server sends unknown config members", () =>
1076
Effect.gen(function* () {
1077
const { factory, sockets } = yield* makeFactory();
packages/client-runtime/src/rpc/session.ts
+13
@@ -9,6 +9,7 @@ import {
9
SOCKET_FRAME_PARTS_QUERY_PARAM,
10
} from "@t3tools/shared/socketFrameParts";
11
import * as Cause from "effect/Cause";
12
+import * as Clock from "effect/Clock";
13
import * as Context from "effect/Context";
14
import * as Deferred from "effect/Deferred";
15
import * as Duration from "effect/Duration";
@@ -46,6 +47,7 @@ import {
47
withoutEnvironmentThemes,
48
} from "../state/serverConfigProjection.ts";
49
import { environmentMismatchError } from "../connection/errors.ts";
50
+import { recordServerClock } from "../clock.ts";
51
52
const SOCKET_OPEN_TIMEOUT = "15 seconds";
53
@@ -295,6 +297,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
297
reason: "remote-unavailable",
298
detail: `${connection.label} config subscription ended.`,
299
});
300
+ const configRequestedAtMs = yield* Clock.currentTimeMillis;
301
const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
302
onDemandSnapshots(serverConfigInput),
303
).pipe(
@@ -332,6 +335,16 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
335
yield* PubSub.publish(serverConfigUpdates, buffered.value);
336
}
337
if (event.type === "snapshot") {
338
+ // Later snapshots may repeat the first one's serverTime. Record
339
+ // before readiness so the first timers already use its clock.
340
+ if (!(yield* Deferred.isDone(initialConfigDeferred))) {
341
+ const { serverTime } = event.config;
342
+ recordServerClock(connection.environmentId, {
343
+ serverTimeMs: serverTime === undefined ? undefined : Date.parse(serverTime),
344
+ requestedAtMs: configRequestedAtMs,
345
+ receivedAtMs: yield* Clock.currentTimeMillis,
346
+ });
347
+ }
348
yield* Deferred.succeed(initialConfigDeferred, event.config);
349
}
350
}),
packages/client-runtime/src/state/server.ts
+3
-1
@@ -489,11 +489,13 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf
489
const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
490
config: ServerConfig,
491
) {
492
- // A cached stall would read as a fresh freeze on the next launch.
492
+ // A cached stall would read as a fresh freeze on the next launch, and
493
+ // serverTime changes every connect, which would rewrite the cache each time.
494
const {
495
environmentThemes: _themes,
496
usageLimitSources: _sources,
497
lastEventLoopStall: _stall,
498
+ serverTime: _serverTime,
499
...cacheable
500
} = config;
501
if (lastPersisted !== undefined && sameCacheValue(lastPersisted, cacheable)) {
packages/contracts/src/server.ts
+6
@@ -726,6 +726,12 @@ export const ServerConfig = Schema.Struct({
726
* answering. Clients do not cache it, since it describes the host at connect.
727
*/
728
lastEventLoopStall: Schema.optionalKey(ServerEventLoopStall),
729
+ /**
730
+ * The host's clock when it built the config, so clients can count live
731
+ * elapsed times against host timestamps despite clock skew. Only a
732
+ * subscription's first snapshot is fresh; later snapshots may repeat it.
733
+ */
734
+ serverTime: Schema.optionalKey(IsoDateTime),
735
/**
736
* Never sent in a config snapshot: the theme stream emits the current set
737
* before any change, so a snapshot carrying it too would hand every