Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
22 changes: 22 additions & 0 deletions apps/desktop/src/settings/DesktopAppSettings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,28 @@ describe("DesktopSettings", () => {
),
);

it.effect("keeps Local environment off when another value in the file is unreadable", () =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.desktopSettingsPath,
`{ "localEnvironmentEnabled": false, "serverExposureMode": "tailnet" }\n`,
);

assert.isFalse((yield* settings.load).localEnvironmentEnabled);
yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 800, height: 600 }, false);
assert.include(
yield* fileSystem.readFileString(environment.desktopSettingsPath),
`"localEnvironmentEnabled":false`,
);
}),
),
);

it.effect("rejects window bounds that do not satisfy the domain schema", () =>
withSettings(
Effect.gen(function* () {
Expand Down
31 changes: 18 additions & 13 deletions apps/desktop/src/settings/DesktopAppSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,20 +90,25 @@ const DesktopWindowBoundsDocument = Schema.Struct({
height: Schema.Number,
});

// A value this build cannot read drops only its own key, so the rest of the file
// still loads and is written back instead of every setting resetting to defaults.
const optionalReadableKey = <S extends Schema.Top>(schema: S) =>
Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone)));

const DesktopSettingsDocument = Schema.Struct({
localEnvironmentEnabled: Schema.optionalKey(Schema.Boolean),
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean),
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
wslOnly: Schema.optionalKey(Schema.Boolean),
localEnvironmentEnabled: optionalReadableKey(Schema.Boolean),
linuxPasswordStore: optionalReadableKey(Schema.Unknown),
mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: optionalReadableKey(Schema.Boolean),
serverExposureMode: optionalReadableKey(DesktopServerExposureModeSchema),
tailscaleServeEnabled: optionalReadableKey(Schema.Boolean),
tailscaleServePort: optionalReadableKey(Schema.Number),
updateChannel: optionalReadableKey(DesktopUpdateChannelSchema),
updateChannelConfiguredByUser: optionalReadableKey(Schema.Boolean),
wslBackendEnabled: optionalReadableKey(Schema.Boolean),
wslMode: optionalReadableKey(Schema.Literals(["local", "wsl"])),
wslDistro: optionalReadableKey(Schema.NullOr(Schema.String)),
wslOnly: optionalReadableKey(Schema.Boolean),
});

type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
Expand Down
38 changes: 30 additions & 8 deletions apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte
didSet {
guard oldValue != fontSize else { return }
inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
resetSurface()
applyConfigInPlace()
}
}

Expand Down Expand Up @@ -321,14 +321,14 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte
didSet {
guard oldValue != appearanceScheme else { return }
appearance = TerminalAppearanceScheme(value: appearanceScheme)
resetSurface()
applyConfigInPlace()
}
}

var themeConfig: String = "" {
didSet {
guard oldValue != themeConfig else { return }
resetSurface()
applyConfigInPlace()
}
}

Expand Down Expand Up @@ -663,7 +663,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte
surfaceCreationFailed = true
return
}
loadThemeConfig(into: config)
// Creation proceeds without the file, as before; font_size is also set on the surface config.
_ = loadThemeConfig(into: config)
ghostty_config_finalize(config)
defer { ghostty_config_free(config) }

Expand Down Expand Up @@ -710,6 +711,27 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte
setNeedsLayout()
}

// Font and theme change in place: a new surface would replay output and re-answer its queries.
private func applyConfigInPlace() {
guard let app, let surface else {
resetSurface()
return
}
guard let config = ghostty_config_new() else { return }
defer { ghostty_config_free(config) }
let loaded = loadThemeConfig(into: config)
ghostty_config_finalize(config)
ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme)
ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme)
tickApp()
// Without the file, the config lacks font-size and would reset the surface to defaults.
if loaded {
ghostty_surface_update_config(surface, config)
}
resizeSurface()
setNeedsLayout()
}

private func destroySurface() {
// Unblock the io thread before ghostty_surface_free joins it.
tickApp()
Expand Down Expand Up @@ -933,16 +955,16 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte
terminalViewport.backgroundColor = backgroundColorValue
}

