Compare commits

..
Author SHA1 Message Date
t3-code[bot]andmaria 4c9a6e2179 chore: refresh composer spacing screenshot
Co-authored-by: maria <[email protected]>
2026-08-12 02:17:11 +00:00
t3-code[bot]andmaria 554f7c99b6 chore: host composer spacing screenshots
Co-authored-by: maria <[email protected]>
2026-08-12 00:52:26 +00:00
24 changed files with 91 additions and 753 deletions

No files matched your search

-1
View File
@@ -37,4 +37,3 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

@@ -45,7 +45,6 @@ export function HomeRouteScreen() {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -187,7 +186,6 @@ export function HomeRouteScreen() {
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() =>
@@ -115,7 +115,6 @@ interface HomeScreenProps {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -539,12 +538,6 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnpinThread],
);
const handleRegenerateThreadTitle = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onRegenerateThreadTitle(thread);
},
[props.onRegenerateThreadTitle],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -622,15 +615,6 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order (reorder-capable threads only) for the
// Move up/down position flags. Computed from all shells, not the rendered
// list, so search/scope filtering never disables or misdirects a move.
@@ -827,8 +811,6 @@ export function HomeScreen(props: HomeScreenProps) {
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -860,7 +842,6 @@ export function HomeScreen(props: HomeScreenProps) {
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleRegenerateThreadTitle,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
@@ -882,7 +863,6 @@ export function HomeScreen(props: HomeScreenProps) {
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
@@ -987,8 +967,6 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1010,7 +988,6 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleSwipeableClose,
handleSwipeableWillOpen,
handleRegenerateThreadTitle,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
@@ -1021,7 +998,6 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
updateGroupDisplay,
],
);
@@ -48,15 +48,6 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
);
}
function environmentSupportsTitleRegeneration(
environmentId: EnvironmentThreadShell["environmentId"],
) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadTitleRegeneration === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -236,18 +227,13 @@ export function useThreadListActions(): {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -419,47 +405,6 @@ export function useThreadListActions(): {
},
[unpinMutation],
);
const regenerateThreadTitle = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (
thread.titleRegeneration != null ||
titleRegenerationInFlightThreadKeys.current.has(key)
) {
return false;
}
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
Alert.alert(
"Could not regenerate title",
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
);
return false;
}
titleRegenerationInFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const result = await updateThreadMetadata({
environmentId: thread.environmentId,
input: { threadId: thread.id, regenerateTitle: true },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not regenerate title",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread title could not be regenerated.",
);
return false;
}
return true;
} finally {
titleRegenerationInFlightThreadKeys.current.delete(key);
}
},
[updateThreadMetadata],
);
// Move up / Move down for the pinned block. Computed against the CANONICAL
// keyed pinned order (not the rendered list), so the move is valid even
@@ -552,7 +497,6 @@ export function useThreadListActions(): {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
};
}
@@ -211,7 +211,6 @@ function ThreadNavigationSidebarPane(
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -506,15 +505,6 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order for Move up/down flags — computed from
// all shells so search/scope filtering never disables a valid move.
const arrangedPinnedKeys = useMemo(() => {
@@ -960,8 +950,6 @@ function ThreadNavigationSidebarPane(
onSelectThread={handleSelectThread}
onDeleteThread={confirmDeleteThread}
onArchiveThread={archiveThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -1079,8 +1067,6 @@ function ThreadNavigationSidebarPane(
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1117,7 +1103,6 @@ function ThreadNavigationSidebarPane(
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
regenerateThreadTitle,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
@@ -1125,7 +1110,6 @@ function ThreadNavigationSidebarPane(
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -22,7 +22,6 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -431,8 +430,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly titleRegenerationSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
@@ -454,8 +451,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
props;
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
@@ -475,21 +471,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const menuActions = useMemo<MenuAction[]>(
() => [
THREAD_ROW_MENU_ACTIONS[0]!,
...buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
THREAD_ROW_MENU_ACTIONS[1]!,
],
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const primaryAction = useMemo(
() => ({
accessibilityLabel: `Archive ${thread.title}`,
@@ -502,10 +483,9 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete, handleRegenerateTitle],
[handleArchive, handleDelete],
);
const statusPill = effectiveStatus ? (
@@ -694,7 +674,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
// ControlPillMenu injects onLongPress into the row and anchors the
// token-styled dropdown to it; taps and swipes are untouched.
<ControlPillMenu
actions={menuActions}
actions={THREAD_ROW_MENU_ACTIONS}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
@@ -27,7 +27,6 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
@@ -66,8 +65,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus keep lifecycle and title regeneration together. Archive keeps its
// own surface (thread screen / settings) rather than crowding v2 rows.
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
@@ -342,7 +341,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
@@ -357,8 +355,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
/** False on servers that predate thread title regeneration. */
readonly titleRegenerationSupported: boolean;
/** False on servers that predate thread.pin.reorder. Gates the pinned
Move up / Move down menu items. */
readonly pinReorderSupported?: boolean;
@@ -388,7 +384,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
variant,
onSelectThread,
onDeleteThread,
onRegenerateThreadTitle,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
@@ -422,10 +417,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
@@ -515,14 +506,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
props.pinningSupported,
],
);
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
() =>
buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -533,31 +516,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
subactions: snoozePresetActions,
},
...pinMenuItem,
...titleRegenerationMenuItems,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
[pinMenuItem, snoozePresetActions],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [
CARD_MENU_ACTIONS[0]!,
...pinMenuItem,
...titleRegenerationMenuItems,
...CARD_MENU_ACTIONS.slice(1),
],
[pinMenuItem, titleRegenerationMenuItems],
);
const slimMenuActions = useMemo<MenuAction[]>(
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const snoozedMenuActions = useMemo<MenuAction[]>(
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const legacyMenuActions = useMemo<MenuAction[]>(
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -569,7 +534,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
@@ -585,7 +549,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleRegenerateTitle,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
@@ -927,11 +890,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ControlPillMenu
actions={
snoozedRow
? snoozedMenuActions
? SNOOZED_MENU_ACTIONS
: !props.settlementSupported
? legacyMenuActions
? LEGACY_MENU_ACTIONS
: canUnsettle
? slimMenuActions
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
@@ -1,36 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
describe("buildThreadTitleRegenerationMenuItems", () => {
it("hides regeneration when the environment does not advertise support", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
).toEqual([]);
});
it("offers regeneration for a supported environment", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerate title",
image: "arrow.clockwise",
},
]);
});
it("shows and disables the pending state", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerating…",
image: "arrow.clockwise",
attributes: { disabled: true },
},
]);
});
});
@@ -1,17 +0,0 @@
import type { MenuAction } from "@react-native-menu/menu";
export function buildThreadTitleRegenerationMenuItems(input: {
readonly supported: boolean;
readonly isRegenerating: boolean;
}): MenuAction[] {
if (!input.supported) return [];
return [
{
id: "regenerate-title",
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
image: "arrow.clockwise",
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
},
];
}
+1 -5
View File
@@ -5,7 +5,6 @@ import {
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
@@ -695,11 +694,8 @@ export const connectCommand = Command.make("connect", {
// fail the command, just tell the user what happened and move on.
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
if (background) {
const platform = yield* HostProcessPlatform;
yield* Console.log(
platform === "darwin"
? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."
: "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
);
return;
}
+2 -2
View File
@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {
);
});
it("explains where the service is supported", () => {
it("explains service availability without systemd", () => {
assert.include(
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
"Supported on: Linux with systemd, macOS with launchd",
"Supported on: Linux with systemd",
);
});
+3 -10
View File
@@ -1,4 +1,3 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -49,7 +48,7 @@ export function formatServiceStatus(
cliVersion: string,
): string {
if (!status.supported) {
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
}
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
@@ -153,18 +152,12 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
// A LaunchAgent starts at login and dies at logout; there is no
// enable-linger equivalent on macOS. Do not promise more than that.
const platform = yield* HostProcessPlatform;
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
? "The installed T3 Code service needs an update or repair. Update it now?"
: platform === "darwin"
? "Run T3 Code in the background whenever you log in to this Mac? " +
"It stays reachable through T3 Connect while you are logged in."
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
initial: true,
}),
);
+4 -143
View File
@@ -4,10 +4,8 @@ import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -49,51 +47,6 @@ it("survives the kernel OOM-killing a greedy agent child", () => {
expect(unit).toContain("OOMPolicy=continue");
});
const macPlan = {
nodePath: "/opt/homebrew/bin/node",
launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",
baseDir: "/Users/theo/.t3",
logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
};
it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
expect(plist).not.toContain("versions/1.2.3");
});
it("restarts the launch agent on the systemd cadence", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
});
it("appends both stdio streams to the boot service log", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain(
"<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
);
expect(plist).toContain(
"<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
);
});
it("escapes XML in host paths", () => {
const plist = BootService.renderBootServicePlist(
{ ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
{ homeDir: "/Users/theo" },
);
expect(plist).toContain("<string>/Users/theo/T3 &amp; &lt;Co&gt;</string>");
});
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
platform: NodeJS.Platform = "linux",
usePinnedLauncher = false,
@@ -115,14 +68,12 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
const commands: string[] = [];
const timeouts = new Map<string, unknown>();
const control: { failCommand: string | undefined } = { failCommand: undefined };
const runner = ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
const command = `${input.command} ${input.args.join(" ")}`;
commands.push(command);
timeouts.set(command, input.timeout);
return {
stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
stderr: "",
@@ -148,20 +99,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessUserId, 501),
Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
),
);
return { service, fs, statePath, commands, timeouts, control };
return { service, fs, statePath, commands, control };
});
it.layer(NodeServices.layer)("boot service install", (it) => {
it.effect("installs, reports current state, and uninstalls", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
const { service, fs, statePath, commands } = yield* makeHarness();
const plan = yield* service.install;
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
@@ -187,11 +137,6 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
// The stop can block up to systemd's 90s TimeoutStopSec; the runner's
// 60s default would cancel it mid-shutdown.
expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
Duration.seconds(120),
);
}),
);
@@ -250,95 +195,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("fails closed on Windows", () =>
it.effect("fails closed off Linux", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness("win32");
const { service } = yield* makeHarness("darwin");
expect((yield* service.status).supported).toBe(false);
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
}),
);
it.effect("installs, reports current state, and uninstalls on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
const plan = yield* service.install;
expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
true,
);
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
// A bootout can block up to the plist's 90s ExitTimeOut; the runner's
// 60s default would cancel it and let bootstrap race a loaded job.
expect(timeouts.get("launchctl bootout gui/501/com.t3tools.t3code.service")).toEqual(
Duration.seconds(120),
);
}),
);
it.effect("restarts the launch agent when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness("darwin");
yield* service.install;
const plistPath = (yield* service.status).unitPath;
commands.length = 0;
control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
const error = yield* service.install.pipe(Effect.flip);
expect(error._tag).toBe("BootServiceCommandError");
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
"launchctl bootout gui/501/com.t3tools.t3code.service",
"launchctl enable gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plistPath}`,
`launchctl bootstrap gui/501 ${plistPath}`,
]);
}),
);
it.effect("ignores a bootout for an agent that is not loaded", () =>
Effect.gen(function* () {
const { service, control } = yield* makeHarness("darwin");
yield* service.install;
control.failCommand = "launchctl bootout gui/501/com.t3tools.t3code.service";
yield* service.install;
expect((yield* service.status).current).toBe(true);
}),
);
it.effect("restarts without overwriting a pending remote update on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness("darwin");
yield* service.install;
const plistPath = (yield* service.status).unitPath;
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
activeVersion: "1.2.3",
update: {
id: "remote-update",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
commands.length = 0;
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
"launchctl bootout gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plistPath}`,
]);
}),
);
});
+47 -310
View File
@@ -1,8 +1,4 @@
import {
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -31,10 +27,6 @@ import {
const BOOT_SERVICE_NAME = "t3code";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
// `.service` suffix keeps the label distinct from the desktop app's bundle id
// (com.t3tools.t3code), so launchd and TCC records never collide.
export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
/** systemd expands `%` specifiers, including in unquoted append-log paths. */
@@ -91,276 +83,12 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
].join("\n");
}
/** Plist values are emitted as XML text nodes; only these three need escaping. */
export function escapeXmlText(value: string): string {
return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}
/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
export function renderBootServicePlist(
plan: BootServicePlan,
options: { readonly homeDir: string },
): string {
// KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
// has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
// ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
// completes within the launcher's 5s child grace, but a stop that queues
// behind an in-flight update transition can take much longer; launchd's
// system-defined default (5s on current macOS) would SIGKILL the launcher
// (and, with it, the process group) mid-handoff.
// ProcessType Interactive opts out of background-job resource throttling.
// AbandonProcessGroup stays at its default (false): launchd reaps leftover
// process-group members only when the launcher itself exits — the analog of
// KillMode=mixed's final cgroup kill — and not when the launcher restarts its
// child, so agent children survive server updates.
return [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
`<plist version="1.0">`,
`<dict>`,
` <key>Label</key>`,
` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
` <key>ProgramArguments</key>`,
` <array>`,
` <string>${escapeXmlText(plan.nodePath)}</string>`,
` <string>${escapeXmlText(plan.launcherPath)}</string>`,
` </array>`,
` <key>EnvironmentVariables</key>`,
` <dict>`,
` <key>T3CODE_HOME</key>`,
` <string>${escapeXmlText(plan.baseDir)}</string>`,
` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
` </dict>`,
` <key>WorkingDirectory</key>`,
` <string>${escapeXmlText(options.homeDir)}</string>`,
` <key>RunAtLoad</key>`,
` <true/>`,
` <key>KeepAlive</key>`,
` <true/>`,
` <key>ThrottleInterval</key>`,
` <integer>5</integer>`,
` <key>ExitTimeOut</key>`,
` <integer>90</integer>`,
` <key>ProcessType</key>`,
` <string>Interactive</string>`,
` <key>StandardOutPath</key>`,
` <string>${escapeXmlText(plan.logPath)}</string>`,
` <key>StandardErrorPath</key>`,
` <string>${escapeXmlText(plan.logPath)}</string>`,
`</dict>`,
`</plist>`,
``,
].join("\n");
}
export interface BootServiceStep {
readonly step: string;
readonly command: string;
readonly args: ReadonlyArray<string>;
/**
* Non-zero exit is logged and ignored. Reserved for steps whose common
* failures (not loaded, already enabled) leave a state a later strict step
* either tolerates or fails loudly on.
*/
readonly optional?: boolean;
/** Override the ProcessRunner default (60s) for steps that block longer. */
readonly timeout?: Duration.Input;
}
/**
* Stop commands block until the service manager gives up: 90s by default for
* systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
* must stay above both, or the runner cancels the stop mid-shutdown and the
* next step races a still-loaded service.
*/
const STOP_STEP_TIMEOUT = Duration.seconds(120);
/**
* Platform service-manager integration as data: paths, a pure renderer, and
* the command steps each flow runs. install/uninstall/status consume this and
* never branch on platform.
*/
export interface BootServiceManager {
readonly kind: "systemd" | "launchd";
readonly unitPath: string;
readonly render: (plan: BootServicePlan) => string;
/** Before rewriting files, when a unit is already installed. */
readonly stop: ReadonlyArray<BootServiceStep>;
/** After files are written. The last entry starts the service. */
readonly activate: ReadonlyArray<BootServiceStep>;
/** Best-effort recovery after a failed repair of an installed service. */
readonly restart: ReadonlyArray<BootServiceStep>;
/** Uninstall, before the unit file is removed. */
readonly deactivate: ReadonlyArray<BootServiceStep>;
/** Uninstall, after the unit file is removed. */
readonly finalize: ReadonlyArray<BootServiceStep>;
}
export function systemdManager(input: {
readonly path: Path.Path;
readonly homeDir: string;
}): BootServiceManager {
const unitPath = input.path.join(
input.homeDir,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
return {
kind: "systemd",
unitPath,
render: renderBootServiceUnit,
stop: [
{
step: "stopping the installed service",
command: "systemctl",
args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
timeout: STOP_STEP_TIMEOUT,
},
],
activate: [
{
step: "reloading systemd user units",
command: "systemctl",
args: ["--user", "daemon-reload"],
},
{
step: "enabling the service",
command: "systemctl",
args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
},
{ step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
// Start last. No administrative state write occurs after this succeeds.
{
step: "starting the service",
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
},
],
restart: [
{
step: "restarting the service after a failed update",
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
},
],
deactivate: [
{
step: "stopping the service",
command: "systemctl",
args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
timeout: STOP_STEP_TIMEOUT,
},
],
finalize: [
{
step: "reloading systemd user units",
command: "systemctl",
args: ["--user", "daemon-reload"],
},
],
};
}
export function launchdManager(input: {
readonly path: Path.Path;
readonly homeDir: string;
readonly uid: number;
}): BootServiceManager {
const unitPath = input.path.join(
input.homeDir,
"Library",
"LaunchAgents",
BOOT_SERVICE_PLIST_FILE,
);
const domainTarget = `gui/${input.uid}`;
const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
// bootout/enable are optional: they fail on not-loaded states that are fine
// to proceed from. The strict `bootstrap` runs last and is also the start:
// loading a RunAtLoad/KeepAlive plist starts the job, so a separate
// kickstart would kill and restart a server it just booted. A lingering job
// that survived bootout, or a gui domain with nobody logged in at the
// screen (SSH install), makes bootstrap fail the flow loudly rather than
// silently keeping a stale server.
return {
kind: "launchd",
unitPath,
render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),
stop: [
{
step: "stopping the installed launch agent",
command: "launchctl",
args: ["bootout", serviceTarget],
optional: true,
timeout: STOP_STEP_TIMEOUT,
},
],
activate: [
// A persisted `launchctl disable` override refuses bootstrap; clear it.
{
step: "enabling the launch agent",
command: "launchctl",
args: ["enable", serviceTarget],
optional: true,
},
// Start last. No administrative state write occurs after this succeeds.
{
step: "starting the service",
command: "launchctl",
args: ["bootstrap", domainTarget, unitPath],
},
],
restart: [
{
step: "restarting the service after a failed update",
command: "launchctl",
args: ["bootstrap", domainTarget, unitPath],
},
],
// No `launchctl disable` here: a persisted override would sabotage a
// later reinstall. Removing the plist is what stops the next login load.
// A bootout that fails for a reason other than "not loaded" leaves the
// job running until logout; the failure is in the boot-service log.
deactivate: [
{
step: "stopping the service",
command: "launchctl",
args: ["bootout", serviceTarget],
optional: true,
timeout: STOP_STEP_TIMEOUT,
},
],
finalize: [],
};
}
/** Undefined means this host cannot run the background service. */
export function selectBootServiceManager(input: {
readonly platform: NodeJS.Platform;
readonly homeDir: string;
readonly uid: number | undefined;
readonly path: Path.Path;
}): BootServiceManager | undefined {
if (input.homeDir === "") {
return undefined;
}
if (input.platform === "linux") {
return systemdManager({ path: input.path, homeDir: input.homeDir });
}
if (input.platform === "darwin" && input.uid !== undefined) {
return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });
}
return undefined;
}
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
"BootServiceUnsupportedError",
{ platform: Schema.String },
) {
override get message(): string {
return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
}
}
@@ -435,15 +163,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}) {
const hostExecPath = yield* HostProcessExecutablePath;
const platform = yield* HostProcessPlatform;
const uid = yield* HostProcessUserId;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const host = input.host ?? { execPath: hostExecPath };
const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });
const unitPath = detectedManager?.unitPath ?? "";
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
@@ -471,11 +198,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
unitPath,
};
const requireManager = Effect.suspend(() =>
detectedManager === undefined
? new BootServiceUnsupportedError({ platform })
: Effect.succeed(detectedManager),
);
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return yield* new BootServiceUnsupportedError({ platform });
}
});
const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
step: string,
@@ -508,25 +235,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
Effect.forEach(
steps,
(entry) => {
const run = runStep(
entry.step,
entry.command,
entry.args,
entry.timeout === undefined ? undefined : { timeout: entry.timeout },
);
// runStep's tapError already appends the failure to the log, so an
// ignored optional step still leaves a trace.
return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
},
{ discard: true },
);
const install: BootService["Service"]["install"] = Effect.gen(function* () {
const manager = yield* requireManager;
yield* requireSystemdLinux;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -588,7 +298,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (installed) {
yield* runSteps(manager.stop);
yield* runStep("stopping the installed service", "systemctl", [
"--user",
"stop",
BOOT_SERVICE_UNIT_FILE,
]);
}
yield* Effect.gen(function* () {
@@ -602,7 +316,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}
}
yield* fs
.makeDirectory(path.dirname(unitPath), { recursive: true })
.makeDirectory(unitDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* writeDurably(launcherPath, launcherSource);
yield* writeDurably(
@@ -617,35 +331,58 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
2,
)}\n`,
);
yield* writeDurably(unitPath, manager.render(plan));
yield* writeDurably(unitPath, renderBootServiceUnit(plan));
yield* runSteps(manager.activate);
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
"enable",
BOOT_SERVICE_UNIT_FILE,
]);
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
// Start last. No administrative state write occurs after this succeeds.
yield* runStep("starting the service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]);
}).pipe(
Effect.tapError(() =>
installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
installed
? runStep("restarting the service after a failed update", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore)
: Effect.void,
),
);
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
const manager = yield* requireManager;
yield* requireSystemdLinux;
if (
!(yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
)
return false;
yield* runSteps(manager.deactivate);
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]);
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* runSteps(manager.finalize);
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
return true;
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
if (detectedManager === undefined) {
if (platform !== "linux" || homeDir === "") {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
if (!(yield* fs.exists(unitPath))) {
@@ -664,7 +401,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
supported: true,
installed: true,
current:
unit === detectedManager.render(plan) &&
unit === renderBootServiceUnit(plan) &&
launcherExists &&
runtimeEntryExists &&
Option.isSome(runtimeSentinel) &&
+1 -2
View File
@@ -649,8 +649,7 @@ export const pendingServiceUpdateExists = Effect.gen(function* () {
});
// A pending update alone is not proof a replacement server is coming: an
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
// `launchctl bootout`) during
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
// the pending window also tears this server down. The launcher marks that case
// just before it signals the child, so pending + no marker is the handoff.
const pendingUpdateHandoffExists = Effect.gen(function* () {
+2 -2
View File
@@ -10,8 +10,8 @@ import * as ProcessRunner from "../processRunner.ts";
/**
* A pinned runtime is an exact `t3@<version>` npm-installed into
* <baseDir>/runtime/versions/<version>. The boot service points its unit or
* launch agent here, and server self-update installs the target version here before
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
* unit here, and server self-update installs the target version here before
* switching over, never `npx t3`, whose cache is ephemeral and whose
* registry fetch at boot would make startup depend on the network.
*/
+1 -3
View File
@@ -317,9 +317,7 @@ export class Launcher {
// This must happen synchronously at signal receipt. A queued update
// transition may already be terminating the active child, and that child
// needs to see the marker in its shutdown finalizer. KillMode=mixed also
// ensures systemd signals the launcher before the rest of the cgroup, and
// launchd signals only the job's main process (this launcher), so the
// marker lands before the child sees any signal on both platforms.
// ensures systemd signals the launcher before the rest of the cgroup.
try {
NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
} catch {
@@ -3106,7 +3106,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showMobilePendingAnswerActions && "hidden sm:flex",
)}
>
<div className="-m-1 -ms-3.5 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 ps-3.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{noProviderAvailable ? (
<Button
type="button"
@@ -3129,7 +3129,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
instanceEntries={providerInstanceEntries}
keybindings={keybindings}
modelOptionsByInstance={modelOptionsByInstance}
triggerClassName="-ms-2.5"
triggerClassName="-ms-px"
terminalOpen={terminalOpen}
open={isComposerModelPickerOpen}
{...(composerProviderState.modelPickerIconClassName
+6 -7
View File
@@ -2,15 +2,14 @@
> For maintainers. Using T3 Code? See [docs/user](../user/).
Remote server updates use one stable launcher selected by the platform service manager (systemd on
Linux, launchd on macOS). Foreground CLI processes do not self-update, and a running server never
edits its service definition or durable service state.
Remote server updates use one stable systemd launcher. Foreground CLI processes do not self-update,
and a running server never edits its systemd unit or durable service state.
## Ownership
The service files under `<baseDir>/runtime` are:
- `service-launcher.mjs`, the stable process selected by the service manager;
- `service-launcher.mjs`, the stable process selected by systemd;
- `service-state.json`, the launcher's durable selection state;
- `versions/<version>`, immutable exact-version npm installs.
@@ -23,7 +22,7 @@ The state contains one active version and, at most, one update record:
- `pending A → B` selects B as a retryable trial;
- `committed A → B` selects B for ordinary restarts;
- `rolled-back A → B` or `failed A → B` selects A;
- invalid state fails closed so the service manager cannot guess at a runtime.
- invalid state fails closed so systemd cannot guess at a runtime.
Every write uses same-directory replacement plus file and directory fsync.
@@ -51,8 +50,8 @@ operations. It only opens prepared gates and publishes prepared lifecycle state.
The launcher serializes child exits, IPC messages, and timers. A trial must report prepared within
120 seconds. If the trial exits or times out before prepared, the launcher stops it, restores the
snapshot, records rollback, and starts A. A durable restore marker makes an interrupted restore
resume before either version can boot. After commit, B is active and the service manager's normal
restart policy applies.
resume before either version can boot. After commit, B is active and normal systemd restart policy
applies.
## Database Rollback
+11 -35
View File
@@ -1,7 +1,7 @@
# Running T3 Code in the Background
On Linux and macOS, T3 Code can run as a background service for your user, so it is ready without
keeping a terminal open.
On a Linux host, T3 Code can run as a background service for your user. It starts when the machine
boots and keeps running after you log out.
## Manage the Service
@@ -32,42 +32,18 @@ npx t3@latest service uninstall
Updating restarts T3 Code briefly. Let active agent work and terminal commands finish first.
If a remote update is already in progress, wait for it to finish before retrying a local update.
The service runs a small stable launcher. Exact T3 Code versions are installed separately, so a
failed remote candidate can return to the previous version without rewriting the service
definition. The launcher snapshots the database before a remote candidate starts, so database
updates roll back with the server version. An older launcher may require one local
`service update` before this is available.
## Platform Support
**Linux** uses a systemd user unit at `~/.config/systemd/user/t3code.service`. The service starts
when the machine boots and keeps running after you log out (lingering is enabled during install).
**macOS** uses a launch agent at `~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. It
starts when you log in, not when the Mac boots, and it stops when you log out; macOS has no
equivalent of Linux lingering for user agents. For a Mac that should stay reachable unattended,
turn on automatic login (System Settings → Users & Groups; unavailable while FileVault is on) and
keep the Mac from sleeping.
Two more macOS notes:
- Installing over SSH needs someone logged in at the Mac's screen to start the agent right away.
Without that, the install command reports an error at the final start step, but the agent is
fully installed and starts at the next login.
- macOS may show privacy prompts for protected folders such as Desktop, Documents, or Downloads,
attributed to a bare `node` process, or deny access without a prompt. If agent work fails to
read those folders, grant Full Disk Access to the node binary listed in the launch agent's
`ProgramArguments`.
- The agent appears under System Settings → General → Login Items. If it was switched off there,
or disabled with `launchctl disable`, macOS will not start it at login until you switch it back
on.
**Windows** is not supported yet.
The systemd unit runs a small stable launcher. Exact T3 Code versions are installed separately, so
a failed remote candidate can return to the previous version without rewriting the unit. The
launcher snapshots the database before a remote candidate starts, so database updates roll back
with the server version. An older launcher may require one local `service update` before this is
available.
## Using It with T3 Connect
T3 Connect may offer to install the service during setup so the host stays reachable in the
background. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
T3 Connect may offer to install the service during setup so the host stays reachable after you log
out. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longer
want T3 Code to start in the background.
The background service currently requires Linux with systemd.
-4
View File
@@ -18,7 +18,3 @@ Dev and Nightly environments can identify themselves with artwork at the top of
the send button. Choose **Artwork**, **Version pill**, or **None** in Settings under environment
identification. Artwork is recolored to match each built-in theme. Custom themes use the **Version
pill** fallback because their colors are not controlled by T3 Code.
To generate a fresh title from the conversation, open a thread's context menu and choose
**Regenerate title**. While T3 Code is generating it, the action reads **Regenerating…** and cannot
be selected again. The option is hidden when the connected environment needs a server update.
-8
View File
@@ -51,12 +51,4 @@ export const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(
},
);
/** Undefined on platforms without POSIX uids (Windows). */
export const HostProcessUserId = Context.Reference<number | undefined>(
"@t3tools/shared/hostProcess/HostProcessUserId",
{
defaultValue: () => process.getuid?.(),
},
);
export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");