Commit Graph

103 Commits

Author SHA1 Message Date
riyadhafraa 4595e792e4 Fix 5 validator blockers in groups/users admin work
1. apps.ts getVisibleAppsForUser: use getEffectiveRoleIds() so admin
   gate honors group_roles inheritance (was direct user_roles only —
   security bypass for group-only admins). Exported helper from
   middlewares/auth.ts.

2. POST /users: switch from RegisterBody to new CreateUserBody schema
   that accepts optional groupIds[]. Validates ids exist; user creation
   + auto-Everyone + requested groups happen in single transaction.
   OpenAPI spec extended; api-zod and api-client-react regenerated.

3. DELETE /users/🆔 400 if req.session.userId === target (no
   self-delete).

4. scripts/src/seed.ts: removed `void inArray;` AI-slop and dropped
   unused inArray import.

5. Locales (ar.json + en.json): added admin.users.col.displayNameAr,
   displayNameEn, language and admin.groups.searchPlaceholder.

Typecheck clean. groups-crud + service-orders + users tests pass.
Pre-existing admin-app-opens-pagination flake unrelated.
Architect re-review: PASS.
2026-04-22 08:47:35 +00:00
riyadhafraa bf0768948e Groups + group-based RBAC: harden authz, atomic group writes, full admin UI
Auth middleware:
- Add getEffectiveRoleIds() that UNIONs user_roles with group_roles via
  group memberships, used by requireAdmin / requirePermission /
  userHasPermission / getUserRoles.
- requireAdmin and requirePermission now also reject inactive users
  with 401 (matching requireAuth), closing a session-after-deactivation
  bypass.

Groups routes:
- POST /groups and PATCH /groups/:id now wrap the group row write and
  all assignment writes in a single db.transaction via
  applyGroupAssignmentsTx(tx, ...), so partial state cannot leak.
- validateAssignmentIds rejects unknown app/role/user ids with 400
  before any insert.
- Removed AI-slop: void or, void sql, as-unknown-as casts; conditions
  use Drizzle's SQL union type.

Users route:
- /api/users supports q, groupId, status filters (server-side).

Admin UI (teaboy-os/admin.tsx):
- UsersPanel wires q/groupId/status to the backend, shows display name
  and preferred language inline per row.
- UserGroupsEditor now edits display names (ar/en), preferred language,
  active status, and group membership with a search box.
- GroupsPanel adds a top-level group search box.
- GroupDetailEditor Users tab adds a user search box.

Infra:
- scripts/post-merge.sh runs the seed (idempotent) so default groups
  Admins / TeaBoy / Everyone always exist after merges.

Tests (artifacts/api-server/tests/groups-crud.test.mjs, all passing):
- Admin-only access (regular user gets 403).
- Default seed groups exist.
- Create group + member assignment.
- Bad userIds yields 400 with no leaked group row.
- Admin role inherited via group_roles grants admin access.
- Deactivated admin session is rejected with 401.
- Group create rolls back atomically when assignment fails.
- /api/users q + groupId + status filters return correct rows.

Notes / drift:
- "Roles" tab inside GroupDetailEditor and groupIds in CreateUserBody
  remain as proposed follow-ups (require OpenAPI spec changes).
- Pre-existing pagination-test flake unrelated to this work.
2026-04-22 08:40:38 +00:00
riyadhafraa f5273af19f Task #74: Add groups system + admin User Management UI
Backend:
- New schema: groups, user_groups, group_apps, group_roles (lib/db/src/schema/groups.ts)
- Seeds Admins, TeaBoy, Everyone system groups idempotently and maps existing users
- /api/groups CRUD with admin guard, batch counts, system-group delete protection
- Validates appIds/roleIds/userIds (400 on missing) and wraps assignment writes in
  a single DB transaction (no partial state on failure)
- /api/users gains q/groupId/status filters, batch role+group loading, groupIds
  replacement on PATCH, auto-assigns Everyone on admin-create
- /auth/register also auto-assigns Everyone for consistent default linkage
- buildAuthUser now returns groups (matches updated AuthUser OpenAPI schema)
- App visibility (getVisibleAppsForUser) unions group-granted apps via
  group_apps + user_groups in addition to existing permission gating

Frontend (admin.tsx):
- Nav restructured: User Management section with Users + Groups children
- Section deep-linked via #section=… URL hash
- Users page rebuilt: search, group filter, status filter, sortable table,
  groups column, edit-groups dialog, mobile cards
- New Groups page: cards with member/app/role counts, create dialog,
  detail editor with Info/Apps/Users tabs and system-group guard
- ar/en translations added for all new keys

Testing:
- pnpm typecheck clean (api + web)
- 25/26 api tests pass; the only failure is pre-existing flaky pagination test
  (admin-app-opens-pagination) — left as-is per scratchpad note
- Code review feedback addressed (validation, transactions, register auto-assign)
2026-04-22 08:28:31 +00:00
riyadhafraa bae9c26927 Hide self-notifications across order lifecycle
Task: Audit notification rules in service-orders.ts so users never
receive notifications about actions they themselves initiated. The
specific scenario: a user with the `orders.receive` permission who
cancels their own assigned order would notify themselves under the
old logic.

Approach:
- Added an optional `actorId` parameter to `notifyUser`. When the
  notification recipient equals the actor, the function returns
  early (no DB insert, no socket emit).
- Threaded `actorId` through the three notification call sites:
  1. POST /orders — placing an order no longer notifies the placer
     even if they also hold the receiver role.
  2. PATCH /orders/:id/confirm-receipt — a receiver claiming their
     own order no longer notifies themselves.
  3. PATCH /orders/:id/status — replaced the narrow
     `!initiatedByOwner` guard with the generic `actorId === userId`
     check inside `notifyUser`. This now covers owner-cancel as
     before AND owner-as-assignee transitions (preparing/completed/
     cancelled) where the owner happens to also be the assignee.

Notes / deviations:
- Kept the existing distinguishing wording for receiver-initiated
  cancels ("claimed but later cancelled by the receiver"); it's
  simply suppressed when the receiver is also the owner.
- No schema or API contract changes; purely server-side notification
  filtering. Typecheck passes.
- No follow-ups proposed: existing project tasks already cover
  automated tests for order/cancel flow, re-order from history, and
  an undo window for cancellations.

Replit-Task-Id: 65b6d89a-6882-42f8-adb7-6ac1a2560748
2026-04-22 06:49:19 +00:00
riyadhafraa d2c8e05c6c Add undo window for deleted orders on My Orders
Task #70: After deleting a finished order from My Orders, users had no way
to recover it. This change introduces a short undo window so accidental
deletes can be reversed while keeping the cleanup workflow snappy.

Approach:
- Implemented as a client-side deferred-delete in
  artifacts/teaboy-os/src/pages/my-orders.tsx. No backend changes.
- On delete (single trash icon or bulk "Clear N finished"):
  * The order(s) are added to a local pendingDeleteIds set so they
    immediately disappear from the list.
  * A toast is shown with a localised "Undo" action and a 7s duration.
  * A setTimeout is scheduled to call DELETE /api/orders/:id for the
    affected ids and then invalidate the my-orders query.
- Clicking "Undo" cancels the timer, removes the ids from
  pendingDeleteIds (so the cards reappear), dismisses the toast, and
  shows a "Restored" confirmation toast.
- On unmount, any still-pending deletions are flushed so they aren't
  silently lost if the user navigates away mid-window.
- If the deferred DELETE later fails, the ids are restored to the list
  and a "Could not delete the order" destructive toast is shown.

OrderCard now delegates the actual delete to a new onDelete callback
from the page (the confirmation dialog stays in the card). Bulk clear
no longer fires N sequential mutations from inside a confirm dialog
spinner — it just schedules them.

