feat(home): add Home, an agent that manages threads across your machines #15975
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 13 commits into
main fromt3code/cross-environment-meta-threadopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge added labelsmacroscope-review
- apps/server/src/mcp/toolkits/home/handlers.ts line 60OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +40,21 @@40+ };41+ }),42+43+ t3_thread_watch: (input) =>44+ Effect.gen(function* () {45+ if (!(yield* callerIsHome()))46+ return yield* new OrchestratorMcpFailure({47+ code: "capability_denied",48+ message: "Only Home can watch threads.",49+ });50+ const { scope } = yield* readHomeChangeCaller();51+ const home = yield* HomeService.HomeService;52+ const environmentId = input.environmentId ?? scope.environmentId;53+ const { threadId } = input;54+ if ((input.action === "watch" || input.action === "unwatch") && threadId === undefined)55+ return yield* new OrchestratorMcpFailure({56+ code: "invalid_request",57+ message: `${input.action} needs threadId.`,58+ });59+ const next = yield* home60+ .updateWatches((current) => {apps/server/src/home/HomeService.ts line 271OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +251,21 @@251+ updateWatches: (update) =>252+ withLock(253+ Effect.gen(function* () {254+ const home = yield* readHome;255+ if (home.threadId === null) return yield* fail("Home is off.");256+ return yield* writeHome(update(home));257+ }),258+ ),259+260+ report: ({ events }) =>261+ Effect.gen(function* () {262+ const home = yield* readHome;263+ if (home.threadId === null) return;264+ const watched = new Set(home.watches.map(watchKey));265+ const wake = events.filter(266+ (event) =>267+ event.kind !== "ended" &&268+ event.threadId !== home.threadId &&269+ (home.watchAll || watched.has(watchKey(event))),270+ );271+ if (wake.length > 0) yield* deliver(home.threadId, wake);apps/server/src/project/ManagedProjectFolders.ts line 569Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -498,3 +554,16 @@498554 };499555 });500556557+ const homeFolder = path.resolve(config.baseDir, "home");558+559+ const ensureHomeProject: ManagedProjectFolders["Service"]["ensureHomeProject"] = Effect.gen(560+ function* () {561+ const workspaceRoot = homeFolder;562+ const folderError = (cause: unknown) =>563+ new NamedProjectFolderError({ folder: workspaceRoot, cause });564+ yield* fileSystem565+ .makeDirectory(workspaceRoot, { recursive: true })566+ .pipe(Effect.mapError(folderError));567+ // Its own repository, so checkpoints never reach into a parent checkout568+ // (a dev worktree's .t3, a dotfiles home).569+ const isRepository = yield* fileSystemapps/server/src/home/FleetService.ts lines 490 to 498Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +460,21 @@460+ approval: {461+ requestKind: item.requestKind,462+ prompt: item.prompt ?? null,463+ appName: item.appName ?? null,464+ options: item.options ?? [],465+ },466+ };467+ }),468+469+ "requests.respond": (input, actor) =>470+ Effect.gen(function* () {471+ const threadId = yield* requireThreadId(input.threadId);472+ const { runtimeRequests } = yield* loadRequests(threadId);473+ const request = runtimeRequests.find(474+ (candidate) => candidate.id === input.requestId && candidate.status === "pending",475+ );476+ if (request === undefined) {477+ return yield* failure("invalid_request", "The pending request was not found.");478+ }479+ const isQuestion = request.kind === "user_input";480+ if (isQuestion ? input.answers === undefined : input.decision === undefined) {packages/contracts/src/rpc.ts line 438Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -420,3 +431,8 @@420431 previewAutomationRespond: "previewAutomation.respond",421432 previewAutomationFocusHost: "previewAutomation.focusHost",422433434+ // Home and fleet methods435+ homeEnable: "home.enable",436+ homeDisable: "home.disable",437+ homeStartFresh: "home.startFresh",438+ fleetInvoke: "fleet.invoke",apps/mobile/src/features/threads/ThreadFeed.tsx line 2250Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2242,3 +2243,4 @@22422243 const userBubbleColor = theme["--color-user-bubble"];22432244 const onMarkdownLinkPress = useCallback(22442245 (href: string) => {2246+ const threadLink = parseThreadLinkHref(href);apps/server/src/home/FleetService.ts line 183OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +163,21 @@163+164+ const handlers: Handlers = {165+ capabilities: () =>166+ Effect.gen(function* () {167+ const providers = yield* providerRegistry.getProviders;168+ const capable = new Set<string>(yield* adapters.list());169+ return { providers: providerCapabilities(providers, capable) };170+ }),171+172+ "projects.list": (input) =>173+ Effect.gen(function* () {174+ const snapshot = yield* projects.snapshot.pipe(Effect.mapError(orchestrationError));175+ const rows = snapshot.projects.filter((project) => project.deletedAt === null);176+ const start = input.cursor ?? 0;177+ const end = start + (input.limit ?? 20);178+ return { projects: rows.slice(start, end), nextCursor: end < rows.length ? end : null };179+ }),180+181+ "threads.list": (input, actor) =>182+ Effect.gen(function* () {183+ const includeSubagents = input.includeSubagents === true;apps/server/src/project/ManagedProjectFolders.ts line 646Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -501,6 +626,21 @@626+ .update({627+ commandId: CommandId.make(`home-project-icon:${id}`),628+ projectId: bootstrapped.project.id,629+ projectIcon: { kind: "lucide", name: "house", color: "gray" },630+ })631+ .pipe(Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause })));632+ }633+ return { projectId: bootstrapped.project.id, workspaceRoot };634+ },635+ );636+501637 return ManagedProjectFolders.of({502638 scratchRoot,503639 ensureScratchProject,504640 folderForThread,505641 namedProjectsRoot,506642 createNamedProject,643+ homeRoot: Effect.succeed(homeFolder),644+ isInHomeFolder: (candidate) =>645+ Effect.sync(() => {646+ const relative = path.relative(path.resolve(homeFolder), path.resolve(candidate));packages/contracts/src/rpc.ts line 439Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -420,3 +431,9 @@420431 previewAutomationRespond: "previewAutomation.respond",421432 previewAutomationFocusHost: "previewAutomation.focusHost",422433434+ // Home and fleet methods435+ homeEnable: "home.enable",436+ homeDisable: "home.disable",437+ homeStartFresh: "home.startFresh",438+ fleetInvoke: "fleet.invoke",439+ fleetConnect: "fleet.connect",packages/contracts/src/rpc.ts line 1485Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1428,0 +1465,21 @@1465+1466+/** Runs one Home operation here. Results are decoded by the caller per operation. */1467+const WsFleetInvokeRpc = Rpc.make(WS_METHODS.fleetInvoke, {1468+ payload: FleetInvokeInput,1469+ success: Schema.Unknown,1470+ error: Schema.Union([OrchestratorMcpFailure, EnvironmentAuthorizationError]),1471+});1472+1473+const WsFleetConnectRpc = Rpc.make(WS_METHODS.fleetConnect, {1474+ payload: FleetHostRegistration,1475+ success: FleetHostRequest,1476+ error: Schema.Union([HomeUnavailableError, EnvironmentAuthorizationError]),1477+ stream: true,1478+});1479+1480+const WsFleetRespondRpc = Rpc.make(WS_METHODS.fleetRespond, {1481+ payload: FleetHostResponse,1482+ error: EnvironmentAuthorizationError,1483+});1484+1485+const WsFleetReportWatchEventsRpc = Rpc.make(WS_METHODS.fleetReportWatchEvents, {apps/web/src/lib/chatThreadActions.ts line 119OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -71,7 +87,20 @@87+ },88+): ScopedProjectRef | null {89+ const project = projects.find(90+ (candidate) =>91+ !(92+ candidate.environmentId === home.primaryEnvironmentId &&93+ isHomeProject(candidate, home.homeWorkspaceRoot)94+ ),95+ );96+ return project ? scopeProjectRef(project.environmentId, project.id) : null;97+}98+7199 export function resolveThreadActionProjectRef(72100 context: ChatThreadActionContext,73101 ): ScopedProjectRef | null {74- if (context.activeThread) {102+ // Home's folder belongs to Home alone, so a new thread from Home uses the default project.103+ if (context.activeThread && !isHomeThreadId(context.activeThread.id ?? "")) {75104 return scopeProjectRef(context.activeThread.environmentId, context.activeThread.projectId);76105 }77106 if (context.activeDraftThread) {
- apps/mobile/src/features/threads/ThreadFeed.tsx lines 2250 to 2256Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2242,3 +2243,10 @@22422243 const userBubbleColor = theme["--color-user-bubble"];22432244 const onMarkdownLinkPress = useCallback(22442245 (href: string) => {2246+ const threadLink = parseThreadLinkHref(href);2247+ if (threadLink) {2248+ navigation.navigate("Thread", {2249+ environmentId: String(threadLink.environmentId),2250+ threadId: String(threadLink.threadId),2251+ });2252+ return;apps/server/src/home/HomeService.ts lines 64 to 65OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +45,21 @@45+ /** Only a server the desktop app hosts can run Home. */46+ readonly available: boolean;47+ /** Starts Home, or returns the running one. */48+ readonly enable: (49+ input: HomeEnableInput,50+ ) => Effect.Effect<HomeThreadResult, HomeUnavailableError>;51+ /** Turns Home off. Its thread stays in history; its watches are dropped. */52+ readonly disable: Effect.Effect<void, HomeUnavailableError>;53+ /** Points Home at a new thread with the same model and settles the old one. */54+ readonly startFresh: Effect.Effect<HomeThreadResult, HomeUnavailableError>;55+ readonly isHome: (threadId: ThreadId) => Effect.Effect<boolean>;56+ readonly updateWatches: (57+ update: (home: HomeSettings) => HomeSettings,58+ ) => Effect.Effect<HomeSettings, HomeUnavailableError>;59+ /** Wakes Home with the watched events in one message. */60+ readonly report: (report: HomeWatchReport) => Effect.Effect<void, HomeUnavailableError>;61+ }62+>()("t3/home/HomeService") {}63+64+export const watchKey = (watch: Pick<HomeWatch, "environmentId" | "threadId">) =>65+ `${watch.environmentId}\u0000${watch.threadId}`;apps/server/src/mcp/toolkits/project/handlers.ts line 145OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -75,3 +126,20 @@75126 message:76127 "scratch:true picks its own project and folder; omit projectId and workspaceStrategy.",77128 });129+ // Checked before the watch is saved, so a refused launch leaves no watch.130+ // Another environment checks its own Home folder in FleetService.131+ if (isHome && !remote && input.projectId !== undefined)132+ yield* refuseHomeFolder(133+ {134+ projects: yield* Project.ProjectService,135+ folders: yield* ManagedProjectFolders.ManagedProjectFolders,136+ },137+ { projectId: input.projectId, workspaceStrategy: input.workspaceStrategy },138+ );139+ const commandId = yield* newCommandId();140+ const threadId = ThreadId.make(141+ isHome ? `${HOME_LAUNCHED_THREAD_ID_PREFIX}${commandId}` : commandId,142+ );143+ const messageId = MessageId.make(commandId);144+ if (isHome && attachments.length === 0) {145+ const modelSelection = input.modelSelection ?? caller?.modelSelection;apps/web/src/components/home/HomeFleetHost.tsx lines 46 to 51Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +29,21 @@29+30+/**31+ * Desktop-only host for Home, which runs on the desktop's own server. While32+ * Home is on, this renderer relays Home's calls to the user's other33+ * environments over the connections it already holds, reports watched thread34+ * changes back to Home, and keeps itself alive when the window closes.35+ */36+export function HomeFleetHost() {37+ const primaryEnvironmentId = usePrimaryEnvironmentId();38+ if (!isElectron || primaryEnvironmentId === null) return null;39+ return <HomeHub environmentId={primaryEnvironmentId} />;40+}41+42+function HomeHub({ environmentId }: { readonly environmentId: EnvironmentId }) {43+ const settings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));44+ const home = settings?.home ?? DEFAULT_HOME_SETTINGS;45+ const on = home.threadId !== null;46+ useEffect(() => {47+ void window.desktopBridge?.setKeepAliveOnClose?.(on);48+ }, [on]);49+ if (!on) return null;apps/web/src/components/settings/SettingsSidebarNav.tsx lines 119 to 127Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -111,5 +116,12 @@111116 const currentHash = useLocation({ select: (location) => location.hash });112117 const currentSearch = useLocation({ select: (location) => location.search });113118 const scopeSearch = useMemo(() => validateSettingsScopeSearch(currentSearch), [currentSearch]);119+ // Only a desktop app's own server can run Home.120+ const canRunHome = useAtomValue(121+ primaryServerConfigAtom,122+ (config) => isElectron && config?.homeWorkspaceRoot !== undefined,123+ );114124 const navItems = SETTINGS_NAV_ITEMS.filter(115- (item) => item.to !== "/settings/projects" || isSettingsOverviewVisible(scopeSearch),125+ (item) =>126+ (item.to !== "/settings/projects" || isSettingsOverviewVisible(scopeSearch)) &&127+ (item.to !== "/settings/home" || canRunHome),apps/web/src/components/ThreadNotificationCoordinator.tsx lines 30 to 31OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -26,3 +27,5 @@26272728 export function ThreadNotificationCoordinator() {2829 const environmentIds = useEnvironmentIds();30+ // Home answers for the threads it launched; it reaches the user through its own thread.31+ const homeOn = useAtomValue(primaryServerSettingsAtom).home.threadId !== null;
- apps/server/src/home/HomeService.ts line 148Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +128,21 @@128+ const fail = (message: string) => new HomeUnavailableError({ message });129+ const requireAvailable = available130+ ? Effect.void131+ : Effect.fail(fail("Home runs only on a server the T3 Code desktop app hosts."));132+133+ const readHome = settings.getSettings.pipe(134+ Effect.map((current) => current.home),135+ Effect.mapError(() => fail("Home's settings could not be read.")),136+ );137+ const writeHome = (home: HomeSettings) =>138+ settings.updateSettings({ home }).pipe(139+ Effect.map((current) => current.home),140+ Effect.mapError(() => fail("Home's settings could not be saved.")),141+ );142+143+ const liveShell = (threadId: ThreadId) =>144+ threads.getThreadShell(threadId).pipe(145+ Effect.map((shell) =>146+ shell === null || shell.deletedAt !== null || shell.archivedAt !== null ? null : shell,147+ ),148+ Effect.orElseSucceed(() => null),apps/server/src/mcp/toolkits/project/handlers.ts line 151Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -77,0 +131,21 @@131+ // Checked before the watch is saved, so a refused launch leaves no watch.132+ // Another environment checks its own Home folder in FleetService.133+ if (isHome && !remote && input.projectId !== undefined)134+ yield* refuseHomeFolder(135+ {136+ projects: yield* Project.ProjectService,137+ folders: yield* ManagedProjectFolders.ManagedProjectFolders,138+ },139+ { projectId: input.projectId, workspaceStrategy: input.workspaceStrategy },140+ );141+ const commandId = yield* newCommandId();142+ const threadId = ThreadId.make(143+ isHome ? `${HOME_LAUNCHED_THREAD_ID_PREFIX}${commandId}` : commandId,144+ );145+ const messageId = MessageId.make(commandId);146+ if (homeThreadId !== undefined && attachments.length === 0) {147+ // Provider instances differ per machine, so another machine uses its own default.148+ const modelSelection =149+ input.modelSelection ?? (remote ? undefined : caller?.modelSelection);150+ yield* watchLaunched(homeThreadId, targetEnvironmentId, threadId);151+ return yield* runAsHome(input.environmentId, "threads.launch", {apps/server/src/home/HomeService.ts line 281Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +224,21 @@224+ yield* writeHome(DEFAULT_HOME_SETTINGS);225+ }),226+ ),227+228+ startFresh: withLock(229+ Effect.gen(function* () {230+ yield* requireAvailable;231+ const home = yield* readHome;232+ const current = home.threadId === null ? null : yield* liveShell(home.threadId);233+ if (current === null) return yield* fail("Turn Home on first.");234+ const threadId = yield* launchHome(current.modelSelection);235+ yield* writeHome({ ...home, threadId });236+ // The old Home stays in history, out of the active list.237+ const id = yield* crypto.randomUUIDv4.pipe(Effect.orDie);238+ yield* threads239+ .dispatch({240+ type: "thread.settle",241+ commandId: CommandId.make(`home-settle:${id}`),242+ threadId: current.id,243+ })244+ .pipe(Effect.ignore);
- apps/server/src/home/HomeService.ts line 196Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +165,21 @@165+ // stops a caller from acting on a thread broader than itself.166+ runtimeMode: "full-access",167+ interactionMode: "default",168+ workspaceStrategy: { type: "root" },169+ createdBy: "user",170+ creationSource: "server",171+ })172+ .pipe(Effect.mapError((error) => fail(error.message)));173+ return result.threadId;174+ });175+176+ const withLock = <A, E>(effect: Effect.Effect<A, E>) => lock.withPermits(1)(effect);177+178+ /**179+ * Stops a former Home's active run once its grant is gone, and holds its180+ * queued messages so none starts it again. Best effort: the grant already moved.181+ */182+ const stopFormerHome = (threadId: ThreadId) =>183+ Effect.gen(function* () {184+ const shell = yield* liveShell(threadId);185+ if (shell === null || shell.activeRunId === null) return;apps/server/src/home/HomeService.ts line 326Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +295,21 @@295+ // Under the lock, so turning Home off or starting fresh cannot slip in296+ // between choosing the Home thread and waking it.297+ report: ({ events }) =>298+ withLock(299+ Effect.gen(function* () {300+ const home = yield* readHome;301+ if (home.threadId === null) return;302+ const watched = new Set(home.watches.map(watchKey));303+ const wake = events.filter(304+ (event) =>305+ event.kind !== "ended" &&306+ event.threadId !== home.threadId &&307+ (home.watchAll || watched.has(watchKey(event))),308+ );309+ if (wake.length > 0) yield* deliver(home.threadId, wake);310+ // Watches end only after delivery, so a retried batch is still eligible.311+ const ended = new Set(312+ events.filter((event) => event.kind === "ended").map((event) => watchKey(event)),313+ );314+ if (!home.watches.some((watch) => ended.has(watchKey(watch)))) return;315+ yield* writeHome({
- apps/web/src/lib/chatThreadActions.ts lines 108 to 115Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -71,3 +89,21 @@89+ const homeRoot =90+ home.homeWorkspaceRoot === null91+ ? ""92+ : normalizeProjectPathForComparison(home.homeWorkspaceRoot);93+ const project = projects.find(94+ (candidate) =>95+ homeRoot.length === 0 ||96+ candidate.environmentId !== home.primaryEnvironmentId ||97+ normalizeProjectPathForComparison(candidate.workspaceRoot) !== homeRoot,98+ );99+ return project ? scopeProjectRef(project.environmentId, project.id) : null;100+}101+71102 export function resolveThreadActionProjectRef(72103 context: ChatThreadActionContext,73104 ): ScopedProjectRef | null {105+ // Home's folder belongs to Home alone, so a new thread from Home, or from a106+ // draft in Home's composer, uses the default project.107+ if (context.activeThread && isHomeThreadId(context.activeThread.id ?? "")) {108+ return context.defaultProjectRef;109+ }
- packages/contracts/src/orchestrationV2.ts line 2801Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2797,3 +2797,5 @@27972797 commandId: CommandId,27982798 threadId: ThreadId,27992799 }),2800+ /** Holds every queued run, so none starts until the queue is resumed. */2801+ Schema.Struct({
- @@ -0,0 +174,21 @@174+ });175+176+ const withLock = <A, E>(effect: Effect.Effect<A, E>) => lock.withPermits(1)(effect);177+178+ /**179+ * Stops a former Home once its grant is gone, so it does not keep working180+ * next to the new Home. Best effort: the grant already moved. Holding the181+ * queue commits under the orchestrator's thread lock, which also starts182+ * queued runs, so after it no queued turn can start; a turn that started183+ * before it is the active run, which is then interrupted.184+ */185+ const stopFormerHome = (threadId: ThreadId) =>186+ Effect.gen(function* () {187+ if ((yield* liveShell(threadId)) === null) return;188+ const commandId = crypto.randomUUIDv4.pipe(189+ Effect.orDie,190+ Effect.map((id) => CommandId.make(`home-stop:${id}`)),191+ );192+ yield* threads193+ .dispatch({ type: "queue.hold", commandId: yield* commandId, threadId })194+ .pipe(Effect.ignore);
juliusmarminge closed this
Sign in to join this conversation.






Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
cf3e714· PR result:b5d05a6· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.