Spaces:
Running
Running
Commit History
Today
-
security(cfskill-run3): deep audit fixes + SonarCloud quality pass
Z UserAudit (cloudflare/security-audit-skill, 7 coverage units, 5 hunter waves): - cache: Redis delPattern prefix->glob — settings/approval-gate invalidation was a silent no-op under Redis (stale contact info + delayed gate close) - jwt/approval: remove hardcoded dev APP_SECRET fallback (public repo secret) - boot: production fatal log when EDGE_HOST_ENFORCE unset (fail-loud) - yt-sync: GET /state now bound to x-sync-ts window (eternal replay lane gone) - paymob webhook: signed currency actually passed to verifyPaymobAmount; promo quota released on terminal FAILED events (+ idempotent re-consume when a later event completes the same order) - push: endpoint rows can no longer be re-bound/cross-deleted between users - sessions: bounded device-metadata strings (column widths) - notification links: protocol-relative URLs rejected; noopener unified; Paymob redirect pinned to accept.paymob.com - deploy.sh: secret gate covers re_/gsk_/nvapi-/modal-/mysql:// families SonarCloud (194 open ->…700d33c
Yesterday
-
fix(mobile+load): full platform review — phone cropping, boot race, hung-provider stalls
Z UserMOBILE (owner report 2026-12-02: admin Users tab clipped on phone): - Users tab approvals rows: min-w-0 + flex-1 on the text block and break-all on the email line — a long unbreakable email token pushed the row past the card edge and the card's overflow-hidden CLIPPED it (reproduced at 320px, row painted 122px off-screen; now wraps inside the row) - Global safety net: html/body overflow-x clip (clip, not hidden — sticky keeps working) so one unbreakable token can never widen the page again - Grid auto-track blowout: 34 grids across 9 files declared cols only at sm/lg (grid gap-4 lg:grid-cols-N) — the implicit auto track sized to max-content, so nowrap content inflated tracks to 715px on a 320px screen (dashboard Recent Activity). Base grid-cols-1 added everywhere - Dialog/AlertDialog primitives: grid-cols-1 on the content grid — the bare shadcn `grid` sized its implicit track to max-content, so dialogs hosting truncate/nowrap rows (lessons manager) scrolled their whol…8054c5d
4 days ago
-
fix(sonar): wave 1 - resolve 511 in-scope findings across 15 app files
Z UserRoot-cause refactors per SonarCloud rules (behavior-preserving): - S3776 cognitive complexity: extracted cohesive helpers in ai-router, chatbot-router, chatbot-refs, chatbot-cables, Admin, ChatBot, skillnet, saadat, pdf, db-init, chat-render, Profile - S3358 nested ternaries -> Record lookups / if-chains / bilingual helper - S7780 String.raw for regex-source literals; S7781 replaceAll - S6594 match->exec / matchAll; S6557 startsWith/endsWith; S7755 .at() - S8786 backtracking: split overlapping-quantifier regexes (citation, refusal, promise/delivery detectors), linear rewrites, documented bounded-pattern NOSONARs where grammar is provably linear - S9382: Promise.all for independent DB upserts; documented NOSONAR for order-dependent/throttled loops only - S3923 real bug: identical-branch ternary in chatbot-cables depthFactor - S6551: honest typed rows instead of String(object) in db-init/sld fence - Source-contract tests re-pinned to the refactored equivalents (admission-gate…9ce5991
7 days ago
-
perf(frontend): react-best-practices pass — 16 files, zero behavior change
Security Audit Run 3Applied the vercel-labs react-best-practices catalog (ECC/vercel skills) across src/. Every fix is behavior-preserving; verified with tsc -b clean, biome 0 errors, eslint 0 errors (1 pre-existing warning, was 2), vitest 1391/1391, vite build OK (precache 1510.06 -> 1500.62 KiB). Code-reviewed per the requesting-code-review skill (read-only reviewer over 12a144f..HEAD); the single Important finding (cv-auto wrapper div would break grid equal-height stretch) is fixed via the repo's own cvClass-prop pattern, and the Register referral snapshot edge is handled with an intentional-deps useMemo. Waterfalls (async-*): - NotificationCenter: VAPID public-key fetch no longer serialized behind an up-to-8s serviceWorker.ready wait on first visits (independent lane, own try/catch — error semantics unchanged) - CertificateView share-image: logo (network) + QR (data-URI) loads start concurrently and are awaited inside their original guarded blocks Re-render (rerender-*): - ui/motion TiltCard +…02797da -
fix(ui): icon beside label on every button + WCAG AA button contrast
Z UserRoot cause (icon stacked ABOVE label): ArcFlashButton — the shared CTA used by the landing hero and AI-assistant section — had gap-2 but NO flex display; Tailwind preflight makes <svg> display:block, so the icon rendered as a block ABOVE the text node. Fix at the component root: inline-flex items-center justify-center — every usage inherits the correct icon-beside-name layout. All 39 raw button sites audited via scanner + manual review; shadcn Button, navLinkBase, admin-sidebar-item and btn-primary already carried flex and were healthy. Contrast (computed WCAG 2.1, brand hues preserved): - .btn-primary white-on-accent 2.80:1 -> 6.89:1 (dark text, bg unchanged; light theme 3.68 -> 5.24). Navbar avatar initials fallback same. - cyan-500->blue-600 + white 2.43:1 -> 5.36:1: gradient start deepened to cyan-700 (Faq support CTA, References buttons/badge, ChatBot send/FAB). - emerald buttons keep their bg, text flipped to near-black #04121c: 2.54/3.77:1 -> 7.47/5.03:1 (Quiz finish, Adm…dec24b8
8 days ago
-
chore(biome): eliminate the organizeImports class repo-wide + close every remaining biome error
Z UserThe three organizeImports errors documented on the avatar feature (review- router, CourseReviews, ChatBot) were one instance of a repo-wide class: 17 assist/source/organizeImports diagnostics across 15 files, all on untouched import blocks. biome check --write applied the safe mechanical reorder (no side-effect-only imports moved — verified against the full diff; the 1391-test suite + tsc + build all pass unchanged). Also closed so `npx biome check .` now exits clean: - email-templates.ts useTemplate: concat → template literal - chatbot-cables-kb.ts noApproximativeNumericConstant ×2: biome-ignore with justification — ac 1.442 Ω/km is measured IEC cable data, NOT the log2(e) constant the rule suspects; auto-fix would have corrupted the table - admin-learning.ts usePlaywrightValidDescribeCallback ×3: biome-ignore — `describe` there is the local error formatter (line 238) for the DB canary diagnostics, not a test-runner describe18afd52 -
feat(avatar): profile photo now surfaces in chat bubbles and course reviews
Z UserOwner request (2026-11-26): the photo uploaded from the profile page (31baaf4) should follow the user across every social surface — chat messages and course reviews — not just the profile/navbar. Server: - review-router.listByCourse now projects userAvatar (users.avatar) with each published review; the sibling lesson-comments router already returned it, so the review list was the odd one out. Client: - CourseReviews.tsx: reviewer avatar circle renders the real photo when set (lazy/async, cover-cropped), initials circle stays the fallback for reviewers without a photo — identical geometry, no layout shift. - ChatBot.tsx: MessageBubble gains a stable userAvatar prop (memo-safe — changes only when the user actually changes their photo); user bubbles wear the real photo in place of the generic User icon chip, icon chip remains the fallback. Assistant bubbles keep the site logo. Admin moderation tables intentionally keep compact initials (moderation rows…2e6a64d -
fix(chatbot): Android back button closes the fullscreen chat instead of leaving the site
Z UserOwner report (2026-11-26): on mobile the chat opens fullscreen (desired), so users press the hardware back button to leave the chat — and the SPA interpreted it as site exit, dropping them out of the platform entirely. Root cause: nothing intercepted the back gesture for the overlay. Android back fired a history pop that react-router honored as real navigation (previous route / site exit) while the fullscreen chat stayed stacked above it visually. Cure — pin-one-entry gate (ChatBot.tsx): - while the fullscreen chat is open on mobile, ONE extra history entry is pinned (same URL, flagged state, router idx preserved) — a same-URL popstate the router reads as a no-op - first back press pops that entry: popstate handler closes the chat only; the site never navigates - the X button and the minimize button consume the pinned entry via history.back() (suppressed pop) so the stack never grows stale entries — the NEXT back press after closing leaves the site normally …ef2f7a3
9 days ago
-
fix(chatbot-docgen): EXPLICIT-REQUEST-ONLY hard gate — no unsolicited file generation, no suggestions (v3.9.1)
ahmdelbaz28-uxOwner directive (2026-11-24, absolute): the permanent file-generation capability stays, but it must NEVER fire without an explicit user request, and the bot must NEVER suggest or offer file generation. - docgenSkillAr/En: removed the auto-trigger clause («يستحق ملفاً» / 'long/tabular enough to deserve one') — long or tabular answers now stay plain prose with no docgen board; added THE FUNDAMENTAL CONDITION block (explicit request = the only key, no self-initiated generation, no suggestion/offer/hint ever, format-name-only mention → prose answer, format follows the user's request verbatim with pdf as the only default when a file IS explicitly requested but no format is named). - Removed the post-delivery offer-to-convert clause («اعرض تحويلها» / 'offer the other on request') — one file per reply, never offer another format; the user asks for it themselves. - docgenQuickAr/En (instant lane): same hard gate in condensed form. - ChatBot.tsx welcome messages (EN+AR): remove…cc06b18 -
feat(chatbot-docgen): permanent in-chat document generation — PDF/DOCX/MD (v3.9.0)
ahmdelbaz28-uxOwner directive (2026-11-24): the bot must ALWAYS be able to build real files for the user inside the chat — no external skill loading, ever. - docgen skill 'docgen-file-export' in SKILL_REGISTRY (category export, thinking+instant): routed on file/export intent, emits a ```docgen DocSpec fence with the immediate-execution contract (file in the FIRST reply, verified numbers only, mandatory citations). - api/lib/docgen/: dependency-free deterministic renderers — PDF written from scratch (Type0/Identity-H CID fonts, two embedded GNU FreeFont subsets, full Arabic presentation-form shaping + simplified UAX#9 bidi with N0 bracket-pair + N1/N2 neutral resolution, RTL tables, page footers), DOCX as stored-ZIP OOXML (bidiVisual RTL tables, w:bidi paragraphs, Word-native shaping), and GFM Markdown. - POST /api/docs/gen: public, stateless, size-capped (60k content chars), typed 422 diagnostics — the /api/diagrams/sld contract. - Chat UI: renderDocgenFence download card (format …aea6c23
12 days ago
-
feat(chatbot): BYOK — bring-your-own-key lane (user's own model first, platform cascade always the baseline)
Z UserOwner contract: the platform ALWAYS runs on owner-managed models. A logged-in user may register ONE custom OpenAI-compatible provider (baseUrl + key + model) via a new key menu inside the chatbot; when enabled, the server tries their endpoint FIRST with the identical system prompt (Saadat identity, citations, ±0.5% discipline) and falls back to the platform cascade on ANY failure — availability can only increase. Vision keeps the platform two-pass pipeline. Backend: - db v16: userAiProviders (1:1 per user, FK cascade, idempotent boot block) - byok-crypto.ts: AES-256-GCM at-rest encryption derived from APP_SECRET (write-only key; only a first3…last4 mask ever leaves the server) - chatbot-byok.ts: provider catalog (OpenRouter/Groq/OpenAI/NVIDIA/Cerebras/ Gemini/custom), config loader (fail-closed SSRF re-check per use), tryByokChat + tryByokStream (same data:{"text"} protocol), testByokProvider - cascade integration: BYOK lane at the TOP of runTextCascade and getStreamResponse; …d241ddf
19 days ago
-
feat(ui): remove the regenerate chip from the chat — owner directive
ahmdelbaz28-ux'بعد رد المساعد الذكي ليظهر في الشات كلمة regenerate reply — مش عاوز دي تظهر في الشات' The 'Regenerate reply' control that appeared under the last assistant reply is gone completely — root removal, not a cosmetic hide: - MessageBubble: chip render block, showRegenerate/onRegenerate props - ChatBot: regenMsgId target computation + handleRegenerate handler - E2E: the regenerate journey spec deleted; new guard spec asserts ZERO regenerate controls (EN/AR text, aria, title) after a real streamed reply — permanent regression protection - typeahead/vision-retry journeys unchanged and still green Verified: tsc clean, build clean, 948/948 unit, 6/6 chat E2E (including the new absence check).b522c6c -
feat(ui): remove fixed WhatsApp FAB — keep assistant + scroll-top as the only fixed widgets
ahmdelbaz28-uxRoot-level removal of the always-on WhatsApp floating button per owner request: - App.tsx: unmount WhatsAppButton (sole mount point) - Delete src/components/WhatsAppButton.tsx (button + welcome bubble + tooltip) - index.css: strip .whatsapp-fab/.whatsapp-pulse/.whatsapp-fab-wrap/enter & welcome keyframes/light-mode rule; re-stack the two remaining FABs — mobile: chatbot now bottom-most (old WhatsApp slot), scroll-top one step above (no empty gap); desktop unchanged (chatbot bottom-right, scroll-top bottom-left) - tailwind.config.js: drop whatsapp-pulse animation + keyframes - ChatBot.tsx / useFabScrollVisibility.ts: purge stale WhatsApp references - Kept intact: admin contact-settings fields (whatsapp number storage) and push-state in-app-browser UA detection (unrelated features) Verified: typecheck clean, 948/948 unit tests, production build OK, 8/8 Playwright DOM checks (no WhatsApp FAB on mobile+desktop, chatbot bottom-most on mobile with scroll-top stacked 10px above, desktop corn…fa37f6d -
feat(chat): proactive professional audit — regenerate chip + vision-retry image carry + type-ahead composer
ahmdelbaz28-uxOwner directive: do what a professional sees is missing, unprompted. Full-audit findings (none previously requested): 1. ↻ REGENERATE — retry existed only on error bubbles; a mediocre reply could never be re-asked without retyping. New chip on the LAST real reply (idle-only, welcome/error-excluded) removes the pair and re-sends the exact question — text AND attached image. 2. ROOT-CURE vision-retry blindness — handleRetry re-sent only the text; the attached image (upload OR live screen frame) was silently dropped, so a retried vision question got answered by a model that could no longer SEE anything. The image now rides the re-send (dataUrl in memory, persisted thumb after reload) and screen_capture re-arms the LIVE SCREEN TEACHER prompt. Same contract applied to regenerate. 3. TYPE-AHEAD — the composer was hard-disabled while streaming; users stared at a frozen input. Now editable mid-stream (send guard + stop button slot make mid-stream sends impossib…8f4e6ee
20 days ago
-
feat(chat): send button transforms into a STOP button that truly aborts the assistant
ahmdelbaz28-uxOwner request (2026-11-14): the moment a message is sent, the send button becomes a stop button; pressing it stops the assistant's response. Root-cure, not a cosmetic abort: - new pure decision table src/lib/chat-stop-flow.ts (15 unit tests): a user stop (abort WITHOUT a generation bump) is distinguished from clearChat — the silent-retry chain can no longer resurrect the killed request, and the non-stream fallback can no longer fire a brand-new fetch after an abort (a listener attached to an already-aborted signal never fired); - partial preservation: text already streamed in is frozen as a real, replayable assistant bubble via one once-guarded commit helper; a stop before any text stays silent — a deliberate stop never shows the soft-busy note; - the stop button also interrupts the cosmetic typewriter reveal (drainReveal observes the stop signal) so the freeze is instant, never up to 45s; - server-side quota already honored: the client abort propagates through the S…3b4f302 -
fix(a11y+lint): zero biome errors — real a11y cures, YT resume race fix, sanitizer widened
ahmdelbaz28-uxBiome 2.6.2 migration (schema matched to CLI) surfaced 31 latent findings; every one is resolved at the root — suppressions only where intentional: REAL BUGS fixed: - YouTubeLessonPlayer auto-resume race: the effect keyed only [ready, lessonId] so progress resolving AFTER player-ready never resumed — lessons silently restarted from 0:00 on slow networks. Now guarded once-per-lesson (resumedLessonRef) with savedProgress in deps; first of (ready AND progress) wins, refetches never re-seek mid-playback. - Admin testimonial form: 6 labels unassociated with controls — proper htmlFor/id pairs so screen readers announce every field. - CourseReviews: stars row gains role=img (aria-label now honored); rating buttons rebuilt as REAL radio inputs inside labels (keyboard-accessible, native checked state); stray <label> with no control becomes a <span>. - ChatBot feedback row: role=group div -> fieldset (border reset via classes). - CommentNudge: role=complementary div -> semantic <a…7e3d3ff
21 days ago
-
fix(chatbot+youtube): deep audit root-cures — reply sanitizer no longer corrupts code/parens, Arabic ؟ sentence-end, INVALID_JSON 400, vision abort, blank-chat rejection, YT placeholder+replay+race cures
ahmdelbaz28-uxCHATBOT (8 fixes): - sanitizeReplyOutput: cleanup is now SEAM-SCOPED — the old global (\s*)/multi-space collapse destroyed every reply's code (f() → f), indentation and ASCII SLD boards; no-CJK text is now byte-identical - finalize-reply: U+061F ؟ added to SENTENCE_END_RE + trim scan — Arabic answers no longer look mid-sentence (needless rescue rounds) and closing questions are never cut off - POST /api/chatbot: malformed JSON now answers 400 INVALID_JSON (the /stream fix finally back-ported; was a false 500 + error log) - normalize: an all-blank conversation is rejected 400 BEFORE dispatch (burned a real provider call) - getChatResponse: permanent (no-keys) failure flag — persistence loop stops retrying the unwalkable, misconfigured deployments answer instantly - vision PASS-1 read now honors the caller abortSignal (gone clients stopped burning vision quota) - think-filter: length-changing lowercase (İ) no longer shifts indices and corrupts output — indexOfCI reports original-string i…c2fa8e6 -
feat(chatbot): LIVE SCREEN TEACHER — the bot sees the user's real screen (ETAP etc.) and guides step-by-step, zero guessing
ahmdelbaz28-uxClient (screen-share lane): - src/lib/screen-share.ts: getDisplayMedia manager — browser picker (explicit consent), snapshot-on-demand frame capture (1440px ladder, 300KB budget), 220px live preview at 2fps, honest teardown on track end. Feature-detected; unsupported browsers never see the button. - ChatBot.tsx: screen-share toggle next to attach, live share bar (preview + pulsing LIVE dot + 'اقرأ الآن' one-tap read), EVERY send while sharing auto-carries the CURRENT frame (manual attachment still wins), capture failure degrades to text-only with an honest notice. Server (teacher mode, no-guessing contract): - chatbot-normalize.ts (extracted, pure): validates image part source:"screen_capture" ONLY on the last user message — unknown tags ignored, data-URL/count/size guards unchanged. - chatbot-vision.ts: dedicated LIVE-SCREEN extraction prompt — verbatim UI reading (window title, menus, tabs, selected element, values), [غير مقروء] for unreadable, 'not visible in th…99b3964 -
feat(chatbot): live screen-context awareness — answers grounded in the user's CURRENT screen
Z UserOwner requirement (2026-11): when a user asks the bot anything about the site, it must answer from the open screen precisely — never guessing. REVIEW (was broken): the client sent {messages, language, chatId, mode} only and the system prompt had no notion of the user's location — every 'this page / this course' question was answered by guesswork. NOW: - src/lib/screen-context.ts — route→exact-navbar-name map (all routes, ar/en), entity registration store (useScreenDetails: cleared on unmount — no stale titles), 6-entry navigation trail, device/auth UI state, sanitized send-time snapshot. Importable in bare Node (guarded browser APIs). - CourseDetail registers the displayed course + open lesson/quiz meta; ArticleDetail registers the article title. - ChatBot tracks navigation (useLocation) and composes a FRESH pageContext per send attempt — a retry after navigation reports the NEW screen. - api/lib/chatbot-screen.ts — untrusted-payload hardening: field whitelist, length cap…062f222
22 days ago
-
perf(react): vercel-react-best-practices sweep — passive viewport listeners
Z UserApplied client-passive-event-listeners where handlers only READ metrics (ChatBot keyboard-viewport listeners x4, ElectricParticles resize) — keeps scrolling smooth while the chat is open. Verified clean against the rule catalog (no churn): memoized MessageBubble/ ChatInputArea, lazy useState initializers (storage + matchMedia), boolean- safe conditionals, no inline components, no render-path RegExp, tree- shakeable imports. tsc clean.1937975 -
security(audit-run1): 7 confirmed findings fixed + chatbot architecture fixes
Z UserSecurity audit run-1 (Cloudflare security-audit-skill, 6 phases, 34 coverage units, 13 independently verified findings) + agent-architecture-audit (12-layer chatbot stack). Shipped fixes: - native-client-detection-token-disclosure (medium): token-source binding — x-renewed-token only for header-sourced tokens; body JWT requires capacitor header AND no auth cookie - promo.leftmost-xff-quota-key (medium): trust-ordered client IP for all three promo throttles; validate probe keyed userId+resolved IP - promo.usage-cap.check-then-act-race (hardening): SELECT ... FOR UPDATE on promoCodes row serializes cap checks inside the payment transaction - ai-router SSRF guard: IPv4-mapped/translated IPv6 decoded to dotted quad before range checks; NAT64 + embedded-IPv4 rejected; redirect:'error' on all key-bearing provider fetches - push-subscription SSRF: push-service host allowlist (subscribe + send time), per-user subscription cap (10), legacy-row healing - ai-diagnostics egress: no …b9b9643
23 days ago
-
perf(cache): bump ?v=2 on login video + logo-circle — HF edge cache holds stale media up to 24h (no purge API available for HF's Cloudflare)
Z UserThe fastdecode video (1.7MB) and 49KB logo were verified live at origin but CF edge kept serving the old cached copies (max-age=86400 + SWR). Query-string versioning gives every user the new assets immediately.6900cd0
24 days ago
-
security(pre-launch-audit-run-2): close HIGH session-revocation hole + chatbot abuse & prompt-leak defenses
Z UserAUTH/SESSIONS: - sessions.revoke.broken-sql (HIGH): drizzle template ${"$"}{users.tokenVersion} emitted invalid MySQL — the tokenVersion bump 500'd and the revoked JWT stayed valid. Fixed to correct interpolation in revoke + revokeAll, with a source regression guard test (api/sessions-router.sql.test.ts). - auth-cache.revocation-window: evictUserAuthCache() called at EVERY revocation site (logout, password change, reset, revoke, revokeAll) — stolen JWT no longer survives 30s in the user cache. - login.per-account-throttle: username-keyed failure bucket (20/15min) before the DB lookup — distributed/IP-rotating stuffing no longer defeats the per-IP login limit. LOG HYGIENE: - Live password-reset / email-verification URLs (working tokens) never logged — hash prefix only. User emails masked via maskEmail() everywhere. CHATBOT (full audit, 10 areas): - daily-quota (HIGH): per-IP 60/day + per-user 200/day UTC buckets gate both /api/chatbot and /api/chatbot/stream before d…07f03e8
-
fix(sld): root-cause repairs — server-side spec repair + img-failure fallback + detector depth
Z UserRoot review of d37025f found two real holes, both closed at the source: 1) 422 → broken <img> in chat: the diagrams GET rendered nothing for a lint-failing spec (overlap, bad/duplicate ids), violating the router's own 'chat never breaks' contract at the last step, and the draw-now chip hid because a shape-valid fence was treated as delivered. Root fix: api/lib/sld/repair.ts — deterministic repair pass (sanitize ids, dedupe with first-occurrence wire mapping, drop dead wires, first-fit overlap relocation down/right/diag). Router GET/POST render the repaired spec; X-Sld-Repair header carries the audit trail; only a still-failing repair answers 422. renderSld/lintSpec untouched. 2) Residual broken-image icons: MessageBubble now attaches error listeners to SLD imgs and swaps failures for a localized note (createElement + textContent only — no model content). Detector depth: past-tense delivery claims (جهزت/حضرت/رسمت + المخطط), 'المخطط التالي/الآتي', EN 'the…e3276d9 -
feat(chat): SLD immediate-draw prompt rule + one-tap 'draw it now' chip
Z UserPrompt (v3.4.0): sldSkill AR/EN gain the IMMEDIATE EXECUTION RULE — sufficient data -> draw the spec board in the FIRST reply (promises, deferrals and permission-asking banned verbatim); one missing essential fact -> exactly ONE question; assumable -> assume + state one line. UI: detectUnfulfilledDiagramPromise() in chat-render.ts flags the last assistant reply when it promised/offered a diagram but carries no valid sld board (token-cap cut, broken fence, bare offer); ChatBot renders the 📐 ارسمها دلوقتي chip under it — one tap sends a language-mirrored follow-up that re-anchors the immediate-draw rule. Tests: 25 renderer cases (promise/offer/delivery vs teaching/imperative phrasing, board-invariance) + 6 quality contracts (happy/edge/failure matrix, thinking-only composition, changelog traceability). 478 total. Metrics snapshot: scripts/prompt-metrics/v3.4.0-sld-draw-now.json.d37025f
-
feat(chatbot+telegram): user feedback loop + Telegram expert brain + join auto-approval
Z User① Feedback loop (real-user fuel for the evolution loop): - chatbotFeedback table (v13 migration, drizzle schema, fail-open lib) - POST /api/chatbot/feedback (public, IP-limited 30/10min, truncated snapshots) - 👍/👎 one-shot buttons on every assistant bubble in the web widget - admin tRPC chatbotFeedback + 'تقييمات الشات بوت' tab: stats cards, satisfaction %, rating filter, export-as-eval-fixtures ② Telegram bot worker (api/lib/telegram-bot.ts, production-only boot): - long-polling getUpdates (offset-confirmed, 409 backoff, 429-aware) - chat_join_request → instant approveChatJoinRequest + group welcome (channels approved silently — no broadcast spam) - private DMs answered by the SAME expert brain (getChatResponse + live course catalog + sanitizeReplyOutput), per-chat 30-min history, 20 msgs/hour per user, 600/day global cap - Arabic-first language resolution (text → language_code → ar) - plain-text chunking at paragraph boundaries (3900 cap), typing …fe662bc -
fix(chatbot): Readonly props + guard-clause narrowing in AttachmentArea (S6759/S3358/S3776)
Z User2198b1b -
refactor(chatbot): close all 15 SonarCloud findings in ChatBot.tsx
Z User- S3776 x2: extract readSseUntilDone (module-level SSE drainer), AttachmentArea + ComposerRow subcomponents — tryStreamOnce and ChatInputArea now well under the complexity cap; behavior byte-identical (leftover-buffer contract kept) - S3358 x5: nested ternaries → independent statements (reply language, attachment area, window shell/inner classes) - S9382 x3: NOSONAR with justification (deliberate 30ms reveal poll + serial retry backoffs — parallelizing would break the never-busy contract) - S6767 x5: NOSONAR with justification (analyzer loses prop tracking through memo(forwardRef()) — all five props destructured + used)49d7b25 -
chore(quality): close all SonarCloud findings in notification stack + biome/hadolint clean
Z UserApplied 4 audited skills end-to-end (triage-vulnerabilities, sonarqube-audit, lint-all, agent-browser). Results: - SonarCloud: all 29 open findings in authored files fixed (S3776 x3 CRITICAL complexity, S4123 real await-precedence bug, S9382 x3 parallelized fan-out/cleanup, S3358/S4043/S4624/S5869/S7780/ S7785/S3735/S5906, python S7632/S1192/S1172/S1186) - lint-all: tsc + ultracheck + eslint + biome + hadolint all exit 0 - vulnerabilities: prod deps 0; deepmerge GHSA low = dev-only, no upstream patch (report-only, forced downgrade rejected) - agent-browser live check: SW activated+controlling, push-sw.js wired, PushManager available, zero console errors on prod build - gates: vitest 344/344, build PWA v1.3.0 51 precache44816d6
-
fix(security): remediate audit run-1 confirmed findings (20)
Z UserCloudflare security-audit skill, full audit of 8ea551b (quick profile, source-only): 34 coverage units, 8 hunter domains, 6 independent verifiers, 21 confirmed + 7 needs_validation records. Artifacts: security-audit-skill/elbaz-platform/run-1/{REPORT,FINDINGS-DETAIL, NEEDS-VALIDATION}.md + findings.json (schema-validated) + coverage-ledger.json. HIGH (both XSS): - chat renderer: extract pure renderer to src/lib/chat-render.ts and escape EVERY text segment before markdown transformation (was: code fences only); href attribute breakout closed; biome-ignore safety claims made true; regression tests (img/script/href-breakout/table-cell payloads) - seo-meta: jsonLdSafeStringify escapes < > U+2028/2029 so stored course titles/FAQ questions cannot break out of the JSON-LD <script> element (the nonce stamper previously re-armed the injected script); tests MEDIUM: - CSRF: same-origin gate in security middleware for POST/PUT/PATCH (Origin/ Referer must match the CORS allowlist when…e5934c3 -
feat(chatbot): table-free replies + guided hands navigation protocol
Z UserLive user feedback: replies contained Markdown tables that this chat UI cannot render (broken pipe grids), and software walkthroughs (ETAP etc.) were described loosely, letting users get stuck on imprecise steps. Prompt layer (api/lib): - reasoningGuard: NEVER use or announce Markdown tables (both modes/languages) - language/format rules: same ban + no table announcements - new guidedNavigationAr/En skill: click-by-click walkthroughs as if holding the user's mouse, committed literal tab/button/page names, ABSOLUTE no-guessing rule (describe location + ask user to confirm when unsure), version statement, verification cue; injected into thinking prompts - instantSkills: condensed click-by-click + no-guessing rule - ETAP expert core rule 16 + quick core: mouse-level paths, never guess names Renderer layer (deterministic enforcement — prompt rules leak, same lesson as the CJK incident): - src/lib/chat-format.ts convertMarkdownTables(): every Markdown table becomes labeled bullets…8ea551b -
feat(chatbot): replace lightning icon with the site logo as the bot identity
Z UserOwner circled the bot avatar (blue Zap) in the chat header and next to message bubbles — all four bot-avatar spots now wear /logo-circle.png: - MessageBubble assistant avatar (h-7 rounded-full, cyan ring) - Chat window header avatar (w-8 rounded-full, green dot kept) - Streaming-response avatar - Typing-indicator avatar User-side icon chip untouched; Zap removed from lucide imports. gates: tsc 0, eslint 0, vitest 250/250, build + PWA v1.3.0f7b31ef
-
fix(chat): vision answers always written by the text cascade — Gemma banned from the chat lane + Arabic writing-quality contract + burst-proof reveal
Z User2026-10-23 user incident (screenshot): instant mode + image → final reply carried corrupted Arabic spelling (verbatim رايت / التعاياث / للاستاتث). Root cause chain, fixed at every layer: SERVER — two-pass vision policy made absolute: - getVisionStreamResponse / getVisionResponse: the legacy 'direct vision streaming' last resorts (Groq Scout / OpenRouter VL writing the FINAL answer) are REMOVED. Vision models only ever READ (PASS 1); the answer writer is ALWAYS the text reasoning cascade. Fallback = the non-streaming text cascade over the SAME (memoized) description → calm busy note. - chatbot-vision.ts: PASS-1 read is MEMOIZED per messages array (WeakMap) — router persistence rounds never re-read the image (was up to 35s/round); read budget 45s→35s, dynamic-pool read 26s→20s, single Groq scout attempt (was ×2), stages gated by remaining budget. - Vision PASS 2 (instant): 10s/12s → 15s/24s budgets — busy moments no longer downgrade the answer writer. ROUTER — Gemma ban…3448e9b -
fix(chat): zero-content stream eliminated — dud winners re-walked, mid-stream rescue now streams, client liveness watchdog
Z UserProd-verified incidents fixed (2026-10-23 live session): - instant lane served model+[DONE] with ZERO text (free-tier model peeked alive via a reasoning delta then died silently) — the user saw the typing indicator then nothing. Root fix at three layers: 1. endpoint: a winner that delivered zero visible content is now treated exactly like a failed walk — the persistence loop re-enters silently until the mode deadline (an empty reply can never reach the client) 2. resilient stream: mid-stream death rescue is now STREAMING (rescueStreamRound pipes the continuation candidate's deltas live through emit, with a 48-char hold-back degenerate-restart guard); the non-streaming rescue remains as fallback 3. client: per-attempt liveness watchdog — 45s of total silence (pings are 4s) aborts the attempt and the silent retry chain takes over; non-stream fallback got a 60s hard cap. A half-dead connection can no longer park the user on 'thinking…' for…ab3b0f9 -
feat(chat): never-busy contract — SSE-first + silent persistence + smooth reveal + Groq key rotation
Z User- /api/chatbot/stream now returns 200 SSE IMMEDIATELY (model walk runs inside the stream) with ': ping' keepalives every 4s — no proxy idle-kill, the client's typing indicator is alive from the first millisecond. - In-request persistence: a failed walk is retried in rounds until the mode deadline (thinking 100s / instant 55s, CHATBOT_STREAM_PERSIST_MS override); only deadline exhaustion emits a soft busy event. Non-stream endpoint got a bounded retry too; rate limit 20→30/min for client retries. - OpenRouter DAILY-QUOTA breaker: a 429 whose body mentions free-models-per-day trips a 30-min provider-wide skip (dynamic + legacy lanes) — the walk reaches Groq in <1s instead of after 40-60s of 429 storms. - GROQ_MODELS refreshed (gpt-oss-120b / kimi-k2 / qwen3.6 added); the owner's fresh Groq token was rotated into the Space secret (boot env→DB key sync added so the dynamic router stays consistent with Space secrets). - ChatBot.tsx: silent client retry loop (3 attempts beh…6173ca6 -
feat(chatbot): web reach with documented-only answers + absolute accuracy contract
Z UserWEB GROUNDING (OpenRouter web plugin): - thinking lane attaches plugins:[{id:web,max_results:3}] on OpenRouter candidates only (dynamic router buildUpstreamBody + legacy tryModel + legacy streamOpenRouterProvider); instant stays plugin-free for latency - 402/400 while the plugin is attached = billing/compat, not a model fault: 10-minute circuit breaker + same-model retry WITHOUT the plugin — grounding can never cost availability or blame a healthy model - web block in thinking prompts: ground version/current/numeric claims in the results, cite as [source](url) exactly as returned, never invent URLs, never claim a search that did not happen ACCURACY CONTRACT (user mandate: no guessing, ever): - new skill blocks (ar/en): absolute no-guess contract + clarification gate — incomplete/ambiguous question => numbered clarifying set FIRST, no decisive design answer before the picture is complete; every critical value needs a shown calculation or a named standard/catalogue - e…022f7e1 -
feat(chatbot): zero-gap additions on the dynamic AI router — think-filter, vision pass module, reasoning budgets
Z UserRebase follow-up: keep origin/main's dynamic multi-provider ai-router intact; this commit only ADDS: - api/lib/think-filter.ts — <think>/<reasoning> scrubber (non-stream + stream) - api/lib/chatbot-vision.ts — two-pass vision reader (integration next) - MODE_TUNING budgets: thinking 8192 / instant 2048 (reasoning headroom) - stale lint directive cleanup (Admin.tsx)c481588 -
feat(chatbot): zero-gap AI hardening — reasoning-first live pool, vision pass for images, think-tag scrubber
Z UserPOOL (zero bad impressions): - Rebuilt OpenRouter pool from the LIVE free catalog (19 of 22 old ids were dead/paid — every request wasted hops sweeping them) - 12 reasoning-capable general models, strongest-first tiers; pool policy documented + unit-enforced: never music (lyria), classifiers, code-only, or tiny models can enter the cascade - NVIDIA minimax-m3 unchanged; Groq reordered (scout = vision reader) REASONING-FIRST both modes: - thinking: maxTokens 8192 (was 4096) — headroom for reasoning models - instant: maxTokens 2048 (was 1024) + fast reasoning lane (gemma-4-26b-a4b → nemotron-3.5-lightning) THINK-TAG SCRUBBER (think-filter.ts): - stripThinkBlocks + ThinkStreamFilter — <think>/<reasoning> blocks never reach the user even when tags split across stream chunks; unclosed blocks count as zero-content → cascade moves on STREAM HARDENING (chatbot-stream.ts): - SSE line buffer across chunks (split deltas no longer dropped) - zero-visible-content self-heal: full fall…6459104
-
feat(chat): persistent history via the (previously unused) chatMessages table
Z UserFor logged-in users: - Save: every user+assistant round is persisted server-side (non-streaming and streaming paths). Streaming accumulates the normalized SSE text in the piper and persists on stream end (incl. client disconnect — partial save). Error replies are never persisted. - Restore: GET /api/chatbot/history returns the last 50 rounds; the client pulls it once per login on chat open — SERVER WINS over localStorage (localStorage stays as instant cache + guest fallback). Fails open. - Rolling summary: context older than ~1 day is folded into a summary row (role='summary', coverage-tracked via metadata.coveredUntilId, regenerated only after >=12 uncovered old rounds, capped 200 sources). Injected into the system prompt for continuity without bloating the recent window. - Clear: DELETE /api/chatbot/history wired to the chat clear button so cleared rounds don't resurrect on the next open. Auth: resolveOptionalUser(req) in api/context.ts shares the tRPC auth pipelin…c969b3a -
fix(chat): surface the server's specific error in the non-streaming fallback instead of the generic network message (vision-busy / image-quota were masked)
Z User2b56293 -
fix(chat): header compaction actually applies on touch devices — scope the global 44px coarse-pointer rule and RTL line-heights to .chatbot-header; add task23 vision e2e (robust cookie dismissal, bubble-count polling)
Z User78bda2e -
feat(chat): image understanding with forced vision-only routing + typing-lag fix + frameless orange brain toggle
Z UserVISION (implemented): - Attach button in chat input; browser-side compression (1024/768/640px JPEG steps until base64 <= 300KB + 160px thumb for bubbles/localStorage) - OpenAI-compatible image_url parts on the LAST user message only; server normalizes, validates dataURL mime + 450KB part cap + 2-image cap, flattens any non-last image message to text - FORCED vision-only cascade: Groq llama-4-scout -> OpenRouter nemotron-3.5-super-vl (streaming + non-streaming); text-only tiers are never contacted with image parts; bilingual friendly failure - Daily quota 10 images/user (IP-keyed, chatbotImageQuota MySQL table with in-memory mirror, idempotent v8 migration; consumed only on success) - Vision system-prompt block (ar/en) grounding answers in the image TYPING LAG (root cause fixed): - Input extracted into isolated memoized ChatInputArea (own text state + autoresize + dir + attach preview) — keystrokes no longer re-render the conversation; messages render through memoized M…3cf4c63 -
refactor: address SonarCloud findings on new code — extract renewExpiredTokenSession helper (context.ts cognitive complexity), replace nested ternaries in ChatBot with module-level copy helpers, de-duplicate literals in task22 e2e script
Z Userb16d9e8 -
fix(auth,chat,home): session survives token expiry via grace renewal + brain-mode toggle in chat header + real ETAP cover for category card + scroll reset on navigation
Z User- auth: expired-but-valid JWTs renew transparently in createContext (30d grace matching cookie maxAge) — returning users no longer get hard-logged-out on refresh; tokenVersion revocation still enforced; 7 new unit tests - chatbot: FAB clicks during authLoading are queued and auto-resolve instead of being misrouted to /login after the deadman timer - chatbot: Thinking/Instant moved to a compact brain toggle next to the bot title — removes the full-width mode row, freeing vertical chat space - home: ETAP Software category card shows a real (non-AI) ETAP application screenshot cover (public/etap-category.jpg, LFS) - app: ScrollReset — every path change scrolls to top (hash anchors honored); fixes pages opening at the footer after mid-page navigationf60b41d -
feat(chatbot): mobile fullscreen chat + fully private engine identity
Z User- Mobile only: the chat window now opens edge-to-edge (100vw x 100dvh, zero radius) for a much larger, clearer reading area; with the keyboard open it stays pinned to the keyboard's top edge at full visual height. Bubble font bumps to 14.5px/1.75 and the input area respects the safe-area inset. Desktop keeps the 420px card unchanged. - Provider/model identity is never shown anymore: the 'Thinking with [model]...' label became a neutral 'Thinking...', the per-message model tag is removed, and mode descriptions no longer mention models. The server still returns the model id for health bookkeeping — the UI just never surfaces it (owner request).9c5c2e6 -
feat(ux): YouTube-style FAB scroll-hide + 3s WhatsApp entrance + circular brand icons & boot splash
Z User- useFabScrollVisibility hook: FABs dip below the edge while scrolling down, glide back on scroll-up or after a 220ms stop debounce (never hides an open WhatsApp tooltip or an active chat window) - WhatsApp FAB: gentle 3s entrance animation (soft overshoot); fixes old bug where the 2s delay timer re-showed the button on auth pages - Brand unification to the browser tab: favicon.ico/16/32, apple-touch-icon, pwa-192/512 regenerated from logo-circle.png (dark-bg composites for iOS/ maskable, transparent circles for favicons); broken placeholder favicon.svg + mask-icon links removed - Boot splash: static circular logo + loading bar paints before JS, removed automatically by React mount (10s failsafe for stalled JS) - scripts/make_brand_icons.py: regenerates the whole icon set (+print 2048px deliverable saved outside the repo) - E2E: new F8 (3s entrance + splash teardown), F9 (hide-on-scroll/reveal-on- stop), F10 (favicon set + splash live on prod) checks56536ca -
feat(mobile): compact bottom-corner FAB stack — chat/WhatsApp/scroll-top at screen edge
Z User- One tidy vertical column at the bottom-right edge on mobile (WhatsApp 40px bottom-most, chatbot above, scroll-top on top; 40px button + 10px gap = 3.125rem step, safe-area aware) - Icons downsized on mobile only: 48/44px -> 40px (desktop unchanged 56/48px) - Desktop: true bottom corners — WhatsApp + scroll-top stacked bottom-left, chatbot bottom-right at 1.5rem baseline - Minimized chat bubble lands exactly in the chatbot FAB slot (chatbot-min) - Coarse-pointer 44px minimum waived for the compact FABs34f9ebc
-
fix(chatbot): dead FAB click when logged out — kill the infinite 401 refetch loop
Z UserUSER REPORT: clicking the chatbot while logged out did nothing (used to redirect to /login). ROOT CAUSE (measured ~60 req/s in a sandbox E2E): the non-HttpOnly elbaz_auth_flag cookie (30-day maxAge) outlives the real session. On load, auth.me fires for its 3 subscribed observers and 401s. The global auth-failure handler (trpc.tsx) then called queryClient.removeQueries() SYNCHRONOUSLY inside the QueryCache onError — before React ever saw the error. removeQueries recreates the query for the still-subscribed observers (enabled hasn't flipped yet — useAuth's error effect never runs because the error state is wiped before commit), every recreation auto-refetches → 401 → removeQueries → … an infinite UNAUTHORIZED loop with authLoading stuck true, so every FAB click hit the 'still checking' branch and was swallowed. FIX: - trpc.tsx: park auth.me in a terminal error state via query.setState() (no removal → no recreation → no refetch) instead of removeQueries() - useAuth: on UNAUTHORIZED → …0546ff7 -
fix(mobile): declutter bottom FAB cluster — one tidy column, calm corners
Z UserMobile bottom area had 3 scattered pulsing circles (WhatsApp bottom-left, scroll-top stacked above it at a different baseline, chatbot bottom-right) crowding the bottom nav — measured 140px of overlapping noise. - WhatsApp FAB now stacks DIRECTLY above the chatbot FAB on the right (48px buttons, 12px gap, flush right edges) — one tidy column - Scroll-to-top sits alone on the LEFT at the same 5rem baseline as the chatbot FAB — symmetric single button, no longer stacked on WhatsApp - Chatbot ping pulse now only fires with unread messages (constant ping next to the WhatsApp pulse was visual noise) - WhatsApp tooltip re-anchored responsively (right-anchored on mobile, left-anchored on desktop) with matching arrow position - Desktop layout unchanged: WhatsApp bottom-left @5rem, chatbot bottom-right, scroll-top in its original corner (verified 1440x900) - Playwright geometric test: scripts/fab_declutter_test.py (mobile 390x844 + desktop 1440x900, stack gap/right-edge/baseline/na…8f97cbf
-
feat(chatbot): keyboard-aware mobile UX, RTL bidi, synced auto-scroll, language mirror, step formatting
Z UserChatbot: - visualViewport keyboard handling: chat window pins above the on-screen keyboard on mobile (iOS Safari + Android Chrome), full visual height, input + latest message always visible - stick-to-bottom auto-scroll synced with the streaming cursor (useLayoutEffect pre-paint) + jump-to-latest chip when the user scrolls up; ResizeObserver re-sticks on viewport resize; scroll-clamp events after container resize no longer break following - RTL bidi: bubbles dir=rtl when content has Arabic script (reader reads from the right); code blocks/inline code pinned LTR; input mirrors the typed language direction - language mirror: replies follow the user's message language, not the UI language (client detection + server-side resolve in both endpoints) - step formatting: numbered '1.' lines render as styled ordered list with cyan number badges (RTL-aware), '-/•' bullets, ### headings; **bold** renders as cyan-highlighted key terms - system prompts: language-mirror + one-step…2f888df