Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge e0909c502e Optimize sidebar thread rename rerenders
Co-authored-by: Julius Marminge <[email protected]>
2026-06-08 16:10:17 +00:00
5 changed files with 96 additions and 282 deletions

No files matched your search

+73 -82
View File
@@ -284,11 +284,7 @@ interface SidebarThreadRowProps {
isActive: boolean;
jumpLabel: string | null;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
isRenaming: boolean;
confirmingArchiveThreadKey: string | null;
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
@@ -314,17 +310,77 @@ interface SidebarThreadRowProps {
openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void;
}
interface SidebarThreadRenameInputProps {
thread: SidebarThreadSummary;
threadRef: ScopedThreadRef;
commitRename: (
threadRef: ScopedThreadRef,
newTitle: string,
originalTitle: string,
) => Promise<void>;
cancelRename: () => void;
}
const SidebarThreadRenameInput = memo(function SidebarThreadRenameInput({
thread,
threadRef,
commitRename,
cancelRename,
}: SidebarThreadRenameInputProps) {
const [title, setTitle] = useState(thread.title);
const committedRef = useRef(false);
const handleInputRef = useCallback((element: HTMLInputElement | null) => {
if (!element) return;
element.focus();
element.select();
}, []);
const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value);
}, []);
const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
event.stopPropagation();
if (event.key === "Enter") {
event.preventDefault();
committedRef.current = true;
void commitRename(threadRef, title, thread.title);
} else if (event.key === "Escape") {
event.preventDefault();
committedRef.current = true;
cancelRename();
}
},
[cancelRename, commitRename, thread.title, threadRef, title],
);
const handleBlur = useCallback(() => {
if (!committedRef.current) {
void commitRename(threadRef, title, thread.title);
}
}, [commitRename, thread.title, threadRef, title]);
const handleClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
event.stopPropagation();
}, []);
return (
<input
ref={handleInputRef}
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={title}
onChange={handleChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
onClick={handleClick}
/>
);
});
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
isActive,
jumpLabel,
appSettingsConfirmThreadArchive,
renamingThreadKey,
renamingTitle,
setRenamingTitle,
renamingInputRef,
renamingCommittedRef,
isRenaming,
confirmingArchiveThreadKey,
setConfirmingArchiveThreadKey,
confirmArchiveButtonRefs,
@@ -454,45 +510,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
},
[openPrLink, prStatus],
);
const handleRenameInputRef = useCallback(
(element: HTMLInputElement | null) => {
if (element && renamingInputRef.current !== element) {
renamingInputRef.current = element;
element.focus();
element.select();
}
},
[renamingInputRef],
);
const handleRenameInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setRenamingTitle(event.target.value);
},
[setRenamingTitle],
);
const handleRenameInputKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
event.stopPropagation();
if (event.key === "Enter") {
event.preventDefault();
renamingCommittedRef.current = true;
void commitRename(threadRef, renamingTitle, thread.title);
} else if (event.key === "Escape") {
event.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
},
[cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef],
);
const handleRenameInputBlur = useCallback(() => {
if (!renamingCommittedRef.current) {
void commitRename(threadRef, renamingTitle, thread.title);
}
}, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]);
const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
event.stopPropagation();
}, []);
const handleConfirmArchiveRef = useCallback(
(element: HTMLButtonElement | null) => {
if (element) {
@@ -578,15 +595,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadKey === threadKey ? (
<input
ref={handleRenameInputRef}
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={handleRenameInputChange}
onKeyDown={handleRenameInputKeyDown}
onBlur={handleRenameInputBlur}
onClick={handleRenameInputClick}
{isRenaming ? (
<SidebarThreadRenameInput
thread={thread}
threadRef={threadRef}
commitRename={commitRename}
cancelRename={cancelRename}
/>
) : (
<Tooltip>
@@ -734,10 +748,6 @@ interface SidebarProjectThreadListProps {
threadJumpLabelByKey: ReadonlyMap<string, string>;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
confirmingArchiveThreadKey: string | null;
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
@@ -784,10 +794,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
threadJumpLabelByKey,
appSettingsConfirmThreadArchive,
renamingThreadKey,
renamingTitle,
setRenamingTitle,
renamingInputRef,
renamingCommittedRef,
confirmingArchiveThreadKey,
setConfirmingArchiveThreadKey,
confirmArchiveButtonRefs,
@@ -834,11 +840,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
isActive={activeRouteThreadKey === threadKey}
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
isRenaming={renamingThreadKey === threadKey}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
@@ -1058,7 +1060,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
),
);
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
const [projectRenameTarget, setProjectRenameTarget] = useState<SidebarProjectGroupMember | null>(
null,
@@ -1069,8 +1070,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const [projectGroupingSelection, setProjectGroupingSelection] = useState<
SidebarProjectGroupingMode | "inherit"
>("inherit");
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
const memberProjectByScopedKey = useMemo(
() =>
@@ -1762,7 +1761,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const cancelRename = useCallback(() => {
setRenamingThreadKey(null);
renamingInputRef.current = null;
}, []);
const commitRename = useCallback(
@@ -1771,7 +1769,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const finishRename = () => {
setRenamingThreadKey((current) => {
if (current !== threadKey) return current;
renamingInputRef.current = null;
return null;
});
};
@@ -1925,8 +1922,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
if (clicked === "rename") {
setRenamingThreadKey(threadKey);
setRenamingTitle(thread.title);
renamingCommittedRef.current = false;
return;
}
@@ -2088,10 +2083,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
threadJumpLabelByKey={threadJumpLabelByKey}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
@@ -132,47 +132,6 @@ describe("createManagedRelayQueryManager", () => {
});
});
it("uses schema encoded status keys for equivalent environment inputs", async () => {
const getEnvironmentStatus = vi.fn(() =>
Effect.succeed({
environmentId: environment.environmentId,
endpoint: environment.endpoint,
status: "online" as const,
checkedAt: "2026-06-01T00:00:00.000Z",
}),
);
const manager = createManager({ getEnvironmentStatus });
const reorderedEnvironment = {
linkedAt: environment.linkedAt,
endpoint: {
providerKind: environment.endpoint.providerKind,
wsBaseUrl: environment.endpoint.wsBaseUrl,
httpBaseUrl: environment.endpoint.httpBaseUrl,
},
label: environment.label,
environmentId: environment.environmentId,
} satisfies RelayClientEnvironmentRecord;
setSession();
const atom = manager.environmentStatusAtom({ accountId: "account-1", environment });
registry.get(atom);
await vi.waitFor(() => expect(getEnvironmentStatus).toHaveBeenCalledTimes(1));
registry.get(
manager.environmentStatusAtom({
accountId: "account-1",
environment: reorderedEnvironment,
}),
);
expect(getEnvironmentStatus).toHaveBeenCalledTimes(1);
manager.refreshEnvironmentStatus(registry, {
accountId: "account-1",
environment: reorderedEnvironment,
});
await vi.waitFor(() => expect(getEnvironmentStatus).toHaveBeenCalledTimes(2));
});
it("rejects status responses for a different environment", async () => {
const mismatchedStatus = {
environmentId: EnvironmentId.make("environment-2"),
@@ -1,15 +1,15 @@
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import {
import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import {
RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope,
type RelayClientEnvironmentRecord as RelayClientEnvironmentRecordType,
} from "@t3tools/contracts/relay";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { ManagedRelayClient } from "./managedRelay.ts";
@@ -37,16 +37,6 @@ export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySna
readonly message: string;
}> {}
const EnvironmentStatusKey = Schema.Struct({
accountId: Schema.String,
environment: RelayClientEnvironmentRecord,
});
type EnvironmentStatusKey = typeof EnvironmentStatusKey.Type;
const EnvironmentStatusKeyJson = Schema.fromJsonString(EnvironmentStatusKey);
const encodeEnvironmentStatusKey = Schema.encodeSync(EnvironmentStatusKeyJson);
const decodeEnvironmentStatusKey = Schema.decodeSync(EnvironmentStatusKeyJson);
export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("managed-relay:session"),
@@ -140,13 +130,19 @@ function requireClerkToken(
function statusKey(input: {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecordType;
readonly environment: RelayClientEnvironmentRecord;
}): string {
return encodeEnvironmentStatusKey(input);
return JSON.stringify(input);
}
function parseStatusKey(key: string): EnvironmentStatusKey {
return decodeEnvironmentStatusKey(key);
function parseStatusKey(key: string): {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecord;
} {
return JSON.parse(key) as {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecord;
};
}
function endpointMatches(
@@ -161,7 +157,7 @@ function endpointMatches(
}
function validateEnvironmentStatus(
environment: RelayClientEnvironmentRecordType,
environment: RelayClientEnvironmentRecord,
status: RelayEnvironmentStatusResponse,
): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
if (status.environmentId !== environment.environmentId) {
@@ -272,7 +268,7 @@ export function createManagedRelayQueryManager(
devicesAtom,
environmentStatusAtom: (input: {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecordType;
readonly environment: RelayClientEnvironmentRecord;
}) => environmentStatusAtom(statusKey(input)),
refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {
registry.refresh(environmentsAtom(accountId));
@@ -284,7 +280,7 @@ export function createManagedRelayQueryManager(
registry: AtomRegistry.AtomRegistry,
input: {
readonly accountId: string;
readonly environment: RelayClientEnvironmentRecordType;
readonly environment: RelayClientEnvironmentRecord;
},
): void {
registry.refresh(environmentStatusAtom(statusKey(input)));
-101
View File
@@ -1,101 +0,0 @@
import * as NodeCrypto from "node:crypto";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import {
RelayJwtSignError,
RelayJwtVerifyError,
signRelayJwt,
verifyRelayJwt,
} from "./relayJwt.ts";
const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
privateKeyEncoding: { format: "pem", type: "pkcs8" },
publicKeyEncoding: { format: "pem", type: "spki" },
});
const isRelayJwtSignError = Schema.is(RelayJwtSignError);
const isRelayJwtVerifyError = Schema.is(RelayJwtVerifyError);
describe("relayJwt", () => {
it.effect("signs and verifies relay JWTs", () =>
Effect.gen(function* () {
const token = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: "test+jwt",
payload: {
iss: "https://relay.example.test",
aud: "https://relay.example.test",
sub: "user_123",
jti: "nonce-1",
iat: 100,
exp: 200,
},
});
const payload = yield* verifyRelayJwt({
publicKey: keyPair.publicKey,
token,
typ: "test+jwt",
issuer: "https://relay.example.test",
audience: "https://relay.example.test",
nowEpochSeconds: 150,
});
assert.equal(payload.sub, "user_123");
assert.equal(payload.jti, "nonce-1");
}),
);
it.effect("returns a structured sign error for invalid private key material", () =>
Effect.gen(function* () {
const error = yield* signRelayJwt({
privateKey: "not a pem",
typ: "test+jwt",
payload: {},
}).pipe(Effect.flip);
assert.equal(error._tag, "RelayJwtSignError");
assert.equal(error.typ, "test+jwt");
assert.equal(error.message, "Failed to sign relay JWT (test+jwt).");
assert.equal(isRelayJwtSignError(error), true);
}),
);
it.effect("returns a structured verify error with expected claim context", () =>
Effect.gen(function* () {
const token = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: "test+jwt",
payload: {
iss: "https://relay.example.test",
aud: "https://relay.example.test",
sub: "user_123",
iat: 100,
exp: 200,
},
});
const error = yield* verifyRelayJwt({
publicKey: keyPair.publicKey,
token,
typ: "other+jwt",
issuer: "https://relay.example.test",
audience: "https://relay.example.test",
nowEpochSeconds: 150,
}).pipe(Effect.flip);
assert.equal(error._tag, "RelayJwtVerifyError");
if (error._tag !== "RelayJwtVerifyError") {
assert.fail(`Expected RelayJwtVerifyError, got ${error._tag}`);
}
assert.equal(error.typ, "other+jwt");
assert.equal(error.issuer, "https://relay.example.test");
assert.equal(error.audience, "https://relay.example.test");
assert.equal(error.message, "Failed to verify relay JWT (other+jwt).");
assert.equal(isRelayJwtVerifyError(error), true);
}),
);
});
+6 -37
View File
@@ -1,7 +1,7 @@
import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";
export const RELAY_MINT_REQUEST_TYP = "t3-cloud-mint+jwt";
@@ -10,34 +10,9 @@ export const RELAY_MINT_RESPONSE_TYP = "t3-env-mint+jwt";
export const RELAY_HEALTH_RESPONSE_TYP = "t3-env-health+jwt";
export const RELAY_ACTIVITY_PUBLISH_TYP = "t3-env-activity+jwt";
export class RelayJwtSignError extends Schema.TaggedErrorClass<RelayJwtSignError>()(
"RelayJwtSignError",
{
typ: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to sign relay JWT (${this.typ}).`;
}
}
export class RelayJwtVerifyError extends Schema.TaggedErrorClass<RelayJwtVerifyError>()(
"RelayJwtVerifyError",
{
typ: Schema.String,
issuer: Schema.String,
audience: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to verify relay JWT (${this.typ}).`;
}
}
export const RelayJwtError = Schema.Union([RelayJwtSignError, RelayJwtVerifyError]);
export type RelayJwtError = typeof RelayJwtError.Type;
export class RelayJwtError extends Data.TaggedError("RelayJwtError")<{
readonly cause: unknown;
}> {}
export function normalizeRelayIssuer(value: string): string {
return value.trim().replace(/\/+$/gu, "");
@@ -63,7 +38,7 @@ export function signRelayJwt(input: {
.setProtectedHeader({ alg: "EdDSA", typ: input.typ })
.sign(key);
},
catch: (cause) => new RelayJwtSignError({ typ: input.typ, cause }),
catch: (cause) => new RelayJwtError({ cause }),
});
}
@@ -89,12 +64,6 @@ export function verifyRelayJwt(input: {
});
return verified.payload;
},
catch: (cause) =>
new RelayJwtVerifyError({
typ: input.typ,
issuer: input.issuer,
audience: input.audience,
cause,
}),
catch: (cause) => new RelayJwtError({ cause }),
});
}