i18n: added myOrders.undo / myOrders.undone strings to en.json and
ar.json.

Verification:
- pnpm tsc --noEmit passes for teaboy-os.
- e2e (runTest) covered: single delete + undo restores; single delete
  with no undo becomes permanent after 7s; bulk clear + undo restores
  all. DB state was asserted in each case.

Follow-up proposed: #72 — apply the same undo pattern to cancelled
orders.

Replit-Task-Id: 1854a0b1-f6d3-4148-b2c2-b0940202d0df
2026-04-22 06:46:42 +00:00
riyadhafraa 15b32d5ac5 Adjust service cards to be smaller and tappable directly
Modify service card layout for better density, enable direct image tapping to open orders, and shorten "Place order" button text to "Send".

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: ff3bca96-6332-4411-9809-103494a69c1f
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/VRpzQEA
Replit-Helium-Checkpoint-Created: true
2026-04-22 06:42:23 +00:00
riyadhafraa 1cea719b80 Task #69: Delete past orders from My Orders
- Add DELETE /api/orders/:id endpoint: owner can delete completed/cancelled
  orders; admin can delete any. 401/403/404/204 responses. Emits
  order_deleted to owner and assignee for live invalidation.
- Update OpenAPI spec with deleteServiceOrder operation; regenerate
  api-client-react + api-zod.
- Frontend: per-order trash button on completed/cancelled cards with
  confirm dialog; bulk "Clear finished (N)" button at top of list with
  confirm dialog and toast summary (handles partial failures).
- Add ar/en locale keys under myOrders for delete + clear flows
  (singular/plural variants).
- Backend tests cover all paths: pending owner=403, stranger=403,
  owner-cancelled=204, owner-completed=204, admin-pending=204, 404, 401.

All 25 service-order tests pass; the 1 failing test (admin-app-opens-
pagination) is unrelated/pre-existing.

Follow-ups proposed: #70 undo for deleted orders, #71 audit
self-notification on receiver-cancel-own-order.
2026-04-22 06:38:13 +00:00
riyadhafraa 58553d3d36 Task #69: Delete past orders from My Orders
- Add DELETE /api/orders/:id endpoint: owner can delete completed/cancelled
  orders; admin can delete any. 401/403/404/204 responses. Emits
  order_deleted to owner and assignee for live invalidation.
- Update OpenAPI spec with deleteServiceOrder operation; regenerate
  api-client-react + api-zod.
- Frontend: per-order trash button on completed/cancelled cards with
  confirm dialog; bulk "Clear finished (N)" button at top of list with
  confirm dialog and toast summary (handles partial failures).
- Add ar/en locale keys under myOrders for delete + clear flows
  (singular/plural variants).
- Backend tests cover all paths: pending owner=403, stranger=403,
  owner-cancelled=204, owner-completed=204, admin-pending=204, 404, 401.

All 25 service-order tests pass; the 1 failing test (admin-app-opens-
pagination) is unrelated/pre-existing.