private func loadThemeConfig(into config: ghostty_config_t) {
guard let path = writeThemeConfigFile() else { return }
private func loadThemeConfig(into config: ghostty_config_t) -> Bool {
guard let path = writeThemeConfigFile() else { return false }
path.withCString { cString in
ghostty_config_load_file(config, cString)
}
return true
}

private func writeThemeConfigFile() -> String? {
guard !themeConfig.isEmpty else { return nil }
let configContents = themeConfig
let configContents = "\(themeConfig)\nfont-size = \(String(format: "%g", Double(fontSize)))\n"
let url = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty")

Expand Down
17 changes: 14 additions & 3 deletions apps/mobile/src/components/ui/AppBar.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Toolbar } from "./Toolbar";
import { AppActivityIndicator } from "./AppActivityIndicator";
import type { HeaderBarButtonMailSearchToolbarItem, SearchBarCommands } from "react-native-screens";
import { NavigationContext } from "@react-navigation/native";
import { use, useId, useLayoutEffect, useRef } from "react";
import { NavigationContext, NavigationRouteContext } from "@react-navigation/native";
import { use, useId, useLayoutEffect, useRef, useSyncExternalStore } from "react";
import { View } from "react-native";
import { createNativeHeaderMenu } from "./nativeHeaderMenu.ios";
import { ScreenHeaderButton } from "./ScreenHeaderButton";
Expand Down Expand Up @@ -63,6 +63,17 @@ export function AppBar(props: AppBarProps) {
? { ...props.backInSplitView, onPress: splitBackPress }
: null;
const navigation = use(NavigationContext);
const route = use(NavigationRouteContext);
// A thread opened from another thread sits on it, not beside the list, so it keeps Back.
const threadBelow = useSyncExternalStore(
(onChange) => navigation?.addListener("state", onChange) ?? (() => {}),
() => {
const routes = navigation?.getState()?.routes;
const index = routes?.findIndex((candidate) => candidate.key === route?.key) ?? -1;
return route?.name === "Thread" && index > 0 && routes?.[index - 1]?.name === "Thread";
},
);
const listBeside = layout.usesSplitView && props.onBackToList !== undefined && !threadBelow;
const rootBack =
!layout.usesSplitView && props.onBackToList && navigation?.canGoBack() === false
? props.onBackToList
Expand Down Expand Up @@ -113,7 +124,7 @@ export function AppBar(props: AppBarProps) {
headerBackVisible:
props.onClose === undefined &&
splitBack === null &&
!(layout.usesSplitView && props.onBackToList) &&
!listBeside &&
!(props.guardBack && props.onBack),
...(props.guardBack ? { gestureEnabled: false } : undefined),
title: props.title,
Expand Down
68 changes: 51 additions & 17 deletions apps/server/src/device/LocalDeviceHost.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { describe, expect, it } from "@effect/vitest";
import * as NodePath from "@effect/platform-node/NodePath";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
Expand Down Expand Up @@ -45,7 +47,8 @@ const agentFixture = Effect.fn("agentFixture")(function* (
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });
const hub = { running: true, spawnFails: false };
const hub = { running: true, spawnFails: false, cleanup: Effect.void };
const daemonStopRequested = yield* Deferred.make<ReadonlyArray<string>>();
const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
const daemonHealthy = yield* Ref.make(true);
const runs: Array<ProcessRunner.ProcessRunInput> = [];
Expand Down Expand Up @@ -80,20 +83,22 @@ const agentFixture = Effect.fn("agentFixture")(function* (
description: "Hub entry missing",
}),
)
: Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
exitCode: Effect.never,
isRunning: Effect.sync(() => hub.running),
kill: () => Effect.void,
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
}),
: Effect.addFinalizer(() => hub.cleanup).pipe(
Effect.as(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
exitCode: Effect.never,
isRunning: Effect.sync(() => hub.running),
kill: () => Effect.void,
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
}),
),
),
),
),
Expand All @@ -102,7 +107,9 @@ const agentFixture = Effect.fn("agentFixture")(function* (
runs.push(input);
return input.args.includes("devices")
? startup(stateDir)
: Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0));
: input.args.includes("daemon")
? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0)))
: Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0));
},
}),
Effect.provideService(
Expand All @@ -122,7 +129,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (
),
);
yield* host.ensureReady(() => Effect.void);
return { host, fs, baseDir, stateDir, hub, daemonHealthy, runs };
return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs };
});

describe("AgentDevice startup", () => {
Expand Down Expand Up @@ -353,6 +360,33 @@ describe("AgentDevice startup", () => {
expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect("stops the agent daemon while the hub is still shutting down", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { host, hub, stateDir, daemonStopRequested } = yield* agentFixture((stateDir) =>
fs
.writeFileString(
`${stateDir}/daemon.json`,
JSON.stringify({ httpPort: 12345, token: "test-token" }),
)
.pipe(Effect.orDie, Effect.as(processOutput(0))),
);
yield* host.ensureAgentReady(() => Effect.void);
const hubExited = yield* Deferred.make<void>();
hub.cleanup = Deferred.await(hubExited);
const stopping = yield* Effect.forkChild(host.stop);
expect((yield* Deferred.await(daemonStopRequested)).slice(1)).toEqual([
"daemon",
"stop",
"--state-dir",
stateDir,
]);
yield* Deferred.succeed(hubExited, undefined);
yield* Fiber.join(stopping);
expect(yield* fs.exists(`${stateDir}/hub.json`)).toBe(false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});

const diagnose = (
Expand Down
13 changes: 10 additions & 3 deletions apps/server/src/device/LocalDeviceHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -870,9 +870,16 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)(
Effect.gen(function* () {
const running = yield* Ref.getAndSet(runningRef, null);
yield* stopHub(running?.hub);
yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore);
yield* stopAgentDeviceDaemon;
// Hub cleanup waits for its exit unbounded; it must not strand the detached agent daemon.
yield* Effect.all(
[
stopHub(running?.hub).pipe(
Effect.andThen(fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore)),
),
stopAgentDeviceDaemon,
],
{ concurrency: "unbounded", discard: true },
);
}),
);

Expand Down
7 changes: 1 addition & 6 deletions apps/server/src/provider/CodexProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ import {
import * as HostProcess from "@t3tools/shared/HostProcess";
import packageJson from "../../package.json" with { type: "json" };
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000;

type CodexRateLimitsProbe =
| {
Expand Down Expand Up @@ -686,11 +685,7 @@ const readCodexRateLimits = (
client: CodexClient.CodexAppServerClient["Service"],
deadlineMs: number,
) =>
withCodexDiscoveryDeadline(
client.request("account/rateLimits/read", null),
deadlineMs,
RATE_LIMITS_PROBE_TIMEOUT_MS,
).pipe(
withCodexDiscoveryDeadline(client.request("account/rateLimits/read", null), deadlineMs).pipe(
Effect.map((response): CodexRateLimitsProbe =>
response
? {
Expand Down
Loading
Loading