Skip to content

Commit 1af6333

Browse files
donjorrsi-pr-agent
authored andcommitted
fix(upstream-fixes): fork controls respect upstream's split session permissions
Upstream `28ce9d1c175`, `321c6f9d26e`, and `2eda8ac6a31` split environment admin, file write, and source control write scopes. Fork controls now gate on them: checkout-move retry and undo, link-to-thread menus, rich file preview editing, terminal retarget, sidebar thread actions, and pairing scopes. Fork auth requests go through the shared authenticated request boundary. Squashes: - 1e4cd7d fix(upstream-fixes): fork controls respect upstream's split session permissions - ef76810 fixup! fix(upstream-fixes): fork controls respect upstream's split session permissions Fork-Domain: upstream-fixes Fork-Tier: bugfix Fork-Upstreamable: no
1 parent 5151ad4 commit 1af6333

14 files changed

Lines changed: 266 additions & 82 deletions

‎apps/web/src/components/BranchToolbarBranchSelector.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -563,17 +563,17 @@ export function BranchToolbarBranchSelector({
563563
});
564564
};
565565

566-
const retryOrUndoCheckoutMove = useCallback(() => {
566+
const retryOrUndoCheckoutMove = () => {
567567
const move = serverThread?.checkoutMove;
568-
if (!move || checkoutMoveControlsLocked) return;
568+
if (!move || checkoutMoveControlsLocked || !canOperateThread) return; // fork-hook: upstream-fixes/split-session-permissions
569569
const undo = move.status === "committed";
570570
void runCheckoutMove({
571571
requestedPath: undo ? move.source.checkoutRoot : move.requestedPath,
572572
expectedCheckoutRoot: checkoutMoveExpectedRoot(move),
573573
...(undo ? { reverseOfRequestId: move.requestId } : {}),
574574
failureTitle: undo ? "Failed to undo checkout move" : "Failed to retry checkout move",
575575
});
576-
}, [checkoutMoveControlsLocked, runCheckoutMove, serverThread?.checkoutMove]);
576+
}; // fork-hook: upstream-fixes/split-session-permissions
577577
const undoUnavailable =
578578
serverThread?.checkoutMove?.status === "committed" &&
579579
staleUndoRequestId === serverThread.checkoutMove.requestId;
@@ -853,7 +853,7 @@ export function BranchToolbarBranchSelector({
853853
<Button
854854
variant="ghost"
855855
size="micro" // fork-hook: zmux-estate/checkout-move-size
856-
disabled={checkoutMoveControlsLocked || undoUnavailable}
856+
disabled={checkoutMoveControlsLocked || undoUnavailable || !canOperateThread} // fork-hook: upstream-fixes/split-session-permissions
857857
onClick={retryOrUndoCheckoutMove}
858858
aria-label={`${displayedCheckoutMove.label}. ${displayedCheckoutMove.detail}`}
859859
/>

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,6 +1124,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
11241124
props,
11251125
children: linkChildren,
11261126
canOpenInPreview,
1127+
canOperateHost,
11271128
faviconHost,
11281129
openChangeRequestLink,
11291130
linkedThreadPullRequestFor,

‎apps/web/src/components/Sidebar.logic.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,17 @@ export type SidebarThreadGroupContextMenuId =
721721
| `move-to-group:${string}`
722722
| "move-out-of-group";
723723

724+
export function isSidebarThreadGroupContextMenuId(
725+
id: string,
726+
): id is SidebarThreadGroupContextMenuId {
727+
return (
728+
id === "create-thread-group" ||
729+
id === "move-to-group" ||
730+
id === "move-out-of-group" ||
731+
id.startsWith("move-to-group:")
732+
);
733+
} // fork-hook: upstream-fixes/split-session-permissions
734+
724735
export function buildCreateThreadGroupContextMenuItem(input: {
725736
readonly count: number;
726737
readonly eligible: boolean;

‎apps/web/src/components/Sidebar.tsx‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ import {
164164
resolveActiveThreadRouteRef,
165165
resolveThreadRouteTarget,
166166
} from "../threadRoutes";
167+
import { useAtomCommand } from "../state/use-atom-command"; // fork-hook: upstream-fixes/thread-group-title-command
167168
import type { SidebarThreadSummary } from "../types";
168169
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
169170
import { cn } from "~/lib/utils";
@@ -190,10 +191,10 @@ import {
190191
buildSidebarListItems,
191192
buildSidebarThreadGroupLayout,
192193
buildThreadGroupMembershipContextMenuItems,
193-
deleteSelectedThreadEntries,
194194
filterSidebarProjectScopeItems,
195195
firstValidTimestampMs,
196196
isSidebarNestedLinkClick,
197+
isSidebarThreadGroupContextMenuId, // fork-hook: upstream-fixes/split-session-permissions
197198
isTrailingDoubleClick,
198199
orderItemsByPreferredIds,
199200
planSidebarThreadDrop,
@@ -2645,6 +2646,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
26452646
});
26462647
return;
26472648
}
2649+
if (clicked.value === "move-out-of-group") {
2650+
// Group membership is local UI state, so it stays available without the operate scope.
2651+
setThreadGroupMembership(projectKey, projectThreadKeys, [threadKey], { kind: "none" });
2652+
return;
2653+
} // fork-hook: upstream-fixes/split-session-permissions
2654+
if (isSidebarThreadGroupContextMenuId(clicked.value)) return; // fork-hook: upstream-fixes/split-session-permissions
26482655
if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return;
26492656
if (clicked.value?.startsWith("snooze:")) {
26502657
const preset =
@@ -2758,9 +2765,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
27582765
case "mark-unread":
27592766
markThreadUnread(threadRef);
27602767
return;
2761-
case "move-out-of-group":
2762-
setThreadGroupMembership(projectKey, projectThreadKeys, [threadKey], { kind: "none" });
2763-
return;
27642768
case "copy-path":
27652769
if (!threadWorkspacePath) {
27662770
toastManager.add(
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
import {
2+
AuthTerminalOperateScope,
3+
EnvironmentId,
4+
ThreadId,
5+
type AuthEnvironmentScope,
6+
} from "@t3tools/contracts";
7+
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
8+
import { nextTerminalAttachSeedState } from "@t3tools/client-runtime/state/terminal";
9+
import { AsyncResult } from "effect/reactivity";
10+
import { act, create, type ReactTestRenderer } from "react-test-renderer";
11+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12+
import type {
13+
GhosttyTerminalSurface,
14+
GhosttyTerminalSurfaceOptions,
15+
} from "~/terminal/ghostty/surface";
16+
import { terminalAttachmentId } from "../terminalAttachmentIdentity";
17+
18+
const state = vi.hoisted(() => ({
19+
allowed: true,
20+
listeners: new Set<() => void>(),
21+
resize: vi.fn(),
22+
otherCommand: vi.fn(),
23+
createSurface:
24+
vi.fn<
25+
(
26+
mount: HTMLElement,
27+
options: GhosttyTerminalSurfaceOptions,
28+
) => Promise<GhosttyTerminalSurface>
29+
>(),
30+
}));
31+
32+
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
33+
vi.mock("../hooks/useSettings", () => ({
34+
getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
35+
useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
36+
select(DEFAULT_CLIENT_SETTINGS),
37+
}));
38+
vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => state.otherCommand }));
39+
vi.mock("../localApi", () => ({ readLocalApi: () => null }));
40+
vi.mock("../state/server", () => ({
41+
serverEnvironment: { configValueAtom: () => "config" },
42+
}));
43+
vi.mock("../state/preview", () => ({ previewEnvironment: { open: "open" } }));
44+
vi.mock("../state/terminal", () => ({ terminalEnvironment: { resize: "resize", write: "write" } }));
45+
vi.mock("../state/use-atom-command", () => ({
46+
useAtomCommand: (command: string) => (command === "resize" ? state.resize : state.otherCommand),
47+
}));
48+
vi.mock("../state/terminalSessions", () => ({
49+
useAttachedTerminalSession: () => session,
50+
}));
51+
vi.mock("~/terminal/ghostty/surface", () => ({
52+
GhosttyTerminalSurface: { create: state.createSurface },
53+
}));
54+
vi.mock("../state/session", async () => {
55+
const { useSyncExternalStore } = await import("react");
56+
const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
57+
id !== null &&
58+
(scope !== AuthTerminalOperateScope || id !== threadRef.environmentId || state.allowed);
59+
return {
60+
readEnvironmentScope,
61+
useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
62+
useSyncExternalStore(
63+
(listener) => {
64+
state.listeners.add(listener);
65+
return () => state.listeners.delete(listener);
66+
},
67+
() => readEnvironmentScope(id, scope),
68+
),
69+
};
70+
});
71+
72+
import { TerminalViewport } from "./ThreadTerminalDrawer";
73+
74+
const threadRef = {
75+
environmentId: EnvironmentId.make("secondary-terminal"),
76+
threadId: ThreadId.make("thread"),
77+
};
78+
const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };
79+
let renderer: ReactTestRenderer | undefined;
80+
81+
beforeEach(() => {
82+
state.allowed = true;
83+
state.listeners.clear();
84+
state.resize.mockReset().mockResolvedValue(AsyncResult.success(undefined));
85+
state.otherCommand.mockReset().mockResolvedValue(AsyncResult.success(undefined));
86+
// A surface can report its initial grid while asynchronous WASM setup is
87+
// pending. Keep that unrelated setup pending while exercising its callback.
88+
state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));
89+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
90+
vi.stubGlobal("document", {
91+
body: {},
92+
documentElement: { classList: { contains: () => false } },
93+
querySelector: () => null,
94+
createElement: () => ({ getContext: () => null }),
95+
});
96+
vi.stubGlobal("getComputedStyle", () => ({
97+
colorScheme: "light",
98+
backgroundColor: "",
99+
color: "",
100+
getPropertyValue: () => "",
101+
}));
102+
});
103+
104+
afterEach(async () => {
105+
await act(async () => renderer?.unmount());
106+
renderer = undefined;
107+
vi.unstubAllGlobals();
108+
});
109+
110+
it("sends the attachment id with a resize that passes the target terminal grant recheck", async () => {
111+
await act(async () => {
112+
renderer = create(
113+
<TerminalViewport
114+
advancedTypography={false}
115+
threadRef={threadRef}
116+
threadId={threadRef.threadId}
117+
terminalId="terminal-1"
118+
terminalLabel="Terminal 1"
119+
cwd="/repo"
120+
onSessionExited={state.otherCommand}
121+
focusRequestId={0}
122+
autoFocus={false}
123+
visible={true}
124+
resizeEpoch={0}
125+
drawerHeight={200}
126+
keybindings={[]}
127+
attached
128+
restoreFocusOnReattach
129+
/>,
130+
{ createNodeMock: () => ({ closest: () => null, contains: () => false }) },
131+
);
132+
});
133+
expect(state.createSurface).toHaveBeenCalledOnce();
134+
const onResize = state.createSurface.mock.calls[0]![1].onResize;
135+
if (!onResize) throw new Error("The terminal did not register its resize callback.");
136+
137+
onResize(80, 24);
138+
expect(state.resize).toHaveBeenCalledExactlyOnceWith({
139+
environmentId: threadRef.environmentId,
140+
input: {
141+
threadId: threadRef.threadId,
142+
terminalId: "terminal-1",
143+
attachmentId: terminalAttachmentId("terminal-1"),
144+
cols: 80,
145+
rows: 24,
146+
},
147+
});
148+
149+
// The connection updates before React commits its external-store update.
150+
// Other environments retain access; only this terminal's target is revoked.
151+
state.allowed = false;
152+
onResize(120, 40);
153+
expect(state.resize).toHaveBeenCalledTimes(1);
154+
155+
state.allowed = true;
156+
onResize(100, 30);
157+
expect(state.resize).toHaveBeenCalledTimes(2);
158+
expect(state.resize).toHaveBeenLastCalledWith({
159+
environmentId: threadRef.environmentId,
160+
input: {
161+
threadId: threadRef.threadId,
162+
terminalId: "terminal-1",
163+
attachmentId: terminalAttachmentId("terminal-1"),
164+
cols: 100,
165+
rows: 30,
166+
},
167+
});
168+
});

