Skip to content

Address user rage-quit feedback across 6 tracks - #13

Merged
Jaiminp007 merged 6 commits into
devfrom
fix/fixed-user-errors
May 7, 2026
Merged

Jaiminp007 merged 6 commits into
devfrom
fix/fixed-user-errors

Conversation

@Jaiminp007

Copy link
Copy Markdown
Collaborator

Summary

Pulled from May 1-3 export analysis. Six related fix tracks landing in one PR.

  • Telemetry: enrich agent.run / command.executed / error.surfaced metadata; classify allowlists keep plugin identifiers private; new sessions get user_id at sync time.
  • Prompt/registry alignment: strip hallucinated tool names from build / research / chat (get_market_overview, save_research_report, websearch, save_*_insight, ...); sandbox the three Finny agents from filesystem access (no read/edit/glob/grep/bash/external_directory).
  • Backtest reliability: permissive symbol resolver (60+ curated symbols spanning crypto / stocks / ETFs, plus any yfinance ticker passes through); shared managed Python venv kills PEP 668 / no-pip failures; structured error attribution with stable error kinds.
  • Algorithm versioning: convex storage rewritten as insert-per-version (was overwriting prior versions and destroying history); saveMode now required on every finny_algorithm_save; new finny_algorithm_versions and finny_algorithm_export tools; TUI version-list dialog.
  • Conversational fit: build-mode completion contract (don't stop before save+backtest+summary); explicit step budgets per agent (build 25 / research 15 / chat 8); inline-answer rule for definitional questions; user-actionable MAX_STEPS prompt.
  • Onboarding: welcome dialog rewrite, /examples template picker (7 strategies), upgrade URL surfaced (https://www.finnyai.tech/pro), compact GettingStartedCard that hides on short terminals.

Removed unrelated cron-feature files (live on adding-cronjobs).

Test plan

  • Cold-start home shows new GettingStartedCard with Browse-7-templates CTA
  • /help dialog fits on screen, lists Free/Lite/Pro plans + upgrade URL
  • /examples opens template picker; clicking a template fills the prompt input immediately
  • Build mode does scaffold → save → backtest → summary in one turn (no premature stop)
  • Mid-build "what is drawdown?" returns 1-3 sentence answer + chat-mode tip + continue prompt
  • Save → tweak → re-save with saveMode:version preserves both versions in My Algos → Versions
  • finny_algorithm_export writes the file via Node fs (bypasses generic write tool)
  • Backtest with BTCUSD / BTC-USD / BTC/USD / btc all normalize and run
  • Backtest with FOOBAR returns clean (unknown_symbol) error after yfinance no-data
  • Cold venv: rm -rf ~/.local/share/finny/python-env then run a backtest
  • Ctrl-C twice during a prompt → toast → /retry re-submits last text
  • Disconnect network → toast → ↑ restores prompt
  • FINNY_TELEMETRY_DEBUG=1 shows rich agent.run / command.executed metadata

- Telemetry: enrich agent.run / command.executed / error.surfaced
  metadata; classify allowlists keep plugin identifiers private;
  new sessions get user_id at sync time.
- Prompt/registry: strip hallucinated tool names from build /
  research / chat (get_market_overview, save_research_report,
  websearch, ...); sandbox the three agents from filesystem access.
- Backtest reliability: permissive symbol resolver (60+ curated +
  yfinance pass-through); shared managed Python venv kills PEP 668;
  structured error attribution.
- Algorithm versioning: insert-per-version storage (was overwriting
  history); saveMode required; new finny_algorithm_versions and
  finny_algorithm_export tools; TUI version-list dialog.
- Conversational fit: completion contract (don't stop before
  save+backtest+summary); explicit step budgets; inline-answer rule
  for definitional questions.
- Onboarding: welcome dialog rewrite, /examples templates picker
  (7 strategies), upgrade URL surfaced, compact GettingStartedCard.

Removed unrelated cron-feature files (live on adding-cronjobs branch).
Copilot AI review requested due to automatic review settings May 6, 2026 20:17

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR batches several “rage-quit” fixes across Finny/OpenCode: richer privacy-safe telemetry, tighter agent tool/prompt alignment (including filesystem sandboxing), improved backtest reliability via a managed Python venv + symbol normalization, algorithm version-history preservation + export tooling, and multiple TUI UX/onboarding updates.

Changes:

  • Added a curated+permissive symbol registry and normalized backtest error attribution (stable error kinds + improved symbol handling).
  • Implemented algorithm versioning as append-only (per-version rows) with new tools/UI for listing versions and exporting a specific version to disk.
  • Introduced managed shared Python venv setup and new market-data tools (finny_get_quote, finny_get_history), plus multiple TUI usability improvements (/examples templates, /retry, help dialog, onboarding card).

Reviewed changes

Copilot reviewed 38 out of 39 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
packages/opencode/test/backtest/symbol-normalize.test.ts Adds tests for symbol normalization and fetch-error classification.
packages/opencode/src/tool/registry.ts Registers new tools (quote/history + algorithm versions/export).
packages/opencode/src/tool/quote.ts New finny_get_quote tool backed by yfinance via managed venv.
packages/opencode/src/tool/price-history.ts New finny_get_history tool to fetch OHLCV bars via yfinance.
packages/opencode/src/tool/algorithm-versions.ts New finny_algorithm_versions tool to list lineage versions.
packages/opencode/src/tool/algorithm-save.txt Updates tool guidance: saveMode required + version history semantics.
packages/opencode/src/tool/algorithm-save.ts Enforces saveMode and formats conflicts via tagged errors.
packages/opencode/src/tool/algorithm-export.ts New finny_algorithm_export tool to write a saved version to disk.
packages/opencode/src/storage/convex/algorithms.ts Updates Convex client API for insert-per-version + version reads.
packages/opencode/src/session/prompt/max-steps.txt Tightens MAX_STEPS user-facing response structure.
packages/opencode/src/server/instance/session.ts Tracks agent.run on completion with privacy-safe model/provider classification.
packages/opencode/src/python/env.ts Introduces shared managed Python venv + lazy pip installs.
packages/opencode/src/plan/index.ts Adds Plan.UPGRADE_URL as a single CTA source of truth.
packages/opencode/src/live/python-env.ts Refactors live env to reuse the shared managed Python env helper.
packages/opencode/src/device/index.ts Documents DeviceProfile.userId() as the canonical install user id.
packages/opencode/src/data/symbols.ts Adds symbol registry + permissive resolver + prompt placeholder rendering.
packages/opencode/src/cli/cmd/tui/ui/dialog-help.tsx Reworks help dialog into a scrollable onboarding/plan overview.
packages/opencode/src/cli/cmd/tui/ui/dialog-examples.tsx Adds /examples strategy template picker dialog.
packages/opencode/src/cli/cmd/tui/routes/session/index.tsx Clears initialPrompt after seeding to avoid stale re-seeding.
packages/opencode/src/cli/cmd/tui/routes/home.tsx Adds GettingStarted gating by terminal height + route initialPrompt handling.
packages/opencode/src/cli/cmd/tui/routes/algorithms.tsx Adds “Versions” action to open version list dialog per algorithm.
packages/opencode/src/cli/cmd/tui/context/route.tsx Uses reconcile navigation + adds clearInitialPrompt() helper.
packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx Adds /retry command and improves submit-failure UX with toasts/logging.
packages/opencode/src/cli/cmd/tui/component/dialog-command.tsx Adds privacy-safe command telemetry classification.
packages/opencode/src/cli/cmd/tui/component/dialog-algorithm-versions.tsx New dialog to browse versions and open code viewer per version.
packages/opencode/src/cli/cmd/tui/component/card-getting-started.tsx Simplifies getting-started card and links to template browser.
packages/opencode/src/cli/cmd/tui/app.tsx Adds /examples command and enhances error telemetry bucketing.
packages/opencode/src/backtest/runner.ts Adds symbol normalization, managed venv usage, and stable error kinds.
packages/opencode/src/analytics/session-sync.ts Injects user_id into Convex session rows at sync time.
packages/opencode/src/analytics/classify.ts Adds allowlists to bucket plugin/user identifiers as “custom”.
packages/opencode/src/algorithm/index.ts Implements explicit save-mode semantics + version listing/export helpers.
packages/opencode/src/agent/prompt/finny-research.txt Updates tool list/instructions; adds sandbox and symbol placeholder.
packages/opencode/src/agent/prompt/finny-chat.txt Updates tool list/instructions; adds sandbox and symbol placeholder.
packages/opencode/src/agent/prompt/finny-build.txt Updates tool list/instructions; adds sandbox, completion contract, saveMode rules.
packages/opencode/src/agent/agent.ts Renders prompts with supported symbols + adds Finny sandbox + step budgets.
package.json Adds dev:schedule script.
convex/schema.ts Adds algorithm version index and documents per-version row model.
convex/algoclashAlgorithms.ts Replaces upsert with insert-per-version + adds version queries + lineage-wide status/remove.
bun.lock Adds workspace entry for @finny/schedule-status.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +20 to +35
function makeQuoteScript(yfSymbol: string): string {
// yfinance is guaranteed to be installed by the managed venv before this
// script runs (see ensurePythonEnv call below). No subprocess pip install
// needed — and on PEP 668 / no-pip Linux that fallback was broken anyway.
return `
import json, sys
import yfinance as yf

t = yf.Ticker("${yfSymbol}")
df = t.history(period="2d", interval="1m")
if df.empty:
df = t.history(period="5d", interval="1h")
if df.empty:
print(json.dumps({"error": "no data"}))
sys.exit(1)

Comment on lines +56 to +65
return `
import json, sys
import yfinance as yf

t = yf.Ticker("${yfSymbol}")
df = t.history(period="${period}", interval="${interval}")
if df.empty:
print(json.dumps({"error": "no data"}))
sys.exit(1)

Comment on lines +14 to +22
const YF_INTERVAL: Record<Interval, string> = {
"1m": "1m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "1h",
"4h": "1h", // yfinance has no native 4h; client-side resampling deferred
"1d": "1d",
}
Comment on lines +46 to +55
// Resolve full destination first so the permission prompt shows the
// real path the user will see written.
const destPath = path.resolve(expandHome(params.destPath))
if (!path.isAbsolute(destPath)) {
return {
title: "Bad destPath",
output: `destPath must be absolute (got "${params.destPath}").`,
metadata: { blocked: true },
}
}
Comment on lines +27 to +38
let scrollRef: any
useKeyboard((evt) => {
if (!scrollRef) return
if (evt.name === "up" || (evt.ctrl && evt.name === "p")) {
scrollRef.scrollBy(-1)
evt.preventDefault()
}
if (evt.name === "down" || (evt.ctrl && evt.name === "n")) {
scrollRef.scrollBy(1)
evt.preventDefault()
}
})
Comment thread convex/algoclashAlgorithms.ts Outdated
Comment on lines +58 to +59
await ctx.db.patch(latest._id, { config: args.config, time_updated: Date.now() })
return { ...latest, config: args.config }
Comment on lines +18 to +28
The complete list of tools you actually have. ANYTHING NOT ON THIS LIST DOES NOT EXIST — do not invent names like `get_market_overview`, `get_portfolio_summary`, `get_news_guidance`, `save_chat_insight`, etc. Calling unregistered tools fails with an "invalid tool" error.

### Market Data
- **finny_get_quote** — Latest quote (price, OHLCV, timestamp) for a supported symbol. Use for "what's the price of X?" questions.
- **finny_get_history** — Historical OHLCV bars (interval 1m–1d, limit up to 500). Use to ground analysis in real numbers; compute indicators (RSI, stddev, correlations) yourself from the rows.

### Algorithm Browsing (read-only here — saving / editing belongs to Build mode)
- **finny_algorithm_list** — List all saved algorithms (one per lineage, latest version each).
- **finny_algorithm_get** — Read a specific algorithm's full code (latest version).
- **finny_algorithm_versions** — List every saved version of one algorithm.

- quote.ts / price-history.ts: exit 0 (not 1) when emitting the
  {"error":"no data"} JSON sentinel so the TS caller can map it to
  the no_data branch instead of falling through to fetch_failed.
- price-history.ts: drop "4h" interval entirely — yfinance has no
  native 4h bars and the previous alias to 1h was lying about bar
  size in the response.
- algorithm-export.ts: validate destPath absoluteness on the
  EXPANDED path (post-`~` expansion, pre-resolve). path.resolve()
  always returns absolute by prefixing cwd, so the old check was
  unreachable.
- dialog-algorithm-versions.tsx: handle escape in useKeyboard so
  the "esc close" footer hint actually works (was mouse-only).
- algoclashAlgorithms.patchLatestConfig: return the new
  time_updated alongside the patched row so callers don't show
  stale timestamps.
- finny-chat.txt: list finny_algorithm_set_params explicitly under
  Available Tools — chat is told to call it but the tool wasn't on
  the published list.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 38 out of 39 changed files in this pull request and generated 12 comments.

import type { Algorithm } from "@/algorithm"
import { FINNY_BROKER_PY } from "./broker-py"
import { ensurePythonEnv } from "@/python/env"
import { resolveSymbol, SUPPORTED_SYMBOLS } from "@/data/symbols"
Comment thread packages/opencode/src/data/symbols.ts Outdated
Comment on lines +159 to +163
// (3) bare stock/ETF ticker — assume yfinance has it.
if (looksLikeStockTicker(upper)) {
return { name: upper, kind: "stock", yfinance: upper, canonical: upper, unknown: true }
}

Comment on lines 78 to 80
### Web (optional, for ticker disambiguation, docs, recent news)
- `webfetch` - Fetch a specific URL
- `websearch` - Search the web

### Insights
- `save_build_insight` - Save coding learnings, bug fixes, patterns
- `list_build_insights` - Review saved insights
- `webfetch` - Fetch a specific URL. There is NO `websearch` tool in this build — if you need to search, use `webfetch` against a known search-results URL or skip it.

Comment on lines +33 to +35
### Web
- **webfetch** — Fetch a specific URL (filings, articles, docs) when the user gives one. There is NO websearch tool in this build.

Comment on lines +38 to +41
### Web Tools
- **webfetch** - Fetch a specific URL (filings, articles, docs) when you have a known source. There is NO websearch tool in this build — if you need search, fall back to asking the user for a URL or skipping web context.

### Research Report Tools
- **save_research_report** - Save your research to a markdown file
- Required: `title`, `symbol`, `summary`
- Optional: `strategy_type`, `market_analysis`, `technical_analysis`,
`strategy_recommendation`, `risk_parameters`, `additional_notes`
- Saves to: .finny/research/<timestamp>-<symbol>.md
Use webfetch to ground analysis in current real-world context — earnings, macro events, regulatory news — that the price/indicator tools alone won't surface.
Comment on lines +137 to +140
const result = await Process.run([pythonCmd, scriptPath], {
cwd: tmpDir,
nothrow: true,
})
Comment thread packages/opencode/src/python/env.ts Outdated
Comment on lines +122 to +126
if (!(await exists(PY_BIN))) {
await createVenv(onProgress)
}

const missing: string[] = []
Comment on lines +92 to +96
// still gets created, just without ownership for that one session.
const user_id = await DeviceProfile.userId().catch(() => undefined)
// No upsert mutation server-side — try create, swallow duplicate errors.
// Rare path (once per session per process), so the extra round-trip is fine.
await ConvexSessions.create(Session.toRow(sess) as any).catch((err) => {
await ConvexSessions.create({ ...(Session.toRow(sess) as any), user_id }).catch((err) => {
</scrollbox>

<text fg={theme.textMuted}>
<span style={{ fg: theme.text }}>↑/↓</span> scroll · <span style={{ fg: theme.text }}>esc</span> close
Comment on lines +128 to +129
<span style={{ fg: theme.text }}>↑/↓</span> scroll · <span style={{ fg: theme.text }}>click</span> a template ·{" "}
<span style={{ fg: theme.text }}>esc</span> close
- runner.ts: drop unused SUPPORTED_SYMBOLS import (became dead when
  the suggestions list was inlined to a top-8 array).
- data/symbols.ts: check known crypto bases (PEPE / SHIB / BONK /
  WIF / etc.) BEFORE the generic 1-5-caps stock-ticker fallback.
  Without the reorder, 4-letter crypto bases were misrouted to
  yfinance equities.
- agent/agent.ts: deny `websearch` in the Finny filesystem sandbox so
  the runtime matches what build / research / chat prompts already
  advertise ("there is no websearch tool"). Removes the conflicting
  instruction the model could exploit by calling the still-registered
  search tool.
- finny-research.txt: drop `4h` from the documented finny_get_history
  intervals — the tool schema removed it for the same lying-bar-size
  reason and prompt was out of date.
- quote.ts / price-history.ts: pass `ctx.abort` and a wall-clock
  `timeout` to Process.run so a stalled yfinance fetch can't tie up
  the session forever (30s for quote, 60s for history).
- python/env.ts: in-process Promise dedup on ensurePythonEnv so
  parallel callers (quote+history+backtest in one turn) don't race
  through createVenv / pipInstall against the same directory.
- session-sync.ts: only set user_id on the Convex create payload
  when DeviceProfile.userId() resolved. Spreading
  `{user_id: undefined}` was getting rejected by Convex's optional
  arg validator on devices where the lookup failed.
- dialog-help.tsx / dialog-examples.tsx: wire up ↑/↓/PgUp/PgDn key
  handlers to scroll the scrollbox. Footers advertised scrolling
  but only escape was actually handled.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 38 out of 39 changed files in this pull request and generated 3 comments.

Comments suppressed due to low confidence (2)

packages/opencode/src/backtest/runner.ts:587

  • config.symbol is normalized before configOverrides are merged. If configOverrides includes symbol, the override can reintroduce a non-canonical value (e.g. "btcusdt"), undoing the normalization guarantees and potentially changing error attribution. Normalize the final config.symbol after applying overrides (and/or explicitly normalize configOverrides.symbol when present).
      // Canonicalize the configured symbol up front so a mismatch between
      // strategy code (e.g. "BTCUSDT") and the data layer (yfinance "BTC-USD")
      // can never silently produce empty data — and so failures at this layer
      // get an `unknown_symbol` attribution instead of a generic stderr blob.
      if (config.symbol) {
        try {
          config.symbol = normalizeSymbol(String(config.symbol))
        } catch (e) {
          if (e instanceof UnknownSymbolError) {
            return {
              ok: false,
              error: e.message,
              kind: "unknown_symbol",
              suggestions: e.suggestions,
            }
          }
          throw e
        }
      }

      if (configOverrides) {
        for (const [k, v] of Object.entries(configOverrides)) {
          const isPlainObj = (x: unknown): x is Record<string, unknown> =>
            x !== null && typeof x === "object" && !Array.isArray(x)
          if (isPlainObj(v) && isPlainObj(config[k])) {
            config[k] = { ...config[k], ...v }
          } else {
            config[k] = v
          }
        }
      }

packages/opencode/src/backtest/runner.ts:651

  • The yfinance fetch/backtest subprocesses are run without a timeout (or any upper bound). If yfinance/network hangs, BacktestRunner.run() can block indefinitely and tie up the UI/tool executor. Quote/history tools added explicit timeouts; consider doing the same here (and, if possible, wire an abort signal from the caller).
      // Fetch market data
      const fetchResult = await Process.run([pythonCmd, "_fetch_data.py"], {
        cwd: tmpDir,
        nothrow: true,
      })

      if (fetchResult.code !== 0) {
        const stderr = fetchResult.stderr.toString().trim()
        const { kind, detail } = classifyFetchError(stderr)
        const human =
          kind === "unknown_symbol"
            ? `Backtest failed (unknown_symbol): ${symbol} is not a recognized symbol. ` +
              `Try one of: ${SUPPORTED_CANONICAL.join(", ")}.`
            : kind === "empty_window"
              ? `Backtest failed (empty_window): no bars for ${symbol} between ${start} and ${end} at ${yfinanceInterval}. Try a wider duration or a coarser interval.`
              : kind === "network"
                ? `Backtest failed (network): could not reach the market data provider. ${detail}`
                : kind === "python_env"
                  ? `Backtest failed (python_env): ${detail}`
                  : `Backtest failed: ${detail || "unknown error"}`
        return {
          ok: false,
          error: human,
          kind,
          suggestions: kind === "unknown_symbol" ? SUPPORTED_CANONICAL : undefined,
        }
      }

      // Run backtest
      const backtestResult = await Process.run(
        [pythonCmd, "backtest.py", "--csv", csvPath, "--config", "config.json", "--interval", interval, "--capital", capital],
        {
          cwd: tmpDir,
          nothrow: true,
        },
      )

Comment on lines +160 to +161
print(f"__FINNY_FETCH_ERROR__: network: ${symbol}: {e}", file=sys.stderr)
sys.exit(4)
Comment on lines 81 to +111
const existing = await ConvexAlgorithms.getByName(userId, input.name)
const version = existing ? existing.version + 1 : 1
const algorithmId = existing?.algorithmId ?? crypto.randomUUID()

let algorithmId: string
let version: number
let time_created: number
let status: string

if (input.saveMode === "new") {
if (existing) {
throw new SaveModeConflictError(
"name_taken",
`Algorithm "${input.name}" already exists. Either choose a different name or use saveMode: "version" to bump it.`,
deriveSiblingName(input.name),
)
}
algorithmId = crypto.randomUUID()
version = 1
time_created = now
status = "draft"
} else {
if (!existing) {
throw new SaveModeConflictError(
"no_existing_to_version",
`Cannot version-bump "${input.name}" — no existing algorithm with that name. Use saveMode: "new".`,
)
}
algorithmId = existing.algorithmId
version = existing.version + 1
time_created = existing.time_created
status = existing.status ?? "draft"
}
Comment on lines +40 to +47
test("wider crypto base outside the supported set still canonicalizes", () => {
// XRP, DOGE etc. are in CRYPTO_BASES but not in the user-facing
// SUPPORTED_SYMBOLS list — the normalizer should still produce a
// sane pair so legacy algorithms don't break.
expect(normalizeSymbol("XRP")).toBe("XRP/USD")
expect(normalizeSymbol("DOGE-USD")).toBe("DOGE/USD")
expect(normalizeSymbol("XRPUSDT")).toBe("XRP/USD")
})
- runner.ts (_fetch_data.py): unknown exception classes now emit
  "internal" sentinel (exit 6) instead of falling through to
  "network" (exit 4). Misclassification produced misleading user
  errors that blamed connectivity for unrelated failures.
- runner.ts: re-normalize config.symbol AFTER configOverrides have
  been merged. Without the second pass, an override (e.g. a sweep
  passing "btcusdt") could undo the up-front canonicalization and
  silently produce empty yfinance results.
- runner.ts: timeout on both Process.run subprocess calls
  (2 min for fetch, 5 min for backtest). Without these, a stalled
  yfinance pull or runaway strategy could hang the tool executor
  indefinitely. Matches the timeouts already on quote / history.
- algorithm/index.ts + storage/convex/algorithms.ts +
  convex/algoclashAlgorithms.ts: version assignment moved
  server-side so it's atomic. The mutation now scans existing rows
  for the lineage and picks max+1 inside the Convex transaction.
  Concurrent saves from multiple devices can no longer collide on
  the (algorithmId, version) tuple.
- test/symbol-normalize.test.ts: drop stale comment claiming XRP
  and DOGE aren't in SUPPORTED_SYMBOLS — they were added to the
  curated list in this PR.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 38 out of 39 changed files in this pull request and generated 2 comments.

Comment on lines +33 to +35
function expandHome(p: string): string {
if (p.startsWith("~/") || p === "~") return path.join(os.homedir(), p.slice(1))
return p
Comment thread packages/opencode/src/python/env.ts Outdated
Comment on lines +119 to +156
* tools firing in parallel during a single agent turn) are coalesced via
* the `inflight` Map keyed by the install target. Without this, two cold
* callers would race through `createVenv` and `pipInstall` against the
* same directory, occasionally corrupting the env or producing flaky
* "module not found" errors. Cross-process locking (e.g. when multiple
* finny instances run concurrently) is intentionally not handled here —
* callers in that scenario should retry or run `Python.reset()`.
*/
const inflight = new Map<string, Promise<Environment>>()

export async function ensurePythonEnv(
packages: PackageRequirement[],
onProgress: ProgressCallback = () => {},
): Promise<Environment> {
// Stable key over the requested packages so independent callers asking
// for the same set share a single in-flight promise.
const key = packages.map((p) => p.spec).sort().join("|")
const existing = inflight.get(key)
if (existing) return existing

const promise = (async () => {
if (!(await exists(PY_BIN))) {
await createVenv(onProgress)
}
const missing: string[] = []
for (const pkg of packages) {
if (!(await checkPackage(pkg.importCheck))) missing.push(pkg.spec)
}
if (missing.length > 0) {
await pipInstall(missing, onProgress)
}
return { python: PY_BIN, pip: PIP_BIN, envDir: ENV_DIR }
})().finally(() => {
inflight.delete(key)
})

inflight.set(key, promise)
return promise
@Jaiminp007

Copy link
Copy Markdown
Collaborator Author

@copilot apply changes based on the comments in this thread

Copilot AI commented May 7, 2026 •

Copy link
Copy Markdown

@copilot apply changes based on the comments in this thread

Done — I applied the fixes from that review thread. Specifically: ~/... expansion now resolves correctly in algorithm export, and Python env setup/install is now serialized per shared env directory to prevent concurrent cold-start races across different package sets. Addressed in commits 9779f83 and f4569c8.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • https://api.github.com/repos/anomalyco/ghostty-web/tarball/main
    • Triggering command: /home/REDACTED/.bun/bin/bun bun install (http block)

If you need me to access, download, or install something from one of these locations, you can either:

@Jaiminp007
Jaiminp007 merged commit 55cfdc3 into dev May 7, 2026
spandanniroula pushed a commit to spandanniroula/finny that referenced this pull request Jun 12, 2026
Fixes all 17 Copilot comments:

Telemetry opt-out (polarline-markets#1, polarline-markets#2, polarline-markets#3, polarline-markets#9, polarline-markets#16):
- tracker.ts now reads FINNY_TELEMETRY=0 / OPENCODE_TELEMETRY=0 at module
  load, so the opt-out applies in every entrypoint (TUI worker, server,
  CLI), not just the bootstrap path.
- Email dialog auto-prompt and /subscribe slash command also gated on
  Analytics.isEnabled() — email POST goes to the same Convex deployment.

Tracker correctness (polarline-markets#5, polarline-markets#14, polarline-markets#17):
- drain() now also waits for the DeviceProfile.userId() resolution promise,
  not just the post-send promise.
- worker rpc.shutdown() and main-thread thread.ts both call
  Analytics.drain() before tearing down — neither beforeExit nor SIGTERM
  fire on worker.terminate() / process.exit(0).
- beforeExit handler runs at most once per process, preventing an infinite
  drain loop when a hung telemetry request later resolves and re-empties
  the loop.

Privacy (polarline-markets#10, polarline-markets#11, polarline-markets#12):
- Drop process.argv from tui.worker.booted (could include --prompt text
  and project paths).
- error.surfaced now sends only error.name; error messages frequently
  embed user prompt content and local file paths.
- Don't persist the submitted email address to local KV (no reader, just
  unnecessary PII retention).

Email dialog state machine (polarline-markets#4, polarline-markets#6, polarline-markets#8):
- Wait for kv.ready before evaluating the prompt gate so we don't re-show
  the dialog to users who already submitted/skipped.
- Conditional dismiss handler — only marks "skipped" when no terminal
  status has been set, so a successful submit isn't overwritten by the
  dismiss callback that fires on dialog.clear() and isn't suppressed by
  another dialog replacing this one.

Server-side validation (polarline-markets#15):
- subscribe mutation now rejects empty / oversized / regex-failing emails
  with a ConvexError, so the public Convex client can't bypass the TUI
  regex.

Command coverage (polarline-markets#13):
- Hook Analytics.track() in DialogCommand.trigger() instead of the bus
  event handler. trigger() is the central activation point for palette,
  slash, keybind, plugin, and bus paths — single hook, full coverage,
  no double-counting.

Comment wording (polarline-markets#7):
- bootstrap.ts: "opt-in by default" → "enabled by default" (correct
  description of opt-out semantics).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants