8 Commits
Author SHA1 Message Date
2aad6fc93e feat(config): add OPENCLAUDE_CONFIG_DIR override (#1683)
* feat(config): add OPENCLAUDE_CONFIG_DIR env var as preferred alias for CLAUDE_CONFIG_DIR (#454)

The legacy CLAUDE_CONFIG_DIR name was the only way to point openclaude
at a non-default config home, which leaked Anthropic branding for a
fork that has otherwise rebranded to OpenClaude. Add OPENCLAUDE_CONFIG_DIR
as the preferred name. CLAUDE_CONFIG_DIR continues to work for
backward compatibility; when both are set with different values,
OPENCLAUDE_CONFIG_DIR wins and a one-time warning is logged.

- src/utils/envUtils.ts: introduce resolveConfigDirEnv() that picks
  OPENCLAUDE_CONFIG_DIR over CLAUDE_CONFIG_DIR and emits a conflict
  warning. Memoize cache key now tracks both env vars so changing
  either invalidates the cached result.
- src/utils/env.ts: getGlobalClaudeFile() previously read
  CLAUDE_CONFIG_DIR directly, missing the new alias. Route through
  resolveConfigDirEnv() so the global config file path follows the
  same precedence.
- src/utils/secureStorage/macOsKeychainHelpers.ts: the "is default
  dir" check used by keychain service-name scoping now considers
  both env vars.
- src/utils/swarm/spawnUtils.ts: forward OPENCLAUDE_CONFIG_DIR to
  teammate processes alongside the legacy var.
- src/utils/openclaudePaths.test.ts: +6 unit tests covering the new
  alias, fallthrough, conflict warning, and resolveConfigDirEnv()
  in isolation.
- .env.example: document both env vars and the precedence rule.

Verified locally on Linux: with only OPENCLAUDE_CONFIG_DIR set, with
only CLAUDE_CONFIG_DIR set (legacy still works), with both set
matching (silent), with both set conflicting (warn once + OPENCLAUDE
wins), with neither set (default ~/.openclaude). Memo cache
invalidates across 4 sequential env transitions. Built dist/cli.mjs
honors the new var and emits the conflict warning to the user.

* Fix config-dir warning and docs review findings

Only mark the config-dir conflict warning as emitted when a warning callback actually receives it, add coverage for warn-once and silent callers, and update web configuration docs for OPENCLAUDE_CONFIG_DIR precedence.

# Conflicts:
#	web/src/data/configuration.ts

* Align configuration docs with openclaude paths

Update the configuration page settings-file table to point default users at .openclaude settings and keybindings paths, matching the new config home behavior.

* Align keybindings docs with openclaude config home

Update the keybindings page, keybindings docs data, and skill index to point default users at ~/.openclaude/keybindings.json.

* Align skill and hook labels with openclaude paths

Update bundled config/keybindings skill prompts, public skills docs, hook/trust labels, and the user memory selector to use the active OpenClaude config home paths.

# Conflicts:
#	src/components/TrustDialog/utils.ts
#	src/components/hooks/SelectEventMode.tsx
#	src/skills/bundled/updateConfig.ts
#	src/utils/hooks/hooksSettings.ts

* Resolve config-home paths dynamically in skill prompts

Use runtime settings/keybindings path helpers for bundled skill prompts and the restricted-hooks banner so custom OPENCLAUDE_CONFIG_DIR values are reflected in user-facing guidance.

* Update active command prompts for openclaude paths

Point statusline, setup/onboarding prompts, plugin messages, and the external user-memory warning at the active OpenClaude settings and memory paths.

# Conflicts:
#	src/commands/auto-fix.ts
#	src/commands/onboard-github/onboard-github.tsx
#	src/commands/plugin/ManagePlugins.tsx
#	src/commands/statusline.tsx

* Fix remaining config path review findings

* Cover dynamic config paths in UI and storage tests

* Fix config path smoke failures after rebase

* Fix remaining config path review findings

---------

Co-authored-by: gnanam1990 <gnanasekaran.sekareee@gmail.com>
2026-06-18 08:57:22 +08:00
JATMNandGitHub c3db79832b fix: sandbox temp dir fallback (#1662)
* Fix sandbox temp dir fallback

Probe Claude temp directories before returning them and fall back through platform temp and config-home temp paths when the primary temp base is inaccessible.

Use the resolved Claude temp dir for sandboxed shell cwd tracking and TMPDIR/CLAUDE_TMPDIR propagation so the sandbox allowlist, Bash, and PowerShell providers agree on the writable temp path.

Update @anthropic-ai/sandbox-runtime to 0.0.55 and refresh bun.lock.

Validation: bun install passed after escalation; bun run build passed; python -m pytest -q python/tests passed; bun run typecheck:type-tests passed; git diff --check passed. bun run check still reports full-suite order/global-state failures; focused reruns of the reported failing files passed with a dummy ANTHROPIC_API_KEY. bun run typecheck has pre-existing unrelated repo-wide strictness failures; security:pr-scan fails before scanning on mergeBase.stderr.

* Fix PR typecheck and read-only temp fallback

Handle EROFS as an inaccessible filesystem error for sandbox temp fallback behavior.

Add narrow type annotations and inference fixes so the stricter typecheck job passes.
2026-06-16 15:23:23 +08:00
9755550137 Typecheck/zero tsc errors (#1597)
* ci(typecheck): add error-count ratchet toward zero tsc errors

tsc --noEmit currently reports 697 pre-existing errors (issue #473), so
PRs cannot be gated on a clean typecheck yet. This adds
scripts/typecheck-ratchet.ts and a per-file baseline: CI fails when the
count rises above the baseline (listing exactly which files regressed),
passes at or below it, and --update lowers the baseline to lock in
gains. Wired into pr-checks as its own step; once the baseline reaches
zero the step becomes a plain `bun run typecheck`.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(typecheck): mechanical sweep — 697 → 624 tsc errors

Type-only fixes with no runtime behavior change, except the deliberate
NODE_ENV restorations:

- Restore process.env.NODE_ENV comparisons that the source snapshot had
  baked into the literal "production", making the conditions constant
  (AutoUpdater dev/test skip, useTypeahead, ink devtools injection,
  interactiveHelpers onboarding skip, TestingPermissionTool.isEnabled —
  the last now correctly enables under bun test, +3 tests run green)
- Type stream read helpers in openaiShim/codexShim as
  Bun.ReadableStreamDefaultReadResult<Uint8Array<ArrayBuffer>> and
  annotate throwClassifiedTransportError as never-returning, clearing
  the reader/response undefined cascades (29 errors)
- Delete 14 stale @ts-expect-error directives
- Widen useState/useRef/array generics inferred from null/[] literals
- as-const notification priority/color literals to match Priority
- Accept readonly Tool[] in checkLocalModelContextLoad/getCombinedTools

Baseline lowered via typecheck:ratchet --update; full suite green
(3690 tests), smoke + bundle guard green.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(typecheck): recreate missing modules — 624 → 415 tsc errors

The open snapshot never mirrored ~60 modules; the bundler noop-stubs
them at build time (() => null named exports), so every recreated
module here is runtime-inert by construction: no import-time side
effects, gated features stay off (isAssistantMode/isSkillSearchEnabled
→ false, tools isEnabled → false, dialogs render null), lookups return
empty, telemetry no-ops. Types are honest and derived from importer
usage — no any.

Highlights:
- sdk: runtimeTypes re-exports/aliases, sdkUtilityTypes
  (NonNullableUsage), settingsTypes.generated; coreTypes.generated
  usage fields regenerated as a self-contained structural type (the
  consumer package ships without sdkUtilityTypes/@anthropic-ai/sdk, so
  the generated file must stay dependency-free — generator override
  updated to match, package-consumer-types tests green)
- services: contextCollapse operations/persist/stats, compact
  cachedMicrocompact state/types + reactiveCompact, skillSearch (7
  modules), oauth/types, lsp/types, sessionTranscript
- cli/server/daemon: Transport interface, parseConnectUrl, server/*
  (7), daemon/*, bg/templateJobs/runners; assistant/* (KAIROS), ssh/*
- tools/components: WorkflowTool trio, ReviewArtifact pair,
  OverflowTest/TerminalCapture/VerifyPlanExecution/DiscoverSkills,
  WebBrowserPanel, task dialogs, message variants, ink events/cursor
- types: statusLine, fileSuggestion, notebook, messageQueueTypes;
  SerializedMessage rebuilt as distributed Omit-union so transcript
  guards narrow again; vitest-compat.d.ts mirrors Bun's runtime
  'vitest' → 'bun:test' aliasing
- TS2304 names: ant-model helpers imported from existing antModels.ts,
  inert Ultraplan/Gates/LogoV2 stubs, PromiseWithResolvers local type
- build.ts: ACCEPTABLE_RUNTIME_STUBS emptied — both grandfathered
  bundle-reaching stubs (MonitorMcpDetailDialog,
  VerifyPlanExecutionTool/constants) are now real typed modules, so
  the degrade-on-use debt the guard tracked is retired

Validation: full suite 3690 green, smoke + bundle guard green,
typecheck:type-tests green, sdk package-consumer tests green; baseline
lowered via typecheck:ratchet --update.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(typecheck): reconstruct Message discriminated union — 415 → 342 tsc errors

src/types/message.ts was a stub where all ~40 message type aliases were
'export type X = any'. Bare-any aliases break the one thing the union is
for: narrowing. Type predicates like isHookAttachmentMessage collapsed to
'never' in guard chains, cascading TS2339/TS2345 through utils/messages.ts,
messageFilters.ts, groupToolUses.ts, collapseReadSearch.ts, REPL.tsx,
compact.ts, stopHooks.ts and the message components.

Envelope design (permissive-body discriminated union):
- Each variant declares its literal discriminant(s) — message.type for the
  envelope union (user/assistant/attachment/progress/system), subtype for
  the 17-variant System family — plus the properties constructor functions
  in utils/messages.ts actually populate, with '[key: string]: any' as an
  escape hatch so unreconstructed properties never error.
- UserMessage<C> / AssistantMessage<T> are generic over content shape so
  NormalizedUserMessage / NormalizedAssistantMessage<T> reuse the envelope
  without Omit (Omit over an index-signature type collapses keyof to
  string and silently drops the discriminant, breaking narrowing).
- AssistantMessage.message is a structural AssistantMessageContent<T>, not
  the SDK's BetaMessage: synthetic constructors don't populate every
  SDK-required field (stop_details), and SDK-facing consumers need
  assignability to Record<string, unknown>-style bodies.
- AttachmentMessage<T = Attachment> / ProgressMessage<T = Progress> stay
  generic over their payloads (utils/attachments.ts and Tool.ts types).
- UI wrappers (GroupedToolUseMessage, CollapsedReadSearchGroup,
  CollapsibleMessage, RenderableMessage) and stream/control envelopes
  (StreamEvent over BetaRawMessageStreamEvent, RequestStartEvent,
  TombstoneMessage, ToolUseSummaryMessage) reconstructed from call sites.
- logs.ts SerializedMessage switched from the Omit<Message, never> trick
  (only sound against an any stub) to an Extract-based distributed union,
  keeping TranscriptMessage assignable to Message.

All other touched files are type-level-only adjustments (annotations on
evolving arrays that inferred never[], predicate types, casts in SDK wire
adapters and test fixtures) — no runtime logic changed anywhere; the full
bun test suite passes 3690/0 before and after.

Result: 415 → 342 tsc errors, every never-cascade in the message pipeline
resolved, no file above its per-file baseline (ratchet updated).

Part of issue #473.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(typecheck): narrow unknowns and fix signature drift — 342 → 94 tsc errors

Clears every remaining non-test error. Honest fixes dominate: evolving
array/let/useState/useRef annotations (the repo's noImplicitAny:false
disables evolving types), real type guards over unknown wire payloads,
hoisted react-compiler-style params annotated with their components'
real Props, and callee signature corrections (useRegisterOverlay
optional param, generic useVoiceState<T>, growthbook shim's accepted
refresh-interval param) that each cleared several call sites. Targeted
reason-commented casts only at SDK/stub/wire boundaries; no any, no
new suppressions.

Runtime deviations are confined to already-broken paths: benchmark.ts
imported a function name that never existed (module-load crash),
caches.ts called stub methods unguarded (TypeError for ant-gated
users), messageActions returned undefined from a string function;
CACHE_EDITING_BETA_HEADER is a best-effort reconstruction of a
squash-lost constant, reachable only behind feature-gated first-party
paths (flagged for review).

Also: ConnectorTextBlock gains its wire-proven optional signature
field; MCP server factory ambient types gain close(); ink
render-node-to-output's nodeType cast fixed (intersection was
collapsing the intended widening); upstreamproxy relay normalizes the
socket data union.

Validation: full suite 3690 green, smoke + bundle guard green;
remaining 94 errors are all in test files (PR 5). Baseline lowered via
typecheck:ratchet --update.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(typecheck): clean test typing, gate CI on zero tsc errors — 94 → 0

Closes the typecheck burn-down (issue #473): bun run typecheck now
exits 0 across the whole repo and CI fails on any new error.

Test typing: new src/test/typedMocks.ts centralizes the two bun:test
gaps (asMockFetch — Mock<T> lacks fetch.preconnect; callArgs —
argless-signature mocks collapse mock.calls to []). Beyond the
helpers, fixes are honest: discriminated-union narrowing before
member access, fixture typing with boundary casts, assertion-type
corrections, and two tests realigned to production signatures they
had drifted from (requestLogging logApiCallEnd args,
incrementalTokenCounter tokenBudget rename) with identical assert
outcomes. No assertion semantics changed; all touched suites pass.

CI: the ratchet served its purpose and is retired — pr-checks now
runs a plain `bun run typecheck` step; ratchet script and baseline
deleted.

Burn-down summary across the series: 697 → 624 (mechanical sweep) →
415 (recreate ~60 missing modules) → 342 (Message discriminated
union) → 94 (narrowing + signature drift) → 0 (this PR).

Validation: tsc --noEmit exit 0, full suite 3690 green, smoke +
bundle guard green.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(typecheck): reconcile with upstream parallel typecheck fixes

Upstream landed #1591/#1592/#1595 while this series was in flight,
fixing some of the same errors differently. Rebase resolutions prefer
upstream where it is authoritative: their CACHE_EDITING_BETA_HEADER
value ('cache-editing-2025-12-01', unconditional) replaces this
series' feature-gated reconstruction; their cachedMicrocompact stub
shapes (with their new test file) replace ours, with boundary casts in
claude.ts where the stub's unknown[] edits meet the local pinned
delete-edit shape; their reader/ReadResult stream typing in openaiShim
replaces ours. MessageWithoutProgress now matches its name
(Exclude<NormalizedMessage, ProgressMessage>), reconciling upstream's
RenderableMessage GroupingResult with this series' message union; the
@ts-expect-error upstream added for settingsTypes.generated is removed
since the module now exists.

tsc exit 0; full suite 3697 green (incl. upstream's new
cachedMicrocompact tests); smoke + bundle guard green.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

* fix(sdk): keep result usage counters required, fix assistant stub exports

Addresses jatmn's and chioarub's review on the typecheck PR:

1. SDK usage contract restored: the generated result types' usage now
   keeps input_tokens, output_tokens, cache_creation_input_tokens, and
   cache_read_input_tokens as REQUIRED numbers — result messages are
   populated from QueryEngine.totalUsage (initialized from
   EMPTY_USAGE), so they are always present at runtime and strict
   consumers may sum them without undefined guards. The richer nested
   metadata (cache_creation, server_tool_use, service_tier) is modeled
   explicitly instead of hiding behind the index signature; the nested
   objects carry no index signature so the SDK's interface types stay
   assignable. Generator override updated and artifacts regenerated; a
   new package-consumer type test sums the counters and reads the
   nested fields so this contract cannot silently regress. The
   sessionHistory test fixture now carries all four counters, matching
   runtime shape.

2. Assistant install wizard stub mismatch fixed: dialogLaunchers
   imported NewInstallWizard/computeDefaultInstallDir through a module
   shape cast, but the assistant stub only exported default — a
   guaranteed runtime crash if the gated path lit up. The stub now
   provides real typed exports: a wizard that cancels immediately (so
   the launcher resolves null/user-cancelled instead of hanging on an
   empty dialog) and an inert computeDefaultInstallDir; the unsafe
   cast in dialogLaunchers is gone.

Validation: tsc exit 0; full suite 3698 green (incl. the new consumer
counters test); smoke + bundle guard green.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>

---------

Co-authored-by: OpenClaude <openclaude@gitlawb.com>
2026-06-11 07:59:18 +08:00
4cb963e660 feat(api): improve local provider reliability with readiness and self-healing (#738)
* feat(api): classify openai-compatible provider failures

* Update src/services/api/providerConfig.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/errors.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* feat(api): harden openai-compatible diagnostics and env fallback

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/errors.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/errors.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix openaiShim duplicate requests and diagnostics

* remove unused url from http failure classifier

* dedupe env diagnostic warnings

* Remove hardcoded URLs from OpenAI error tests

Removed hardcoded URLs from network failure classification tests.

* Update providerConfig.envDiagnostics.test.ts

* fix(openai-shim): return successful responses and restore localhost classifier tests

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* feat(provider): add truthful local generation readiness checks

Implement Phase 2 provider readiness behavior by adding structured Ollama generation probes, wiring setup flows to readiness states, extending system-check with generation readiness output, and updating focused tests.

* feat(api): add local self-healing fallback retries

Implement Phase 3 self-healing behavior for local OpenAI-compatible providers: retry base URL fallbacks for localhost resolution and endpoint mismatches, plus capability-gated toolless retry for tool-incompatible local models; include diagnostics and focused tests.

* fix(api): address review blockers for local provider reliability

* Update src/utils/providerDiscovery.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/services/api/openaiShim.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: harden readiness probes and cross-platform test stability

* fix: refresh toolless retry payload and stabilize osc clipboard test

* fix: harden Ollama readiness parsing and redact provider URLs

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-20 16:24:02 +08:00
b3f3dc4e66 Prefer AGENTS.md over CLAUDE.md for project instructions (#439)
* Prefer AGENTS.md over CLAUDE.md for project instructions

* fix: preserve CLAUDE.md fallback behavior

* fix: isolate onboarding tests and preserve legacy init

* fix: restore full fsOperations exports in test mock and align compact cwd

* Fix onboarding test isolation and init migration guidance

* Tighten init prompt coverage and onboarding copy

* Handle nested project instruction paths consistently

* Fix NEW_INIT feature gate for Bun build

---------

Co-authored-by: 赵小落 <zhaoxiaoluo@zhaoxiaoluodeMac-mini.local>
Co-authored-by: zhaomo01 <zhaomo01@baidu.com>
2026-04-12 21:31:33 +08:00
462a985d7e Remove embedded source map directives from tracked sources (#329)
Inline base64 source maps had been checked into tracked src files. This strips those comments from the repository without changing runtime behavior or adding ongoing guardrails, per the requested one-time cleanup scope.

Constraint: Keep this change limited to tracked source cleanup only
Rejected: Add CI/source verification guard | user requested one-time cleanup only
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: If these directives reappear, fix the producing transform instead of reintroducing repo-side cleanup code
Tested: rg -n "sourceMappingURL" ., bun run smoke, bun run verify:privacy, bun run test:provider, npm run test:provider-recommendation
Not-tested: bun run typecheck (repository has many pre-existing unrelated failures)

Co-authored-by: anandh8x <test@example.com>
2026-04-04 21:19:27 +08:00
Reservieren 009c29d318 refactor: update import paths for react/compiler-runtime to react-compiler-runtime
feat: add OpenClaude local agent playbook for setup and usage instructions

chore: implement provider bootstrap script for profile initialization

chore: create provider launch script to manage provider execution

chore: add system check script for runtime diagnostics and validation

feat: implement useEffectEventCompat hook for React 18 compatibility
2026-03-31 22:09:56 -03:00
did:key:z6MkqDnb7Siv3Cwj7pGJq4T5EsUisECqR8KpnDLwcaZq5TPr d2542c9a62 asdf
Squash the current repository state back into one baseline commit while
preserving the README reframing and repository contents.

Constraint: User explicitly requested a single squashed commit with subject "asdf"
Confidence: high
Scope-risk: broad
Reversibility: clean
Directive: This commit intentionally rewrites published history; coordinate before future force-pushes
Tested: git status clean; local history rewritten to one commit; force-pushed main to origin and instructkr
Not-tested: Fresh clone verification after push
2026-03-31 03:34:03 -07:00