Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ffd43b41ec | ||
|
|
04ae0412ef | ||
|
|
3cc7cf3c83 |
No files matched your search
@@ -5,23 +5,6 @@ name: Mobile EAS Production
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
#
|
||||
# Every merge to main that touches the mobile app reconciles, per platform:
|
||||
# 1. Store builds: if the latest production build's version differs from
|
||||
# app.config.ts, cut a new build with --auto-submit (TestFlight +
|
||||
# Play internal track). Bumping `version` is therefore all it takes to
|
||||
# start the next release train — the first build of a version enters
|
||||
# external-TestFlight beta review immediately, and later builds of the
|
||||
# same version auto-approve. Releasing to the App Store stays a manual
|
||||
# App Store Connect step.
|
||||
# 2. OTA: publish a production-channel update for each platform where at
|
||||
# least one finished production build matches the current native
|
||||
# fingerprint. Old-version binaries with a matching fingerprint receive
|
||||
# it too. When native drift means no binary could install the update,
|
||||
# it is skipped and flagged in the job summary instead of published
|
||||
# into the void.
|
||||
# workflow_dispatch remains as a manual override for both modes (e.g. to
|
||||
# retry an errored build or force an OTA).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -46,30 +29,10 @@ on:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-eas-production.yml
|
||||
|
||||
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
|
||||
# queued run per group, so a burst of merges collapses into one run of the
|
||||
# newest commit — intermediate commits don't need their own OTA.
|
||||
concurrency:
|
||||
group: mobile-eas-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -135,15 +98,15 @@ jobs:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
@@ -154,62 +117,3 @@ jobs:
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
|
||||
# No --status filter on build:list: an in-queue/in-progress build must
|
||||
# count as existing, or every merge during the build window would cut a
|
||||
# duplicate. Builds started here stay attached to this serialized run so
|
||||
# the queued run for a later merge cannot overtake them and lose its OTA.
|
||||
# After an errored build, retry via workflow_dispatch mode=build — pushes
|
||||
# won't re-trigger it until the app version changes.
|
||||
- id: store_builds
|
||||
name: Ensure store builds exist for the current app version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
failed=0
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
for platform in ios android; do
|
||||
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
|
||||
if [ "$latest" = "$version" ]; then
|
||||
echo "$platform: production build for $version already exists (or is in progress)"
|
||||
continue
|
||||
fi
|
||||
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
|
||||
if eas build --platform "$platform" --profile production --auto-submit --non-interactive; then
|
||||
echo ":building_construction: $platform: cut production build for $version (auto-submitted)" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
failed=1
|
||||
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
- name: Publish fingerprint-gated OTA
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
|
||||
for platform in ios android; do
|
||||
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | jq -r '.hash')"
|
||||
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
|
||||
if [ "$matching" -gt 0 ]; then
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform "$platform" \
|
||||
--message "$message" \
|
||||
--non-interactive
|
||||
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Propagate store build failure
|
||||
if: steps.store_builds.outcome == 'failure'
|
||||
run: exit 1
|
||||
@@ -1,205 +0,0 @@
|
||||
name: Mobile Fingerprint Check
|
||||
|
||||
# Detects whether a PR changes the native fingerprint — i.e. whether merging
|
||||
# it would leave main un-OTA-able until a new store build ships. Native-change
|
||||
# PRs get the "📱 Native Change" label so they can be held and merged as a
|
||||
# batch right before the next store submission, keeping main OTA-able for
|
||||
# everything else in between. (Once one native PR merges, every later merge
|
||||
# inherits the drifted fingerprint and loses OTA reach too — that is why the
|
||||
# signal has to fire before merge, not after.)
|
||||
#
|
||||
# The check is advisory: it always passes, the label is the signal. Both
|
||||
# fingerprints are computed in this one job (same OS, same corepack-pinned
|
||||
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-fingerprint-check.yml
|
||||
|
||||
concurrency:
|
||||
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fingerprint:
|
||||
name: Native fingerprint diff
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# Default pull_request checkout is the merge commit (PR applied on
|
||||
# top of base), so the "head" fingerprint is the state main would
|
||||
# actually be in after merging — stale branches compare cleanly.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Fingerprint merge result
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
|
||||
done
|
||||
|
||||
- name: Fingerprint base
|
||||
run: |
|
||||
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
|
||||
# Re-sync node_modules to the base commit's lockfile before
|
||||
# fingerprinting — a dep-changing PR must not fingerprint the base
|
||||
# against head's installed packages.
|
||||
pnpm install --filter=@t3tools/mobile...
|
||||
cd apps/mobile
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
|
||||
done
|
||||
|
||||
- id: compare
|
||||
name: Compare fingerprints
|
||||
run: |
|
||||
changed=""
|
||||
{
|
||||
echo "## Native fingerprint diff"
|
||||
echo
|
||||
for platform in ios android; do
|
||||
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
|
||||
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
|
||||
if [ "$head_hash" = "$base_hash" ]; then
|
||||
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
|
||||
continue
|
||||
fi
|
||||
changed="$changed $platform"
|
||||
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
|
||||
jq -r -n \
|
||||
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
|
||||
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
|
||||
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
|
||||
| $h[0].sources[]
|
||||
| select($bm[(.filePath // .id)] != .hash)
|
||||
| " - \(.type): `\(.filePath // .id)`"'
|
||||
done
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Sync native change label
|
||||
# Fork PRs get a read-only token under pull_request; the check stays
|
||||
# advisory there (summary only). This workflow must not move to
|
||||
# pull_request_target — it installs and runs PR code.
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
|
||||
with:
|
||||
script: |
|
||||
const managedLabel = {
|
||||
name: "📱 Native Change",
|
||||
color: "d93f0b",
|
||||
description:
|
||||
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
|
||||
};
|
||||
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== managedLabel.color ||
|
||||
(existing.description ?? "") !== managedLabel.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
|
||||
|
||||
if (nativeChanged && !hasLabel) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [managedLabel.name],
|
||||
});
|
||||
} else if (!nativeChanged && hasLabel) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
|
||||
);
|
||||
@@ -1,132 +0,0 @@
|
||||
name: Web Preview
|
||||
|
||||
# Label a PR `preview:web` to get a hosted-web preview deployment on Vercel for
|
||||
# that push and every subsequent push. The deployment is a plain (non-prod,
|
||||
# non-aliased) deploy into the existing hosted-web Vercel project, so the
|
||||
# latest/nightly channel aliases are never touched.
|
||||
#
|
||||
# The build intentionally omits the T3 Connect cloud config (Clerk keys, relay
|
||||
# URL): previews boot as the hosted-static app with manual pairing only. Pair a
|
||||
# server into a preview with `t3 pair --tailscale` (or any reachable HTTPS
|
||||
# backend) and open the pairing URL against the preview origin.
|
||||
#
|
||||
# The preview must be opened at the exact deployment URL from the PR comment.
|
||||
# Vite bakes that URL in as the hosted origin (via VERCEL_URL), and
|
||||
# `isHostedStaticApp` matches on origin, so branch-alias URLs will not
|
||||
# self-identify as the hosted app.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: web-preview-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy web preview
|
||||
# Same-repo PRs only: fork PRs do not receive the Vercel secrets, and this
|
||||
# workflow should skip rather than fail for them. On `labeled` events, only
|
||||
# the preview label itself triggers a deploy.
|
||||
if: >-
|
||||
github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
contains(github.event.pull_request.labels.*.name, 'preview:web') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'preview:web')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- id: deploy
|
||||
name: Deploy preview
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
|
||||
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
|
||||
|
||||
deployment_url="$(
|
||||
vp dlx [email protected] deploy \
|
||||
--archive=tgz \
|
||||
--yes \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
--scope "$vercel_scope"
|
||||
)"
|
||||
|
||||
echo "Deployed $deployment_url"
|
||||
echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Comment deployment URL
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
with:
|
||||
script: |
|
||||
const marker = "<!-- web-preview-deploy -->";
|
||||
const body = [
|
||||
marker,
|
||||
"### Web preview",
|
||||
"",
|
||||
`${process.env.DEPLOYMENT_URL} (for ${process.env.HEAD_SHA.slice(0, 7)})`,
|
||||
"",
|
||||
"Open this exact URL — the hosted-app origin is baked in at build time.",
|
||||
"Pair a server into it with `t3 pair --tailscale`, or paste a host + pairing",
|
||||
"code under Settings → Connections.",
|
||||
].join("\n");
|
||||
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.pull_request.number,
|
||||
per_page: 100,
|
||||
});
|
||||
const existing = comments.find((comment) => comment.body?.includes(marker));
|
||||
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.pull_request.number,
|
||||
body,
|
||||
});
|
||||
}
|
||||
@@ -68,7 +68,6 @@ Full docs live in [docs/](./docs). There's no docs site yet.
|
||||
- [Install and first run](./docs/user/install.md)
|
||||
- [Permission modes](./docs/user/permission-modes.md)
|
||||
- [Keyboard shortcuts](./docs/user/keybindings.md)
|
||||
- [Customize a project icon](./docs/user/project-settings.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
|
||||
@@ -28,6 +28,70 @@ describe("ElectronDialog", () => {
|
||||
showErrorBoxMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("returns false without opening a confirm dialog for empty messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: " ",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.equal(showMessageBoxMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens a confirm dialog for the owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
const owner = { id: 1 } as BrowserWindow;
|
||||
showMessageBoxMock.mockResolvedValue({ response: 1 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.some(owner),
|
||||
});
|
||||
|
||||
assert.isTrue(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
owner,
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
showMessageBoxMock.mockResolvedValue({ response: 0 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
@@ -53,6 +117,31 @@ describe("ElectronDialog", () => {
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves confirmation request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("confirmation failed");
|
||||
const owner = { id: 9 } as BrowserWindow;
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.confirm({
|
||||
owner: Option.some(owner),
|
||||
message: " Confirm removal? ",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
|
||||
assert.strictEqual(error.ownerWindowId, 9);
|
||||
assert.strictEqual(error.promptLength, "Confirm removal?".length);
|
||||
assert.notProperty(error, "promptMessage");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 9");
|
||||
assert.notInclude(error.message, "Confirm removal?");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message box request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("message box failed");
|
||||
|
||||
@@ -6,6 +6,8 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
@@ -36,6 +38,20 @@ export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<Electr
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
|
||||
"ElectronDialogShowMessageBoxError",
|
||||
{
|
||||
@@ -69,6 +85,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
@@ -86,6 +103,11 @@ export interface ElectronDialogPickFilesInput {
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<
|
||||
ElectronDialog,
|
||||
{
|
||||
@@ -95,6 +117,9 @@ export class ElectronDialog extends Context.Service<
|
||||
readonly pickFiles: (
|
||||
input: ElectronDialogPickFilesInput,
|
||||
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
@@ -163,6 +188,39 @@ export const make = ElectronDialog.of({
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}),
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.dialog.showMessageBox(options),
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
setUpdateChannel,
|
||||
} from "./methods/updates.ts";
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
@@ -80,6 +81,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(pickThemeFiles);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
|
||||
@@ -220,6 +220,19 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
return yield* electronWindow.focusedMainOrFirst.pipe(
|
||||
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
|
||||
@@ -98,6 +98,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) =>
|
||||
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
|
||||
|
||||
@@ -231,7 +231,6 @@ describe("DesktopShellEnvironment", () => {
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.local\\bin",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
|
||||
@@ -207,7 +207,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
|
||||
...trimNonEmpty(env.USERPROFILE).pipe(
|
||||
Option.match({
|
||||
onNone: () => [],
|
||||
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -53,6 +53,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
pickFiles: () => Effect.succeed([]),
|
||||
confirm: () => Effect.succeed(false),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
} satisfies ElectronDialog.ElectronDialog["Service"]);
|
||||
|
||||
@@ -48,7 +48,6 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
|
||||
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
@@ -191,13 +190,6 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Client Storage",
|
||||
},
|
||||
}),
|
||||
SettingsUsage: createNativeStackScreen({
|
||||
screen: UsageRouteScreen,
|
||||
linking: "usage",
|
||||
options: {
|
||||
title: "Usage",
|
||||
},
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
IconBellRinging,
|
||||
IconBolt,
|
||||
IconCamera,
|
||||
IconChartBar,
|
||||
IconCheck,
|
||||
IconChevronDown,
|
||||
IconCode,
|
||||
@@ -98,7 +97,6 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
"bolt.circle": IconBolt,
|
||||
"bolt.horizontal.circle": IconBolt,
|
||||
camera: IconCamera,
|
||||
"chart.bar.xaxis": IconChartBar,
|
||||
checkmark: IconCheck,
|
||||
"checkmark.circle": IconCircleCheck,
|
||||
clock: IconClock,
|
||||
|
||||
@@ -133,25 +133,9 @@ export function ControlPillMenu(
|
||||
}
|
||||
|
||||
const { className: _className, ...menuProps } = props;
|
||||
let children = menuProps.children;
|
||||
// In long-press mode the wrapped pressable still receives the touch (the
|
||||
// patched MenuView button is touch-transparent) and RN's Fabric touch
|
||||
// handler is never cancelled by the in-tree UIContextMenuInteraction, so a
|
||||
// bare onPress would fire on finger-up even after the menu opened — and
|
||||
// also on a long press released just under the menu threshold. A dispatched
|
||||
// onLongPress makes Pressability swallow the release, so holds past 350ms
|
||||
// (below the ~500ms context-menu threshold) can only open the menu, never
|
||||
// tap through.
|
||||
if (props.shouldOpenOnLongPress && isValidElement(children)) {
|
||||
const child = children as ReactElement<{ onLongPress?: () => void; delayLongPress?: number }>;
|
||||
children = cloneElement(child, {
|
||||
onLongPress: child.props.onLongPress ?? (() => undefined),
|
||||
delayLongPress: child.props.delayLongPress ?? 350,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
|
||||
{children}
|
||||
{menuProps.children}
|
||||
</MenuView>
|
||||
);
|
||||
}
|
||||
@@ -24,18 +24,13 @@ export function ProjectFavicon(props: {
|
||||
readonly size?: number;
|
||||
readonly projectTitle: string;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly faviconPath?: string | null;
|
||||
}) {
|
||||
const size = props.size ?? 42;
|
||||
const faviconUrl = useAssetUrl(
|
||||
props.environmentId,
|
||||
props.workspaceRoot === null || props.workspaceRoot === undefined
|
||||
? null
|
||||
: {
|
||||
_tag: "project-favicon",
|
||||
cwd: props.workspaceRoot,
|
||||
...(props.faviconPath ? { path: props.faviconPath } : {}),
|
||||
},
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
const cacheKey =
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
|
||||
import {
|
||||
type BackgroundScope,
|
||||
@@ -103,40 +103,6 @@ export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
|
||||
Stream.runForEach(() => Effect.sync(requestReport)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
// Re-report on every newly connected session generation. The AppState
|
||||
// report races the reconnect (the RPC fails while the socket is down and
|
||||
// is ignored), so without this the server's lease can lag a resume by up
|
||||
// to REPORT_INTERVAL_MS, keeping provider/VCS work paused. The generation
|
||||
// dedup lives inside the per-supervisor stream because a replacement
|
||||
// supervisor restarts generations; switchMap (default concurrency)
|
||||
// interrupts the previous subscription set on environment changes.
|
||||
const connectedGenerations = (environmentId: EnvironmentId) =>
|
||||
registry.followStream(
|
||||
environmentId,
|
||||
Stream.unwrap(
|
||||
Effect.map(EnvironmentSupervisor, (supervisor) =>
|
||||
SubscriptionRef.changes(supervisor.state).pipe(
|
||||
Stream.filter((state) => state.phase === "connected"),
|
||||
Stream.map((state) => state.generation),
|
||||
Stream.changes,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Stream.concat(
|
||||
Stream.fromEffect(SubscriptionRef.get(registry.entries)),
|
||||
SubscriptionRef.changes(registry.entries),
|
||||
).pipe(
|
||||
Stream.map((entries) => [...entries.keys()].sort()),
|
||||
Stream.changesWith((a, b) => a.length === b.length && a.every((id, i) => id === b[i])),
|
||||
Stream.switchMap((environmentIds) =>
|
||||
Stream.mergeAll(environmentIds.map(connectedGenerations), {
|
||||
concurrency: "unbounded",
|
||||
}),
|
||||
),
|
||||
Stream.runForEach(() => Effect.sync(requestReport)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.fromQueue(reportRequests).pipe(
|
||||
Stream.debounce("250 millis"),
|
||||
Stream.runForEach(() => report),
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
observeNetworkPath,
|
||||
seedNetworkPathBaseline,
|
||||
UNKNOWN_NETWORK_PATH,
|
||||
} from "./network-path-change";
|
||||
|
||||
describe("network path change detection", () => {
|
||||
it("does not probe when the listener matches the seeded interface", () => {
|
||||
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
|
||||
|
||||
expect(observeNetworkPath(seeded, "WIFI")).toEqual({
|
||||
baseline: { known: true, type: "WIFI" },
|
||||
shouldProbe: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("probes when a known interface changes", () => {
|
||||
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
|
||||
|
||||
expect(observeNetworkPath(seeded, "CELLULAR").shouldProbe).toBe(true);
|
||||
});
|
||||
|
||||
it("probes when the listener wins the race with the async seed", () => {
|
||||
const observed = observeNetworkPath(UNKNOWN_NETWORK_PATH, "CELLULAR");
|
||||
|
||||
expect(observed.shouldProbe).toBe(true);
|
||||
expect(seedNetworkPathBaseline(observed.baseline, "WIFI")).toEqual({
|
||||
known: true,
|
||||
type: "CELLULAR",
|
||||
});
|
||||
});
|
||||
|
||||
it("probes on the first known interface after an unknown observation", () => {
|
||||
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
|
||||
const unknown = observeNetworkPath(seeded, null);
|
||||
|
||||
expect(unknown.shouldProbe).toBe(false);
|
||||
expect(observeNetworkPath(unknown.baseline, "CELLULAR").shouldProbe).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
export interface NetworkPathBaseline {
|
||||
readonly known: boolean;
|
||||
readonly type: string | null;
|
||||
}
|
||||
|
||||
export const UNKNOWN_NETWORK_PATH: NetworkPathBaseline = {
|
||||
known: false,
|
||||
type: null,
|
||||
};
|
||||
|
||||
export function seedNetworkPathBaseline(
|
||||
baseline: NetworkPathBaseline,
|
||||
type: string | null,
|
||||
): NetworkPathBaseline {
|
||||
if (baseline.known || type === null) {
|
||||
return baseline;
|
||||
}
|
||||
return { known: true, type };
|
||||
}
|
||||
|
||||
export function observeNetworkPath(
|
||||
baseline: NetworkPathBaseline,
|
||||
type: string | null,
|
||||
): {
|
||||
readonly baseline: NetworkPathBaseline;
|
||||
readonly shouldProbe: boolean;
|
||||
} {
|
||||
if (type === null) {
|
||||
return {
|
||||
baseline: UNKNOWN_NETWORK_PATH,
|
||||
shouldProbe: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
baseline: { known: true, type },
|
||||
// If the initial async seed has not landed, the first listener event may
|
||||
// itself be the WiFi/cellular transition. A cheap advisory probe is safer
|
||||
// than losing that transition and waiting for the socket ping timeout.
|
||||
shouldProbe: !baseline.known || baseline.type !== type,
|
||||
};
|
||||
}
|
||||
@@ -31,11 +31,6 @@ import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
|
||||
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
|
||||
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
|
||||
import {
|
||||
observeNetworkPath,
|
||||
seedNetworkPathBaseline,
|
||||
UNKNOWN_NETWORK_PATH,
|
||||
} from "./network-path-change";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
|
||||
@@ -92,13 +87,11 @@ const connectivityLayer = Connectivity.layer({
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<
|
||||
"application-active-probe" | "application-active-reconnect" | "network-path-changed"
|
||||
>((queue) =>
|
||||
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
|
||||
const appStateSubscription = AppState.addEventListener("change", (state) => {
|
||||
return AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
@@ -108,36 +101,6 @@ const wakeupsLayer = Wakeups.layer({
|
||||
backgroundedAtMs = null;
|
||||
}
|
||||
});
|
||||
// WiFi <-> cellular keeps isConnected true while invalidating the
|
||||
// socket's path, so the coarse online/offline signal never fires.
|
||||
// Emit an advisory wakeup on interface-type changes while active;
|
||||
// the supervisor probes the session rather than blindly replacing
|
||||
// it, which keeps flapping paths cheap. Seed the current type so
|
||||
// the first flip after startup is detected; the listener only
|
||||
// reports changes.
|
||||
let networkPath = UNKNOWN_NETWORK_PATH;
|
||||
void Network.getNetworkStateAsync()
|
||||
.then((current) => {
|
||||
networkPath = seedNetworkPathBaseline(networkPath, current.type ?? null);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const networkSubscription = Network.addNetworkStateListener((state) => {
|
||||
const observation = observeNetworkPath(networkPath, state.type ?? null);
|
||||
networkPath = observation.baseline;
|
||||
if (
|
||||
observation.shouldProbe &&
|
||||
state.isConnected === true &&
|
||||
AppState.currentState === "active"
|
||||
) {
|
||||
Queue.offerUnsafe(queue, "network-path-changed");
|
||||
}
|
||||
});
|
||||
return {
|
||||
remove: () => {
|
||||
appStateSubscription.remove();
|
||||
networkSubscription.remove();
|
||||
},
|
||||
};
|
||||
}),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
|
||||
@@ -368,7 +368,6 @@ function ProjectGroupLabel(props: {
|
||||
<View className="flex-row items-center gap-2.5 px-1 pb-2">
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
projectTitle={props.project.title}
|
||||
size={18}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
|
||||
@@ -533,7 +533,6 @@ function GeneralSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ export type SettingsSheetTarget =
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage"
|
||||
| "SettingsUsage";
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -296,7 +296,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
<View className="h-7 w-7 items-center justify-center">
|
||||
<ProjectFavicon
|
||||
environmentId={scope.representative.environmentId}
|
||||
faviconPath={scope.representative.faviconPath}
|
||||
size={20}
|
||||
projectTitle={scope.title}
|
||||
workspaceRoot={scope.representative.workspaceRoot}
|
||||
@@ -331,7 +330,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
faviconPath={project.faviconPath}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
|
||||
@@ -49,7 +49,6 @@ import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reani
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
@@ -877,12 +876,6 @@ function renderFeedEntry(
|
||||
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
|
||||
const attachments = message.attachments ?? [];
|
||||
const hasReviewCommentContext = message.text.includes("<review_comment");
|
||||
// A bubble that sizes itself from its content cannot lay out a block whose
|
||||
// intrinsic width overflows `maxWidth`: Android positions the bubble's
|
||||
// children during the unclamped pass and never moves them once the width
|
||||
// is clamped, so the paragraphs around the block end up drawn on top of
|
||||
// each other. Pinning the width removes that pass.
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text);
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
@@ -905,11 +898,7 @@ function renderFeedEntry(
|
||||
style={{
|
||||
backgroundColor: userBubbleColor,
|
||||
maxWidth: props.userBubbleMaxWidth,
|
||||
...(hasReviewCommentContext
|
||||
? { width: props.reviewCommentBubbleWidth }
|
||||
: hasWideBlock
|
||||
? { width: props.userBubbleMaxWidth }
|
||||
: null),
|
||||
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
||||
}}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
|
||||
@@ -134,7 +134,6 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
open={!props.collapsed}
|
||||
size={compact ? 22 : 18}
|
||||
projectTitle={props.project.title}
|
||||
|
||||
@@ -230,7 +230,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={pendingTask.message.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
size={15}
|
||||
projectTitle={projectTitle}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
@@ -631,7 +630,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
@@ -820,7 +818,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
faviconPath={props.project.faviconPath}
|
||||
size={15}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { Chart, Host, type ChartDataPoint } from "@expo/ui/swift-ui";
|
||||
import { frame } from "@expo/ui/swift-ui/modifiers";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { DailyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
|
||||
import { useProviderColors } from "./usageProviders";
|
||||
|
||||
export interface UsageDailyChartProps {
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Native Swift Charts daily bars. Points sharing an x value stack, so emitting
|
||||
* one point per provider per day yields per-provider bands whose stack height
|
||||
* is the day's total; changes animate natively.
|
||||
*
|
||||
* Axes are hidden: 30-90 categorical day labels cannot fit on a phone, so the
|
||||
* screen renders its own edge labels under the chart instead.
|
||||
*/
|
||||
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
|
||||
const colors = useProviderColors();
|
||||
|
||||
const data = useMemo((): ChartDataPoint[] => {
|
||||
return buildChartDays(days, daily, metric).flatMap((day) =>
|
||||
day.values.map((entry) => ({
|
||||
x: day.day,
|
||||
y: entry.value,
|
||||
color: colors[entry.provider],
|
||||
})),
|
||||
);
|
||||
}, [days, daily, metric, colors]);
|
||||
|
||||
return (
|
||||
<Host style={{ height, width: "100%" }}>
|
||||
<Chart
|
||||
type="bar"
|
||||
data={data}
|
||||
animate
|
||||
showGrid={false}
|
||||
barStyle={{ cornerRadius: 2 }}
|
||||
modifiers={[frame({ height })]}
|
||||
/>
|
||||
</Host>
|
||||
);
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import type { DailyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
|
||||
import { useProviderColors } from "./usageProviders";
|
||||
|
||||
export interface UsageDailyChartProps {
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacked daily bars drawn with plain views. Android and any platform without
|
||||
* Swift Charts land here; iOS resolves `UsageDailyChart.ios.tsx` instead.
|
||||
*/
|
||||
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
|
||||
const colors = useProviderColors();
|
||||
const chartDays = useMemo(() => buildChartDays(days, daily, metric), [days, daily, metric]);
|
||||
const max = chartDays.reduce((peak, day) => Math.max(peak, day.total), 0);
|
||||
|
||||
return (
|
||||
<View style={{ height }} className="flex-row items-end gap-px">
|
||||
{/* column-reverse stacks the bottom-first provider values upward
|
||||
without reversing the array (Hermes lacks Array#toReversed). */}
|
||||
{chartDays.map((day) => (
|
||||
<View key={day.day} className="h-full flex-1 flex-col-reverse overflow-hidden rounded-sm">
|
||||
{day.values.map((entry) => (
|
||||
<View
|
||||
key={entry.provider}
|
||||
style={{
|
||||
height: max === 0 ? 0 : (entry.value / max) * height,
|
||||
backgroundColor: colors[entry.provider],
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,442 +0,0 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
formatCount,
|
||||
formatDayShort,
|
||||
formatPercent,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
makeWindow,
|
||||
} from "@t3tools/shared/usageFormat";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
|
||||
import { SettingsSection } from "../settings/components/SettingsSection";
|
||||
import { UsageDailyChart } from "./UsageDailyChart";
|
||||
import type { UsageChartMetric } from "./usageChartData";
|
||||
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
|
||||
|
||||
const WINDOW_OPTIONS = [
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
{ days: 90, label: "90 days" },
|
||||
] as const;
|
||||
|
||||
const CHART_HEIGHT = 180;
|
||||
|
||||
export function UsageRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const [windowDays, setWindowDays] = useState<number>(30);
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
|
||||
// Recomputed only when the window length changes, so a re-render does not
|
||||
// shift the range and refetch every environment.
|
||||
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
|
||||
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
|
||||
|
||||
const days = useMemo(
|
||||
() => enumerateDays(window.sinceDay, window.untilDay),
|
||||
[window.sinceDay, window.untilDay],
|
||||
);
|
||||
|
||||
// The pull spinner tracks re-scans of environments that have answered
|
||||
// before. The initial scan renders its own placeholder, and an unreachable
|
||||
// environment stays pending forever — neither may pin the spinner on.
|
||||
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Usage" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-6 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}
|
||||
>
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
|
||||
selected={windowDays}
|
||||
onSelect={setWindowDays}
|
||||
/>
|
||||
|
||||
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
|
||||
|
||||
{isPending ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
Scanning provider transcripts…
|
||||
</Text>
|
||||
) : environments.length === 0 ? (
|
||||
<Text className="py-16 text-center text-base text-foreground-muted">
|
||||
Connect an environment to see usage.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<ChartCard
|
||||
merged={merged}
|
||||
days={days}
|
||||
metric={metric}
|
||||
onMetricChange={setMetric}
|
||||
sinceDay={window.sinceDay}
|
||||
untilDay={window.untilDay}
|
||||
/>
|
||||
<ProviderSection merged={merged} metric={metric} />
|
||||
<TotalsSection merged={merged} />
|
||||
<ModelsSection merged={merged} />
|
||||
</>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SegmentedControl<Value extends number | string>(props: {
|
||||
readonly options: readonly { readonly value: Value; readonly label: string }[];
|
||||
readonly selected: Value;
|
||||
readonly onSelect: (value: Value) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row overflow-hidden rounded-full border-continuous bg-card">
|
||||
{props.options.map((option) => {
|
||||
const active = option.value === props.selected;
|
||||
return (
|
||||
<Pressable
|
||||
key={String(option.value)}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: active }}
|
||||
onPress={() => props.onSelect(option.value)}
|
||||
className={
|
||||
active
|
||||
? "flex-1 items-center rounded-full bg-subtle-strong py-2"
|
||||
: "flex-1 items-center py-2"
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
active ? "text-sm font-t3-medium text-foreground" : "text-sm text-foreground-muted"
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Headline figure, the animated daily chart, and its legend, in one card. */
|
||||
function ChartCard(props: {
|
||||
readonly merged: MergedUsage;
|
||||
readonly days: readonly string[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly onMetricChange: (metric: UsageChartMetric) => void;
|
||||
readonly sinceDay: string;
|
||||
readonly untilDay: string;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
const hasActivity = merged.daily.some((day) => day.totalTokens > 0);
|
||||
|
||||
return (
|
||||
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
|
||||
<View className="flex-row items-start justify-between gap-3">
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
|
||||
</Text>
|
||||
<Text className="text-4xl font-t3-bold tabular-nums text-foreground">
|
||||
{metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{metric === "cost"
|
||||
? "* if billed at full API rate"
|
||||
: `Across ${formatCount(merged.sessions)} sessions`}
|
||||
</Text>
|
||||
</View>
|
||||
<MetricToggle metric={metric} onChange={props.onMetricChange} />
|
||||
</View>
|
||||
|
||||
{hasActivity ? (
|
||||
<UsageDailyChart
|
||||
days={props.days}
|
||||
daily={merged.daily}
|
||||
metric={metric}
|
||||
height={CHART_HEIGHT}
|
||||
/>
|
||||
) : (
|
||||
<View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
|
||||
<Text className="text-base text-foreground-muted">No activity in this window.</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View className="flex-row items-center justify-between">
|
||||
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>
|
||||
<View className="flex-row items-center gap-4">
|
||||
{merged.providers.map((provider) => (
|
||||
<View key={provider.provider} className="flex-row items-center gap-1.5">
|
||||
<View
|
||||
className="size-2 rounded-full"
|
||||
style={{ backgroundColor: colors[provider.provider] }}
|
||||
/>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{PROVIDER_LABEL[provider.provider]}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricToggle(props: {
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly onChange: (metric: UsageChartMetric) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row overflow-hidden rounded-full bg-subtle">
|
||||
{(["cost", "tokens"] as const).map((option) => {
|
||||
const active = option === props.metric;
|
||||
return (
|
||||
<Pressable
|
||||
key={option}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: active }}
|
||||
onPress={() => props.onChange(option)}
|
||||
className={active ? "rounded-full bg-subtle-strong px-3 py-1.5" : "px-3 py-1.5"}
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
active
|
||||
? "text-xs font-t3-medium uppercase text-foreground"
|
||||
: "text-xs uppercase text-foreground-muted"
|
||||
}
|
||||
>
|
||||
{option}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderSection(props: {
|
||||
readonly merged: MergedUsage;
|
||||
readonly metric: UsageChartMetric;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
if (merged.providers.length === 0) return null;
|
||||
|
||||
// Ranked by whatever the toggle is showing, so the rows always descend.
|
||||
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
|
||||
const ordered = [...merged.providers].sort((a, b) =>
|
||||
metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="Providers" card>
|
||||
{ordered.map((provider, index) => {
|
||||
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
|
||||
return (
|
||||
<View
|
||||
key={provider.provider}
|
||||
className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
|
||||
>
|
||||
<View className="flex-row items-baseline justify-between gap-3">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View
|
||||
className="size-2.5 rounded-full"
|
||||
style={{ backgroundColor: colors[provider.provider] }}
|
||||
/>
|
||||
<Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
|
||||
</View>
|
||||
<Text className="text-lg tabular-nums text-foreground">
|
||||
{metric === "cost"
|
||||
? formatUsd(provider.costUsd)
|
||||
: formatTokens(provider.totalTokens)}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
|
||||
<View
|
||||
className="h-full rounded-full"
|
||||
style={{ flex: share, backgroundColor: colors[provider.provider] }}
|
||||
/>
|
||||
<View style={{ flex: 1 - share }} />
|
||||
</View>
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{metric === "cost"
|
||||
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
|
||||
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function TotalsSection(props: { readonly merged: MergedUsage }) {
|
||||
const { merged } = props;
|
||||
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
|
||||
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
|
||||
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
|
||||
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
|
||||
|
||||
return (
|
||||
<SettingsSection title="Totals" card>
|
||||
<View className="flex-row flex-wrap">
|
||||
<MetricCell
|
||||
label="Processed tokens"
|
||||
value={formatTokens(merged.totalTokens)}
|
||||
detail={`${formatTokens(dailyAverage)} per active day`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Cache savings"
|
||||
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
|
||||
detail={
|
||||
merged.costUsd > 0
|
||||
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
|
||||
: "vs full input rates"
|
||||
}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Cached input"
|
||||
value={formatTokens(merged.cachedInputTokens)}
|
||||
detail={`${formatPercent(cachedShare)} of observed input`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Uncached input"
|
||||
value={formatTokens(merged.uncachedInputTokens)}
|
||||
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Output"
|
||||
value={formatTokens(merged.outputTokens)}
|
||||
detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Unpriced"
|
||||
value={formatPercent(merged.costQuality.unpricedShare)}
|
||||
detail="of records, excluded from cost"
|
||||
/>
|
||||
</View>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCell(props: {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly detail: string;
|
||||
}) {
|
||||
return (
|
||||
<View className="w-1/2 gap-0.5 p-4">
|
||||
<Text className="text-sm text-foreground-muted">{props.label}</Text>
|
||||
<Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ModelsSection(props: { readonly merged: MergedUsage }) {
|
||||
const { merged } = props;
|
||||
const colors = useProviderColors();
|
||||
if (merged.models.length === 0) return null;
|
||||
|
||||
return (
|
||||
<SettingsSection title="By model" card>
|
||||
{merged.models.map((model, index) => (
|
||||
<View
|
||||
key={`${model.provider}:${model.model}`}
|
||||
className={
|
||||
index === 0
|
||||
? "flex-row items-center gap-3 p-4"
|
||||
: "flex-row items-center gap-3 border-t border-border-subtle p-4"
|
||||
}
|
||||
>
|
||||
<View
|
||||
className="size-2.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: colors[model.provider] }}
|
||||
/>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="text-base text-foreground" numberOfLines={1}>
|
||||
{model.model}
|
||||
</Text>
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
{formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>
|
||||
</View>
|
||||
))}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Says plainly when the totals are incomplete: an environment still answering,
|
||||
* one that failed, or one whose transcripts another environment already
|
||||
* reported.
|
||||
*/
|
||||
function UsageCoverageNotice(props: {
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
readonly merged: MergedUsage;
|
||||
readonly isPartial: boolean;
|
||||
}) {
|
||||
const failed = props.environments.filter((environment) => environment.error !== null);
|
||||
const stale = props.environments.filter((environment) =>
|
||||
props.merged.staleEnvironments.includes(environment.environmentId),
|
||||
);
|
||||
const duplicateSources = props.merged.duplicateSources;
|
||||
if (
|
||||
failed.length === 0 &&
|
||||
stale.length === 0 &&
|
||||
duplicateSources.length === 0 &&
|
||||
!props.isPartial
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">
|
||||
{props.isPartial ? (
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
Some environments are still reporting. Totals are partial.
|
||||
</Text>
|
||||
) : null}
|
||||
{failed.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} could not report usage.
|
||||
</Text>
|
||||
))}
|
||||
{stale.map((environment) => (
|
||||
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
|
||||
{environment.label} runs an older server version and is excluded from totals.
|
||||
</Text>
|
||||
))}
|
||||
{duplicateSources.length > 0 ? (
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
Counted once across environments sharing a transcript directory:{" "}
|
||||
{duplicateSources.join(", ")}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* Shapes merged daily totals into the per-day provider stacks both chart
|
||||
* implementations (Swift Charts on iOS, plain views elsewhere) render.
|
||||
*
|
||||
* @module usageChartData
|
||||
*/
|
||||
import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
import type { DailyTotals } from "@t3tools/shared/usageMerge";
|
||||
|
||||
import { PROVIDER_ORDER } from "./usageProviders";
|
||||
|
||||
export type UsageChartMetric = "cost" | "tokens";
|
||||
|
||||
export interface UsageChartDay {
|
||||
readonly day: string;
|
||||
/** In {@link PROVIDER_ORDER}, i.e. bottom of the stack first. */
|
||||
readonly values: readonly { readonly provider: UsageProviderKind; readonly value: number }[];
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
/** One entry per day in the window, zero-filled where nothing happened. */
|
||||
export function buildChartDays(
|
||||
days: readonly string[],
|
||||
daily: readonly DailyTotals[],
|
||||
metric: UsageChartMetric,
|
||||
): readonly UsageChartDay[] {
|
||||
const byDay = new Map(daily.map((totals) => [totals.day, totals]));
|
||||
return days.map((day) => {
|
||||
const totals = byDay.get(day);
|
||||
const values = PROVIDER_ORDER.map((provider) => {
|
||||
const entry = totals?.byProvider.get(provider);
|
||||
const value = entry === undefined ? 0 : metric === "cost" ? entry.costUsd : entry.totalTokens;
|
||||
return { provider, value };
|
||||
});
|
||||
return {
|
||||
day,
|
||||
values,
|
||||
total: values.reduce((sum, entry) => sum + entry.value, 0),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
import { useColorScheme } from "react-native";
|
||||
|
||||
/**
|
||||
* Series and table order. The chart stacks providers from the bottom in this
|
||||
* order, so it also fixes which band sits on top of the bars.
|
||||
*/
|
||||
export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];
|
||||
|
||||
export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
|
||||
claude: "Claude Code",
|
||||
codex: "Codex",
|
||||
};
|
||||
|
||||
/**
|
||||
* Claude's brand orange holds in both themes; Codex is neutral and must flip
|
||||
* with the theme or its bars vanish against the matching background.
|
||||
*/
|
||||
export function useProviderColors(): Record<UsageProviderKind, string> {
|
||||
const scheme = useColorScheme();
|
||||
return {
|
||||
claude: "#d97757",
|
||||
codex: scheme === "dark" ? "#e6e6e6" : "#3c3c43",
|
||||
};
|
||||
}
|
||||
@@ -554,8 +554,6 @@ function toolDetailTextLooksLikeFailure(text: string): boolean {
|
||||
normalized.includes("command not found") ||
|
||||
(normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
|
||||
(normalized.includes("is not recognized") && normalized.includes("the term '")) ||
|
||||
normalized.includes("is not recognized as the name of a cmdlet") ||
|
||||
normalized.includes("a parameter cannot be found that matches parameter name") ||
|
||||
/<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
|
||||
/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
|
||||
/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { hasWideMarkdownBlock } from "./wideMarkdownBlocks";
|
||||
|
||||
describe("hasWideMarkdownBlock", () => {
|
||||
it("ignores prose, inline code, and emphasis", () => {
|
||||
expect(hasWideMarkdownBlock("just a message")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("I found it in `secteurs_intervention` earlier")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("a | b in a sentence")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("an em dash — and a rule\n\n---\n")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects fenced code blocks", () => {
|
||||
expect(hasWideMarkdownBlock("before\n```\ncode\n```\nafter")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n```ts\ncode\n```")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n~~~\ncode\n~~~")).toBe(true);
|
||||
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
|
||||
});
|
||||
|
||||
it("detects GFM tables", () => {
|
||||
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* Detects markdown that the JS renderer draws as a standalone block View
|
||||
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
|
||||
*
|
||||
* Those blocks report an intrinsic width equal to their widest line, which is
|
||||
* effectively unbounded. A user bubble sizes itself from its content
|
||||
* (`maxWidth` with no `width`), so Android lays the bubble's children out
|
||||
* during the unclamped intrinsic pass — where the surrounding paragraphs
|
||||
* collapse to a single line — and never repositions them once the width is
|
||||
* clamped back to `maxWidth`. The result is siblings drawn on top of each
|
||||
* other inside an over-tall bubble. Pinning the bubble's width removes the
|
||||
* intrinsic pass entirely, which is the same reason review-comment bubbles
|
||||
* already carry an explicit width.
|
||||
*
|
||||
* Indented (four-space) code blocks are deliberately not detected: they are
|
||||
* vanishingly rare in chat input and the check would fire on ordinary nested
|
||||
* list continuations.
|
||||
*/
|
||||
|
||||
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
|
||||
|
||||
function isTableDelimiterRow(line: string): boolean {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.includes("|") || !trimmed.includes("-")) {
|
||||
return false;
|
||||
}
|
||||
return /^[|\-: \t]+$/.test(trimmed);
|
||||
}
|
||||
|
||||
export function hasWideMarkdownBlock(text: string): boolean {
|
||||
if (FENCED_CODE_BLOCK.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (!text.includes("|")) {
|
||||
return false;
|
||||
}
|
||||
return text.split("\n").some(isTableDelimiterRow);
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/**
|
||||
* Multi-environment usage state.
|
||||
*
|
||||
* Every connected environment answers the same typed query; the client merges
|
||||
* the results. Raw transcripts never leave the machine that produced them.
|
||||
*
|
||||
* Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
|
||||
* rules themselves live in `@t3tools/shared/usageMerge`.
|
||||
*
|
||||
* @module state/usage
|
||||
*/
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
USAGE_CONTRACT_VERSION,
|
||||
type EnvironmentId,
|
||||
type UsageSummary,
|
||||
type UsageSummaryInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { environmentPresentations } from "./presentation";
|
||||
import { serverEnvironment } from "./server";
|
||||
|
||||
export interface EnvironmentUsageStatus {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly isPending: boolean;
|
||||
readonly error: string | null;
|
||||
readonly summary: UsageSummary | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads every environment's summary for one window.
|
||||
*
|
||||
* Keyed by the serialised window so switching ranges does not thrash the atom
|
||||
* cache, and so each environment's query is shared with any other reader of the
|
||||
* same window.
|
||||
*/
|
||||
const usageByWindowAtom = Atom.family((windowKey: string) =>
|
||||
Atom.make((get): readonly EnvironmentUsageStatus[] => {
|
||||
const input = JSON.parse(windowKey) as UsageSummaryInput;
|
||||
const presentations = get(environmentPresentations.presentationsAtom);
|
||||
|
||||
const statuses: EnvironmentUsageStatus[] = [];
|
||||
for (const [environmentId, presentation] of presentations) {
|
||||
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
|
||||
statuses.push({
|
||||
environmentId,
|
||||
label: presentation.entry.target.label,
|
||||
isPending: result.waiting,
|
||||
error: result._tag === "Failure" ? "This environment could not report usage." : null,
|
||||
summary: Option.getOrNull(AsyncResult.value(result)),
|
||||
});
|
||||
}
|
||||
return statuses;
|
||||
}).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
|
||||
);
|
||||
|
||||
export interface UsageView {
|
||||
readonly merged: MergedUsage;
|
||||
readonly environments: readonly EnvironmentUsageStatus[];
|
||||
/** True until at least one environment has answered. */
|
||||
readonly isPending: boolean;
|
||||
/**
|
||||
* True while environments that have not failed are still answering. Failed
|
||||
* environments are reported through their own error rows: totals will not
|
||||
* improve by waiting on them, so they must not read as "still reporting".
|
||||
*/
|
||||
readonly isPartial: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
export function useUsage(input: UsageSummaryInput): UsageView {
|
||||
const windowKey = useMemo(
|
||||
() =>
|
||||
JSON.stringify({
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
}),
|
||||
[input.sinceDay, input.untilDay, input.timeZone],
|
||||
);
|
||||
const atom = usageByWindowAtom(windowKey);
|
||||
const environments = useAtomValue(atom);
|
||||
|
||||
// Refreshing only the derived atom would re-read the per-environment SWR
|
||||
// queries within their stale window and change nothing. Refresh each
|
||||
// environment's query so pull-to-refresh always rescans.
|
||||
const refresh = useCallback(() => {
|
||||
const input = JSON.parse(windowKey) as UsageSummaryInput;
|
||||
for (const environment of environments) {
|
||||
appAtomRegistry.refresh(
|
||||
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
|
||||
);
|
||||
}
|
||||
}, [environments, windowKey]);
|
||||
|
||||
const merged = useMemo(() => {
|
||||
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
|
||||
environment.summary === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
summary: environment.summary,
|
||||
},
|
||||
],
|
||||
);
|
||||
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
|
||||
}, [environments]);
|
||||
|
||||
const answeredCount = environments.filter((environment) => environment.summary !== null).length;
|
||||
const stillReporting = environments.filter(
|
||||
(environment) => environment.summary === null && environment.error === null,
|
||||
).length;
|
||||
|
||||
return {
|
||||
merged,
|
||||
environments,
|
||||
isPending: answeredCount === 0 && stillReporting > 0,
|
||||
isPartial: answeredCount > 0 && stillReporting > 0,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -225,7 +225,6 @@ describe("AssetAccess", () => {
|
||||
const faviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(faviconResult.sourcePath).toBe("favicon.svg");
|
||||
expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
expect(
|
||||
yield* issueAssetUrl({
|
||||
@@ -254,7 +253,6 @@ describe("AssetAccess", () => {
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
|
||||
expect(fallbackResult.sourcePath).toBeUndefined();
|
||||
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -266,86 +264,6 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues project favicon capabilities for a saved override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-override-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
projectFaviconPath: "brand/custom.svg",
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("brand/custom.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("ignores a client favicon path hint", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-hint-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
|
||||
projectFaviconPath: "brand/saved.svg",
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("brand/saved.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("keeps automatic favicon resolution separate from a saved override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-automatic-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("favicon.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects a resolved project favicon with a non-image extension", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-type-",
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
projectFaviconPath: "secret.txt",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("buckets project favicon expiry after content hashing", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
@@ -169,7 +169,6 @@ const resolveCanonicalWorkspaceFileForRequest = (input: {
|
||||
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
|
||||
readonly resource: AssetResource;
|
||||
readonly workspaceRoot?: string;
|
||||
readonly projectFaviconPath?: string;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -177,7 +176,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let claims: AssetClaims;
|
||||
let fileName: string;
|
||||
let sourcePath: string | undefined;
|
||||
|
||||
switch (input.resource._tag) {
|
||||
case "workspace-file": {
|
||||
@@ -289,22 +287,16 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
),
|
||||
);
|
||||
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const faviconPath = yield* faviconResolver
|
||||
.resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (relativePath && !isWorkspaceImagePreviewPath(relativePath)) {
|
||||
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
|
||||
}
|
||||
sourcePath = relativePath ?? undefined;
|
||||
const canonicalFaviconPath = relativePath
|
||||
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
@@ -387,7 +379,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
return {
|
||||
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
|
||||
expiresAt,
|
||||
...(sourcePath !== undefined ? { sourcePath } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
traceKeepAllSpans: false,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
|
||||
@@ -45,7 +45,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 1_000,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
traceMaxFiles: 30,
|
||||
traceKeepAllSpans: false,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
|
||||
@@ -84,8 +84,13 @@ const EnvServerConfig = Config.all({
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
// Rotated backups are gzip-compressed (~12x on span NDJSON), so a larger
|
||||
// file count buys hours of incident history for tens of megabytes.
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(30)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
|
||||
// Escape hatch: persist every sampled span (no tail filtering) when full
|
||||
// fidelity matters more than the retention window.
|
||||
traceKeepAllSpans: Config.boolean("T3CODE_TRACE_KEEP_ALL_SPANS").pipe(Config.withDefault(false)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -356,6 +361,7 @@ export const resolveServerConfig = (
|
||||
traceBatchWindowMs: env.traceBatchWindowMs,
|
||||
traceMaxBytes: env.traceMaxBytes,
|
||||
traceMaxFiles: env.traceMaxFiles,
|
||||
traceKeepAllSpans: env.traceKeepAllSpans,
|
||||
otlpTracesUrl:
|
||||
env.otlpTracesUrl ??
|
||||
bootstrap?.otlpTracesUrl ??
|
||||
|
||||
@@ -328,6 +328,7 @@ const makePairServerConfig = Effect.fn(function* (input: {
|
||||
traceBatchWindowMs: 1_000,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
traceKeepAllSpans: false,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
|
||||
@@ -35,18 +35,6 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
|
||||
expect(unit).not.toContain("versions/1.2.3");
|
||||
});
|
||||
|
||||
it("survives the kernel OOM-killing a greedy agent child", () => {
|
||||
const unit = BootService.renderBootServiceUnit({
|
||||
nodePath: "/usr/bin/node",
|
||||
launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
|
||||
baseDir: "/home/theo/.t3",
|
||||
logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
|
||||
unitPath: "/home/theo/.config/systemd/user/t3code.service",
|
||||
});
|
||||
|
||||
expect(unit).toContain("OOMPolicy=continue");
|
||||
});
|
||||
|
||||
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
platform: NodeJS.Platform = "linux",
|
||||
usePinnedLauncher = false,
|
||||
|
||||
@@ -67,11 +67,6 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
// Let the launcher mark an explicit stop before it signals the server.
|
||||
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
|
||||
"KillMode=mixed",
|
||||
// Agent tool calls run as children of the server, so they share this cgroup.
|
||||
// With the systemd default of OOMPolicy=stop, the kernel killing one greedy
|
||||
// child stops the whole unit: the server, every live agent, and the user's
|
||||
// connection. Keep running and let Restart=always cover the main process.
|
||||
"OOMPolicy=continue",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
|
||||
|
||||
@@ -61,6 +61,7 @@ export class ServerConfig extends Context.Service<
|
||||
readonly traceBatchWindowMs: number;
|
||||
readonly traceMaxBytes: number;
|
||||
readonly traceMaxFiles: number;
|
||||
readonly traceKeepAllSpans: boolean;
|
||||
readonly otlpTracesUrl: string | undefined;
|
||||
readonly otlpMetricsUrl: string | undefined;
|
||||
readonly otlpExportIntervalMs: number;
|
||||
@@ -174,6 +175,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
traceKeepAllSpans: false,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeZlib from "node:zlib";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -237,7 +238,11 @@ describe("TraceDiagnostics", () => {
|
||||
kind: "trace-file-read-failed",
|
||||
message: `Failed to read local trace file '${traceFilePath}.1'.`,
|
||||
});
|
||||
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
|
||||
assert.deepStrictEqual(diagnostics.scannedFilePaths, [
|
||||
`${traceFilePath}.1.gz`,
|
||||
`${traceFilePath}.1`,
|
||||
traceFilePath,
|
||||
]);
|
||||
|
||||
const failureLog = logAnnotations.find(
|
||||
(annotations) => annotations.traceFilePath === `${traceFilePath}.1`,
|
||||
@@ -251,6 +256,65 @@ describe("TraceDiagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads gzip-compressed rotated backups", () =>
|
||||
Effect.gen(function* () {
|
||||
const traceFilePath = "/tmp/server.trace.ndjson";
|
||||
const notFound = (method: string, path: string) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method,
|
||||
description: "missing",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
);
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
readFile: (path) =>
|
||||
path === `${traceFilePath}.1.gz`
|
||||
? Effect.succeed(
|
||||
new Uint8Array(
|
||||
NodeZlib.gzipSync(
|
||||
record({
|
||||
name: "backup.span",
|
||||
traceId: "trace-gz",
|
||||
spanId: "span-gz",
|
||||
startMs: 1_000,
|
||||
durationMs: 10,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
: notFound("readFile", path),
|
||||
readFileString: (path) =>
|
||||
path === traceFilePath
|
||||
? Effect.succeed(
|
||||
record({
|
||||
name: "current.span",
|
||||
traceId: "trace-live",
|
||||
spanId: "span-live",
|
||||
startMs: 2_000,
|
||||
durationMs: 10,
|
||||
}),
|
||||
)
|
||||
: notFound("readFileString", path),
|
||||
});
|
||||
|
||||
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath,
|
||||
maxFiles: 1,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
|
||||
|
||||
assert.equal(diagnostics.recordCount, 2);
|
||||
assert.equal(Option.isNone(diagnostics.error), true);
|
||||
assert.deepStrictEqual(diagnostics.topSpansByCount.map((span) => span.name).toSorted(), [
|
||||
"backup.span",
|
||||
"current.span",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps only the slowest span occurrences while aggregating large inputs", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
ServerTraceDiagnosticsSpanOccurrence,
|
||||
ServerTraceDiagnosticsSpanSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeZlib from "node:zlib";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -81,11 +82,12 @@ interface TraceDiagnosticsErrorSummary {
|
||||
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
|
||||
const TOP_LIMIT = 10;
|
||||
const RECENT_LIMIT = 20;
|
||||
// Backups rotate as `.N.gz` since compressBackups, but plain `.N` files from
|
||||
// before the change age along the chain untouched, so both are candidates.
|
||||
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
|
||||
const backupCount = Math.max(0, Math.floor(maxFiles));
|
||||
const backups = Array.from(
|
||||
{ length: backupCount },
|
||||
(_, index) => `${traceFilePath}.${backupCount - index}`,
|
||||
const backups = Array.from({ length: backupCount }, (_, index) => backupCount - index).flatMap(
|
||||
(suffix) => [`${traceFilePath}.${suffix}.gz`, `${traceFilePath}.${suffix}`],
|
||||
);
|
||||
return [...backups, traceFilePath];
|
||||
}
|
||||
@@ -186,26 +188,10 @@ function insertBoundedSlowestSpan(
|
||||
}
|
||||
}
|
||||
|
||||
export function aggregateTraceDiagnostics(
|
||||
input: TraceDiagnosticsInput,
|
||||
): ServerTraceDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
|
||||
if (input.files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error: input.error ?? {
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
},
|
||||
...(input.partialFailure ? { partialFailure: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
// Incremental aggregation lets the reader feed one decoded file at a time and
|
||||
// drop its text before touching the next, so peak memory stays one file wide
|
||||
// no matter how many rotated backups exist.
|
||||
export function createTraceDiagnosticsAggregator(slowSpanThresholdMs: number) {
|
||||
let parseErrorCount = 0;
|
||||
let recordCount = 0;
|
||||
let failureCount = 0;
|
||||
@@ -224,8 +210,8 @@ export function aggregateTraceDiagnostics(
|
||||
const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
|
||||
const logLevelCounts: Record<string, number> = {};
|
||||
|
||||
for (const file of input.files) {
|
||||
const lines = file.text.split(/\r?\n/);
|
||||
const addFileText = (text: string) => {
|
||||
const lines = text.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
@@ -334,56 +320,102 @@ export function aggregateTraceDiagnostics(
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (input: {
|
||||
readonly traceFilePath: string;
|
||||
readonly scannedFilePaths: ReadonlyArray<string>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}): ServerTraceDiagnosticsResult => {
|
||||
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
|
||||
.map(([name, span]) => ({
|
||||
name,
|
||||
count: span.count,
|
||||
failureCount: span.failureCount,
|
||||
totalDurationMs: span.totalDurationMs,
|
||||
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
|
||||
maxDurationMs: span.maxDurationMs,
|
||||
}))
|
||||
.toSorted(
|
||||
(left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs,
|
||||
)
|
||||
.slice(0, TOP_LIMIT);
|
||||
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths: [...input.scannedFilePaths],
|
||||
readAt: input.readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
slowSpanCount,
|
||||
logLevelCounts,
|
||||
topSpansByCount,
|
||||
slowestSpans,
|
||||
commonFailures: [...failuresByKey.values()]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.count - left.count ||
|
||||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
|
||||
)
|
||||
.slice(0, TOP_LIMIT),
|
||||
latestFailures: latestFailures
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
latestWarningAndErrorLogs: latestWarningAndErrorLogs
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
};
|
||||
|
||||
return { addFileText, finish };
|
||||
}
|
||||
|
||||
export function aggregateTraceDiagnostics(
|
||||
input: TraceDiagnosticsInput,
|
||||
): ServerTraceDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
|
||||
if (input.files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error: input.error ?? {
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
},
|
||||
...(input.partialFailure ? { partialFailure: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
|
||||
.map(([name, span]) => ({
|
||||
name,
|
||||
count: span.count,
|
||||
failureCount: span.failureCount,
|
||||
totalDurationMs: span.totalDurationMs,
|
||||
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
|
||||
maxDurationMs: span.maxDurationMs,
|
||||
}))
|
||||
.toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)
|
||||
.slice(0, TOP_LIMIT);
|
||||
|
||||
return {
|
||||
const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs);
|
||||
for (const file of input.files) {
|
||||
aggregator.addFileText(file.text);
|
||||
}
|
||||
return aggregator.finish({
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
slowSpanCount,
|
||||
logLevelCounts,
|
||||
topSpansByCount,
|
||||
slowestSpans,
|
||||
commonFailures: [...failuresByKey.values()]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.count - left.count ||
|
||||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
|
||||
)
|
||||
.slice(0, TOP_LIMIT),
|
||||
latestFailures: latestFailures
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
latestWarningAndErrorLogs: latestWarningAndErrorLogs
|
||||
.toSorted(
|
||||
(left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
...(input.error ? { error: input.error } : {}),
|
||||
...(input.partialFailure ? { partialFailure: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
type TraceFileReadResult =
|
||||
@@ -394,7 +426,22 @@ function readTraceFile(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
path: string,
|
||||
): Effect.Effect<TraceFileReadResult, TraceFileReadError> {
|
||||
return fileSystem.readFileString(path).pipe(
|
||||
const decoded = path.endsWith(".gz")
|
||||
? fileSystem.readFile(path).pipe(
|
||||
Effect.flatMap((bytes) =>
|
||||
Effect.try({
|
||||
try: () => NodeZlib.gunzipSync(bytes).toString("utf8"),
|
||||
catch: (cause) =>
|
||||
new TraceFileReadError({
|
||||
traceFilePath: path,
|
||||
causeTag: "GzipDecode",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
)
|
||||
: fileSystem.readFileString(path);
|
||||
return decoded.pipe(
|
||||
Effect.map((text): TraceFileReadResult => ({ _tag: "Loaded", path, text })),
|
||||
Effect.catchTags({
|
||||
PlatformError: (cause) =>
|
||||
@@ -419,39 +466,46 @@ export const make = Effect.gen(function* () {
|
||||
const readAt = options.readAt ?? (yield* DateTime.now);
|
||||
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
|
||||
const results = yield* Effect.all(
|
||||
paths.map((path) =>
|
||||
readTraceFile(fileSystem, path).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to read local trace file.").pipe(
|
||||
Effect.annotateLogs({
|
||||
traceFilePath: cause.traceFilePath,
|
||||
errorTag: cause._tag,
|
||||
causeTag: cause.causeTag,
|
||||
}),
|
||||
),
|
||||
// One file at a time: each decoded text is aggregated and released
|
||||
// before the next read, so a large maxFiles never loads the whole
|
||||
// rotation window into memory at once.
|
||||
const aggregator = createTraceDiagnosticsAggregator(slowSpanThresholdMs);
|
||||
let loadedFileCount = 0;
|
||||
let readFailureError: TraceDiagnosticsErrorSummary | undefined;
|
||||
const loadedPaths = new Set<string>();
|
||||
for (const path of paths) {
|
||||
// A plain backup next to its own .gz copy is a crash leftover with
|
||||
// identical content — counting both would double every span in it.
|
||||
if (!path.endsWith(".gz") && loadedPaths.has(`${path}.gz`)) {
|
||||
continue;
|
||||
}
|
||||
const result = yield* readTraceFile(fileSystem, path).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to read local trace file.").pipe(
|
||||
Effect.annotateLogs({
|
||||
traceFilePath: cause.traceFilePath,
|
||||
errorTag: cause._tag,
|
||||
causeTag: cause.causeTag,
|
||||
}),
|
||||
),
|
||||
Effect.result,
|
||||
),
|
||||
),
|
||||
{
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
const files = results.flatMap((result) =>
|
||||
Result.isSuccess(result) && result.success._tag === "Loaded"
|
||||
? [{ path: result.success.path, text: result.success.text }]
|
||||
: [],
|
||||
);
|
||||
const readFailure = results.find(Result.isFailure);
|
||||
const readFailureError = readFailure
|
||||
? ({
|
||||
Effect.result,
|
||||
);
|
||||
if (Result.isFailure(result)) {
|
||||
readFailureError ??= {
|
||||
kind: "trace-file-read-failed",
|
||||
message: readFailure.failure.message,
|
||||
} satisfies TraceDiagnosticsErrorSummary)
|
||||
: undefined;
|
||||
message: result.failure.message,
|
||||
} satisfies TraceDiagnosticsErrorSummary;
|
||||
continue;
|
||||
}
|
||||
if (result.success._tag === "Loaded") {
|
||||
loadedFileCount += 1;
|
||||
loadedPaths.add(path);
|
||||
aggregator.addFileText(result.success.text);
|
||||
}
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
if (loadedFileCount === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
scannedFilePaths: paths,
|
||||
@@ -466,12 +520,10 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
return aggregateTraceDiagnostics({
|
||||
return aggregator.finish({
|
||||
traceFilePath: options.traceFilePath,
|
||||
files,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
|
||||
});
|
||||
},
|
||||
|
||||
@@ -27,6 +27,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
traceKeepAllSpans: false,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { assetResponseHeaders, isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
@@ -26,22 +26,3 @@ describe("http dev routing", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assetResponseHeaders", () => {
|
||||
it("sandboxes SVG assets", () => {
|
||||
expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
|
||||
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
|
||||
"Content-Security-Policy",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not apply document policy to raster images", () => {
|
||||
expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
});
|
||||
+4
-13
@@ -43,18 +43,6 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
|
||||
|
||||
export function assetResponseHeaders(filePath: string): Record<string, string> {
|
||||
return {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...(filePath.toLowerCase().endsWith(".svg")
|
||||
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
|
||||
global: true,
|
||||
});
|
||||
@@ -219,7 +207,10 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: assetResponseHeaders(asset.path),
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
import { bunWebSocketOptions } from "./httpServerOptions.ts";
|
||||
|
||||
it("reaps Bun websocket connections after six missed client ping windows", () => {
|
||||
expect(bunWebSocketOptions).toEqual({
|
||||
perMessageDeflate: {
|
||||
compress: "dedicated",
|
||||
decompress: "shared",
|
||||
},
|
||||
idleTimeout: 30,
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
export const bunWebSocketOptions = {
|
||||
// Negotiate permessage-deflate with clients that offer it; clients that
|
||||
// don't still get uncompressed frames on their connection. A dedicated
|
||||
// compressor keeps a per-connection sliding window (context takeover) so the
|
||||
// compression dictionary is shared across server-to-client frames.
|
||||
// Decompression uses the shared decompressor: uWebSockets' dedicated
|
||||
// decompressor path can abort connections (close 1006) on valid DEFLATE
|
||||
// input — see https://github.com/uNetworking/uWebSockets.js/issues/633.
|
||||
perMessageDeflate: {
|
||||
compress: "dedicated",
|
||||
decompress: "shared",
|
||||
},
|
||||
// RPC clients ping every 5s. Reaping a connection after six missed ping
|
||||
// windows releases suspended-mobile sockets well before Bun's 120s default.
|
||||
idleTimeout: 30,
|
||||
} as const;
|
||||
@@ -34,6 +34,7 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
maxBytes: config.traceMaxBytes,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
compressBackups: true,
|
||||
onFlush: (stats) =>
|
||||
attribution.record({
|
||||
component: "server-trace",
|
||||
@@ -65,6 +66,9 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
// Tail policy applies to the local file only; the OTLP delegate
|
||||
// still receives every sampled span.
|
||||
...(config.traceKeepAllSpans ? {} : { tailPolicy: {} }),
|
||||
});
|
||||
|
||||
return Layer.mergeAll(
|
||||
|
||||
@@ -2764,18 +2764,15 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5",
|
||||
},
|
||||
faviconPath: "brand/icon.svg",
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
readonly scriptsJson: string;
|
||||
readonly defaultModelSelection: string;
|
||||
readonly faviconPath: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
scripts_json AS "scriptsJson",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
favicon_path AS "faviconPath"
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-scripts'
|
||||
`;
|
||||
@@ -2784,7 +2781,6 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
scriptsJson:
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
|
||||
faviconPath: "brand/icon.svg",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
|
||||
@@ -496,7 +496,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModelSelection: event.payload.defaultModelSelection,
|
||||
defaultThreadEnvMode: null,
|
||||
faviconPath: event.payload.faviconPath ?? null,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -523,9 +522,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...(event.payload.defaultThreadEnvMode !== undefined
|
||||
? { defaultThreadEnvMode: event.payload.defaultThreadEnvMode }
|
||||
: {}),
|
||||
...(event.payload.faviconPath !== undefined
|
||||
? { faviconPath: event.payload.faviconPath }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
|
||||
@@ -275,7 +275,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
faviconPath: null,
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -395,7 +394,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
faviconPath: null,
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
|
||||
@@ -317,7 +317,6 @@ function mapProjectShellRow(
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
defaultThreadEnvMode: row.defaultThreadEnvMode,
|
||||
faviconPath: row.faviconPath ?? null,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -394,7 +393,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -849,7 +847,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -873,7 +870,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -1551,7 +1547,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
defaultThreadEnvMode: row.defaultThreadEnvMode,
|
||||
faviconPath: row.faviconPath ?? null,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -1682,7 +1677,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
defaultThreadEnvMode: row.defaultThreadEnvMode,
|
||||
faviconPath: row.faviconPath ?? null,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -2175,7 +2169,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: option.value.defaultModelSelection,
|
||||
defaultThreadEnvMode: option.value.defaultThreadEnvMode,
|
||||
faviconPath: option.value.faviconPath ?? null,
|
||||
scripts: option.value.scripts,
|
||||
createdAt: option.value.createdAt,
|
||||
updatedAt: option.value.updatedAt,
|
||||
|
||||
@@ -94,47 +94,6 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates a project favicon path in project.meta.update", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(now), {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-favicon"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-favicon"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-favicon"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-favicon"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-favicon"),
|
||||
title: "Favicon",
|
||||
workspaceRoot: "/tmp/favicon",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-favicon"),
|
||||
projectId: asProjectId("project-favicon"),
|
||||
faviconPath: "brand/icon.svg",
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const event = Array.isArray(result) ? result[0] : result;
|
||||
expect(event.type).toBe("project.meta-updated");
|
||||
expect((event.payload as { faviconPath?: string }).faviconPath).toBe("brand/icon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects project.create for an active workspace root that already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -250,7 +250,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
||||
faviconPath: null,
|
||||
scripts: [],
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
@@ -291,7 +290,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
...(command.defaultThreadEnvMode !== undefined
|
||||
? { defaultThreadEnvMode: command.defaultThreadEnvMode }
|
||||
: {}),
|
||||
...(command.faviconPath !== undefined ? { faviconPath: command.faviconPath } : {}),
|
||||
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
|
||||
@@ -215,7 +215,6 @@ export function projectEvent(
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
defaultModelSelection: payload.defaultModelSelection,
|
||||
defaultThreadEnvMode: null,
|
||||
faviconPath: payload.faviconPath ?? null,
|
||||
scripts: payload.scripts,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -251,9 +250,6 @@ export function projectEvent(
|
||||
...(payload.defaultThreadEnvMode !== undefined
|
||||
? { defaultThreadEnvMode: payload.defaultThreadEnvMode }
|
||||
: {}),
|
||||
...(payload.faviconPath !== undefined
|
||||
? { faviconPath: payload.faviconPath }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
}
|
||||
|
||||
@@ -36,7 +36,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
default_thread_env_mode,
|
||||
favicon_path,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -48,7 +47,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
|
||||
${row.defaultThreadEnvMode},
|
||||
${row.faviconPath ?? null},
|
||||
${JSON.stringify(row.scripts)},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
@@ -60,7 +58,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_model_selection_json = excluded.default_model_selection_json,
|
||||
default_thread_env_mode = excluded.default_thread_env_mode,
|
||||
favicon_path = excluded.favicon_path,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
@@ -79,7 +76,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -100,7 +96,6 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
default_thread_env_mode AS "defaultThreadEnvMode",
|
||||
favicon_path AS "faviconPath",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
|
||||
@@ -46,16 +46,9 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
|
||||
const path = yield* Path.Path;
|
||||
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
|
||||
|
||||
return Layer.provideMerge(
|
||||
setup,
|
||||
makeRuntimeSqliteLayer({
|
||||
filename: dbPath,
|
||||
spanAttributes: {
|
||||
"db.name": path.basename(dbPath),
|
||||
"service.name": "t3-server",
|
||||
},
|
||||
}),
|
||||
);
|
||||
// No per-span attributes: sql.execute fires ~76/s under load and constant
|
||||
// attributes on every span were a measurable share of local trace volume.
|
||||
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
|
||||
}, Layer.unwrap);
|
||||
|
||||
export const SqlitePersistenceMemory = Layer.provideMerge(
|
||||
|
||||
@@ -52,7 +52,6 @@ import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
|
||||
import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
|
||||
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
|
||||
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
|
||||
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -104,7 +103,6 @@ export const migrationEntries = [
|
||||
[37, "ProjectionTurnsKeysetIndex", Migration0037],
|
||||
[38, "ProjectionThreadsPinOrderKey", Migration0038],
|
||||
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
|
||||
[40, "ProjectionProjectFaviconPath", Migration0040],
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("040_ProjectionProjectFaviconPath", (it) => {
|
||||
it.effect("adds the nullable favicon path to project projections", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 39 });
|
||||
yield* runMigrations({ toMigrationInclusive: 40 });
|
||||
|
||||
const columns = yield* sql<{ readonly name: string; readonly notnull: number }>`
|
||||
PRAGMA table_info(projection_projects)
|
||||
`;
|
||||
const faviconPath = columns.find((column) => column.name === "favicon_path");
|
||||
|
||||
assert.equal(faviconPath?.name, "favicon_path");
|
||||
assert.equal(faviconPath?.notnull, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_projects)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "favicon_path")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
ADD COLUMN favicon_path TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -26,7 +26,6 @@ export const ProjectionProject = Schema.Struct({
|
||||
workspaceRoot: Schema.String,
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
defaultThreadEnvMode: Schema.NullOr(ThreadEnvMode),
|
||||
faviconPath: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -77,33 +77,6 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses a saved project favicon override", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "brand/custom.svg", "<svg>custom</svg>");
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>automatic</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd, "brand/custom.svg");
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("brand/custom.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back when a saved override is missing from a checkout", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(cwd, "favicon.svg", "<svg>automatic</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd, "brand/missing.svg");
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("favicon.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to well-known files when the t3.json iconPath does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
@@ -160,109 +133,6 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves icon hrefs from object-literal route metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/routes/__root.tsx",
|
||||
`export const Route = createRootRoute({
|
||||
head: () => ({
|
||||
links: [
|
||||
{ rel: "stylesheet", href: "/app.css" },
|
||||
{ rel: "icon", href: "/brand/logo.svg" },
|
||||
],
|
||||
}),
|
||||
});`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves object-literal icon metadata when href precedes rel", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/root.tsx",
|
||||
`const links = [{ href: "/brand/logo.svg", rel: "shortcut icon" }];`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves object-literal icon metadata alongside nested objects", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/root.tsx",
|
||||
`const links = [{ attributes: {}, rel: "icon", href: "/brand/logo.svg" }];`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips icon metadata without an href and keeps scanning", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"src/root.tsx",
|
||||
`const links = [{ rel: "icon" }, { rel: "icon", href: "/brand/logo.svg" }];`,
|
||||
);
|
||||
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
|
||||
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
|
||||
expect(resolved).not.toBeNull();
|
||||
expect(resolved).toContain("public/brand/logo.svg");
|
||||
}),
|
||||
);
|
||||
|
||||
// A large icon source with no icon metadata used to pin the server's event loop for
|
||||
// minutes: the object pattern was unanchored, so it restarted at every offset and
|
||||
// rescanned forward from each one. Anchoring keeps this proportional to file size.
|
||||
it.effect("scans large icon sources without an icon in reasonable time", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const cwd = yield* makeTempDir;
|
||||
// Mirrors a generated single-file build: large, brace-sparse, and no icon metadata.
|
||||
const filler = `<p>${"pokopia companion guide ".repeat(24)}</p>\n`;
|
||||
yield* writeTextFile(
|
||||
cwd,
|
||||
"index.html",
|
||||
`<!doctype html><html><head><title>guide</title></head><body>\n${filler.repeat(1200)}</body></html>`,
|
||||
);
|
||||
|
||||
const startedAt = performance.now();
|
||||
const resolved = yield* resolver.resolvePath(cwd);
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
expect(elapsedMs).toBeLessThan(5_000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null when no icon is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
|
||||
@@ -55,13 +55,10 @@ const ICON_SOURCE_FILES = [
|
||||
] as const;
|
||||
|
||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
||||
// The tag pattern is anchored on `<link`, so it only starts at real candidates. Object metadata
|
||||
// is matched by scanning brace-free runs instead of by one combined pattern: an unanchored
|
||||
// pattern restarts at every offset and rescans forward, which is quadratic on large sources.
|
||||
const LINK_ICON_HTML_RE =
|
||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
||||
const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
|
||||
const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
|
||||
const LINK_ICON_OBJ_RE =
|
||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
||||
|
||||
export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
|
||||
"ProjectFaviconResolutionError",
|
||||
@@ -94,7 +91,6 @@ export class ProjectFaviconResolver extends Context.Service<
|
||||
*/
|
||||
readonly resolvePath: (
|
||||
cwd: string,
|
||||
faviconPath?: string,
|
||||
) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
|
||||
}
|
||||
>()("t3/project/ProjectFaviconResolver") {}
|
||||
@@ -102,13 +98,8 @@ export class ProjectFaviconResolver extends Context.Service<
|
||||
function extractIconHref(source: string): string | null {
|
||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
// Icon metadata counts when `rel` and `href` share a brace-free run, so a run holding `rel`
|
||||
// but no href falls through to the next one rather than ending the search.
|
||||
for (const run of source.split("}")) {
|
||||
if (!ICON_REL_RE.test(run)) continue;
|
||||
const hrefMatch = run.match(ICON_HREF_RE);
|
||||
if (hrefMatch?.[1]) return hrefMatch[1];
|
||||
}
|
||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
||||
if (objMatch?.[1]) return objMatch[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -177,7 +168,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
|
||||
"ProjectFaviconResolver.resolvePath",
|
||||
)(function* (cwd, faviconPath) {
|
||||
)(function* (cwd) {
|
||||
const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -188,15 +179,6 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
// A grouped project's saved path can be absent from one checkout. Use it
|
||||
// where it exists and retain automatic discovery for the other checkouts.
|
||||
if (faviconPath !== undefined) {
|
||||
const existing = yield* findExistingFile(projectCwd, [faviconPath]);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
// A t3.json iconPath takes precedence over the well-known locations.
|
||||
const projectFile = yield* projectFileLoader.load(projectCwd);
|
||||
if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
|
||||
|
||||
@@ -434,6 +434,7 @@ const buildAppUnderTest = (options?: {
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
traceKeepAllSpans: false,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
|
||||
@@ -10,7 +10,6 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { bunWebSocketOptions } from "./httpServerOptions.ts";
|
||||
import {
|
||||
otlpTracesProxyRouteLayer,
|
||||
assetRouteLayer,
|
||||
@@ -186,7 +185,20 @@ const HttpServerLive = Layer.unwrap(
|
||||
port: config.port,
|
||||
hostname: config.host ?? "127.0.0.1",
|
||||
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
|
||||
websocket: bunWebSocketOptions,
|
||||
websocket: {
|
||||
// Negotiate permessage-deflate with clients that offer it; clients
|
||||
// that don't still get uncompressed frames on their connection. A
|
||||
// dedicated compressor keeps a per-connection sliding window
|
||||
// (context takeover) so the compression dictionary is shared across
|
||||
// server-to-client frames. Decompression uses the shared
|
||||
// decompressor: uWebSockets' dedicated decompressor path can abort
|
||||
// connections (close 1006) on valid DEFLATE input — see
|
||||
// https://github.com/uNetworking/uWebSockets.js/issues/633.
|
||||
perMessageDeflate: {
|
||||
compress: "dedicated",
|
||||
decompress: "shared",
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
|
||||
|
||||
@@ -1764,3 +1764,26 @@ it.layer(
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
|
||||
it("inspectSubprocessFromSnapshot resolves child command and descendants from one table", () => {
|
||||
const snapshot = TerminalManager.processTableFromRows([
|
||||
[100, 1, "zsh"],
|
||||
[200, 100, "node"],
|
||||
[201, 200, "esbuild"],
|
||||
[202, 200, "tmux: server"],
|
||||
[900, 1, "unrelated"],
|
||||
]);
|
||||
|
||||
const inspected = TerminalManager.inspectSubprocessFromSnapshot(100, snapshot, "linux");
|
||||
assert.equal(inspected.hasRunningSubprocess, true);
|
||||
assert.equal(inspected.childCommand, "node");
|
||||
assert.deepStrictEqual([...inspected.processIds].toSorted(), [100, 200, 201, 202]);
|
||||
|
||||
const idle = TerminalManager.inspectSubprocessFromSnapshot(900, snapshot, "linux");
|
||||
assert.equal(idle.hasRunningSubprocess, false);
|
||||
assert.equal(idle.childCommand, null);
|
||||
assert.deepStrictEqual(idle.processIds, []);
|
||||
|
||||
const missing = TerminalManager.inspectSubprocessFromSnapshot(555, snapshot, "linux");
|
||||
assert.equal(missing.hasRunningSubprocess, false);
|
||||
});
|
||||
+270
-268
@@ -46,6 +46,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -90,7 +91,7 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
|
||||
{
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
terminalPid: Schema.Number,
|
||||
command: Schema.Literals(["powershell", "pgrep", "ps"]),
|
||||
command: Schema.Literals(["powershell", "ps"]),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
@@ -98,6 +99,22 @@ class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubpr
|
||||
}
|
||||
}
|
||||
|
||||
// The whole-table snapshot has no per-terminal identity, so its failure is a
|
||||
// separate error rather than a TerminalSubprocessCheckError with a sentinel
|
||||
// pid.
|
||||
class TerminalProcessTableCaptureError extends Schema.TaggedErrorClass<TerminalProcessTableCaptureError>()(
|
||||
"TerminalProcessTableCaptureError",
|
||||
{
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
command: Schema.Literals(["powershell", "ps"]),
|
||||
truncated: Schema.optional(Schema.Boolean),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to capture the process table with ${this.command}`;
|
||||
}
|
||||
}
|
||||
|
||||
class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcessSignalError>()(
|
||||
"TerminalProcessSignalError",
|
||||
{
|
||||
@@ -188,7 +205,7 @@ export class TerminalManager extends Context.Service<
|
||||
}
|
||||
>()("t3/terminal/Manager/TerminalManager") {}
|
||||
|
||||
interface TerminalSubprocessInspectResult {
|
||||
export interface TerminalSubprocessInspectResult {
|
||||
readonly hasRunningSubprocess: boolean;
|
||||
readonly childCommand: string | null;
|
||||
readonly processIds: ReadonlyArray<number>;
|
||||
@@ -610,246 +627,156 @@ function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function parseFirstChildPidFromPgrep(stdout: string): number | null {
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
const n = Number.parseInt(line.trim(), 10);
|
||||
if (Number.isInteger(n) && n > 0) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
// One pid/ppid/name table read per poll tick serves every running terminal.
|
||||
// The previous per-terminal inspection spawned pgrep plus up to three ps
|
||||
// invocations per session per second (a full `ps -e` table each time), which
|
||||
// dominated both process churn and trace volume on hosts with many terminals.
|
||||
export interface ProcessTableSnapshot {
|
||||
readonly commandByPid: ReadonlyMap<number, string>;
|
||||
readonly childrenByParent: ReadonlyMap<number, ReadonlyArray<number>>;
|
||||
}
|
||||
|
||||
function windowsInspectSubprocess(
|
||||
terminalPid: number,
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<
|
||||
TerminalSubprocessInspectResult,
|
||||
TerminalSubprocessCheckError,
|
||||
export function processTableFromRows(
|
||||
rows: Iterable<readonly [pid: number, parentPid: number, command: string]>,
|
||||
): ProcessTableSnapshot {
|
||||
const commandByPid = new Map<number, string>();
|
||||
const childrenByParent = new Map<number, number[]>();
|
||||
for (const [pid, parentPid, command] of rows) {
|
||||
commandByPid.set(pid, command);
|
||||
const children = childrenByParent.get(parentPid) ?? [];
|
||||
children.push(pid);
|
||||
childrenByParent.set(parentPid, children);
|
||||
}
|
||||
return { commandByPid, childrenByParent };
|
||||
}
|
||||
|
||||
const PROCESS_TABLE_MAX_OUTPUT_BYTES = 4 * 1_048_576;
|
||||
|
||||
function captureWindowsProcessTable(): Effect.Effect<
|
||||
ProcessTableSnapshot,
|
||||
TerminalProcessTableCaptureError,
|
||||
ProcessRunner.ProcessRunner
|
||||
> {
|
||||
const command =
|
||||
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
|
||||
return Effect.gen(function* () {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
return yield* processRunner.run({
|
||||
// powershell.exe is a real executable — never spawn it through cmd.exe
|
||||
// shell mode, which would re-tokenize the `-Command` payload (pipes,
|
||||
// semicolons) before PowerShell ever sees it.
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeout: "1500 millis",
|
||||
maxOutputBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
|
||||
}
|
||||
const processNameById = new Map<number, string>();
|
||||
const childrenByParent = new Map<number, number[]>();
|
||||
for (const line of result.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
|
||||
const pid = Number(pidRaw);
|
||||
const parentPid = Number(parentPidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
|
||||
processNameById.set(pid, nameRaw?.trim() ?? "");
|
||||
const children = childrenByParent.get(parentPid) ?? [];
|
||||
children.push(pid);
|
||||
childrenByParent.set(parentPid, children);
|
||||
}
|
||||
const directChildren = childrenByParent.get(terminalPid) ?? [];
|
||||
const childPid = directChildren[0];
|
||||
if (childPid === undefined) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
|
||||
}
|
||||
const processIds = new Set<number>([terminalPid]);
|
||||
const pending = [terminalPid];
|
||||
while (pending.length > 0) {
|
||||
const parentPid = pending.pop();
|
||||
if (parentPid === undefined) continue;
|
||||
for (const pid of childrenByParent.get(parentPid) ?? []) {
|
||||
if (processIds.has(pid)) continue;
|
||||
processIds.add(pid);
|
||||
pending.push(pid);
|
||||
}
|
||||
}
|
||||
const normalized = normalizeChildCommandName(processNameById.get(childPid) ?? "", platform);
|
||||
return {
|
||||
hasRunningSubprocess: true,
|
||||
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
|
||||
processIds: [...processIds],
|
||||
} as const;
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "powershell",
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* processRunner
|
||||
.run({
|
||||
// powershell.exe is a real executable — never spawn it through cmd.exe
|
||||
// shell mode, which would re-tokenize the `-Command` payload (pipes,
|
||||
// semicolons) before PowerShell ever sees it.
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeout: "1500 millis",
|
||||
maxOutputBytes: PROCESS_TABLE_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new TerminalProcessTableCaptureError({ cause, command: "powershell" }),
|
||||
),
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return yield* new TerminalProcessTableCaptureError({ command: "powershell" });
|
||||
}
|
||||
// A truncated table silently loses the sessions past the cutoff — they
|
||||
// would read as "no subprocesses" and drop out of resource registration.
|
||||
if (result.stdoutTruncated) {
|
||||
return yield* new TerminalProcessTableCaptureError({
|
||||
command: "powershell",
|
||||
truncated: true,
|
||||
});
|
||||
}
|
||||
const rows: Array<readonly [number, number, string]> = [];
|
||||
for (const line of result.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
|
||||
const pid = Number(pidRaw);
|
||||
const parentPid = Number(parentPidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
|
||||
rows.push([pid, parentPid, nameRaw?.trim() ?? ""]);
|
||||
}
|
||||
return processTableFromRows(rows);
|
||||
});
|
||||
}
|
||||
|
||||
const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(function* (
|
||||
terminalPid: number,
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.fn.Return<
|
||||
TerminalSubprocessInspectResult,
|
||||
TerminalSubprocessCheckError,
|
||||
function capturePosixProcessTable(): Effect.Effect<
|
||||
ProcessTableSnapshot,
|
||||
TerminalProcessTableCaptureError,
|
||||
ProcessRunner.ProcessRunner
|
||||
> {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const runPgrep = processRunner
|
||||
.run({
|
||||
command: "pgrep",
|
||||
args: ["-P", String(terminalPid)],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "pgrep",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runPs = processRunner
|
||||
.run({
|
||||
command: "ps",
|
||||
args: ["-eo", "pid=,ppid="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
let childPid: number | null = null;
|
||||
|
||||
const pgrepResult = yield* Effect.exit(runPgrep);
|
||||
if (pgrepResult._tag === "Success") {
|
||||
if (pgrepResult.value.code === 0) {
|
||||
childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout);
|
||||
} else if (pgrepResult.value.code === 1) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
|
||||
return Effect.gen(function* () {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const result = yield* processRunner
|
||||
.run({
|
||||
command: "ps",
|
||||
args: ["-eo", "pid=,ppid=,comm="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: PROCESS_TABLE_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new TerminalProcessTableCaptureError({ cause, command: "ps" })),
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return yield* new TerminalProcessTableCaptureError({ command: "ps" });
|
||||
}
|
||||
}
|
||||
|
||||
if (childPid === null) {
|
||||
const psResult = yield* Effect.exit(runPs);
|
||||
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
|
||||
if (result.stdoutTruncated) {
|
||||
return yield* new TerminalProcessTableCaptureError({ command: "ps", truncated: true });
|
||||
}
|
||||
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
if (ppid === terminalPid) {
|
||||
childPid = pid;
|
||||
break;
|
||||
}
|
||||
const rows: Array<readonly [number, number, string]> = [];
|
||||
for (const line of result.stdout.split(/\r?\n/g)) {
|
||||
// comm may contain spaces ("tmux: server"), so only the two leading
|
||||
// numeric columns are positional.
|
||||
const match = /^(\d+)\s+(\d+)\s*(.*)$/.exec(line.trim());
|
||||
if (!match) continue;
|
||||
rows.push([Number(match[1]), Number(match[2]), match[3] ?? ""]);
|
||||
}
|
||||
}
|
||||
return processTableFromRows(rows);
|
||||
});
|
||||
}
|
||||
|
||||
if (childPid === null) {
|
||||
function captureProcessTableSnapshot(
|
||||
platform: NodeJS.Platform,
|
||||
): Effect.Effect<
|
||||
ProcessTableSnapshot,
|
||||
TerminalProcessTableCaptureError,
|
||||
ProcessRunner.ProcessRunner
|
||||
> {
|
||||
return platform === "win32" ? captureWindowsProcessTable() : capturePosixProcessTable();
|
||||
}
|
||||
|
||||
export function inspectSubprocessFromSnapshot(
|
||||
terminalPid: number,
|
||||
snapshot: ProcessTableSnapshot,
|
||||
platform: NodeJS.Platform,
|
||||
): TerminalSubprocessInspectResult {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
|
||||
}
|
||||
|
||||
const runComm = processRunner.run({
|
||||
command: "ps",
|
||||
args: ["-p", String(childPid), "-o", "comm="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 8_192,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
});
|
||||
|
||||
const commResult = yield* Effect.exit(runComm);
|
||||
let rawComm: string | null = null;
|
||||
if (commResult._tag === "Success" && commResult.value && commResult.value.code === 0) {
|
||||
rawComm = commResult.value.stdout.trim();
|
||||
const childPid = (snapshot.childrenByParent.get(terminalPid) ?? [])[0];
|
||||
if (childPid === undefined) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
|
||||
}
|
||||
|
||||
if (!rawComm || rawComm.length === 0) {
|
||||
const runArgs = processRunner.run({
|
||||
command: "ps",
|
||||
args: ["-p", String(childPid), "-o", "args="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 16_384,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
});
|
||||
const argsResult = yield* Effect.exit(runArgs);
|
||||
if (argsResult._tag === "Success" && argsResult.value && argsResult.value.code === 0) {
|
||||
const first = argsResult.value.stdout.trim().split(/\s+/)[0] ?? "";
|
||||
rawComm = first.length > 0 ? first : null;
|
||||
}
|
||||
}
|
||||
|
||||
const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null;
|
||||
const processIds = new Set<number>([terminalPid]);
|
||||
const psResult = yield* Effect.exit(runPs);
|
||||
if (psResult._tag === "Success" && psResult.value.code === 0) {
|
||||
const childrenByParent = new Map<number, number[]>();
|
||||
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
const children = childrenByParent.get(ppid) ?? [];
|
||||
children.push(pid);
|
||||
childrenByParent.set(ppid, children);
|
||||
const pending = [terminalPid];
|
||||
while (pending.length > 0) {
|
||||
const parentPid = pending.pop();
|
||||
if (parentPid === undefined) continue;
|
||||
for (const pid of snapshot.childrenByParent.get(parentPid) ?? []) {
|
||||
if (processIds.has(pid)) continue;
|
||||
processIds.add(pid);
|
||||
pending.push(pid);
|
||||
}
|
||||
const pending = [terminalPid];
|
||||
while (pending.length > 0) {
|
||||
const parentPid = pending.pop();
|
||||
if (parentPid === undefined) continue;
|
||||
for (const child of childrenByParent.get(parentPid) ?? []) {
|
||||
if (processIds.has(child)) continue;
|
||||
processIds.add(child);
|
||||
pending.push(child);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
processIds.add(childPid);
|
||||
}
|
||||
const normalized = normalizeChildCommandName(snapshot.commandByPid.get(childPid) ?? "", platform);
|
||||
return {
|
||||
hasRunningSubprocess: true,
|
||||
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
|
||||
processIds: [...processIds],
|
||||
};
|
||||
});
|
||||
|
||||
function defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) {
|
||||
return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
|
||||
}
|
||||
if (platform === "win32") {
|
||||
return yield* windowsInspectSubprocess(terminalPid, platform);
|
||||
}
|
||||
return yield* posixInspectSubprocess(terminalPid, platform);
|
||||
});
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -1227,12 +1154,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
const baseEnv = options.env ?? process.env;
|
||||
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const subprocessInspector =
|
||||
options.subprocessInspector ??
|
||||
((terminalPid) =>
|
||||
defaultSubprocessInspectorForPlatform(platform)(terminalPid).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
|
||||
));
|
||||
// Injected per-terminal inspector is the test seam; the default path takes
|
||||
// one process-table snapshot per tick instead (see pollSubprocessActivity).
|
||||
const subprocessInspector = options.subprocessInspector ?? null;
|
||||
const subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -2053,56 +1977,100 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
}
|
||||
});
|
||||
|
||||
// The session objects are mutable and a restart can swap pid mid-tick, so
|
||||
// every poll entry carries the pid it was inspected under; downstream guards
|
||||
// compare against this captured pid, never a re-read of session.pid.
|
||||
interface RunningSessionPoll {
|
||||
readonly session: TerminalSessionState;
|
||||
readonly pid: number;
|
||||
}
|
||||
|
||||
const inspectRunningSubprocesses = Effect.fn("terminal.inspectRunningSubprocesses")(function* (
|
||||
entries: ReadonlyArray<RunningSessionPoll>,
|
||||
) {
|
||||
const results = new Map<number, TerminalSubprocessInspectResult>();
|
||||
if (subprocessInspector !== null) {
|
||||
for (const { session, pid } of entries) {
|
||||
const inspectResult = yield* subprocessInspector(pid).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((reason) =>
|
||||
Effect.logWarning("failed to check terminal subprocess activity", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
terminalPid: pid,
|
||||
reason,
|
||||
}).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(inspectResult)) {
|
||||
results.set(pid, inspectResult.value);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
const snapshot = yield* captureProcessTableSnapshot(platform).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
|
||||
Effect.map(Option.some),
|
||||
// A failed snapshot skips the tick: sessions keep their previous state
|
||||
// and the next tick retries.
|
||||
Effect.catch((reason) =>
|
||||
Effect.logWarning("failed to capture process table for subprocess activity", {
|
||||
reason,
|
||||
}).pipe(Effect.as(Option.none<ProcessTableSnapshot>())),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(snapshot)) {
|
||||
return results;
|
||||
}
|
||||
for (const { pid } of entries) {
|
||||
results.set(pid, inspectSubprocessFromSnapshot(pid, snapshot.value, platform));
|
||||
}
|
||||
return results;
|
||||
});
|
||||
|
||||
const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () {
|
||||
const state = yield* readManagerState;
|
||||
const runningSessions = [...state.sessions.values()].filter(
|
||||
(session): session is TerminalSessionState & { pid: number } =>
|
||||
session.status === "running" && Number.isInteger(session.pid),
|
||||
);
|
||||
const runningSessions: Array<RunningSessionPoll> = [];
|
||||
for (const session of state.sessions.values()) {
|
||||
if (session.status === "running" && session.pid !== null && Number.isInteger(session.pid)) {
|
||||
runningSessions.push({ session, pid: session.pid });
|
||||
}
|
||||
}
|
||||
|
||||
if (runningSessions.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
|
||||
session: TerminalSessionState & { pid: number },
|
||||
const inspections = yield* inspectRunningSubprocesses(runningSessions);
|
||||
|
||||
const applySubprocessActivity = Effect.fn("terminal.applySubprocessActivity")(function* (
|
||||
{ session, pid: terminalPid }: RunningSessionPoll,
|
||||
next: TerminalSubprocessInspectResult,
|
||||
) {
|
||||
const terminalPid = session.pid;
|
||||
const inspectResult = yield* subprocessInspector(terminalPid).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((reason) =>
|
||||
Effect.logWarning("failed to check terminal subprocess activity", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
terminalPid,
|
||||
reason,
|
||||
}).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
|
||||
),
|
||||
);
|
||||
|
||||
if (Option.isNone(inspectResult)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const next = inspectResult.value;
|
||||
yield* registerTerminalProcesses({
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
processIds: next.processIds,
|
||||
});
|
||||
const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null;
|
||||
const event = yield* modifyManagerState((state) => {
|
||||
const outcome = yield* modifyManagerState<{
|
||||
readonly live: boolean;
|
||||
readonly event: Option.Option<TerminalEvent>;
|
||||
}>((state) => {
|
||||
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
|
||||
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
|
||||
);
|
||||
// Liveness is decided here, before process registration, so a
|
||||
// terminal that exited or restarted mid-tick cannot get its old
|
||||
// process tree re-registered with port discovery.
|
||||
if (
|
||||
Option.isNone(liveSession) ||
|
||||
liveSession.value.status !== "running" ||
|
||||
liveSession.value.pid !== terminalPid ||
|
||||
(liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
|
||||
liveSession.value.childCommandLabel === nextChildLabel)
|
||||
liveSession.value.pid !== terminalPid
|
||||
) {
|
||||
return [Option.none(), state] as const;
|
||||
return [{ live: false, event: Option.none<TerminalEvent>() }, state] as const;
|
||||
}
|
||||
if (
|
||||
liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
|
||||
liveSession.value.childCommandLabel === nextChildLabel
|
||||
) {
|
||||
return [{ live: true, event: Option.none<TerminalEvent>() }, state] as const;
|
||||
}
|
||||
|
||||
liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess;
|
||||
@@ -2110,27 +2078,56 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
const eventStamp = advanceEventSequence(liveSession.value);
|
||||
|
||||
return [
|
||||
Option.some({
|
||||
type: "activity" as const,
|
||||
threadId: liveSession.value.threadId,
|
||||
terminalId: liveSession.value.terminalId,
|
||||
sequence: eventStamp.sequence,
|
||||
hasRunningSubprocess: next.hasRunningSubprocess,
|
||||
label: terminalWireLabel(liveSession.value),
|
||||
}),
|
||||
{
|
||||
live: true,
|
||||
event: Option.some({
|
||||
type: "activity" as const,
|
||||
threadId: liveSession.value.threadId,
|
||||
terminalId: liveSession.value.terminalId,
|
||||
sequence: eventStamp.sequence,
|
||||
hasRunningSubprocess: next.hasRunningSubprocess,
|
||||
label: terminalWireLabel(liveSession.value),
|
||||
}),
|
||||
},
|
||||
state,
|
||||
] as const;
|
||||
});
|
||||
|
||||
if (!outcome.live) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* registerTerminalProcesses({
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
processIds: next.processIds,
|
||||
});
|
||||
|
||||
const event = outcome.event;
|
||||
if (Option.isSome(event)) {
|
||||
yield* publishEvent(event.value);
|
||||
// The poll tick runs with tracing suppressed; an actual state flip is
|
||||
// the only part worth a span, so tracing is re-enabled just for it.
|
||||
yield* publishEvent(event.value).pipe(
|
||||
Effect.withSpan("terminal.subprocessActivityChanged", {
|
||||
attributes: {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
hasRunningSubprocess: next.hasRunningSubprocess,
|
||||
...(nextChildLabel !== null ? { childCommand: nextChildLabel } : {}),
|
||||
},
|
||||
}),
|
||||
Effect.provideService(References.TracerEnabled, true),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
yield* Effect.forEach(runningSessions, checkSubprocessActivity, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
for (const entry of runningSessions) {
|
||||
const next = inspections.get(entry.pid);
|
||||
if (next === undefined) {
|
||||
continue;
|
||||
}
|
||||
yield* applySubprocessActivity(entry, next);
|
||||
}
|
||||
});
|
||||
|
||||
const hasRunningSessions = readManagerState.pipe(
|
||||
@@ -2144,6 +2141,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
Effect.flatMap((active) =>
|
||||
active
|
||||
? pollSubprocessActivity().pipe(
|
||||
// Steady-state polling emitted several empty always-success
|
||||
// spans per terminal per second. Suppress the whole tick; the
|
||||
// explicit subprocessActivityChanged span above is the only
|
||||
// trace output.
|
||||
Effect.provideService(References.TracerEnabled, false),
|
||||
Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)),
|
||||
)
|
||||
: Effect.sleep(subprocessPollIntervalMs),
|
||||
|
||||
@@ -18,9 +18,7 @@ import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
|
||||
import type { UsageRecord } from "./usageTranscripts.ts";
|
||||
|
||||
// v2: Codex fork-copy suppression changed what a file parses to, so v1
|
||||
// entries would keep serving double-counted records forever.
|
||||
export const USAGE_SCAN_CACHE_VERSION = 2 as const;
|
||||
export const USAGE_SCAN_CACHE_VERSION = 1 as const;
|
||||
|
||||
export interface CachedFile {
|
||||
readonly size: number;
|
||||
|
||||
@@ -134,106 +134,6 @@ describe("parseCodexLine", () => {
|
||||
parseCodexLine(turnContext, state);
|
||||
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
|
||||
});
|
||||
|
||||
// A forked/subagent rollout opens with the parent's history copied in and
|
||||
// every line re-stamped to the fork instant, then the ancestors' session
|
||||
// metas. Counting those again multiplied usage ~1.85x on real data (#5758).
|
||||
describe("forked rollouts", () => {
|
||||
const meta = (overrides: {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
forkedFromId?: string;
|
||||
spawnParentId?: string;
|
||||
}) =>
|
||||
JSON.stringify({
|
||||
type: "session_meta",
|
||||
timestamp: overrides.timestamp,
|
||||
payload: {
|
||||
type: "session_meta",
|
||||
id: overrides.id,
|
||||
...(overrides.forkedFromId === undefined
|
||||
? {}
|
||||
: { forked_from_id: overrides.forkedFromId }),
|
||||
...(overrides.spawnParentId === undefined
|
||||
? {}
|
||||
: {
|
||||
source: {
|
||||
subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
const stamped = (timestamp: string, line: string) => {
|
||||
const parsed = JSON.parse(line) as { timestamp: string };
|
||||
parsed.timestamp = timestamp;
|
||||
return JSON.stringify(parsed);
|
||||
};
|
||||
|
||||
it("keeps the child session id over copied ancestor metas", () => {
|
||||
const state = initialCodexScanState();
|
||||
parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
|
||||
parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
|
||||
parseCodexLine(turnContext, state);
|
||||
const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
|
||||
|
||||
expect(record?.sessionId).toBe("child");
|
||||
});
|
||||
|
||||
it("drops the re-stamped copied burst and keeps the first real event", () => {
|
||||
const state = initialCodexScanState();
|
||||
const forkInstant = "2026-08-01T05:00:00.000Z";
|
||||
parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
|
||||
parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
|
||||
parseCodexLine(stamped(forkInstant, turnContext), state);
|
||||
|
||||
// Copied history: written in one burst at the fork instant.
|
||||
expect(
|
||||
parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
|
||||
).toBeNull();
|
||||
|
||||
// The child's first genuine turn lands seconds later and must count.
|
||||
const real = parseCodexLine(
|
||||
stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
|
||||
state,
|
||||
);
|
||||
expect(real).not.toBeNull();
|
||||
expect(real?.totals.outputTokens).toBe(30);
|
||||
|
||||
// Suppression never restarts, even for closely spaced later events.
|
||||
const next = parseCodexLine(
|
||||
stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
|
||||
state,
|
||||
);
|
||||
expect(next).not.toBeNull();
|
||||
});
|
||||
|
||||
it("recognizes subagent spawns without forked_from_id", () => {
|
||||
const state = initialCodexScanState();
|
||||
const spawnInstant = "2026-08-01T05:00:00.000Z";
|
||||
parseCodexLine(
|
||||
meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
|
||||
state,
|
||||
);
|
||||
parseCodexLine(stamped(spawnInstant, turnContext), state);
|
||||
expect(
|
||||
parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("does not suppress anything in a rollout that is not a fork", () => {
|
||||
const state = initialCodexScanState();
|
||||
parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
|
||||
parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
|
||||
const record = parseCodexLine(
|
||||
stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
|
||||
state,
|
||||
);
|
||||
expect(record).not.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("totalTokens", () => {
|
||||
|
||||
@@ -151,42 +151,10 @@ export interface CodexScanState {
|
||||
model: string;
|
||||
sessionId: string;
|
||||
lastUsageSignature: string | null;
|
||||
sawSessionMeta: boolean;
|
||||
/** While true, leading usage events are re-stamped copies of parent history. */
|
||||
suppressingForkCopies: boolean;
|
||||
forkCopyAnchorMs: number;
|
||||
}
|
||||
|
||||
export function initialCodexScanState(): CodexScanState {
|
||||
return {
|
||||
model: "",
|
||||
sessionId: "",
|
||||
lastUsageSignature: null,
|
||||
sawSessionMeta: false,
|
||||
suppressingForkCopies: false,
|
||||
forkCopyAnchorMs: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A forked or subagent rollout opens with the parent's full history copied in,
|
||||
* every line re-stamped to the fork instant. Those copies are written in one
|
||||
* synchronous burst (observed gaps 0-40ms), while the child's first genuine
|
||||
* usage event only lands after a real model turn (observed 5s+). One second of
|
||||
* separation splits the two cleanly; `ccusage` uses the same threshold.
|
||||
*/
|
||||
const FORK_COPY_MAX_GAP_MS = 1000;
|
||||
|
||||
/** Whether a `session_meta` payload marks the rollout as a fork or subagent. */
|
||||
function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
|
||||
if (typeof payload["forked_from_id"] === "string") return true;
|
||||
const source = payload["source"];
|
||||
if (typeof source !== "object" || source === null) return false;
|
||||
const subagent = (source as Record<string, unknown>)["subagent"];
|
||||
if (typeof subagent !== "object" || subagent === null) return false;
|
||||
const spawn = (subagent as Record<string, unknown>)["thread_spawn"];
|
||||
if (typeof spawn !== "object" || spawn === null) return false;
|
||||
return typeof (spawn as Record<string, unknown>)["parent_thread_id"] === "string";
|
||||
return { model: "", sessionId: "", lastUsageSignature: null };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -213,18 +181,8 @@ export function parseCodexLine(line: string, state: CodexScanState): UsageRecord
|
||||
const payloadType = payloadRecord["type"];
|
||||
|
||||
if (record["type"] === "session_meta") {
|
||||
// Only the first meta describes this file's own session. A forked rollout
|
||||
// repeats the ancestors' metas right after it; letting those through would
|
||||
// reassign every subsequent record to an ancestor session.
|
||||
if (state.sawSessionMeta) return null;
|
||||
state.sawSessionMeta = true;
|
||||
const id = payloadRecord["id"] ?? payloadRecord["session_id"];
|
||||
if (typeof id === "string") state.sessionId = id;
|
||||
const metaTimestampMs = parseTimestampMs(record["timestamp"]);
|
||||
if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) {
|
||||
state.suppressingForkCopies = true;
|
||||
state.forkCopyAnchorMs = metaTimestampMs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -255,17 +213,6 @@ export function parseCodexLine(line: string, state: CodexScanState): UsageRecord
|
||||
if (signature === state.lastUsageSignature) return null;
|
||||
state.lastUsageSignature = signature;
|
||||
|
||||
// In a forked rollout the copied parent history was already counted from the
|
||||
// parent's own file. Drop the leading burst; the first usage event separated
|
||||
// from its predecessor by a real turn's worth of time ends it for good.
|
||||
if (state.suppressingForkCopies) {
|
||||
if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
|
||||
state.forkCopyAnchorMs = timestampMs;
|
||||
return null;
|
||||
}
|
||||
state.suppressingForkCopies = false;
|
||||
}
|
||||
|
||||
const inputTokens = int(lastRecord["input_tokens"]);
|
||||
const cachedInputTokens = int(lastRecord["cached_input_tokens"]);
|
||||
const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]);
|
||||
@@ -291,8 +238,7 @@ export function parseCodexLine(line: string, state: CodexScanState): UsageRecord
|
||||
totals,
|
||||
// Codex does not report cost in the rollout.
|
||||
reportedCostUsd: null,
|
||||
// Events surviving the fork-copy suppression above are unique to this
|
||||
// rollout, so they need no global dedup.
|
||||
// Rollout files are unique per session, so events need no global dedup.
|
||||
dedupeKey: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -245,7 +245,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
return yield* Effect.gen(function* () {
|
||||
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
|
||||
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
|
||||
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
workspaceSearchIndexes.get(
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
FileFinder,
|
||||
type FileItem,
|
||||
type GrepCursor,
|
||||
type GrepOptions,
|
||||
type GrepResult,
|
||||
} from "@ff-labs/fff-node";
|
||||
import { FileFinder, type GrepCursor, type GrepOptions, type GrepResult } from "@ff-labs/fff-node";
|
||||
import { afterEach, expect, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -17,54 +11,6 @@ afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function fileItem(relativePath: string): FileItem {
|
||||
return {
|
||||
relativePath,
|
||||
fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
|
||||
size: 1,
|
||||
modified: 0,
|
||||
accessFrecencyScore: 0,
|
||||
modificationFrecencyScore: 0,
|
||||
totalFrecencyScore: 0,
|
||||
gitStatus: "clean",
|
||||
};
|
||||
}
|
||||
|
||||
it.effect("filters image searches before applying the result limit", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const items = [
|
||||
...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)),
|
||||
fileItem("public/icon.svg"),
|
||||
];
|
||||
const fileSearch = vi.fn(() => ({
|
||||
ok: true as const,
|
||||
value: {
|
||||
items,
|
||||
scores: [],
|
||||
totalMatched: items.length,
|
||||
totalFiles: items.length,
|
||||
},
|
||||
}));
|
||||
const finder = {
|
||||
destroy: vi.fn(),
|
||||
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
|
||||
fileSearch,
|
||||
} as unknown as FileFinder;
|
||||
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
|
||||
|
||||
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
|
||||
const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true);
|
||||
const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true);
|
||||
|
||||
expect(resultWithoutKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
|
||||
expect(resultWithDirectoryKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
|
||||
expect(fileSearch).toHaveBeenCalledTimes(2);
|
||||
expect(fileSearch).toHaveBeenCalledWith("", { pageSize: 25_002 });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves unexpected FileFinder creation failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native initialization failed");
|
||||
|
||||
@@ -23,7 +23,6 @@ import type {
|
||||
ProjectSearchContentsResult,
|
||||
ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
|
||||
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
|
||||
@@ -112,7 +111,6 @@ export class WorkspaceSearchIndex extends Context.Service<
|
||||
query: string,
|
||||
limit: number,
|
||||
kind?: ProjectEntryKind,
|
||||
imageOnly?: boolean,
|
||||
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
|
||||
readonly searchContents: (
|
||||
input: Omit<ProjectSearchContentsInput, "cwd">,
|
||||
@@ -159,18 +157,15 @@ function toDirectoryEntry(item: DirItem): ProjectEntry | null {
|
||||
return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
|
||||
}
|
||||
|
||||
function mapFileSearchResult(
|
||||
result: SearchResult,
|
||||
limit: number,
|
||||
imageOnly = false,
|
||||
): ProjectSearchEntriesResult {
|
||||
const entries = result.items.flatMap((item) => {
|
||||
const entry = toFileEntry(item);
|
||||
return entry && (!imageOnly || isWorkspaceImagePreviewPath(entry.path)) ? [entry] : [];
|
||||
});
|
||||
function mapFileSearchResult(result: SearchResult, limit: number): ProjectSearchEntriesResult {
|
||||
return {
|
||||
entries: entries.slice(0, limit),
|
||||
truncated: entries.length > limit || result.totalMatched > result.items.length,
|
||||
entries: result.items
|
||||
.flatMap((item) => {
|
||||
const entry = toFileEntry(item);
|
||||
return entry ? [entry] : [];
|
||||
})
|
||||
.slice(0, limit),
|
||||
truncated: result.totalMatched > limit,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -450,13 +445,13 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
|
||||
|
||||
const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
|
||||
"WorkspaceSearchIndex.search",
|
||||
)(function* (query, limit, kind, imageOnly) {
|
||||
const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
|
||||
if (kind === "file" || imageOnly) {
|
||||
)(function* (query, limit, kind) {
|
||||
const pageSize = Math.max(1, limit + 1);
|
||||
if (kind === "file") {
|
||||
const result = yield* runSearch(query, pageSize, "fileSearch", () =>
|
||||
finder.fileSearch(query, { pageSize }),
|
||||
);
|
||||
return mapFileSearchResult(result, limit, imageOnly);
|
||||
return mapFileSearchResult(result, limit);
|
||||
}
|
||||
if (kind === "directory") {
|
||||
const result = yield* runSearch(query, pageSize, "directorySearch", () =>
|
||||
|
||||
+1
-25
@@ -1763,33 +1763,9 @@ const makeWsRpcLayer = (
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsCreateUrl,
|
||||
Effect.gen(function* () {
|
||||
if (input.resource._tag === "attachment") {
|
||||
if (input.resource._tag !== "workspace-file") {
|
||||
return yield* issueAssetUrl({ resource: input.resource });
|
||||
}
|
||||
if (input.resource._tag === "project-favicon") {
|
||||
const project = yield* projectionSnapshotQuery
|
||||
.getActiveProjectByWorkspaceRoot(input.resource.cwd)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetWorkspaceContextResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(project)) {
|
||||
return yield* new AssetWorkspaceContextNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
}
|
||||
return yield* issueAssetUrl({
|
||||
resource: input.resource,
|
||||
...(project.value.faviconPath
|
||||
? { projectFaviconPath: project.value.faviconPath }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(input.resource.threadId)
|
||||
.pipe(
|
||||
|
||||
@@ -12,7 +12,7 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
|
||||
export type AssetUrlState =
|
||||
| { readonly _tag: "Loading" }
|
||||
| { readonly _tag: "Failure" }
|
||||
| { readonly _tag: "Success"; readonly url: string; readonly sourcePath?: string };
|
||||
| { readonly _tag: "Success"; readonly url: string };
|
||||
|
||||
export function useAssetUrlState(
|
||||
environmentId: EnvironmentId,
|
||||
@@ -32,13 +32,7 @@ export function useAssetUrlState(
|
||||
return { _tag: "Loading" };
|
||||
}
|
||||
const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl);
|
||||
return url === null
|
||||
? { _tag: "Failure" }
|
||||
: {
|
||||
_tag: "Success",
|
||||
url,
|
||||
...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
|
||||
};
|
||||
return url === null ? { _tag: "Failure" } : { _tag: "Success", url };
|
||||
}
|
||||
|
||||
export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResource): string | null {
|
||||
|
||||
@@ -20,7 +20,6 @@ import ThreadSidebar from "./Sidebar";
|
||||
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
|
||||
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
import { useProjects } from "../state/entities";
|
||||
import {
|
||||
resolveInitialThreadSidebarWidth,
|
||||
resolveThreadSidebarMaximumWidth,
|
||||
@@ -119,14 +118,6 @@ function SidebarControl() {
|
||||
);
|
||||
}
|
||||
|
||||
// Settings swaps the thread sidebar out of the tree. Keep the lightweight
|
||||
// project projection subscribed so returning to a draft never renders the
|
||||
// zero-project state while the environment snapshot reconnects.
|
||||
function ProjectProjectionRetention() {
|
||||
useProjects();
|
||||
return null;
|
||||
}
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const legacySidebarEnabled = useLegacySidebarEnabled();
|
||||
@@ -193,7 +184,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={sidebarProviderStyle}>
|
||||
<ProjectProjectionRetention />
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
|
||||
@@ -4745,7 +4745,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
"This will discard newer messages and turn diffs in this thread.",
|
||||
"This action cannot be undone.",
|
||||
].join("\n"),
|
||||
{ variant: "destructive" },
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -6049,7 +6048,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
changeRequestState={activeThreadPr?.state ?? null}
|
||||
activeProjectName={activeProject?.title}
|
||||
activeProjectCwd={activeProject?.workspaceRoot ?? null}
|
||||
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
|
||||
@@ -150,7 +150,6 @@ function projectFavicon(project: Project) {
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
faviconPath={project.faviconPath}
|
||||
className={ITEM_ICON_CLASS}
|
||||
/>
|
||||
);
|
||||
@@ -1506,32 +1505,16 @@ function OpenCommandPaletteDialog(props: {
|
||||
},
|
||||
});
|
||||
|
||||
// There is no projects listing page; the action targets the contextual
|
||||
// project (active thread/draft, falling back to the first sidebar group).
|
||||
const contextualProjectGroup =
|
||||
(contextualProjectRef
|
||||
? projectGroupByTargetKey.get(
|
||||
`${contextualProjectRef.environmentId}:${contextualProjectRef.projectId}`,
|
||||
)
|
||||
: null) ??
|
||||
projectGroups[0] ??
|
||||
null;
|
||||
if (contextualProjectGroup) {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:project-settings",
|
||||
searchTerms: ["project", "settings", "scripts", "model", "grouping", "checkout"],
|
||||
title: "Project settings",
|
||||
description: contextualProjectGroup.displayName,
|
||||
icon: <FolderIcon className={ITEM_ICON_CLASS} />,
|
||||
run: async () => {
|
||||
await navigate({
|
||||
to: "/projects/$projectKey",
|
||||
params: { projectKey: contextualProjectGroup.projectKey },
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:project-settings",
|
||||
searchTerms: ["project", "settings", "scripts", "model", "grouping", "checkout"],
|
||||
title: "Project settings",
|
||||
icon: <FolderIcon className={ITEM_ICON_CLASS} />,
|
||||
run: async () => {
|
||||
await navigate({ to: "/settings/projects" });
|
||||
},
|
||||
});
|
||||
|
||||
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
|
||||
const sourceSelectionViewValue =
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
import {
|
||||
completeConfirmDialogClose,
|
||||
readConfirmDialogState,
|
||||
registerConfirmDialogHost,
|
||||
respondToConfirmDialog,
|
||||
subscribeConfirmDialog,
|
||||
} from "../confirmDialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogPopup,
|
||||
AlertDialogTitle,
|
||||
} from "./ui/alert-dialog";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
type ConfirmationCopy = {
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
};
|
||||
|
||||
export function resolveConfirmDialogCopy(message: string): ConfirmationCopy {
|
||||
const normalizedMessage = message.trim();
|
||||
const lines = normalizedMessage.split("\n");
|
||||
const questionLineIndex = lines.findIndex((line) => line.trim().endsWith("?"));
|
||||
|
||||
if (questionLineIndex >= 0) {
|
||||
const title = lines[questionLineIndex]!.trim();
|
||||
const description = lines
|
||||
.filter((_, index) => index !== questionLineIndex)
|
||||
.join("\n")
|
||||
.trim();
|
||||
return { title, description: description || null };
|
||||
}
|
||||
|
||||
const questionMarkIndex = normalizedMessage.indexOf("?");
|
||||
if (questionMarkIndex >= 0) {
|
||||
return {
|
||||
title: normalizedMessage.slice(0, questionMarkIndex + 1).trim(),
|
||||
description: normalizedMessage.slice(questionMarkIndex + 1).trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: "Confirm action",
|
||||
description: normalizedMessage || "This action requires your confirmation.",
|
||||
};
|
||||
}
|
||||
|
||||
export function ConfirmDialogHost() {
|
||||
const state = useSyncExternalStore(
|
||||
subscribeConfirmDialog,
|
||||
readConfirmDialogState,
|
||||
readConfirmDialogState,
|
||||
);
|
||||
|
||||
useEffect(() => registerConfirmDialogHost(), []);
|
||||
|
||||
const copy = resolveConfirmDialogCopy(state.status === "idle" ? "" : state.message);
|
||||
const confirmVariant = state.status === "idle" ? "default" : state.variant;
|
||||
const onCancel = () => respondToConfirmDialog(false);
|
||||
const onConfirm = () => respondToConfirmDialog(true);
|
||||
|
||||
return (
|
||||
<AlertDialog
|
||||
open={state.status === "confirming"}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onCancel();
|
||||
}}
|
||||
onOpenChangeComplete={(open) => {
|
||||
if (!open) completeConfirmDialogClose();
|
||||
}}
|
||||
>
|
||||
<AlertDialogPopup className="max-w-lg">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{copy.title}</AlertDialogTitle>
|
||||
{copy.description ? (
|
||||
<AlertDialogDescription className="whitespace-pre-line">
|
||||
{copy.description}
|
||||
</AlertDialogDescription>
|
||||
) : null}
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
|
||||
<Button variant={confirmVariant} onClick={onConfirm}>
|
||||
Confirm
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -104,7 +104,7 @@ import {
|
||||
} from "../keybindings";
|
||||
import { isModelPickerOpen } from "../modelPickerVisibility";
|
||||
import { useShortcutModifierState } from "../shortcutModifierState";
|
||||
import { ensureLocalApi, readLocalApi } from "../localApi";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { useDesktopUpdateState } from "../state/desktopUpdate";
|
||||
@@ -1499,7 +1499,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
: []),
|
||||
"This removes only this project entry.",
|
||||
].join("\n"),
|
||||
{ variant: "destructive" },
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -1548,7 +1547,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []),
|
||||
"This removes only this project entry.",
|
||||
].join("\n");
|
||||
const confirmed = await api.dialogs.confirm(message, { variant: "destructive" });
|
||||
const confirmed = await api.dialogs.confirm(message);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
@@ -1831,7 +1830,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
`Delete ${count} thread${count === 1 ? "" : "s"}?`,
|
||||
"This permanently clears conversation history for these threads.",
|
||||
].join("\n"),
|
||||
{ variant: "destructive" },
|
||||
);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
@@ -2182,7 +2180,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
`Delete thread "${thread.title}"?`,
|
||||
"This permanently clears conversation history for this thread.",
|
||||
].join("\n"),
|
||||
{ variant: "destructive" },
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -2256,11 +2253,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
faviconPath={project.faviconPath}
|
||||
/>
|
||||
<ProjectFavicon environmentId={project.environmentId} cwd={project.workspaceRoot} />
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="truncate text-sm font-medium text-sidebar-foreground/90">
|
||||
{project.displayName}
|
||||
@@ -2733,7 +2726,6 @@ interface SidebarProjectsContentProps {
|
||||
arm64IntelBuildWarningDescription: string | null;
|
||||
desktopUpdateButtonAction: "download" | "install" | "none";
|
||||
desktopUpdateButtonDisabled: boolean;
|
||||
desktopUpdateActionPending: boolean;
|
||||
handleDesktopUpdateButtonClick: () => void;
|
||||
projectSortOrder: SidebarProjectSortOrder;
|
||||
threadSortOrder: SidebarThreadSortOrder;
|
||||
@@ -2774,7 +2766,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
arm64IntelBuildWarningDescription,
|
||||
desktopUpdateButtonAction,
|
||||
desktopUpdateButtonDisabled,
|
||||
desktopUpdateActionPending,
|
||||
handleDesktopUpdateButtonClick,
|
||||
projectSortOrder,
|
||||
threadSortOrder,
|
||||
@@ -2867,7 +2858,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={desktopUpdateButtonDisabled || desktopUpdateActionPending}
|
||||
disabled={desktopUpdateButtonDisabled}
|
||||
onClick={handleDesktopUpdateButtonClick}
|
||||
>
|
||||
{desktopUpdateButtonAction === "download"
|
||||
@@ -3037,7 +3028,6 @@ export default function LegacySidebar() {
|
||||
const suppressProjectClickAfterDragRef = useRef(false);
|
||||
const suppressProjectClickForContextMenuRef = useRef(false);
|
||||
const desktopUpdateState = useDesktopUpdateState();
|
||||
const [desktopUpdateActionPending, setDesktopUpdateActionPending] = useState(false);
|
||||
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
|
||||
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
|
||||
const platform = navigator.platform;
|
||||
@@ -3504,18 +3494,10 @@ export default function LegacySidebar() {
|
||||
"commandPalette.toggle",
|
||||
newThreadShortcutLabelOptions,
|
||||
);
|
||||
const handleDesktopUpdateButtonClick = useCallback(async () => {
|
||||
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || !desktopUpdateState) return;
|
||||
if (
|
||||
desktopUpdateButtonDisabled ||
|
||||
desktopUpdateButtonAction === "none" ||
|
||||
desktopUpdateActionPending
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDesktopUpdateActionPending(true);
|
||||
if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;
|
||||
|
||||
if (desktopUpdateButtonAction === "download") {
|
||||
void bridge
|
||||
@@ -3543,32 +3525,15 @@ export default function LegacySidebar() {
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
}),
|
||||
);
|
||||
})
|
||||
.finally(() => setDesktopUpdateActionPending(false));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (desktopUpdateButtonAction === "install") {
|
||||
let confirmed = false;
|
||||
try {
|
||||
confirmed = await ensureLocalApi().dialogs.confirm(
|
||||
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),
|
||||
);
|
||||
} catch (error) {
|
||||
setDesktopUpdateActionPending(false);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not confirm update",
|
||||
description: error instanceof Error ? error.message : "Update confirmation failed.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!confirmed) {
|
||||
setDesktopUpdateActionPending(false);
|
||||
return;
|
||||
}
|
||||
const confirmed = window.confirm(
|
||||
getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),
|
||||
);
|
||||
if (!confirmed) return;
|
||||
void bridge
|
||||
.installUpdate()
|
||||
.then((result) => {
|
||||
@@ -3591,15 +3556,9 @@ export default function LegacySidebar() {
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||
}),
|
||||
);
|
||||
})
|
||||
.finally(() => setDesktopUpdateActionPending(false));
|
||||
});
|
||||
}
|
||||
}, [
|
||||
desktopUpdateActionPending,
|
||||
desktopUpdateButtonAction,
|
||||
desktopUpdateButtonDisabled,
|
||||
desktopUpdateState,
|
||||
]);
|
||||
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
|
||||
|
||||
const expandThreadListForProject = useCallback((projectKey: string) => {
|
||||
setExpandedThreadListsByProject((current) => {
|
||||
@@ -3631,7 +3590,6 @@ export default function LegacySidebar() {
|
||||
arm64IntelBuildWarningDescription={arm64IntelBuildWarningDescription}
|
||||
desktopUpdateButtonAction={desktopUpdateButtonAction}
|
||||
desktopUpdateButtonDisabled={desktopUpdateButtonDisabled}
|
||||
desktopUpdateActionPending={desktopUpdateActionPending}
|
||||
handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick}
|
||||
projectSortOrder={sidebarProjectSortOrder}
|
||||
threadSortOrder={sidebarThreadSortOrder}
|
||||
|
||||
@@ -4,7 +4,6 @@ import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
faviconUrl: "https://environment.test/api/assets/token-a/v1-20-favicon.svg",
|
||||
lastResource: null as unknown,
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
@@ -53,10 +52,7 @@ vi.mock("react", async (importOriginal) => {
|
||||
|
||||
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
|
||||
vi.mock("../assets/assetUrls", () => ({
|
||||
useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
|
||||
testState.lastResource = resource;
|
||||
return { _tag: "Success", url: testState.faviconUrl };
|
||||
},
|
||||
useAssetUrl: () => testState.faviconUrl,
|
||||
}));
|
||||
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
@@ -129,18 +125,4 @@ describe("ProjectFavicon", () => {
|
||||
expect(afterDisplayedError[0]).not.toBeNull();
|
||||
expect(afterDisplayedError[1]).toBeNull();
|
||||
});
|
||||
|
||||
it("requests a saved favicon path when one is set", () => {
|
||||
ProjectFavicon({
|
||||
environmentId: "environment-test" as EnvironmentId,
|
||||
cwd: "/workspace-test",
|
||||
faviconPath: "brand/icon.svg",
|
||||
});
|
||||
|
||||
expect(testState.lastResource).toEqual({
|
||||
_tag: "project-favicon",
|
||||
cwd: "/workspace-test",
|
||||
path: "brand/icon.svg",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import type { ComponentType } from "react";
|
||||
import { useState } from "react";
|
||||
import { useAssetUrlState } from "../assets/assetUrls";
|
||||
import { useAssetUrl } from "../assets/assetUrls";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Map<string, string>();
|
||||
@@ -14,12 +14,13 @@ const loadedProjectFaviconSrcs = new Map<string, string>();
|
||||
export function ProjectFavicon(input: {
|
||||
environmentId: EnvironmentId;
|
||||
cwd: string;
|
||||
faviconPath?: string | null | undefined;
|
||||
className?: string | undefined;
|
||||
fallbackIcon?: ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
const state = useProjectFaviconAsset(input);
|
||||
const src = state._tag === "Success" ? state.url : null;
|
||||
const src = useAssetUrl(input.environmentId, {
|
||||
_tag: "project-favicon",
|
||||
cwd: input.cwd,
|
||||
});
|
||||
const FallbackIcon = input.fallbackIcon ?? FolderIcon;
|
||||
|
||||
if (!src || isProjectFaviconFallbackUrl(src)) {
|
||||
@@ -39,18 +40,6 @@ export function ProjectFavicon(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function useProjectFaviconAsset(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly cwd: string;
|
||||
readonly faviconPath?: string | null | undefined;
|
||||
}) {
|
||||
return useAssetUrlState(input.environmentId, {
|
||||
_tag: "project-favicon",
|
||||
cwd: input.cwd,
|
||||
...(input.faviconPath ? { path: input.faviconPath } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function ProjectFaviconFallback({
|
||||
className,
|
||||
icon: Icon,
|
||||
|
||||
@@ -42,12 +42,12 @@ import {
|
||||
FolderIcon,
|
||||
FolderPlusIcon,
|
||||
GitBranchIcon,
|
||||
EllipsisIcon,
|
||||
MessageSquareIcon,
|
||||
PinIcon,
|
||||
PlusIcon,
|
||||
SearchIcon,
|
||||
ServerIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
Undo2Icon,
|
||||
@@ -137,7 +137,6 @@ import {
|
||||
} from "./Sidebar.logic";
|
||||
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
ThreadWorktreeIndicator,
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
@@ -237,7 +236,6 @@ function SidebarThreadTooltip({
|
||||
thread,
|
||||
projectTitle,
|
||||
projectCwd,
|
||||
projectFaviconPath,
|
||||
environmentLabel,
|
||||
driverKind,
|
||||
modelInstanceId,
|
||||
@@ -249,7 +247,6 @@ function SidebarThreadTooltip({
|
||||
thread: SidebarThreadSummary;
|
||||
projectTitle: string | null;
|
||||
projectCwd: string | null;
|
||||
projectFaviconPath: string | null;
|
||||
environmentLabel: string | null;
|
||||
driverKind: ProviderInstanceEntry["driverKind"] | null;
|
||||
modelInstanceId: string;
|
||||
@@ -279,7 +276,6 @@ function SidebarThreadTooltip({
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={projectCwd ?? ""}
|
||||
faviconPath={projectFaviconPath}
|
||||
className="size-3 shrink-0 stroke-muted-foreground"
|
||||
/>
|
||||
<div className="min-w-0 truncate text-foreground/75">{projectTitle}</div>
|
||||
@@ -427,7 +423,6 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
|
||||
composer: ComposerThreadDraftState;
|
||||
projectTitle: string | null;
|
||||
projectCwd: string | null;
|
||||
projectFaviconPath: string | null;
|
||||
isActive: boolean;
|
||||
onNavigate: (draftId: DraftId) => void;
|
||||
onDiscard: (draftId: DraftId) => void;
|
||||
@@ -492,7 +487,6 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={session.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
faviconPath={props.projectFaviconPath}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-xs font-medium text-secondary-label">
|
||||
@@ -530,7 +524,6 @@ interface SidebarDraftRowData {
|
||||
const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
|
||||
projectDisplayNameByKey: ReadonlyMap<string, string>;
|
||||
projectCwdByKey: ReadonlyMap<string, string>;
|
||||
projectFaviconPathByKey: ReadonlyMap<string, string | null | undefined>;
|
||||
scopedProjectKeys: ReadonlySet<string> | null;
|
||||
routeDraftId: string | null;
|
||||
onNavigateToDraft: (draftId: DraftId) => void;
|
||||
@@ -625,7 +618,6 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
|
||||
composer={composer}
|
||||
projectTitle={props.projectDisplayNameByKey.get(projectKey) ?? null}
|
||||
projectCwd={props.projectCwdByKey.get(projectKey) ?? null}
|
||||
projectFaviconPath={props.projectFaviconPathByKey.get(projectKey) ?? null}
|
||||
isActive={draftId === props.routeDraftId}
|
||||
onNavigate={props.onNavigateToDraft}
|
||||
onDiscard={handleDiscard}
|
||||
@@ -675,7 +667,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
currentEnvironmentId: string | null;
|
||||
environmentLabel: string | null;
|
||||
projectCwd: string | null;
|
||||
projectFaviconPath: string | null;
|
||||
projectTitle: string | null;
|
||||
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
|
||||
timestampFormat: TimestampFormat;
|
||||
@@ -866,7 +857,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
thread={thread}
|
||||
projectTitle={props.projectTitle}
|
||||
projectCwd={props.projectCwd}
|
||||
projectFaviconPath={props.projectFaviconPath}
|
||||
environmentLabel={props.environmentLabel}
|
||||
driverKind={driverKind}
|
||||
modelInstanceId={modelInstanceId}
|
||||
@@ -1132,7 +1122,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
faviconPath={props.projectFaviconPath}
|
||||
className="size-4"
|
||||
fallbackIcon={MessageSquareIcon}
|
||||
/>
|
||||
@@ -1272,7 +1261,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
faviconPath={props.projectFaviconPath}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
{props.projectTitle ? (
|
||||
@@ -1413,10 +1401,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
working, but it truncated to a half-sentence and dropped the
|
||||
branch, so the row lost its most stable identifier. */}
|
||||
{thread.branch ? (
|
||||
<>
|
||||
<ThreadWorktreeIndicator thread={thread} />
|
||||
<span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span>
|
||||
</>
|
||||
<span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span>
|
||||
) : (
|
||||
<span className="flex-1" />
|
||||
)}
|
||||
@@ -1469,7 +1454,6 @@ function latestTurnDiff(
|
||||
const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
|
||||
thread: SidebarThreadSummary;
|
||||
projectCwd: string | null;
|
||||
projectFaviconPath: string | null;
|
||||
projectTitle: string | null;
|
||||
environmentLabel: string | null;
|
||||
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
|
||||
@@ -1542,7 +1526,6 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
faviconPath={props.projectFaviconPath}
|
||||
className="size-4 shrink-0"
|
||||
fallbackIcon={MessageSquareIcon}
|
||||
/>
|
||||
@@ -1555,7 +1538,6 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
|
||||
thread={thread}
|
||||
projectTitle={props.projectTitle}
|
||||
projectCwd={props.projectCwd}
|
||||
projectFaviconPath={props.projectFaviconPath}
|
||||
environmentLabel={props.environmentLabel}
|
||||
driverKind={driverKind}
|
||||
modelInstanceId={modelInstanceId}
|
||||
@@ -1732,13 +1714,6 @@ export default function Sidebar() {
|
||||
),
|
||||
[projects],
|
||||
);
|
||||
const projectFaviconPathByKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
projects.map((project) => [`${project.environmentId}:${project.id}`, project.faviconPath]),
|
||||
),
|
||||
[projects],
|
||||
);
|
||||
const projectDisplayNameByKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -1840,7 +1815,7 @@ export default function Sidebar() {
|
||||
clearSelection();
|
||||
}, [clearSelection, projectScopeKey]);
|
||||
|
||||
const handleProjectSettings = useCallback(
|
||||
const handleProjectActions = useCallback(
|
||||
(event: ReactMouseEvent<HTMLButtonElement>, projectGroup: SidebarProjectSnapshot) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
@@ -1849,7 +1824,7 @@ export default function Sidebar() {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void router.navigate({
|
||||
to: "/projects/$projectKey",
|
||||
to: "/settings/projects/$projectKey",
|
||||
params: { projectKey: projectGroup.projectKey },
|
||||
});
|
||||
},
|
||||
@@ -2812,7 +2787,6 @@ export default function Sidebar() {
|
||||
`Delete ${count} thread${count === 1 ? "" : "s"}?`,
|
||||
"This permanently clears conversation history for these threads.",
|
||||
].join("\n"),
|
||||
{ variant: "destructive" },
|
||||
),
|
||||
);
|
||||
if (confirmed._tag === "Failure" || !confirmed.value) return;
|
||||
@@ -3015,7 +2989,6 @@ export default function Sidebar() {
|
||||
`Delete thread "${thread.title}"?`,
|
||||
"This permanently clears conversation history for this thread.",
|
||||
].join("\n"),
|
||||
{ variant: "destructive" },
|
||||
),
|
||||
);
|
||||
if (confirmed._tag === "Failure" || !confirmed.value) return;
|
||||
@@ -3257,7 +3230,6 @@ export default function Sidebar() {
|
||||
<ProjectFavicon
|
||||
environmentId={scopedProjectGroup.environmentId}
|
||||
cwd={scopedProjectGroup.workspaceRoot}
|
||||
faviconPath={scopedProjectGroup.faviconPath}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
) : (
|
||||
@@ -3295,21 +3267,20 @@ export default function Sidebar() {
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
faviconPath={project.faviconPath}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Project settings for ${project.displayName}`}
|
||||
title={`Project settings for ${project.displayName}`}
|
||||
aria-label={`Project actions for ${project.displayName}`}
|
||||
title={`Project actions for ${project.displayName}`}
|
||||
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-icon-muted outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
void handleProjectSettings(event, project);
|
||||
void handleProjectActions(event, project);
|
||||
}}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
<EllipsisIcon className="size-3.5" />
|
||||
</button>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
@@ -3368,11 +3339,6 @@ export default function Sidebar() {
|
||||
projectCwd={
|
||||
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
|
||||
}
|
||||
projectFaviconPath={
|
||||
projectFaviconPathByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
) ?? null
|
||||
}
|
||||
projectTitle={
|
||||
projectDisplayNameByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
@@ -3476,11 +3442,6 @@ export default function Sidebar() {
|
||||
projectCwd={
|
||||
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
|
||||
}
|
||||
projectFaviconPath={
|
||||
projectFaviconPathByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
) ?? null
|
||||
}
|
||||
projectTitle={
|
||||
projectDisplayNameByKey.get(
|
||||
`${thread.environmentId}:${thread.projectId}`,
|
||||
@@ -3519,7 +3480,6 @@ export default function Sidebar() {
|
||||
key="draft-sessions"
|
||||
projectDisplayNameByKey={projectDisplayNameByKey}
|
||||
projectCwdByKey={projectCwdByKey}
|
||||
projectFaviconPathByKey={projectFaviconPathByKey}
|
||||
scopedProjectKeys={scopedProjectKeys}
|
||||
routeDraftId={routeDraftIdForRows}
|
||||
onNavigateToDraft={navigateToDraft}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
interface WorkspaceBreadcrumbProps {
|
||||
readonly ariaLabel: string;
|
||||
readonly children: ReactNode;
|
||||
readonly className?: string;
|
||||
}
|
||||
|
||||
export function WorkspaceBreadcrumb({ ariaLabel, children, className }: WorkspaceBreadcrumbProps) {
|
||||
return (
|
||||
<nav aria-label={ariaLabel} className={cn("min-w-0", className)}>
|
||||
{/* Keep the flexible container draggable in Electron. Interactive
|
||||
descendants are excluded by the shared .drag-region CSS rules. */}
|
||||
<ol className="m-0 flex min-w-0 list-none items-center gap-2 p-0 text-sm sm:gap-3">
|
||||
{children}
|
||||
</ol>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
interface WorkspaceBreadcrumbItemProps {
|
||||
readonly children: ReactNode;
|
||||
readonly className?: string;
|
||||
readonly current?: boolean;
|
||||
}
|
||||
|
||||
export function WorkspaceBreadcrumbItem({
|
||||
children,
|
||||
className,
|
||||
current = false,
|
||||
}: WorkspaceBreadcrumbItemProps) {
|
||||
return (
|
||||
<li
|
||||
aria-current={current ? "page" : undefined}
|
||||
className={cn(
|
||||
"flex min-w-0 items-center font-medium",
|
||||
current ? "text-foreground" : "shrink-0 text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceBreadcrumbSeparator() {
|
||||
return (
|
||||
<li aria-hidden="true" className="flex shrink-0 items-center text-icon-muted">
|
||||
/
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -3129,7 +3129,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
instanceEntries={providerInstanceEntries}
|
||||
keybindings={keybindings}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerClassName="-ms-px"
|
||||
triggerClassName="-ms-px ps-0"
|
||||
terminalOpen={terminalOpen}
|
||||
open={isComposerModelPickerOpen}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
|
||||
@@ -36,11 +36,6 @@ import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import {
|
||||
WorkspaceBreadcrumb,
|
||||
WorkspaceBreadcrumbItem,
|
||||
WorkspaceBreadcrumbSeparator,
|
||||
} from "../WorkspaceBreadcrumb";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
@@ -54,7 +49,6 @@ interface ChatHeaderProps {
|
||||
changeRequestState: ChangeRequestStateLike | null;
|
||||
activeProjectName: string | undefined;
|
||||
activeProjectCwd: string | null;
|
||||
activeProjectFaviconPath: string | null;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
|
||||
preferredScriptId: string | null;
|
||||
@@ -107,7 +101,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
changeRequestState,
|
||||
activeProjectName,
|
||||
activeProjectCwd,
|
||||
activeProjectFaviconPath,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
@@ -216,88 +209,90 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
|
||||
onContextMenu={handleHeaderContextMenu}
|
||||
>
|
||||
<WorkspaceBreadcrumb ariaLabel="Thread breadcrumb" className="flex-1">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
{/* The project always leads the header: knowing which project a
|
||||
thread lives in is priority zero, and the thread title alone
|
||||
doesn't answer it. */}
|
||||
{activeProjectName ? (
|
||||
<>
|
||||
<WorkspaceBreadcrumbItem>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`New thread in ${activeProjectName}`}
|
||||
onClick={onNewThreadInProject}
|
||||
className="inline-flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={activeThreadEnvironmentId}
|
||||
cwd={activeProjectCwd ?? ""}
|
||||
faviconPath={activeProjectFaviconPath}
|
||||
className="size-3.5"
|
||||
/>
|
||||
<span className="max-w-40 truncate">{activeProjectName}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</WorkspaceBreadcrumbItem>
|
||||
<WorkspaceBreadcrumbSeparator />
|
||||
</>
|
||||
) : null}
|
||||
<WorkspaceBreadcrumbItem current className="flex-1">
|
||||
{renamingTitle !== null ? (
|
||||
<input
|
||||
autoFocus
|
||||
aria-label="Thread title"
|
||||
className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-ring/50 focus:ring-ring"
|
||||
defaultValue={renamingTitle}
|
||||
onBlur={(event) => {
|
||||
if (renameCommittedRef.current) return;
|
||||
commitRename(event.currentTarget.value);
|
||||
}}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
onKeyDown={handleRenameKeyDown}
|
||||
/>
|
||||
) : isServerThread ? (
|
||||
<span className="inline-flex shrink-0 items-center gap-2">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
ref={titleButtonRef}
|
||||
type="button"
|
||||
aria-label={`Thread actions for ${activeThreadTitle}`}
|
||||
aria-haspopup="menu"
|
||||
onClick={openMenuFromTitle}
|
||||
className="group/thread-title inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
aria-label={`New thread in ${activeProjectName}`}
|
||||
onClick={onNewThreadInProject}
|
||||
className="inline-flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
|
||||
<ProjectFavicon
|
||||
environmentId={activeThreadEnvironmentId}
|
||||
cwd={activeProjectCwd ?? ""}
|
||||
className="size-3.5"
|
||||
/>
|
||||
<span className="max-w-40 truncate text-sm font-medium">{activeProjectName}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
<TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
}
|
||||
<span aria-hidden className="text-icon-muted">
|
||||
/
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
{renamingTitle !== null ? (
|
||||
<input
|
||||
autoFocus
|
||||
aria-label="Thread title"
|
||||
className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-ring/50 focus:ring-ring"
|
||||
defaultValue={renamingTitle}
|
||||
onBlur={(event) => {
|
||||
if (renameCommittedRef.current) return;
|
||||
commitRename(event.currentTarget.value);
|
||||
}}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
onKeyDown={handleRenameKeyDown}
|
||||
/>
|
||||
) : isServerThread ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
ref={titleButtonRef}
|
||||
type="button"
|
||||
aria-label={`Thread actions for ${activeThreadTitle}`}
|
||||
aria-haspopup="menu"
|
||||
onClick={openMenuFromTitle}
|
||||
className="group/thread-title inline-flex min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<h2 className="min-w-0 truncate text-sm font-medium text-foreground">
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
|
||||
/>
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</WorkspaceBreadcrumbItem>
|
||||
</WorkspaceBreadcrumb>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<h2
|
||||
aria-label={activeThreadTitle}
|
||||
className="min-w-0 flex-1 truncate text-sm font-medium text-foreground"
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
data-chat-header-actions
|
||||
className={cn(
|
||||
|
||||
@@ -101,7 +101,7 @@ export function DraftHeroHeadline({
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
|
||||
className="pointer-events-auto inline-block max-w-64 truncate border-foreground/60 border-b border-dotted align-baseline text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="pointer-events-auto inline-block max-w-64 truncate border-foreground/60 border-b border-dotted align-bottom text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
title={activeProjectDisplayName ?? undefined}
|
||||
>
|
||||
{activeProjectDisplayName ?? "Choose a project"}
|
||||
|
||||
@@ -323,9 +323,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
hideIndicator
|
||||
// Base UI keeps radio menus open by default. Close on pick so
|
||||
// the traits menu behaves like the model picker.
|
||||
closeOnClick
|
||||
disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
|
||||
>
|
||||
<span className="flex w-full min-w-0 items-center justify-between gap-3">
|
||||
@@ -365,7 +362,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
}}
|
||||
>
|
||||
{(["on", "off"] as const).map((value) => (
|
||||
<MenuRadioItem key={value} value={value} hideIndicator closeOnClick>
|
||||
<MenuRadioItem key={value} value={value} hideIndicator>
|
||||
<span className="flex w-full min-w-0 items-center justify-between gap-3">
|
||||
<span>{value === "on" ? "On" : "Off"}</span>
|
||||
</span>
|
||||
|
||||
@@ -8,22 +8,11 @@ describe("resolveClerkSignInProps", () => {
|
||||
expect(resolveClerkSignInProps(href, false)).toEqual({ forceRedirectUrl: href });
|
||||
});
|
||||
|
||||
it("removes a Clerk virtual pathname and callback params while preserving the desktop route", () => {
|
||||
expect(
|
||||
resolveClerkSignInProps(
|
||||
"t3code://app/CLERK-ROUTER/VIRTUAL/sign-up?__clerk_status=complete#/settings/connections",
|
||||
true,
|
||||
),
|
||||
).toEqual({
|
||||
forceRedirectUrl: "t3code://app/#/settings/connections",
|
||||
signUpForceRedirectUrl: "t3code://app/#/settings/connections",
|
||||
});
|
||||
it("omits the redirect override on packaged desktop", () => {
|
||||
expect(resolveClerkSignInProps("t3code://app/#/settings/general", true)).toEqual({});
|
||||
});
|
||||
|
||||
it("preserves a clean development desktop route", () => {
|
||||
expect(resolveClerkSignInProps("t3code-dev://app/#/settings/general", true)).toEqual({
|
||||
forceRedirectUrl: "t3code-dev://app/#/settings/general",
|
||||
signUpForceRedirectUrl: "t3code-dev://app/#/settings/general",
|
||||
});
|
||||
it("omits the redirect override on development desktop", () => {
|
||||
expect(resolveClerkSignInProps("t3code-dev://app/#/settings/general", true)).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,12 @@
|
||||
export interface ClerkSignInProps {
|
||||
forceRedirectUrl?: string;
|
||||
signUpForceRedirectUrl?: string;
|
||||
}
|
||||
|
||||
// Clerk's native-app allowlist only authorizes the bare renderer root
|
||||
// (t3code://app/), which @clerk/electron's OAuth transport already supplies,
|
||||
// so any page-derived redirect override gets the whole sign-in request
|
||||
// rejected. On Electron, omit the override and let Clerk use its defaults.
|
||||
export function resolveClerkSignInProps(href: string, isElectron: boolean): ClerkSignInProps {
|
||||
if (isElectron) {
|
||||
// Electron routes through the hash, so reset any Clerk virtual pathname without losing the T3 page.
|
||||
const redirectUrl = new URL(href);
|
||||
redirectUrl.pathname = "/";
|
||||
redirectUrl.search = "";
|
||||
|
||||
return {
|
||||
forceRedirectUrl: redirectUrl.toString(),
|
||||
signUpForceRedirectUrl: redirectUrl.toString(),
|
||||
};
|
||||
}
|
||||
if (isElectron) return {};
|
||||
return { forceRedirectUrl: href };
|
||||
}
|
||||
@@ -150,19 +150,10 @@ export function useProjectFilePickerQuery(
|
||||
cwd: string,
|
||||
query: string,
|
||||
limit: number,
|
||||
options?: { readonly imageOnly?: boolean },
|
||||
) {
|
||||
const search = useProjectPathSearch(
|
||||
{
|
||||
environmentId,
|
||||
cwd,
|
||||
query,
|
||||
kind: "file",
|
||||
...(options?.imageOnly ? { imageOnly: true } : {}),
|
||||
},
|
||||
limit,
|
||||
{ allowEmptyQuery: true },
|
||||
);
|
||||
const search = useProjectPathSearch({ environmentId, cwd, query, kind: "file" }, limit, {
|
||||
allowEmptyQuery: true,
|
||||
});
|
||||
|
||||
return {
|
||||
entries: search.isPending ? [] : search.entries,
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import type {
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessResourceHistorySummary,
|
||||
@@ -22,7 +22,6 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { ensureLocalApi } from "../../localApi";
|
||||
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
|
||||
import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
@@ -858,11 +857,6 @@ export function DiagnosticsSettingsPanel() {
|
||||
const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);
|
||||
const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
|
||||
const [signalingPid, setSignalingPid] = useState<number | null>(null);
|
||||
const signalingPidRef = useRef<number | null>(null);
|
||||
const environmentIdRef = useRef(environmentId);
|
||||
const processDataRef = useRef(processData);
|
||||
environmentIdRef.current = environmentId;
|
||||
processDataRef.current = processData;
|
||||
|
||||
const openLogsDirectory = useCallback(() => {
|
||||
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
|
||||
@@ -901,51 +895,28 @@ export function DiagnosticsSettingsPanel() {
|
||||
const isInitialLoading = isPending && data === null;
|
||||
const isProcessInitialLoading = isProcessPending && processData === null;
|
||||
const signalProcess = useCallback(
|
||||
async (pid: number, signal: ServerProcessSignal) => {
|
||||
if (signalingPidRef.current !== null) return;
|
||||
signalingPidRef.current = pid;
|
||||
setSignalingPid(pid);
|
||||
const clearSignaling = () => {
|
||||
signalingPidRef.current = null;
|
||||
setSignalingPid(null);
|
||||
};
|
||||
if (signal === "SIGKILL") {
|
||||
let confirmed = false;
|
||||
try {
|
||||
confirmed = await ensureLocalApi().dialogs.confirm(
|
||||
`Send SIGKILL to process ${pid}? This cannot be handled by the process.`,
|
||||
{ variant: "destructive" },
|
||||
);
|
||||
} catch (error) {
|
||||
clearSignaling();
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not confirm signal",
|
||||
description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!confirmed) {
|
||||
clearSignaling();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const currentEnvironmentId = environmentIdRef.current;
|
||||
if (currentEnvironmentId === null) {
|
||||
clearSignaling();
|
||||
(pid: number, signal: ServerProcessSignal) => {
|
||||
if (
|
||||
signal === "SIGKILL" &&
|
||||
!window.confirm(`Send SIGKILL to process ${pid}? This cannot be handled by the process.`)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);
|
||||
if (environmentId === null) {
|
||||
return;
|
||||
}
|
||||
const process = processData?.processes.find((entry) => entry.pid === pid);
|
||||
if (process === undefined) {
|
||||
clearSignaling();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSignalingPid(pid);
|
||||
void (async () => {
|
||||
const result = await signalServerProcess({
|
||||
environmentId: currentEnvironmentId,
|
||||
environmentId,
|
||||
input: { pid, startTimeMs: process.startTimeMs, signal },
|
||||
});
|
||||
setSignalingPid(null);
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -978,11 +949,9 @@ export function DiagnosticsSettingsPanel() {
|
||||
return;
|
||||
}
|
||||
refreshProcesses();
|
||||
} finally {
|
||||
clearSignaling();
|
||||
}
|
||||
})();
|
||||
},
|
||||
[refreshProcesses, signalServerProcess],
|
||||
[environmentId, processData?.processes, refreshProcesses, signalServerProcess],
|
||||
);
|
||||
|
||||
const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { primaryServerKeybindingsAtom } from "~/state/server";
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { CommandPaletteContent } from "../CommandPaletteContent";
|
||||
import type { CommandPaletteActionItem } from "../CommandPalette.logic";
|
||||
import { CommandPaletteResults } from "../CommandPaletteResults";
|
||||
import { PierreEntryIcon } from "../chat/PierreEntryIcon";
|
||||
import {
|
||||
getProjectFilePickerMatches,
|
||||
PROJECT_FILE_PICKER_RESULT_LIMIT,
|
||||
} from "../files/ProjectFilePicker.logic";
|
||||
import { useProjectFilePickerQuery } from "../files/projectFilesQueryState";
|
||||
import { CommandDialog, CommandDialogPopup } from "../ui/command";
|
||||
|
||||
function emptyMessage(query: string, error: string | null, isPending: boolean): string {
|
||||
if (error) return error;
|
||||
if (isPending) return query.trim() ? "Searching project files…" : "Indexing project files…";
|
||||
return query.trim() ? "No matching image files." : "No image files found.";
|
||||
}
|
||||
|
||||
export function ProjectFaviconPickerDialog(props: {
|
||||
readonly cwd: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly onOpenChange: (open: boolean) => void;
|
||||
readonly onSelect: (path: string) => void;
|
||||
readonly open: boolean;
|
||||
readonly projectName: string;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
|
||||
const result = useProjectFilePickerQuery(
|
||||
props.environmentId,
|
||||
props.cwd,
|
||||
query,
|
||||
PROJECT_FILE_PICKER_RESULT_LIMIT,
|
||||
{ imageOnly: true },
|
||||
);
|
||||
const { resolvedTheme } = useTheme();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const items = useMemo<CommandPaletteActionItem[]>(
|
||||
() =>
|
||||
getProjectFilePickerMatches(result.entries, result.matchedQuery).map((match) => ({
|
||||
kind: "action",
|
||||
value: `project-favicon:${match.path}`,
|
||||
searchTerms: [match.name, match.path],
|
||||
title: match.name,
|
||||
description: match.path,
|
||||
icon: <PierreEntryIcon pathValue={match.path} kind="file" theme={resolvedTheme} />,
|
||||
run: async () => props.onSelect(match.path),
|
||||
})),
|
||||
[props.onSelect, resolvedTheme, result.entries, result.matchedQuery],
|
||||
);
|
||||
|
||||
return (
|
||||
<CommandDialog open={props.open} onOpenChange={props.onOpenChange}>
|
||||
{props.open ? (
|
||||
<CommandDialogPopup
|
||||
aria-label="Choose project icon"
|
||||
className="overflow-hidden p-0"
|
||||
onBackdropPointerDown={() => props.onOpenChange(false)}
|
||||
>
|
||||
<CommandPaletteContent
|
||||
aria-label="Choose project icon"
|
||||
autoHighlight="always"
|
||||
escapeLabel="Close"
|
||||
footerActionLabel="Select icon"
|
||||
inputProps={{ placeholder: "Search image files…" }}
|
||||
mode="none"
|
||||
onItemHighlighted={(value) => {
|
||||
setHighlightedItemValue(typeof value === "string" ? value : null);
|
||||
}}
|
||||
onValueChange={(value) => {
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(value);
|
||||
}}
|
||||
panelClassName="max-h-[min(34rem,76vh)]"
|
||||
testId="project-favicon-picker"
|
||||
value={query}
|
||||
>
|
||||
<CommandPaletteResults
|
||||
groups={
|
||||
items.length > 0
|
||||
? [{ value: "project-favicon-files", label: props.projectName, items }]
|
||||
: []
|
||||
}
|
||||
highlightedItemValue={highlightedItemValue}
|
||||
isActionsOnly={false}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={(item) => {
|
||||
if (item.kind !== "action") return;
|
||||
props.onOpenChange(false);
|
||||
void item.run();
|
||||
}}
|
||||
emptyStateMessage={emptyMessage(query, result.error, result.isPending)}
|
||||
/>
|
||||
</CommandPaletteContent>
|
||||
</CommandDialogPopup>
|
||||
) : null}
|
||||
</CommandDialog>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user