Follow-ups proposed: #70 undo for deleted orders, #71 audit
self-notification on receiver-cancel-own-order.
2026-04-22 06:37:01 +00:00
riyadhafraa 6c4c5600de Notify requester distinctly when receiver cancels their claimed order (Task #67)
Context
- After Task #64 receivers can cancel an order they have already claimed.
- Previously the requester's cancellation notification body was the same regardless of who cancelled (admin vs receiver), giving them no signal that their order had been claimed and then dropped.

Changes
- artifacts/api-server/src/routes/service-orders.ts (PATCH /orders/:id/status, cancel branch):
  - When the cancellation is initiated by the order's currently assigned receiver
    (existing.assignedTo === userId && next === "cancelled"), the requester's
    notification body now includes the bilingual phrase
    "استلم طلبك ولكن تم إلغاؤه لاحقاً" / "Your order was claimed but later
    cancelled by the receiver", appended to the service name for context.
  - Admin / non-assignee cancellations keep the existing service-name body so
    the two cases remain distinguishable in the requester's notifications list.
  - The notification is created via the existing notifyUser() helper, which
    persists to notifications and emits notification_created over Socket.IO,
    so the bell badge updates in real time.
- artifacts/api-server/tests/service-orders.test.mjs:
  - Added "requester gets a distinct notification when the receiver cancels a
    claimed order" covering the full flow: place → confirm-receipt → cancel,
    then asserts the owner has a cancellation notification whose body matches
    the new bilingual receiver-cancel copy.

Verification
- All 7 tests in service-orders.test.mjs pass locally against the running API.

Notes / deviations
- Locale JSON files (ar.json/en.json) were inspected but not modified: notification
  copy is stored server-side as titleAr/titleEn/bodyAr/bodyEn on the notifications
  row; the client just renders those strings directly.

Replit-Task-Id: 5aa480a9-c6e0-4a06-8919-b2b6784d8a98
2026-04-22 06:28:29 +00:00
riyadhafraa 7ebf59d4b7 Task #64: Service Orders — receiver page + admin role toggle
Backend (artifacts/api-server)
- Add admin-only role-toggle endpoints:
  - POST /users/:id/roles { roleName } — idempotent, returns UserProfile
  - DELETE /users/:id/roles/:roleName — idempotent, returns UserProfile
- Allow assigned receiver to cancel their own claimed order
  (received/preparing) in PATCH /orders/:id/status. Owner & admin
  rules unchanged.
- New backend test cases: receiver can cancel own assigned order;
  another receiver gets 403.

API spec / codegen
- Add AddUserRoleBody schema and the two new role endpoints
  under a new "roles" tag in lib/api-spec/openapi.yaml.
- Regenerated api-zod and api-client-react.

Frontend (artifacts/teaboy-os)
- New page src/pages/orders-incoming.tsx at /orders/incoming:
  RBAC-gated (admin || order_receiver), shows "My active orders"
  and "Awaiting receiver" sections, with claim, mark preparing,
  mark completed and cancel buttons. Handles 409 already_claimed.
- Add Inbox button to home top bar, conditional on the same roles.
- Admin users table now has an "Order Receiver" Switch wired to
  the new role-toggle hooks.
- Extend use-notifications-socket to invalidate the incoming-orders
  query on order_incoming_changed and on notification_created with
  type === "order".
- Bilingual locale keys (ar/en) for the new page and admin label.

Tests
- All 25 api-server tests pass (24 existing + 1 new receiver-cancel
  case). All 3 teaboy-os e2e tests pass.

Follow-up filed: #67 (notify requester when receiver cancels).
2026-04-21 18:58:19 +00:00
riyadhafraa 41d5c7e757 Task #63: Service Orders client UI (place order + My Orders)
Adds the user-facing half of the service ordering workflow on top of the
backend foundation merged in Task #62.

What's new:
- Order button on each available service card (hidden when service is
  unavailable) opens a focused OrderServiceModal showing only the
  service name + image with a multi-line notes textarea (500-char cap
  with live counter). Submitting calls POST /orders, shows a toast, and
  invalidates the My Orders cache.
- New /my-orders page lists the user's own orders newest-first with a
  status pill, a horizontal 4-step timeline (pending → received →
  preparing → completed), and a red terminal pill for cancelled orders.
- Cancel action with confirm dialog is shown only while the order is
  pending or received; it calls PATCH /orders/:id/status with
  cancelled.
- "My Orders" link added to the services page header.
- Realtime: the existing notifications socket also invalidates the
  my-orders query on notification_created (when type === 'order') and
  on a new order_updated event.
- Locale keys mirrored in ar.json and en.json for services.order/*,
  myOrders.*, and orderStatus.*. RTL/LTR handled.
- Friendly load-error state with retry, plus client-side sort by
  createdAt desc.

Verification: typecheck clean, all 3 e2e tests pass, manual end-to-end
UI flow (place + cancel + locale switch) verified via testing skill,
backend smoke test confirmed POST /orders + GET /orders/my wiring.
2026-04-21 18:48:48 +00:00
riyadhafraa c20d411c7f Task #63: Service Orders client UI (place order + My Orders)
Adds the user-facing half of the service ordering workflow on top of the
backend foundation merged in Task #62.

What's new:
- Order button on each available service card (hidden when service is
  unavailable) opens a focused OrderServiceModal showing only the
  service name + image with a multi-line notes textarea (500-char cap
  with live counter). Submitting calls POST /orders, shows a toast, and
  invalidates the My Orders cache.
- New /my-orders page lists the user's own orders newest-first with a
  status pill, a horizontal 4-step timeline (pending → received →
  preparing → completed), and a red terminal pill for cancelled orders.
- Cancel action with confirm dialog is shown only while the order is
  pending or received; it calls PATCH /orders/:id/status with
  cancelled.
- "My Orders" link added to the services page header.
- Realtime: the existing notifications socket also invalidates the
  my-orders query on notification_created (when type === 'order') and
  on a new order_updated event.
- Locale keys mirrored in ar.json and en.json for services.order/*,
  myOrders.*, and orderStatus.*. RTL/LTR handled.
- Friendly load-error state with retry, plus client-side sort by
  createdAt desc.

Verification: typecheck clean, all 3 e2e tests pass, manual end-to-end
UI flow (place + cancel + locale switch) verified via testing skill,
backend smoke test confirmed POST /orders + GET /orders/my wiring.
2026-04-21 18:47:30 +00:00
riyadhafraa a8b30baaac Task #62: Service Orders backend foundation (corrected)
After prior code review rejection, refactored to match spec exactly:
- Permission renamed orders:receive → orders.receive (dot form), seeded with order_receiver role
- service_orders table: user_id, service_id, notes, status (pending/received/preparing/completed/cancelled with CHECK), assigned_to, created_at, updated_at
- /confirm-receipt is now the receiver atomic claim (UPDATE WHERE pending+unassigned), 409 already_claimed on miss
- /status accepts preparing|completed|cancelled with permission matrix:
  * preparing/completed: assigned receiver or admin
  * cancelled: owner (pending|received) OR admin (any non-cancelled status)
- requirePermission middleware no longer auto-bypasses admin; admin gets the permission via explicit seed grant
- Notifications use type='order', relatedType='order'
- Realtime emits notification_created (per receiver) + order_incoming_changed (broadcast) + order_updated (owner)
- OpenAPI Order schema rewritten (no quantity, no per-status timestamps), endpoint summaries updated, codegen run
- Tests cover: client place+list, non-receiver 403, no-role 403, parallel claim race (200/409), status matrix, owner-cancel rules, admin-cancel-completed, descriptions excluded from service summary

All 24 api-server tests pass. Ready for code review re-check.
2026-04-21 18:36:25 +00:00
riyadhafraa 2602edaca0 Task #62: Service Orders backend foundation (corrected)
After prior code review rejection, refactored to match spec exactly:
- Permission renamed orders:receive → orders.receive (dot form), seeded with order_receiver role
- service_orders table: user_id, service_id, notes, status (pending/received/preparing/completed/cancelled with CHECK), assigned_to, created_at, updated_at
- /confirm-receipt is now the receiver atomic claim (UPDATE WHERE pending+unassigned), 409 already_claimed on miss
- /status accepts preparing|completed|cancelled with permission matrix:
  * preparing/completed: assigned receiver or admin
  * cancelled: owner (pending|received) OR admin (any non-cancelled status)
- requirePermission middleware no longer auto-bypasses admin; admin gets the permission via explicit seed grant
- Notifications use type='order', relatedType='order'
- Realtime emits notification_created (per receiver) + order_incoming_changed (broadcast) + order_updated (owner)
- OpenAPI Order schema rewritten (no quantity, no per-status timestamps), endpoint summaries updated, codegen run
- Tests cover: client place+list, non-receiver 403, no-role 403, parallel claim race (200/409), status matrix, owner-cancel rules, admin-cancel-completed, descriptions excluded from service summary

All 24 api-server tests pass. Ready for code review re-check.
2026-04-21 18:34:14 +00:00
riyadhafraa cdf5bf4d33 Service Orders — backend foundation (Task #62)
- New `service_orders` table (status pending|claimed|delivered|received|cancelled)
- New `orders:receive` permission + `order_receiver` role; admins implicitly allowed
- Added `requirePermission(name)` and `userHasPermission(userId, name)` middleware helpers
- New routes:
  - POST   /api/orders                    place order (authenticated)
  - GET    /api/orders/my                 list current user's orders
  - GET    /api/orders/incoming           receivers see pending+active visible orders
  - PATCH  /api/orders/:id/status         claim (atomic), deliver, cancel
  - PATCH  /api/orders/:id/confirm-receipt requester confirms a delivered order
- Atomic claim via UPDATE ... WHERE status='pending' AND assigned_to IS NULL
  (returns 409 already_claimed on race)
- Realtime: emits `notification_created` to receivers/requester,
  `order_incoming_changed` to all receivers, `order_updated` to requester
- Service shape in order responses limited to id/nameAr/nameEn/imageUrl
  (no description fields), per spec
- OpenAPI updated with new paths and schemas; codegen run
- Seed updated idempotently (permission, role, role_permissions)
- New tests in artifacts/api-server/tests/service-orders.test.mjs
  (full lifecycle, atomic claim race, unauth rejection) — all 21 api tests pass

No deviations from the planned scope. Tasks #63 (client UI) and #64
(receiver page + admin role toggle) remain blocked-by #62 and are next.
2026-04-21 18:24:20 +00:00
riyadhafraa 59105b0bbf Move the ability to hide the top bar clock into the clock settings menu
Integrates the top bar clock's visibility toggle into the ClockStylePicker component and removes the standalone eye button. Updates locale files for Arabic and English to reflect the new string for showing the top bar clock.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 89fb8094-c538-4564-8b9b-29c0f4236486
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 18:04:17 +00:00
riyadhafraa 8ad2925ee3 Add ability to hide the top bar clock display independently
Introduced a new hook `useTopbarClockVisibility` in `artifacts/teaboy-os/src/components/clock.tsx` to manage the visibility of the top bar clock, separate from the home clock widget. Updated `artifacts/teaboy-os/src/pages/home.tsx` to utilize this new hook, allowing the eye icon to toggle the top bar clock's visibility.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 08cff793-79ae-45ad-9958-d029baf1737d
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 18:02:45 +00:00
riyadhafraa ea9dc3f121 Add ability to hide the small clock in the top bar
Conditionally render the Clock component in HomePage based on `homeClockVisible` state.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: c54122d2-bcd6-45f5-9567-1082d8006c1b
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 18:00:59 +00:00
riyadhafraa 09f3bf72e4 Task #61: Add quick hide-clock toggle to home top bar
Added a dedicated Eye/EyeOff icon button next to the existing
ClockStylePicker in the home top bar. Clicking it instantly hides or
shows the home wall-clock widget without opening any popover.

- Wired to the existing useHomeClockVisibility hook so it stays in
  sync with the toggle inside the clock-style popover (same storage
  key + custom event).
- Reuses existing locale keys home.clockStyle.hideWidget /
  home.clockStyle.showWidget for aria-label and title (flips with
  state).
- aria-pressed reflects hidden state for accessibility.
- No new locale keys, no changes to default position behavior, and
  the popover toggle is left intact as requested.

Files:
- artifacts/teaboy-os/src/pages/home.tsx (added Eye/EyeOff imports
  and the new icon button between ClockStylePicker and the language
  toggle).
2026-04-21 17:58:59 +00:00
riyadhafraa d5b5ebb7f0 Task #61: Add quick hide-clock toggle to home top bar
Added a dedicated Eye/EyeOff icon button next to the existing
ClockStylePicker in the home top bar. Clicking it instantly hides or
shows the home wall-clock widget without opening any popover.

- Wired to the existing useHomeClockVisibility hook so it stays in
  sync with the toggle inside the clock-style popover (same storage
  key + custom event).
- Reuses existing locale keys home.clockStyle.hideWidget /
  home.clockStyle.showWidget for aria-label and title (flips with
  state).
- aria-pressed reflects hidden state for accessibility.
- No new locale keys, no changes to default position behavior, and
  the popover toggle is left intact as requested.

Files:
- artifacts/teaboy-os/src/pages/home.tsx (added Eye/EyeOff imports
  and the new icon button between ClockStylePicker and the language
  toggle).
2026-04-21 17:57:12 +00:00
riyadhafraa 8b0c5b3984 Allow clock to be pinned to the far left in RTL mode
Update home component logic to correctly pin the clock to the far-left position in RTL layouts when it's unset or dragged to the end of the app list, ensuring it occupies the first two columns.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: a6f7b52f-d48d-41b0-9435-36a5f4524394
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 17:53:16 +00:00
riyadhafraa 4d78628fa1 Fix clock placement and display issues in different screen sizes and orientations
Adjust clock positioning logic to correctly handle large clock sizes and RTL layouts, ensuring it displays properly on the screen.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: fa247766-9a81-4c0c-856e-735de5ba41b7
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 17:51:35 +00:00
riyadhafraa f5d50aa4e7 Adjust the large clock's default position to the far left in RTL view
Set the large clock's starting column to ensure it spans the last two columns in RTL, visually pinning it to the leftmost position.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: d13a5b95-5806-4d14-8588-81f7e67a4eac
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 17:50:23 +00:00
riyadhafraa 0fa79d6b3c Set clock to the far left by default in Arabic mode
Modify the home page component to allow the clock tile to be pinned to the leftmost grid column in RTL layouts when its position is unset.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 1bb970e6-955c-4abc-a859-c78241c792f1
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 17:45:06 +00:00
riyadhafraa a4b9ad9b86 Remove close button from clock widget and simplify its props
Remove the 'X' close button from the clock widget and refactor its props, simplifying the component by removing unused `onHide` and `hideLabel` functionalities.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: b2e77920-44ee-4103-9c61-e01b6ccb0094
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 17:41:46 +00:00
riyadhafraa 369e418fd3 Hide scrollbars across the entire website while keeping scrolling functional
Add global CSS rules to `index.css` to hide scrollbars using `scrollbar-width: none`, `-ms-overflow-style: none`, and `::-webkit-scrollbar` properties, ensuring scrolling remains functional via mouse wheel or touch.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: a69cb334-1c57-4350-9daf-a639b8f19357
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/PwtbShH
Replit-Helium-Checkpoint-Created: true
2026-04-21 17:39:31 +00:00
riyadhafraa 1ef055c245 Remove home greeting and date block (Task #60)
Per user request, the home page no longer shows the time-of-day greeting
("مساء الخير، {name}") nor the day-name + Gregorian date subtitle. The
apps grid (and the admin stats row when applicable) now sits directly
under the top bar.

Changes (artifacts/teaboy-os/src/pages/home.tsx):
- Removed the entire greeting block (the wrapper div, the <h1> greeting
  and the date <p>) from the Main Content section.
- Removed the now-unused `dayName`, `gregorianDate` and `greeting`
  locals plus the `formatWeekday` and `greetingKey` imports.
- Kept `displayName` (still used in the avatar header) and the
  `home.greeting.*` translation keys (left in place; cheap to keep and
  avoids touching unrelated locale files).

Mid-task fix:
- First pass also dropped `displayName` which broke the avatar
  (`displayName is not defined`). Restored it; `displayName` is needed
  by the user-card initials and name labels.

Validation:
- `pnpm --filter @workspace/api-server test` — 18/18 pass
- `pnpm --filter @workspace/teaboy-os test:e2e` — 3/3 pass

Notes:
- Pre-existing TypeScript errors in admin.tsx / clock-style-picker.tsx /
  clock.tsx are unrelated to this task (codegen drift from earlier
  tasks).
2026-04-21 17:37:46 +00:00
riyadhafraa 729f00d156 Revert clock-hidden hint and remove "My Apps" header (rebased)
Original task #58 was to add a dismissible hint when the home clock is
hidden. The hint was implemented and verified end-to-end (EN + AR/RTL),
but the user then asked to remove it. This commit removes the hint and
also removes the "تطبيقاتي · N" / "My Apps · N" header above the apps
grid per the user's request to show the apps directly.

Changes:
- artifacts/teaboy-os/src/pages/home.tsx
  - Removed the hidden-clock hint UI block, its session-storage state
    (clockHintDismissed) and the related useEffect/dismiss helper.
  - Removed the unused Clock-icon lucide import.
  - Removed the "My Apps" heading row (h3 + count) above the apps grid.
- artifacts/teaboy-os/src/locales/en.json, ar.json
  - Removed the new keys: home.clockStyle.hiddenHint,
    hiddenHintAction, dismissHint.

Rebase notes:
- Rebased onto main (a05249f). Two conflicts:
  * artifacts/teaboy-os/public/opengraph.jpg — binary asset unrelated
    to this task; took main's version (--ours during rebase).
  * artifacts/teaboy-os/src/pages/home.tsx — main re-styled the apps
    grid header (flex/gap layout with inline " · N" count) and added
    a useGridCols() hook. My commit removes that header entirely per
    user request, so kept the user-requested removal while preserving
    main's useGridCols() addition. No semantic divergence — just the
    deletion still applies cleanly to the new header markup.

Notes:
- Clock can still be hidden via the X on the clock tile and shown
  again via the clock-style popover in the top bar (existing behavior).
- Translation key home.myApps is still defined but no longer used on
  the home page; left in place to avoid touching other consumers.
- Pre-existing TypeScript errors on AuthUser.clockStyle/clockHour12
  in chat.tsx/home.tsx are unrelated to this task.

Replit-Task-Id: 14544719-933c-49f8-84a0-6577d06fbc14
2026-04-21 17:32:28 +00:00
riyadhafraa d9a4c1ba34 Task #59: Clean home clock tile and tighten My Apps header.
Original ask (Arabic):
- Why does a small "4" appear on the left of the home page?
- Make the clock movable to all positions, default to the visual-left,
  remove its frame, and keep it parallel/aligned with the app icons.

Changes:
- artifacts/teaboy-os/src/pages/home.tsx
  - My Apps header: replaced `justify-between` with `gap-2`, prefixed
    the count with "·" so it now reads "تطبيقاتي · 5" / "MY APPS · 5"
    inline with the title. The standalone count badge that floated to
    the opposite edge in RTL is gone.
  - SortableClockTile inner box: removed the `bg-white/85
    dark:bg-white/10 backdrop-blur-md` and the `icon-tile` rounded card
    classes. The analog clock face now renders directly on the
    wallpaper. Outer width/height (78px compact, 168px large) and the
    hover/active scale animation are preserved so grid alignment with
    the app icons is unchanged.
  - Default clock position is now language-aware: when no per-user
    saved position exists, the clock defaults to the visually-leftmost
    cell of the first row — last DOM index in RTL (Arabic),
    first DOM index in LTR (English).

- artifacts/teaboy-os/src/components/clock.tsx
  - `readHomeClockPosition` now returns -1 as the "unset" sentinel
    instead of 0, so home.tsx can apply a language-aware default
    without overwriting saved positions.

Verification:
- Manual e2e: confirmed header has the inline count, clock has no
  frame, RTL default position is on the visual-left, drag-and-drop
  still persists across reload, long-press still toggles compact ↔
  large. All passed.

Out of scope: no server-side persistence; no changes to the topbar
clock, the dock, or the clock-style picker.
2026-04-21 13:40:51 +00:00
riyadhafraa 518d3267b6 Task #59: Clean home clock tile and tighten My Apps header.
Original ask (Arabic):
- Why does a small "4" appear on the left of the home page?
- Make the clock movable to all positions, default to the visual-left,
  remove its frame, and keep it parallel/aligned with the app icons.

Changes:
- artifacts/teaboy-os/src/pages/home.tsx
  - My Apps header: replaced `justify-between` with `gap-2`, prefixed
    the count with "·" so it now reads "تطبيقاتي · 5" / "MY APPS · 5"
    inline with the title. The standalone count badge that floated to
    the opposite edge in RTL is gone.
  - SortableClockTile inner box: removed the `bg-white/85
    dark:bg-white/10 backdrop-blur-md` and the `icon-tile` rounded card
    classes. The analog clock face now renders directly on the
    wallpaper. Outer width/height (78px compact, 168px large) and the
    hover/active scale animation are preserved so grid alignment with
    the app icons is unchanged.
  - Default clock position is now language-aware: when no per-user
    saved position exists, the clock defaults to the visually-leftmost
    cell of the first row — last DOM index in RTL (Arabic),
    first DOM index in LTR (English).

- artifacts/teaboy-os/src/components/clock.tsx
  - `readHomeClockPosition` now returns -1 as the "unset" sentinel
    instead of 0, so home.tsx can apply a language-aware default
    without overwriting saved positions.

Verification:
- Manual e2e: confirmed header has the inline count, clock has no
  frame, RTL default position is on the visual-left, drag-and-drop
  still persists across reload, long-press still toggles compact ↔
  large. All passed.

Out of scope: no server-side persistence; no changes to the topbar
clock, the dock, or the clock-style picker.
2026-04-21 13:39:22 +00:00
riyadhafraa 967cd628fa Add e2e test for home clock position and size persistence
Task #57: add an automated check that exercises the same flow that was
previously only manually verified — drag the home-page clock tile to a new
grid slot, long-press to flip it from compact to large, reload, and assert
both the position and size survive.

Implementation
- New Playwright spec at
  artifacts/teaboy-os/tests/home-clock-persistence.spec.mjs, mirroring the
  conventions of the existing leave-group-successor.spec.mjs (DB-seeded
  user, UI login, cleanup in afterAll).
- Drives a real pointer drag that satisfies dnd-kit's 8px activation
  threshold, then a separate long-press (>500ms, no movement) to trigger
  the size toggle in home.tsx without aborting the timer.
- Asserts both per-user localStorage keys are written
  (teaboy:home-clock-position:<id> and teaboy:home-clock-size:<id>) and
  that, after page.reload(), the clock tile still has col-span-2 / row-span-2
  classes and lives at the persisted index in the grid (not just in
  storage).

Verification
- Ran the new spec in isolation: 1 passed.
- Ran the full validation workflow (api-server tests + teaboy-os
  test:e2e): 18 + 3 passed.

No production code changes.

Replit-Task-Id: bd8d8372-358c-4676-b842-956dc0813cb8
2026-04-21 13:22:37 +00:00
riyadhafraa f56cd425c8 Add one-tap hide control to home clock tile
Original task: #56 — Let users hide or show the home clock with one tap.

Changes:
- artifacts/teaboy-os/src/pages/home.tsx: Added a small dismiss "×"
  button overlay on the SortableClockTile. The button stops pointer
  propagation so it does not trigger drag or the existing long-press
  size toggle. It calls setHomeClockVisible(false) (now destructured
  from useHomeClockVisibility) to hide the tile in one tap. The button
  uses absolute positioning with `end-1` so it works in both LTR and
  RTL. It is always visible at large size and revealed on hover/focus
  at compact size to keep the tile clean.
- artifacts/teaboy-os/src/locales/{en,ar}.json: Added
  `home.clockStyle.hideWidget` ("Hide clock" / "إخفاء الساعة") used
  as the button's aria-label and tooltip.

Re-showing the clock is handled by the existing toggle in the clock
style picker popover (already bilingual), so users can bring the
clock back later. Hiding/showing keeps the persisted grid position.

Notes / deviations:
- Did not add a context-menu since long-press is already used for the
  size toggle on the same tile and would conflict.
- Pre-existing TypeScript errors in unrelated files (admin.tsx,
  clock-style-picker.tsx codegen drift) are not addressed here.

Replit-Task-Id: 87bb057d-dc81-4916-8bb1-b24e34ff4794
2026-04-21 13:16:15 +00:00
riyadhafraa 2eddc6d407 Task #55: Movable, resizable home clock with Latin digits
- Refactor AnalogClockWidget: Latin 1-12 digits (was Roman), `size`
  (px) prop with scale-based interior, optional `showLabels`.
- Add useHomeClockSize (compact|large) and useHomeClockPosition hooks
  in clock.tsx — both persist to localStorage and broadcast a custom
  event so consumers stay in sync within the tab.
- home.tsx: introduce SortableClockTile that participates in the same
  dnd-kit grid as app icons via id `__clock`. App ids now prefixed
  `app-` so they don't collide. Long-press (500ms) toggles
  compact↔large; large = col-span-2 row-span-2. Custom pointer
  handlers chain with dnd-kit's listener so drag still works.
- handleDragEnd computes new app order excluding the clock and only
  fires updateOrder when app order actually changed.
- Remove the standalone AnalogClockWidget block above the apps grid;
  clock now lives inside the grid.
- When homeClockVisible is false, the clock is also excluded from
  sortable items (no dnd-kit warnings).
- e2e test passed: in-grid placement, Latin digits, long-press
  resize, drag-reorder, position persists across reload.
2026-04-21 13:04:45 +00:00
riyadhafraa 5390a5a315 Task #55: Movable, resizable home clock with Latin digits
- Refactor AnalogClockWidget: Latin 1-12 digits (was Roman), `size`
  (px) prop with scale-based interior, optional `showLabels`.
- Add useHomeClockSize (compact|large) and useHomeClockPosition hooks
  in clock.tsx — both persist to localStorage and broadcast a custom
  event so consumers stay in sync within the tab.
- home.tsx: introduce SortableClockTile that participates in the same
  dnd-kit grid as app icons via id `__clock`. App ids now prefixed
  `app-` so they don't collide. Long-press (500ms) toggles
  compact↔large; large = col-span-2 row-span-2. Custom pointer
  handlers chain with dnd-kit's listener so drag still works.
- handleDragEnd computes new app order excluding the clock and only
  fires updateOrder when app order actually changed.
- Remove the standalone AnalogClockWidget block above the apps grid;
  clock now lives inside the grid.
- When homeClockVisible is false, the clock is also excluded from
  sortable items (no dnd-kit warnings).
- e2e test passed: in-grid placement, Latin digits, long-press
  resize, drag-reorder, position persists across reload.
2026-04-21 13:03:05 +00:00
riyadhafraa f52701ef74 Task #55: Movable, resizable home clock with Latin digits
- Refactor AnalogClockWidget: Latin 1-12 digits (was Roman), `size`
  (px) prop with scale-based interior, optional `showLabels`.
- Add useHomeClockSize (compact|large) and useHomeClockPosition hooks
  in clock.tsx — both persist to localStorage and broadcast a custom
  event so consumers stay in sync within the tab.
- home.tsx: introduce SortableClockTile that participates in the same
  dnd-kit grid as app icons via id `__clock`. App ids now prefixed
  `app-` so they don't collide. Long-press (500ms) toggles
  compact↔large; large = col-span-2 row-span-2. Custom pointer
  handlers chain with dnd-kit's listener so drag still works.
- handleDragEnd computes new app order excluding the clock and only
  fires updateOrder when app order actually changed.
- Remove the standalone AnalogClockWidget block above the apps grid;
  clock now lives inside the grid.
- When homeClockVisible is false, the clock is also excluded from
  sortable items (no dnd-kit warnings).
- e2e test passed: in-grid placement, Latin digits, long-press
  resize, drag-reorder, position persists across reload.
2026-04-21 12:56:33 +00:00
riyadhafraa 1277c71d11 Task #54: Make staying signed in reliable across all sign-in points
Background:
Task #53 fixed the login/register session persistence race by explicitly
awaiting `req.session.save` before responding. Other session-mutating
endpoints (notably `/auth/logout`) still relied on express-session's
default end-hook, which can flush the response before the store write
finishes — producing intermittent "still logged in" / "logged out"
glitches on the immediate next request.

Changes:
- New shared helper `artifacts/api-server/src/lib/session.ts` exporting
  `saveSession(req)` and `destroySession(req)` — promise wrappers around
  `req.session.save` / `req.session.destroy` so handlers can `await`
  store persistence before flushing the HTTP response. Documented the
  rationale in the file so future session-mutating routes use the same
  safe pattern.
- `artifacts/api-server/src/routes/auth.ts`:
  - `/auth/register` and `/auth/login` now use `await saveSession(req)`
    in place of the inline ad-hoc Promise wrapper.
  - `/auth/logout` is now async and `await`s `destroySession(req)`
    before responding, closing the same race for the destroy path.
- Audited remaining routes: only `auth.ts` mutates `req.session`; all
  other handlers only read `req.session.userId`, so no further changes
  are needed.

Notes / deviations:
- Pre-existing TypeScript errors in unrelated files (conversations,
  notes, users, api-zod exports) were left untouched — out of scope.
- New test file `artifacts/api-server/tests/auth-session-persistence.test.mjs`
  covers the acceptance criterion: login / register / logout each
  followed by an immediate `/auth/me` probe to assert the session was
  persisted (or destroyed) before the response was flushed. Modeled on
  the existing leave-test pattern. Full suite: 18/18 passing.

Replit-Task-Id: 11b72d21-d7c2-42cb-a4d9-f1197cfad4c5
2026-04-21 12:37:16 +00:00
riyadhafraa e8245dfa35 Fix flaky 'invalid successor' leave test: persist session before responding from login/register
Original task: investigate why "sole admin leaving with an invalid
successor returns 400 and does not leave" intermittently returned 401
instead of 400 in the API test suite.

Root cause:
express-session 1.19.0 wraps res.end and calls req.session.save()
asynchronously. Its writetop() helper synchronously flushes headers
(including Set-Cookie) and writes the body chunk before save completes,
only deferring the final _end until after the store write. With
Content-Length set, fetch sees the full body and resolves immediately,
so the test's next request (POST /conversations/:id/leave) frequently
arrived before connect-pg-simple finished inserting the session row in
Postgres. requireAuth then read no session, express-session generated a
brand-new sid, and the request was rejected with 401.

This was reproduced ~50% of the time across 10 runs and confirmed via
server-side logging showing the cookie sid not matching the freshly
generated server sid (proving store.get returned nothing).

Fix:
Explicitly await req.session.save() in the /auth/login and
/auth/register handlers after assigning req.session.userId. This
guarantees the session is persisted in Postgres before the response is
sent, eliminating the race for any client that immediately makes a
follow-up authenticated request.

Verification:
Ran the API test suite 15 consecutive times after the fix; all 15 runs
pass cleanly (15/15 tests). The full validation workflow also passes
the api-server tests on the post-fix run.

Files changed:
- artifacts/api-server/src/routes/auth.ts (await session.save in
  /auth/login and /auth/register)
- artifacts/api-server/src/middlewares/auth.ts (no behavior change;
  diagnostic logging added during debug was removed)

Replit-Task-Id: 34cbe0e0-1d23-4257-962a-7e3adddba45c
2026-04-21 12:33:24 +00:00
riyadhafraa a69323986c Wire leave-group successor picker UI test into automated suite
Original task: make the ad-hoc browser test for the leave-group
successor chooser dialog a persistent automated test that runs
alongside the existing api-server backend tests.

Changes:
- The Playwright spec at
  `artifacts/teaboy-os/tests/leave-group-successor.spec.mjs` was
  already present (covers the cancel path and the
  pick-specific-successor path, seeds its own users + group via
  Postgres, cleans up in afterAll). Verified it passes against the
  running web + api workflows.
- Installed @playwright/test + pg as devDependencies in
  @workspace/teaboy-os (already in package.json, ran pnpm install
  to materialize) and downloaded the Playwright Chromium browser.
- Added a root `test` script in package.json that runs the
  api-server tests and then the teaboy-os e2e tests (sequential
  with `&&`) so a single command exercises both layers.
- Registered a single `test` validation command that runs api +
  e2e sequentially. Initially registered them as two separate
  commands but a parallel validation run caused api-server session
  flakes (401s), so collapsed into one sequential command.
- Updated `scripts/post-merge.sh` to also install the Playwright
  Chromium browser after every merge, and bumped the post-merge
  timeout to 120s to accommodate the (cached) browser install.

Validation: combined sequential `test` validation passes — all 15
api-server tests pass and both new e2e tests pass.

Note: `artifacts/teaboy-os/public/opengraph.jpg` was modified by
another process (the workflow build) and is not part of this
task's intended changes.

Replit-Task-Id: ab9b6d6f-b68b-47ea-94e5-c34352afeb64
2026-04-21 12:24:25 +00:00
riyadhafraa cdc32061cb Add a Playwright UI test for the leave-group successor picker
Original task: Add a UI test for the leave-group successor chooser dialog
in artifacts/teaboy-os/src/pages/chat.tsx, mirroring the backend coverage
in artifacts/api-server/tests/conversations-leave.test.mjs.

What I added:
- artifacts/teaboy-os/tests/leave-group-successor.spec.mjs
  A real Playwright e2e test that drives the chat UI in a browser:
  * Cancel path: opens the leave dialog as the sole admin, verifies the
    successor chooser is visible with the auto option pre-selected and
    one option per remaining member, clicks Cancel, and asserts via DB
    that the conversation membership and admin flags are unchanged.
  * Chosen-successor path: re-opens the dialog, picks the *later-joined*
    member (so the choice differs from the auto pick), confirms the
    leave, asserts the POST /conversations/:id/leave call returns 200,
    and verifies via DB that the leaver was removed and the explicitly
    chosen member became the new admin.
  Both tests seed their own users + group via SQL and clean up after
  themselves so they can run repeatedly against the live dev DB.

- artifacts/teaboy-os/playwright.config.mjs
  Minimal Playwright config: testDir=tests, *.spec.mjs match, headless,
  baseURL defaults to http://localhost:80 (the workspace proxy), and
  is overridable via TEST_WEB_BASE.

- artifacts/teaboy-os/package.json
  Added @playwright/test and pg as devDependencies and a `test:e2e`
  script: `playwright test --config playwright.config.mjs`.

- .gitignore
  Ignored Playwright's test-results/ and playwright-report/ output dirs.

How to run:
  pnpm --filter @workspace/teaboy-os exec playwright install chromium
  DATABASE_URL=... pnpm --filter @workspace/teaboy-os run test:e2e

Verification:
  Both tests pass locally (2 passed in ~9s) against the running dev
  workspace. Required system libraries for headless Chromium were
  installed via the workspace's system-deps mechanism (glib, nss, nspr,
  atk, cups, dbus, libdrm, libxkbcommon, libgbm, alsa-lib, pango, cairo,
  and the relevant xorg libs), so `playwright test` works out of the
  box on this environment.

No application source files were modified.

Replit-Task-Id: d2f21eab-498e-4cc0-a913-6035b714b3da
2026-04-21 12:17:20 +00:00
riyadhafraa 8fb6d54d78 Add automated tests for the leave-and-handoff flow (Task #50)
Adds artifacts/api-server/tests/conversations-leave.test.mjs, modeled on
the existing apps-open.test.mjs, covering POST /conversations/:id/leave:

- Solo member leaving deletes the conversation entirely.
- Sole admin leaving with no successor auto-promotes the
  earliest-joined remaining member.
- Sole admin leaving with a chosen successorId promotes that user.
- Sole admin leaving with a non-member successorId returns 400 and
  leaves the group untouched (leaver still admin, no promotion).
- Non-admin leaving a group removes them with no admin promotion.

Tests create their own users (with the standard user role) and groups
directly in Postgres so joined_at ordering is deterministic for the
auto-promotion case, then exercise the route through HTTP using a real
session cookie obtained from POST /api/auth/login. An after() hook
cleans up all created conversations, participants, messages, role
assignments, and users.

The optional e2e for the chooser dialog is intentionally deferred and
proposed as follow-up #51.

Verified by running `pnpm --filter @workspace/api-server test` three
times consecutively; all 15 tests pass on every run.

Replit-Task-Id: e31c169d-a4f5-4387-a642-b39a422c1408
2026-04-21 12:01:41 +00:00
riyadhafraa 42c2910d4b Show new admin clearly after sole admin leaves group chat
Task #49: When the sole admin leaves a group and a successor is auto- or
manually-promoted, surface the change prominently in addition to the existing
system messages.

Changes:
- artifacts/teaboy-os/src/pages/chat.tsx
  - New effect on conversations list: tracks the set of group conversations
    where the current user is currently an admin (from participant.isAdmin).
    On first load it silently records a baseline in localStorage
    (key teaboy:admin-known:<userId>); thereafter, any newly-admin group
    triggers a toast ("You are now the admin of <group>"). The set is pruned
    when the user is no longer admin so a future re-promotion toasts again.
    Using participant.isAdmin (rather than only lastMessage) ensures the cue
    fires even if newer messages have arrived in the conversation since the
    promotion.
  - Conversation list rows now render a small amber "New admin" / "You are now
    the admin" Crown badge whenever the most recent message is an
    admin_promoted system message. Variant differs for the promoted user vs
    other members. data-testid="badge-new-admin-<convId>" for tests.
  - Imported Crown from lucide-react.
- artifacts/teaboy-os/src/locales/en.json + ar.json
  - Added bilingual strings under chat.actions:
    youAreAdminTitle, youAreAdminDescription, newAdminBadge, newAdminLabel.

Implementation notes:
- lastMessage.meta is already returned by GET /conversations and includes the
  promoted user (id, displayNameAr/En, username), so no API changes were needed.
- Regenerated api-client-react via `pnpm --filter @workspace/api-spec run
  codegen` (pre-existing stale codegen was failing typecheck unrelated to this
  task, now clean for chat.tsx).
- Did not add automated tests; the existing follow-up task "Make sure the
  leave-and-handoff flow stays working with automated tests" already covers it.

Replit-Task-Id: 71495f44-8c6c-4f7f-8f48-6400630d1203
2026-04-21 11:53:59 +00:00
riyadhafraa 216ff65e04 Task #48: Let admins page through more than the last 100 opens
Added offset/limit pagination to the two admin app-opens drill-in
endpoints so admins can investigate spikes that span more than the
default 100 most-recent opens.

Backend (artifacts/api-server/src/routes/stats.ts):
- New parsePaging() helper validates `limit` (1..200, default 100) and
  `offset` (>=0, default 0); invalid values return 400.
- Both `/stats/admin/app-opens/by-app/:appId` and
  `/stats/admin/app-opens/by-user/:userId` accept the new params, apply
  `.limit(limit).offset(offset)`, and return `limit`, `offset`, and a
  `nextOffset` (number | null) computed from `totalCount`.
- Added a stable secondary sort (`id desc`) so paged results don't
  shuffle when timestamps tie.

Spec & client (lib/api-spec/openapi.yaml + regenerated clients):
- Added `limit`/`offset` query params and `limit`/`offset`/`nextOffset`
  response fields to AdminAppOpensByApp/AdminAppOpensByUser.
- Re-ran `pnpm --filter @workspace/api-spec run codegen`.

Frontend (artifacts/teaboy-os/src/pages/admin.tsx + locales):
- AppOpensDrillIn / UserOpensDrillIn now accumulate extra pages in
  local state and expose a "Load more" button via a shared
  LoadMoreSection footer that also shows "Showing X of Y".
- Extra pages are fetched via the generated `getAdminAppOpensByApp` /
  `getAdminAppOpensByUser` functions; accumulated state resets when
  the appId/userId or stats query params change.
- Added en/ar translations for `loadMore`, `loadMoreError`, `shownOf`.

Tests:
- New artifacts/api-server/tests/admin-app-opens-pagination.test.mjs
  covers happy-path paging for both endpoints, the default page size,
  and 400 responses for invalid limit/offset.
- All 10 api-server tests pass; full workspace typecheck passes.

Replit-Task-Id: b6382efe-765f-4689-8c93-196fee253f63
2026-04-21 11:48:40 +00:00
riyadhafraa ce0819cfaa Make admin recent-opens drill-in rows clickable
Task: #47 — Let admins jump from a recent open straight to that user.

Changes (artifacts/teaboy-os/src/pages/admin.tsx):
- AppOpensDrillIn: each user row in the per-app recent-opens popup is
  now a focusable button. Clicking jumps to that user's row in the
  Users list (closes the popup, then calls the existing
  handleSelectUserFromDashboard via a new onJumpUser prop), reusing
  the highlight behavior that already powers the leaderboard.
- UserOpensDrillIn: each app row in the per-user recent-opens popup is
  now a focusable button. Clicking opens that app's edit modal
  (closes the popup, then calls the existing
  handleSelectAppFromDashboard via a new onJumpApp prop), mirroring
  the leaderboard click behavior.
- Added type="button", hover/focus styles, and aria-labels reusing
  the existing admin.dashboard.viewUserDetails /
  admin.dashboard.viewAppDetails translation keys (already localized
  for both en and ar).

The footer "Edit app" / "View user" buttons remain unchanged and
keep working alongside the per-row clicks.

No new translation keys, schema changes, or API changes were needed —
AppOpenByAppEntry already exposes userId and AppOpenByUserEntry
already exposes appId.

Verification: tsc --noEmit on teaboy-os shows no new errors from
these edits (only the same pre-existing errors that were present
before this task). E2E was not run because the change is a thin
wiring of existing handlers and admin login requires custom
session setup beyond this task's scope.

Replit-Task-Id: 5db0964e-95fa-4199-9337-631cd1a790ec
2026-04-21 11:39:34 +00:00
riyadhafraa 0b7593bbc2 Let leaving admins choose who takes over the group (task #46)
Original ask: when the only admin leaves a group, let them pick a
specific successor instead of always auto-promoting the longest-tenured
member. Keep "auto" available, with bilingual labels.

Changes:
- lib/api-spec/openapi.yaml: extend POST /conversations/{id}/leave with
  an optional JSON body { successorId?: number | null }.
- Regenerated lib/api-client-react and lib/api-zod via api-spec codegen.
- artifacts/api-server/src/routes/conversations.ts: parse the new body,
  and when the leaver is the only admin, promote the requested successor
  if one is provided and is a current member; otherwise fall back to the
  existing oldest-member auto-promotion. Returns 400 if successorId is
  not a remaining member.
- artifacts/teaboy-os/src/pages/chat.tsx:
  - Track a successorChoice state ("auto" | userId).
  - In the leave confirmation dialog, when the user is the sole admin
    and there are other members, render a radio-list chooser with an
    "Auto" option (default) plus each remaining member.
  - Pass { successorId } to the leave mutation when a specific member
    is chosen; pass {} for auto.
  - Reset choice on success.
- artifacts/teaboy-os/src/locales/{en,ar}.json: added successorTitle,
  successorHelp, successorAuto strings.

Verification:
- pnpm -w run typecheck passes for libs and all artifacts.
- Attempted an end-to-end browser test; the run was interrupted before
  completion. Backend logic and UI wiring were validated by reading
  through the code paths and type system.

Replit-Task-Id: c9065bc1-ab4e-4a3b-a865-81754f5c2e5a
2026-04-21 11:29:39 +00:00
riyadhafraa a864b84567 Add notes functionality to the application with CRUD operations and labeling
Integrates a new Notes feature, including backend API routes for notes and labels, database schema updates, frontend UI components for creating, viewing, editing, and deleting notes, and internationalization support for notes in both English and Arabic.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 4ab7f101-06a9-4dd7-94c8-617f1751327c
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/fYGOSe0
Replit-Helium-Checkpoint-Created: true
2026-04-21 11:29:05 +00:00
riyadhafraa 8729cae01a Task #45: Tapping a chat notification opens the matching conversation
- notifications.tsx: When a notification is clicked, if it has
  relatedType === "conversation" and a relatedId, navigate to
  /chat?c=<conversationId> in addition to marking it read. Other
  notification types continue to behave as before (just mark read).
- chat.tsx: Read the optional `c` query parameter via wouter's
  useSearch hook. When present and valid, set it as the
  selectedConvId so the conversation opens automatically, then
  replace the URL back to /chat so refreshing or navigating away
  doesn't keep re-opening it.

No API or schema changes required; notification records already
carry relatedType/relatedId for chat notifications.

Replit-Task-Id: 2fda1864-99d6-4f07-a3d9-aa3021d5493f
2026-04-21 11:07:55 +00:00
riyadhafraa 1411486602 Push notification_created socket event for instant bell badge updates
Original task: Make the bell badge update instantly when a chat
notification arrives.

Changes:
- artifacts/api-server/src/routes/conversations.ts: After
  createMessageNotifications inserts the rows, emit a
  `notification_created` event to each recipient's `user:{id}` room
  (carrying type/relatedId/relatedType for future routing).
- artifacts/teaboy-os/src/hooks/use-notifications-socket.ts: New hook
  that opens a global socket connection (when the user is logged in)
  and invalidates getListNotificationsQueryKey() and
  getGetHomeStatsQueryKey() whenever `notification_created` fires.
- artifacts/teaboy-os/src/App.tsx: Mounts the hook via a small
  NotificationsSocketBridge component inside AuthProvider so the
  listener is active on every page (home, notifications, services,
  etc.), not just /chat.

Notes:
- Socket join already happens server-side on connect
  (`socket.join('user:{userId}')`), so no API server topology change
  was needed.
- Pre-existing TS errors in api-server and teaboy-os are unrelated to
  this change.

Replit-Task-Id: ff3973f9-1c9d-4283-8091-bfeb3eb0d6a4
2026-04-21 10:41:01 +00:00
riyadhafraa ce1fb84365 Task #43: Stop counting system messages as unread
Problem: Group rename, member-add, and member-remove events insert rows
into the messages table with the actor as senderId, which made them
increment the unread badge for everyone else just like a normal chat
message. That created notification noise for routine admin tweaks.

Fix: In `artifacts/api-server/src/routes/conversations.ts`, the
`buildConversationDetails` unread count query now restricts to
`messages.kind = 'user'`, so only real user chat messages contribute to
the unread count returned for the conversation list / bell badge.

Notes / non-changes:
- The conversation-list "last message" preview is intentionally left
  unfiltered, so the most recent activity (including system messages)
  still surfaces in the list — matches the task's "Done looks like".
- Push-style chat notifications (`createMessageNotifications`) are only
  invoked from the user send-message route, never from
  `insertAndEmitSystemMessage`, so no additional guard is required for
  system events today.
- Frontend chat.tsx already renders system messages distinctly and
  shows them in the list preview; no UI change needed.

Replit-Task-Id: 3734d73b-2df7-4f32-9655-6c7a9e23536c
2026-04-21 10:35:54 +00:00
riyadhafraa b6a0dc6ab9 Add admin recent-opens drill-in popup for top apps and users
Task #41: Show a usage history popup when admins click a top
apps row or a most-active users row on the admin dashboard.

Changes:
- API: extracted the existing range/from/to parser in
  artifacts/api-server/src/routes/stats.ts into a shared
  parseRangeWindow() helper so the same window logic powers
  the existing /stats/admin endpoint and two new ones.
- API: added GET /stats/admin/app-opens/by-app/:appId returning
  the last 100 opens for an app inside the selected window,
  including the user (id, username, displayName, avatarUrl)
  and a totalCount. requireAuth + requireAdmin guarded.
- API: added GET /stats/admin/app-opens/by-user/:userId with
  the same shape but per-app metadata for each open.
- Spec: added matching paths and AdminAppOpensByApp /
  AdminAppOpensByUser schemas in lib/api-spec/openapi.yaml,
  reran orval codegen for api-client-react and api-zod.
- UI: in artifacts/teaboy-os/src/pages/admin.tsx the Top apps
  and Most active users leaderboard rows now open a drill-in
  modal instead of immediately navigating away. The modal
  shows a scrollable timeline of recent opens (timestamp +
  user/app), respects the dashboard's current range selector
  (7d/30d/90d/custom), and exposes an "Edit app" / "View user"
  footer button that preserves the previous jump-to behaviour.
  Loading, error, and empty states are handled.
- i18n: added admin.dashboard.drillIn keys in en.json and
  ar.json (titles, subtitle, empty/error, footer buttons).

Verification: pnpm run typecheck passes.

Follow-ups proposed: #47 (clickable rows inside the popup),

Replit-Task-Id: f2fbe652-a788-4f25-9fb2-9ef2c535c8da
#48 (paginate beyond 100 opens).
2026-04-21 10:17:41 +00:00
riyadhafraa a52c1659fc Stop a group from being orphaned when its only admin leaves (Task #40)
The /conversations/:id/leave handler used to delete the leaver's
participant row unconditionally. If the leaver was the only admin, the
group survived but no one could rename it, change the picture, or
add/remove members. If they were also the only participant, the empty
conversation lingered forever.

Server (artifacts/api-server/src/routes/conversations.ts):
- Load all participants ordered by joinedAt before mutating anything.
- If the leaver is the only participant, delete the conversation row
  (cascades clean up participants, messages, and reads) and skip the
  emit.
- If the leaver is the only admin, promote the longest-tenured
  remaining participant (oldest joinedAt) to admin in the same flow.
- Emit a `member_left` system message and, when applicable, an
  `admin_promoted` system message (with reason `previous_admin_left`)
  before removing the leaver, so members see both events live.

Client (artifacts/teaboy-os/src/pages/chat.tsx + locales):
- Render the new `member_left` and `admin_promoted` system message
  kinds with bilingual copy in en.json and ar.json.
- Extended SystemMessageMeta with `promoted` and `reason` fields.

Approach notes:
- Chose auto-promotion over a chooser dialog to keep the leave flow
  one-tap; proposed a follow-up (#46) for an optional successor
  picker.
- API contract for /leave is unchanged (still POST with no body), so
  no openapi.yaml or codegen changes were needed.
- Pre-existing TypeScript errors in auth.ts, admin.tsx, etc. are
  unrelated codegen drift and were left alone.

Replit-Task-Id: 026e59a5-90c0-4faa-9080-aee0aee0a631
2026-04-21 09:44:00 +00:00