Fixes private-board conversation deletion reappearing after refresh.
- board_started now marks conversation is_local=false (server persisted)
- loadConversations explicitly sets is_local=false as safety net
Root cause: private board meetings are persisted server-side as soon as
board_started is emitted (portal intercepts and saves the message), but
the frontend left the conversation marked is_local=true. deleteConversation
skipped the server DELETE for local conversations, so only the in-memory
list was updated; the next refresh reloaded the conversation from SQLite.
Changes:
- chatStream.ts: on board_started, mark the conversation is_local=false
so the server delete is called.
- chatStore.ts: loadConversations() now explicitly sets is_local=false
for anything returned from the server as a safety net.
Type-check passes (existing unrelated test-file node module errors remain).
Captures the private board streaming hang regression (commit 36b0296)
and its fix (commits ed1e289, 0daa4d2, d0fe661). Key learnings:
- All `async for chunk in stream` calls need first-chunk timeout
(DashScope/DeepSeek via LiteLLM occasionally never emit first chunk)
- Mid-stream break must not trigger full-content re-broadcast
(return partial content instead of double-broadcasting)
- Diagnostic pattern: monkey-patch + per-stage timeout to locate hang
Track: bug
Category: runtime-errors
Overlap: low (related streaming docs exist but different root cause)
Code review finding (P2): when chat_stream successfully emits the first
chunk (broadcasted to UI) but then breaks during subsequent chunks, the
fallback path called gateway.chat() and broadcasted the FULL content
via _replay_stream — causing the UI to see partial streamed content
followed by duplicated full content.
Fix: if `total` already contains partial content from first_chunk,
return it directly without calling gateway.chat(). Partial content is
better than duplicated content. The non-streaming fallback only runs
when no chunks were broadcasted (total is empty).
Add test_stream_breaks_after_first_chunk_returns_partial covering this
edge case: first chunk yields "部分内容", second __anext__ raises
RuntimeError. Asserts result is the partial content, gateway.chat() is
never called, and broadcast_event is called exactly once (for the
first chunk only).
Commit 36b0296 changed expert speech generation from gateway.chat()
(non-streaming) to gateway.chat_stream() (streaming) for progressive
UI output. However, DashScope/DeepSeek via LiteLLM occasionally accept
the streaming request but never emit the first SSE chunk — the async
generator hangs indefinitely with no error and no timeout, freezing
the entire board.
Root cause: `async for chunk in gateway.chat_stream(...)` blocks
forever when the provider silently stalls. The moderator path
(gateway.chat) still works because it's synchronous — that's why
the moderator opening always succeeds but experts hang.
Fix: pull the first chunk via `__anext__()` wrapped in
`asyncio.wait_for(timeout=30s)`. If no chunk arrives within 30s,
close the stream and fall back to non-streaming gateway.chat() +
_replay_stream() (which splits the response into small chunks for
progressive UI rendering). This preserves the "逐个输出" UX while
guaranteeing the board never hangs on a stalled streaming provider.
Add 4 unit tests covering:
- Normal streaming works (existing path)
- First-chunk timeout → fallback to chat()
- Empty stream → fallback to chat()
- chat_stream raising → fallback to chat()
E2E verification: 5-expert board with DashScope completes in ~277s
(status=completed), all experts produce content, no hang.
Same branch as the earlier _handle_llm_gateway fix (commit d0fe661).
AgentPool.create_agent() injects only llm_gateway (v2 path) into
ConfigDrivenAgent and never sets the legacy _llm_client field. The
previous _handle_llm_generate implementation gated the entire LLM
call on `self._llm_client is None`, so every expert/board agent
created via the pool silently fell through to the
`llm_generate_no_client` placeholder — which is why the private
board moderator/experts reported "LLM 不可用" even when the gateway
and providers were healthy.
Mirror the same precedence used by `_handle_direct`: prefer
`_llm_gateway` (with agent_name/task_type for usage tracking), fall
back to `_llm_client` for backward compatibility, and only return
the no-client placeholder when both are unavailable.
Add a unit test that constructs an agent with `llm_gateway` only
(_llm_client is None) and asserts the gateway.chat path is taken.
Test / backend-test (pull_request) Has been cancelledDetails
Test / frontend-unit (pull_request) Has been cancelledDetails
Test / api-e2e (pull_request) Has been cancelledDetails
Test / frontend-e2e (pull_request) Has been cancelledDetails
P0 #1: Fix autonomy_paused event deadlock — split _check_autonomy_pause
into _detect_autonomy_pause (non-blocking) + _await_autonomy_resume
(blocking). Caller now yields the pause event BEFORE awaiting resume,
so the frontend receives it and the resume handler doesn't deadlock.
P1 #2+#6: Fix retrieve_prompt_reflection field mapping — read
output_summary/reflection/quality_score from MemoryItem.value dict
(matching EpisodicMemory.search shape) instead of metadata. Score
filtering uses stored quality_score, not search relevance score.
P1 #3: Add optional task_type filter to cleanup_expired so
prompt_reflection TTL cleanup doesn't delete all episodic records.
P1 #4: Disable parallel tool execution in autonomy mode — dangerous
tools must go through _check_autonomy_gate, which only runs in the
serial path.
P1 #5: Add _track_tool_result_for_autonomy to parallel result loop
so tool failures are counted toward the consecutive_failures threshold.
Tests: adapt test_autonomy_paused.py to new detect/await interface;
fix test_lead_reflection_retrieval.py mock shape (fields in value dict).
137 IQ-boost tests pass, ruff clean.
- ReflexionEngine.retrieve_prompt_reflection(): searches EpisodicMemory
for historical reflections on similar task_input, returns best version
by score (defaults min_score=0.5). Non-blocking: failure → None.
- TeamOrchestrator._decompose_task: prepends historical reflection hint
to Lead's planning prompt when reflexion_engine is wired and a
high-score reflection exists. Default prompt preserved on miss/failure.
- 12 unit tests covering retrieve path (7) + decompose integration (5).
Add explicit support for parallel execution of dependency-free subtasks:
- TeamPlan.get_independent_subtasks(): returns phases with depends_on==[]
(introspection entry — topological_sort already groups them in layer 0)
- TeamOrchestrator.MAX_INDEPENDENT_SUBTASKS=10: aligns with router.MAX_EXPERTS
- _rebalance_independent_subtasks(): when Lead over-decomposes (>10
independent subtasks), re-decompose once with merge hint. Fallbacks:
no gateway → keep original; LLM error → keep original; single-phase
fallback → keep original (don't collapse 11→1); still over → return
new (MAX_PHASES truncation handles it)
Tests: 15 new tests covering get_independent_subtasks, topological_sort
layer contract, SharedWorkspace path uniqueness, rebalance (5 paths),
and full execute() integration. Existing TeamOrchestrator tests pass.
Test / backend-test (pull_request) Has been cancelledDetails
Test / frontend-unit (pull_request) Has been cancelledDetails
Test / api-e2e (pull_request) Has been cancelledDetails
Test / frontend-e2e (pull_request) Has been cancelledDetails
Fixes 4 bugs blocking AE1 acceptance scenario (rollup returns 0):
1. Decimal not recognized as numeric: PostgreSQL JSONB returns numbers
as Decimal; _evaluate_rollup's isinstance(v, (int,float)) missed them.
Added _to_float() helper (also excludes bool, an int subclass).
Applied to _evaluate_lookup for JSON serialization safety.
2. add_relation_link clobbers record values: update_record_values does
full-replace, so setting the relation field wiped amount/etc.
Added merge_record_values (|| operator) and switched all relation
link mutations to use it (add + remove + reverse cleanup).
3. enqueue_recalc ON CONFLICT DO NOTHING swallowed re-enqueues: once a
task reached 'done', the unique constraint silently dropped new
requests for the same (record_id, field_id) — field showed stale
data forever. Changed to ON CONFLICT DO UPDATE: reset done/error
tasks to pending; leave pending/calculating as-is (no double-process).
4. No cross-table recalc on record update: update_record_values only
triggered recalc on the record's own table; rollup on the target
table never updated when source values changed. Added
_trigger_cross_table_recalc() — finds relation fields on the
record's table, triggers recalc on linked target records.
Tests:
- AE1 acceptance: 3 e2e tests (SUM on insert, update-triggered recalc,
AVG aggregation) — all pass against real PG.
- Bidirectional relation deletion: verifies _cleanup_reverse_link
removes source from target's reverse field.
- SSRF guard: 3 tests blocking loopback, private IP, non-HTTP scheme.
- Updated test_recalc_deduplication for new ON CONFLICT DO UPDATE
semantics (returns existing task, not None).
- Fixed test_crash_recovery to use stale_threshold=0 (was always broken
with default 600s threshold).
lfg Step 3 (ce-simplify-code) — 16 files, -89 net lines.
P1 fixes (functional):
- audit.py / scim/router.py: fix OTel span leak — start_span() returned a
context manager but was used as a plain object, so spans never ended
and never exported. Wrap in `with`.
- helm chart: split combined `redisPgPasswords` slot (single JSON key)
into `redisPassword` + `postgresPassword` slots — the combined `key`
field was dead config never referenced by any template; deployment.yaml
hardcoded `redis-password`/`postgres-password` keys were inconsistent
with values.yaml schema.
P2 dedup (reuse):
- Promote `resolve_auth_db_path()` to models.py (canonical); remove 3
duplicate `_resolve_db_path` defs in oidc.py / saml.py / audit.py.
- Reuse `_now_iso` from models.py; remove 5 duplicates across audit /
oidc / saml / scim / local providers.
- Reuse `_row_to_user` from local.py in oidc.py / saml.py (verbatim
copies removed).
- pii_filter._redact: collapse redundant `finditer` + `sub` (2 regex
passes + 2x sha256 per match on hot path) into a single `sub` with a
callback that collects matches and computes hashes once.
P3 simplifications:
- RoleChangeRequest.role: `str` + manual `if not in (...)` → `Literal`
(Pydantic validates automatically).
- Extract `_record_pii_metrics(status, redacted_count)` helper to dedup
3 nearly-identical OTel metric emission blocks.
- Extract `LLMGateway._record_prompt_cache_metric(usage, model)` to dedup
non-stream + stream cache hit/miss counters; switch to use the
`TokenUsage.cache_hit` property (previously added but unused).
- middleware: split `WHITELIST_PATHS` + `PREFIX_MATCH_PATHS` (redundant
cross-reference) into `WHITELIST_PATHS` (exact) + `PREFIX_WHITELIST_PATHS`
(prefix) — single source of truth per kind.
- OIDC token exchange: replace f-string form body with `urlencode` to
correctly escape `&` / `=` in code / redirect_uri.
- auth.py OIDC redirect route: replace hand-rolled `url.split("state=")`
with `urlparse + parse_qs`.
- PII module docstring: clarify that `PIIMatch.original` is in-memory
only (must not be logged / persisted) — the previous "仅 hash, 不含
原文" wording was misleading.
Skipped findings (false-positive or not worth):
- OIDC/SAML `_find_or_create_user` JIT 60-line dedup — high blast
radius across SQL + transaction boundaries; defers to dedicated refactor.
- SAML `_extract_host` hand-rolled split — already has ponytail comment;
stdlib `urlparse` swap is behavior-equivalent for current inputs but
changes OneLogin `http_host` field semantics; conservative keep.
- gateway.py department-quota / usage-record sequential await —
concurrency gain unclear when dept count is typically ≤2.
Verification:
- ruff check (scoped to 12 touched files) clean
- ruff format (1 file reformatted)
- pytest (PII + OIDC + SAML + SCIM + audit + bitable + team_orchestrator):
265 passed, 145 skipped (PG/Docker), 0 failures
- helm lint clean; helm template renders correctly for both
sealed-secrets + external-secrets backends
Test / backend-test (pull_request) Has been cancelledDetails
Test / frontend-unit (pull_request) Has been cancelledDetails
Test / api-e2e (pull_request) Has been cancelledDetails
Test / frontend-e2e (pull_request) Has been cancelledDetails
P1#1 config_driven: propagate trace_outcome into output_data so
lifecycle._is_failure_path() detects non-success outcomes
P1#2 portal: route through ConfigDrivenAgent.execute_stream (not
react_engine.execute_stream directly) so evolution hooks fire
and trace_outcome propagates; add pre-built messages support in
_build_llm_messages
P1#3 sandbox: make network_block reentrant via module-level reference
counter + threading.Lock - concurrent VERIFICATION phases no
longer permanently block all new connections
P1#4 chat: replace dead isinstance(_PlanExecEngine) check with
hasattr(_spec_review_handler) to wire the spec review gate
P1#5 plan_exec_engine: complete max_reflections threading chain
(PlanExecEngine + ReActStepExecutor constructors)
P1#6 plan_exec_engine: enforce phase budgets (max_steps from
phase_budgets, not hardcoded 5)
P1#7 plan_exec_engine: use current plan (not stale plan var) in
aggregation after replan
P1#8 plan_exec_engine: map failure to failed status (not success)
P1#9 app: add drain timeout for pending evolution tasks on shutdown
P1#10 portal: handle spec_review_reply in WS handler
P1#11 chat: persist spec_review_request/reply/timeout to conversation
store so reload can reconstruct gate state
Tests: 116 related tests pass; 26 pre-existing failures unchanged
(stash-verified). ruff lint clean.
Add docs/solutions/architecture-patterns/bitable-agent-tool-parity-patterns.md
capturing three architecture patterns from U6 (R15a):
- Dual-sync action registration (KTD10): handlers dict + input_schema.enum
- 404-before-403 ownership check (KTD9): prevent existence leak via DELETE
- 409 last-view protection: prevent invalid zero-view table state
Update residual findings with DR-4 (TOCTOU race in delete_view) and DR-5
(_update_field silent type drop) surfaced in final pre-merge ce-code-review
pass. Both P2, neither blocks merge. Documented in the solutions doc under
Known Limitations with concrete fix paths.