‎apps/web/src/components/ThreadTerminalDrawer.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,7 @@ function TerminalSessionViewport({
719719
useEffect(() => {
720720
if (launchIdentityRef.current === launchIdentity || !attached) return;
721721
launchIdentityRef.current = launchIdentity;
722+
if (!hasTerminalWriteAccess()) return; // fork-hook: upstream-fixes/split-session-permissions
722723
void retargetTerminal();
723724
}, [attached, launchIdentity]);
724725
const writeTerminal = useEffectEvent((data: string) =>

‎apps/web/src/components/chat/GitHubDestinationLink.fork.tsx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,8 @@ export interface GitHubDestinationRenderInput {
277277
readonly props: ComponentPropsWithoutRef<"a">;
278278
readonly children: ReactNode;
279279
readonly canOpenInPreview: boolean;
280+
/** Operate scope on the link's thread environment; gates the link-to-thread write. */
281+
readonly canOperateHost: boolean;
280282
readonly faviconHost: string | null;
281283
readonly openChangeRequestLink: (
282284
event: MouseEvent<HTMLAnchorElement | HTMLButtonElement>,
@@ -389,8 +391,9 @@ export function useGitHubDestinationLinkFork(accept: {
389391
event.stopPropagation();
390392
const api = readLocalApi();
391393
if (!api) return;
392-
const threadLinkAction =
393-
input.linkedThreadPullRequestFor(input.href) !== null
394+
const threadLinkAction = !input.canOperateHost
395+
? undefined
396+
: input.linkedThreadPullRequestFor(input.href) !== null
394397
? "unlink-from-thread"
395398
: input.resolveThreadPullRequest(input.href) === null
396399
? undefined

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1101,7 +1101,7 @@ export default function FilePreviewPanel({
11011101
fileState: file.data === null ? "loading" : file.data.truncated ? "truncated" : "ready",
11021102
renderPreferred: renderMarkdownPreferred,
11031103
revealHandled,
1104-
readOnly: isHostFile,
1104+
readOnly: isHostFile || !canWriteFiles, // fork-hook: upstream-fixes/split-session-permissions
11051105
}); // fork-hook: markdown-editing/rich-preview-mode
11061106
const renderMarkdown = richMarkdownPreview.rendered; // fork-hook: markdown-editing/rich-preview-rendered
11071107
const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled;

‎apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,11 +143,14 @@ export function PullRequestMarkdownEditor({
143143
<Button
144144
size="xs"
145145
variant="outline"
146-
disabled={!canWriteSourceControl || saving || (empty && !allowEmpty)}
146+
disabled={
147+
!canWriteSourceControl || saving || attachmentFork.busy || (empty && !allowEmpty)
148+
} // fork-hook: upstream-fixes/split-session-permissions
147149
onClick={() => {
148150
if (
149151
!readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
150152
saving ||
153+
attachmentFork.busy || // fork-hook: upstream-fixes/split-session-permissions
151154
(empty && !allowEmpty)
152155
)
153156
return;

‎apps/web/src/components/settings/connectionsSessionScopes.fork.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,13 @@ describe("connectionsSessionScopesFork", () => {
4343

4444
it("reads a browser's scopes from its session", () => {
4545
expect(
46-
connectionsSessionScopesFork(undefined, AuthAdministrativeScopes, standardSession, false),
47-
).toEqual(AuthStandardClientScopes);
46+
connectionsSessionScopesFork(undefined, AuthStandardClientScopes, standardSession, false),
47+
).toEqual([AuthOrchestrationReadScope]);
48+
});
49+
50+
it("prefers the session's permissions over its legacy scopes", () => {
51+
const session: AuthSessionState = { ...standardSession, permissions: [AuthAccessWriteScope] };
52+
const scopes = connectionsSessionScopesFork({}, AuthStandardClientScopes, session, true);
53+
expect(scopes).toEqual([AuthAccessWriteScope]);
4854
});
4955
});

0 commit comments

Comments
 (0)