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
17 changes: 15 additions & 2 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url";

import { approvalKey, autoDecision } from "./auto-approve.ts";
import { validateBotCwd } from "./bot-cwd.ts";
import { groupTurnCwd } from "./room-cwd.ts";
import * as box from "./box.ts";
import * as composio from "./composio.ts";
import { chiefOfStaffSystemPrompt } from "./chief-of-staff.ts";
Expand Down Expand Up @@ -1478,8 +1479,15 @@ async function runGroupMemberTurn(
// same workspace + memory as a 1:1 turn — the room is a different
// conversation, not a different bot
const worksInWorkspace = instance.driverKind !== "grok" && instance.driverKind !== "boxAgent";
const cwd = worksInWorkspace ? ensureWorkspace(bot.id) : undefined;
const roomSystem = cwd ? `${system}\n${memorySystemPrompt(bot.id).trim()}` : system;
const workspace = worksInWorkspace ? ensureWorkspace(bot.id) : undefined;
// The room's folder pins here — on the first turn that actually
// dispatches, not at PATCH time — so a folder set on a never-used room
// still takes effect, while a room that already worked somewhere never
// has its folder moved underneath it. Off-host members skip the folder
// but must not decide the pin: the room's desk is a property of the
// room, not of whichever member happened to speak first.
const cwd = groupTurnCwd(store.pinGroupCwd(group.id), workspace);
const roomSystem = workspace ? `${system}\n${memorySystemPrompt(bot.id).trim()}` : system;

// run the turn and wait for it to settle, folding the reply text so a
// chained @mention can be routed afterwards
Expand Down Expand Up @@ -2344,6 +2352,11 @@ const server = createServer(async (req, res) => {
if (!responder) return json(res, 400, { error: "invalid default responder" });
patch.defaultResponder = responder;
}
if (body.cwd !== undefined) {
const checked = validateBotCwd(body.cwd);
if (!checked.ok) return json(res, 400, { error: checked.error });
patch.cwd = checked.cwd ?? undefined;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const group = store.patchGroup(m[1], patch);
if (!group) return json(res, 404, { error: "no such room" });
return json(res, 200, { group });
Expand Down
18 changes: 18 additions & 0 deletions server/room-cwd.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";

import { groupTurnCwd } from "./room-cwd.ts";

describe("groupTurnCwd", () => {
it("the room's pinned folder overrides the member's own default", () => {
expect(groupTurnCwd("/tmp/room", "/workspaces/bot-a")).toBe("/tmp/room");
});

it("a room with no folder keeps each member's own default", () => {
expect(groupTurnCwd(null, "/workspaces/bot-a")).toBe("/workspaces/bot-a");
});

it("an off-host member (cloud box, API engine) gets no folder even when the room has one", () => {
expect(groupTurnCwd("/tmp/room", undefined)).toBeUndefined();
expect(groupTurnCwd(null, undefined)).toBeUndefined();
});
});
14 changes: 14 additions & 0 deletions server/room-cwd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// How a room member's turn picks its working folder. The room's pinned
// folder is a shared desk — it overrides the member's own default so every
// member works on the same files — except for a member whose engine runs
// with no host filesystem (Grok API, cloud box): its turn happens
// elsewhere, so handing it a host path would point it at a folder it
// cannot reach. Lives outside the dispatch path so the rule is testable
// without booting the server.

/** `memberDefault` is the folder the member would use on its own (its
* private workspace); undefined = the engine runs off-host. */
export function groupTurnCwd(pinnedRoomCwd: string | null, memberDefault: string | undefined): string | undefined {
if (memberDefault === undefined) return undefined;
return pinnedRoomCwd ?? memberDefault;
}
35 changes: 35 additions & 0 deletions server/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,41 @@ describe("Store task working folder", () => {
});
});

describe("Store room working folder", () => {
beforeEach(() => {
rmSync(DATA_DIR, { recursive: true, force: true });
});

it("pins the room's folder on its first turn, and never again", () => {
const store = new Store(selection);
const bot = store.createBot();
const group = store.createGroup("Team", [bot.id]);
store.patchGroup(group.id, { cwd: "/tmp/project-a" });

// first turn: nothing pinned yet → takes the room's folder
expect(store.pinGroupCwd(group.id)).toBe("/tmp/project-a");
expect(store.group(group.id)?.pinnedCwd).toBe("/tmp/project-a");

// the room's folder moves on; the thread stays where it started working
store.patchGroup(group.id, { cwd: "/tmp/project-b" });
expect(store.pinGroupCwd(group.id)).toBe("/tmp/project-a");

// the pin is durable — a restart must not re-pin from the new folder
const reloaded = new Store(selection);
expect(reloaded.pinGroupCwd(group.id)).toBe("/tmp/project-a");
});

it("pins the default (null) when the room has no folder, so a later folder can't move a running room", () => {
const store = new Store(selection);
const bot = store.createBot();
const group = store.createGroup("Team", [bot.id]);
expect(store.pinGroupCwd(group.id)).toBeNull();
store.patchGroup(group.id, { cwd: "/tmp/project-a" });
expect(store.pinGroupCwd(group.id)).toBeNull();
expect(store.group(group.id)?.pinnedCwd).toBeNull();
});
});

describe("Store task working folder — cloud runs", () => {
beforeEach(() => {
rmSync(DATA_DIR, { recursive: true, force: true });
Expand Down
29 changes: 28 additions & 1 deletion server/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ export interface GroupRecord {
dm?: boolean;
/** transient: the member currently running a turn (never persisted) */
busyBotId?: string | null;
/** the room's shared desk: where member turns run their shell tools,
* overriding each member's own folder. The room pins its own copy on its
* first turn (pinnedCwd). Absent = each member's own default. */
cwd?: string;
/** the folder this room's turns actually run in, pinned on the first
* turn that dispatches. null = each member's own default; absent = not
* pinned yet. See pinGroupCwd for why it never moves. */
pinnedCwd?: string | null;
}

/** One task = one conversation with its own context.
Expand Down Expand Up @@ -504,7 +512,7 @@ export class Store {
);
}

patchGroup(id: string, patch: Partial<Pick<GroupRecord, "name" | "memberIds" | "defaultResponder" | "bulletin" | "unread" | "busyBotId">>): GroupRecord | null {
patchGroup(id: string, patch: Partial<Pick<GroupRecord, "name" | "memberIds" | "defaultResponder" | "bulletin" | "unread" | "busyBotId" | "cwd">>): GroupRecord | null {
const group = this.group(id);
if (!group) return null;
Object.assign(group, patch);
Expand Down Expand Up @@ -825,6 +833,25 @@ export class Store {
return task.cwd;
}

/** The folder a room's member turns run in. Pins on the first turn that
* dispatches, from the room's `cwd` at that moment. Pinned, not read
* live, for the same reason tasks pin (see pinTaskCwd): engines key
* their sessions and files to the folder a thread starts in, and a room
* lives on ONE thread forever — so changing the room's folder applies to
* future rooms, never under a room that already started working
* somewhere. Returns the pinned value: a path, or null = each member's
* own default. */
pinGroupCwd(groupId: string): string | null {
const group = this.group(groupId);
if (!group) return null;
if (group.pinnedCwd === undefined) {
group.pinnedCwd = group.cwd ?? null;
this.saveGroups();
this.emit({ type: "group", groupId: group.id });
}
return group.pinnedCwd;
}

// ── tasks ─────────────────────────────────────────────────────────────
/** The first thing the human asked in a thread — a task's natural name. */
private firstUserLine(threadId: string): string | null {
Expand Down
129 changes: 128 additions & 1 deletion src/components/GroupView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// does not become a wall of competing motion. Plain messages go to the room's
// default responder; @mentions override that routing.
import { memo, useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { ArrowDown, ChevronDown, Pin } from "lucide-react";
import { ArrowDown, ChevronDown, Folder, FolderOpen, Pin } from "lucide-react";
import {
api,
useStore,
useStreaming,
formatTime,
Expand All @@ -21,7 +22,9 @@ import { Composer } from "./Composer";
import { GroupCallButton, GroupCallOverlay } from "./GroupCallView";
import { ReactionBar, ReactionChips } from "./Reactions";
import { ApprovalCard } from "./ApprovalCard";
import { useDesktopCapabilities } from "./DesktopCapabilities";
import { cn } from "@/lib/cn";
import { shortPath } from "@/lib/short-path";
import { BOTTOM_FOLLOW_THRESHOLD, shouldResumeBottomFollow } from "@/lib/bottom-follow";
import { showWorkingDots } from "@/lib/turn-tail";
import { expandWindowStart, resolveTranscriptWindow, tailWindowStart } from "@/lib/transcript-window";
Expand Down Expand Up @@ -194,6 +197,117 @@ function DefaultResponderSelect({ group, members }: { group: Group; members: Bot
);
}

/** The room's shared desk: where every member's shell and file tools run,
* overriding each bot's own folder for room turns. The room pins its own
* copy on its first turn (the server does the pinning — engines key their
* sessions to the folder a thread starts in, so a folder must not move
* under a room that already worked somewhere). The PATCH is made directly
* rather than through patchGroup: the server validates the path and a
* rejected folder must not stick in local state. */
function RoomWorkingFolder({ group }: { group: Group }) {
const { capabilities } = useDesktopCapabilities();
const home = capabilities.host.homeDir;
const [draft, setDraft] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const canPick = Boolean(window.ogb?.pickFolder);
const pinned = group.pinnedCwd; // undefined = not yet, null = each bot's own, string = folder
const pinnedElsewhere = pinned !== undefined && (pinned ?? undefined) !== group.cwd;

const save = async (cwd: string | null) => {
setSaving(true);
setError(null);
try {
await api(`/api/groups/${group.id}`, { method: "PATCH", body: JSON.stringify({ cwd }) });
setDraft(null);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setSaving(false);
}
};
const pick = async () => {
const chosen = await window.ogb?.pickFolder?.(group.cwd);
if (chosen) void save(chosen);
};

return (
<div className="rounded-xl bg-card p-4">
<div className="text-[15px] font-medium text-ink">Working folder</div>
<div className="mt-0.5 text-[13px] text-ink-secondary">Where every bot in this room runs its shell and file tools.</div>
{canPick ? (
<div className="mt-3 flex items-center gap-2">
<div className="min-w-0 flex-1 truncate rounded-lg border border-hairline/40 bg-inset px-3 py-2 font-mono text-[12.5px] text-ink" title={group.cwd}>
{group.cwd ? shortPath(group.cwd, home) : <span className="text-ink-secondary">Each bot's own folder</span>}
</div>
<button onClick={() => void pick()} disabled={saving} className="flex shrink-0 items-center gap-1.5 rounded-lg bg-raised px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50">
<FolderOpen size={14} /> Choose…
</button>
{group.cwd && (
<button onClick={() => void save(null)} disabled={saving} className="shrink-0 rounded-lg px-2 py-2 text-[13px] text-ink-secondary hover:text-ink disabled:opacity-50">
Clear
</button>
)}
</div>
) : (
<form
className="mt-3 flex items-center gap-2"
onSubmit={(e) => {
e.preventDefault();
// an emptied field clears the folder — the server wants null
void save((draft ?? group.cwd ?? "").trim() || null);
}}
>
<input
className="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2.5 font-mono text-[12.5px] text-ink placeholder:text-ink-secondary focus:outline-none focus:border-hairline"
placeholder="Each bot's own folder — or an absolute path"
value={draft ?? group.cwd ?? ""}
onChange={(e) => setDraft(e.target.value)}
/>
<button type="submit" disabled={saving || draft === null} className="shrink-0 rounded-lg bg-raised px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50">
Save
</button>
</form>
)}
{error && <div className="mt-2 text-[12px] text-danger">{error}</div>}
{pinnedElsewhere && (
<div className="mt-2 text-[12px] text-ink-secondary">
New rooms start here. This room is pinned to {pinned ? <span className="font-mono">{shortPath(pinned, home)}</span> : "each bot's own folder"} — make a new room to use the new folder.
</div>
)}
</div>
);
}

/** The folder this room's turns run in — the pinned folder once a turn ran,
* else the room folder a first turn would pin. Always present so the desk
* is settable before any folder exists; quiet (icon only) until then. */
function RoomWorkingFolderChip({ group, onToggle }: { group: Group; onToggle: () => void }) {
const folder = group.pinnedCwd === undefined ? group.cwd : (group.pinnedCwd ?? undefined);
if (!folder) {
return (
<button
onClick={onToggle}
className="rounded-md p-1.5 text-ink-secondary hover:bg-raised hover:text-ink"
title="Room working folder"
>
<Folder size={14} />
</button>
);
}
const name = folder.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || folder;
return (
<button
onClick={onToggle}
className="flex max-w-[180px] items-center gap-1.5 rounded-full border border-hairline/40 bg-raised/60 px-2.5 py-1 text-[12.5px] text-ink-secondary hover:bg-raised hover:text-ink"
title={`Working folder: ${folder}`}
>
<Folder size={12} />
<span className="truncate font-mono">{name}</span>
</button>
);
}

export function GroupView({ group }: { group: Group }) {
const { state, dispatch } = useStore();
const stream = useStreaming();
Expand All @@ -205,6 +319,7 @@ export function GroupView({ group }: { group: Group }) {
const touchY = useRef(0);
const [bulletinOpen, setBulletinOpen] = useState(false);
const [bulletinDraft, setBulletinDraft] = useState(group.bulletin);
const [folderOpen, setFolderOpen] = useState(false);

const members = useMemo(
() => group.memberIds.map((id) => state.bots.find((b) => b.id === id)).filter((b): b is Bot => Boolean(b)),
Expand Down Expand Up @@ -239,6 +354,8 @@ export function GroupView({ group }: { group: Group }) {

useEffect(() => setBottomFollow(true), [group.id, setBottomFollow]);
useEffect(() => setBulletinDraft(group.bulletin), [group.id, group.bulletin]);
// an open folder editor belongs to the room it was opened in
useEffect(() => setFolderOpen(false), [group.id]);
// deps track the FULL messages.length, so expanding the window (which only
// changes windowedMessages) can never re-trigger this bottom scrollTo
useEffect(() => {
Expand Down Expand Up @@ -302,6 +419,7 @@ export function GroupView({ group }: { group: Group }) {
<span className="text-[15px] font-semibold text-ink">{group.name}</span>
<div className="flex items-center gap-1.5" style={noDrag}>
<GroupCallButton group={group} members={members} />
{!group.dm && <RoomWorkingFolderChip group={group} onToggle={() => setFolderOpen((open) => !open)} />}
{!group.dm && <DefaultResponderSelect group={group} members={members} />}
{members.map((b) => (
<span
Expand Down Expand Up @@ -361,6 +479,15 @@ export function GroupView({ group }: { group: Group }) {
)}
</div>

{/* Working folder card — the chip in the header toggles it */}
{folderOpen && !group.dm && (
<div className="mx-auto w-full max-w-[900px] px-5">
<div className="mb-1">
<RoomWorkingFolder group={group} />
</div>
</div>
)}

{/* Transcript */}
<div
ref={scrollRef}
Expand Down
6 changes: 6 additions & 0 deletions src/state/store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ export interface Group {
/** auto-created bot⇄bot channel (ask_bot exchanges mirror here) */
dm?: boolean;
busyBotId?: string | null;
/** the room's shared desk — where member turns run their shell tools,
* overriding each member's own folder; absent = each member's own */
cwd?: string;
/** folder the room's turns actually run in, pinned on the first turn;
* null = each member's own default; absent = not pinned yet */
pinnedCwd?: string | null;
messages: Message[];
}

Expand Down
Loading