Skip to content

feat(mobile): PR 5d — kilo-chat routes + deep links#2953

Merged
iscekic merged 76 commits intofeat/kilo-chat-migration-pr1from
feat/kilo-chat-migration-pr5d
Apr 30, 2026
Merged

feat(mobile): PR 5d — kilo-chat routes + deep links#2953
iscekic merged 76 commits intofeat/kilo-chat-migration-pr1from
feat/kilo-chat-migration-pr5d

Conversation

@iscekic
Copy link
Copy Markdown
Contributor

@iscekic iscekic commented Apr 30, 2026

Summary

PR 5d of the mobile kilo-chat migration. Wires up the new sandbox/conversation chat routes and deep links so the app can reach kilo-chat. Stream chat still works in parallel — this is the soak point before PR 6 cuts over.

Stacked on top of #2951 (PR 5c).

What's in this PR

  • New routes under apps/mobile/src/app/(app)/chat/[sandbox-id]/:
    • _layout.tsx — Stack
    • index.tsxConversationListScreen
    • [conversation-id].tsxConversationScreen (looks up title via useConversationDetail)
  • notifications.ts: replaced inline notificationDataSchema with pushDataSchema from @kilocode/notifications. Replaced activeChatInstanceId / setActiveChatInstance with activeChatLocation / setActiveChatLocation({ sandboxId, conversationId }). Tap and cold-start handlers now route to /(app)/chat/{sandboxId}/{conversationId}.
  • conversation-screen.tsx: on focus calls setActiveChatLocation, on blur clears it — suppresses foreground notifications for the conversation the user is viewing.
  • Cascading discriminator update from 'chat''chat.message' in legacy kiloclaw/chat.tsx and use-unread-counts-invalidation.ts (these compile against the new pushDataSchema).

Deviations from the plan

  • index.tsx looks up sandboxLabel from useAllKiloClawInstancesConversationListScreen requires the prop and the plan snippet omitted it.
  • [conversation-id].tsx passes the kilo-chat client as first arg to useConversationDetail(client, conversationId) — matches the actual hook signature.

Route coexistence note

chat/[instance-id].tsx (legacy Stream) and chat/[sandbox-id]/ (new) coexist during the soak window. One-segment navigation (e.g., from kiloclaw-card) lands on the legacy route — intentional. Two-segment navigation (notifications, conversation-list taps) lands on the new route. PR 6 deletes the legacy file.

Test plan

  • Typecheck clean for files in this PR (5 pre-existing errors in kiloclaw/chat.tsx + use-unread-counts.ts are unchanged from base)
  • Lint clean for files in this PR (1 pre-existing error in use-unread-counts.ts unchanged)
  • Manual: tap a kiloclaw card → still lands on legacy chat (soak)
  • Manual: tap a notification → lands on /(app)/chat/{sandboxId}/{conversationId} (new route)
  • Manual: open a conversation → foreground push for that exact conversation is suppressed; pushes for other conversations show normally

iscekic added 30 commits April 29, 2026 17:28
The badge_counts.badge_bucket column is a free-form string. To prevent
namespace collisions as more surfaces start emitting badge updates
(per-instance today, per-conversation later), centralize bucket-key
derivation in @kilocode/notifications and route NotificationChannelDO
through it. Mirrors the presence-context builders in @kilocode/event-service.

Safe to introduce now without a data migration because PR 2's migration
already wipes badge_counts.
…-chat producer

Adds kiloclawInstanceContext and kiloclawConversationContext path
builders to @kilocode/event-service, replacing hardcoded template
literals in kilo-chat's event-push.ts and its test so all callers
share a single source of truth.
When a chat message is persisted, fire-and-forget a call to
NOTIFICATIONS.sendPushForConversation so non-sender human members of the
conversation receive a push. Runs after realtime/event-service delivery
inside postCommitFanOut, with errors swallowed so push failures cannot
fail the send.

- Skip when there are no other human recipients or no sandboxId.
- senderUserId = callerId for human senders, null for bot senders.
- title is "<sandboxLabel> · <conversationTitle>"; bodyPreview is the
  first 200 chars of the concatenated text blocks.
- Add @kilocode/notifications workspace dep and layer the RPC method
  shape into Env via bindings.d.ts.
- Add a notifications-stub worker to the vitest config so tests can
  spy on env.NOTIFICATIONS.sendPushForConversation, and globally mock
  sandbox-lookup in setup.ts (it imports pg via @kilocode/db).
…es, fix test mock

- Remove `stream-chat` from `services/notifications/package.json`; the Stream
  webhook (its only consumer) was deleted earlier in the stack.
- Regenerate `worker-configuration.d.ts` so the workerd runtime types match the
  current toolchain (sibling services were on `1.20260312.1`; this one had
  drifted to `1.20251217.0` from a stale local cache).
- Fix the global test mock to reference the renamed `badge_counts` table; the
  setup file was authored against the pre-rename name and never matched.
- Tidy two pre-existing lint nits in the new test files (`import type` for
  type-only import, drop unused `cols` parameter).
…leak

- Switch `NotificationsService` from default-only to a named class export
  with a separate default. `services/kilo-chat/wrangler.jsonc` binds via
  `entrypoint: "NotificationsService"`, which resolves named module
  exports. The default-only form (`export default class NotificationsService`)
  exports under the `default` key — kilo-chat's RPC binding would not have
  resolved at deploy. Mirrors the existing pattern in
  `services/kilo-chat/src/index.ts` (`KiloChatService`).

- `dispatchPush` now uses a two-stage idempotency record (`pending` →
  `delivered`). The badge increment was previously non-idempotent: an
  Expo failure returned `failed` without writing the idempotency key, so
  upstream retries (which the design explicitly invites) re-ran the
  increment before the next send and inflated the badge by one per
  retry. The `pending` marker is written before the increment and
  short-circuits the increment on retry; the `delivered` marker is only
  written on success.

- `setAlarm` is now gated on `getAlarm() === null`. Calling `setAlarm`
  unconditionally on each successful push — as the previous code did —
  replaces the pending alarm and pushes the cleanup forward indefinitely
  on a conversation receiving more than one push per `IDEM_TTL_MS`,
  leaking expired idempotency entries.

Adds two test cases covering the badge-retry and alarm-reset paths.
- Schedule the cleanup alarm when writing the `pending` marker, not only
  on `delivered`. Without this, an Expo failure followed by no further
  push activity for the conversation leaves the `pending` record in DO
  storage forever (no alarm was ever set to prune it).

- After the alarm fires, reschedule for the earliest remaining record's
  expiry instead of leaving the alarm slot empty. Otherwise a quiet
  conversation strands its younger entries until some unrelated future
  dispatch wakes the DO up.

Both paths go through a small `ensureCleanupAlarm` helper that gates on
`getAlarm() === null` so a busy conversation still doesn't push the
alarm forward on every call.
The kiloclaw-scoped presence paths are literally `/presence` prefixed
onto the kiloclaw event-context paths. Build them by composition so the
`/kiloclaw/{sandboxId}[/{conversationId}]` segment shape is defined in
exactly one place — `kiloclaw-contexts.ts`.

Pure refactor; same string output, template-literal types still narrow
to the same shape.
Introduces a single app-shell EventServiceProvider that owns the
EventServiceClient and KiloChatClient for all authenticated routes.
Mounted in (app)/layout.tsx so platform/instance/conversation presence
subscriptions and the kilo-chat UI share one WebSocket.

KiloChatLayout now consumes the global clients via useEventServiceClient()
instead of spinning up its own pair, and the getToken prop is removed from
KiloChatLayoutProps (along with both call sites). The local
useEventService(getToken) factory is dead code and has been deleted;
useInstanceContext / useConversationContext stay since they take
EventServiceClient as a parameter.
Thin hook that subscribes the global EventServiceClient to a single
context for the lifetime of the calling component, gated by an `active`
flag. Will back upcoming platform- and instance-level presence
indicators.
…eSubscription

- Drop dead getToken field from KiloChatContextValue (no consumers).
- Remove useInstanceContext / useConversationContext hooks; both call
  sites now use the shared usePresenceSubscription primitive directly.
- Harden usePresenceSubscription against empty-string contexts.
- usePresenceSubscription: accept 'string | null' instead of empty-string
  sentinel; update call sites (KiloChatLayout, MessageArea, useInstancePresence)
- kilo-chat router: validate expiresAt with z.iso.datetime()
- kilo-chat-router test: verify the JWT payload (kiloUserId, tokenSource,
  version) and that expiresAt lands in the expected ~1h window
- MessageArea: comment distinguishing the always-on chat-event subscription
  from the visibility-gated presence subscription
Multiple consumers can now independently hold the same context without
trampling each other. The wire context.subscribe/context.unsubscribe
messages are only sent on the 0->1 and 1->0 refcount transitions; the
intermediate churn stays client-side.

Resubscribe-on-reconnect dedupes by context key.

Tests cover: double-subscribe collapses to a single wire send, partial
unsubscribe keeps the context alive, last-consumer-out releases it,
mixed batches only send newly-active contexts, unknown-context
unsubscribes are no-ops, and reconnect resubscribes each context once.
iscekic added 21 commits April 30, 2026 12:13
…send

Move PAGE_SIZE, helper functions (applyReactionAdded/Removed, restoreMessageInCache,
removeMessageFromCache, findMessageInCache), useMessages infinite-query hook, and
useSendMessage mutation into @kilocode/kilo-chat-hooks. Web's useMessages.ts re-exports
the moved hooks and retains local helper copies for remaining mutations (37b will collapse).
…kage

Moves the live event-stream cache patcher from the web-only useMessages
file into @kilocode/kilo-chat-hooks. Adds an optional onActionFailed
callback so platform wrappers inject toasts; web passes toast.error.
…on API

- Add packages/kilo-chat-hooks/src/query-keys.ts with conversations/
  conversation/messages/bot-status helpers; route every hook + invalidator
  through it. Fixes the mobile useInstanceEventSubscription bug where
  invalidations used ['conversations', sandboxId] but the queries register
  under ['kilo-chat', 'conversations', sandboxId], so list previews and
  unread counts never refreshed on incoming events.
- useEventSubscription now takes a single event name; callers register one
  hook per event. Drops the events.join('|') dependency hack and the
  eslint-disable. useInstanceEventSubscription becomes six explicit
  registrations.
- Drop the hardcoded English toast string from useMessageCacheUpdater;
  onActionFailed is () => void and the message lives at each call site.
- Extract useAppActiveAndFocused to deduplicate AppState+focus boilerplate
  shared by useInstancePresence and useConversationPresence.
The instance-level subscription was listening for message.created/updated/
deleted, which are published on conversation contexts and never fire here.
Replace them with conversation.renamed, conversation.read, and
conversation.activity — the events kilo-chat actually pushes to the
instance context — so list updates (title, unread, last-activity)
invalidate the conversations query as intended.
Required by the kilo-chat MessageList and ConversationListScreen components.
…RVICE_URL

These were declared in env-keys.js by PR 5a but never added to apps/mobile/.env,
which broke the dev build.
Implement MessageList using FlashList v2 with maintainVisibleContentPosition
and startRenderingFromBottom for chat layout; wire fetchOlder via onStartReached.
- Drop double-cast `as unknown as Href` in favor of `as Href`
- Use themed `Text` from `@/components/ui/text` and local `useKiloChatClient`
  re-export in `MessageBubble`
- Switch `crypto.randomUUID()` to `expo-crypto`'s `Crypto.randomUUID` to
  match existing usage in `cloud-agent-runtime.ts`
@iscekic iscekic self-assigned this Apr 30, 2026
Comment thread apps/mobile/src/components/kiloclaw/chat.tsx Outdated
@kilo-code-bot
Copy link
Copy Markdown
Contributor

kilo-code-bot Bot commented Apr 30, 2026

Code Review Summary

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 0

Fix these issues in Kilo Cloud

Issue Details (click to expand)

WARNING

File Line Issue
apps/mobile/src/components/kiloclaw/chat.tsx 84 Resolved in d4e68ccd: legacy chat foreground-push clearing now uses badgeBucketForConversation(...) instead of the old { channelId } shape.
Other Observations (not in diff)

Issues found in unchanged code that cannot receive inline comments:

File Line Issue
apps/mobile/src/lib/hooks/use-unread-counts.ts 27 getUnreadCounts now returns badgeBucket, but this hook still reads row.channelId, so dashboard unread maps will be keyed by undefined and badges will not render correctly.
Files Reviewed (1 file incrementally)
  • apps/mobile/src/components/kiloclaw/chat.tsx - 0 new issues

Reviewed by gpt-5.5-20260423 · 372,048 tokens

Base automatically changed from feat/kilo-chat-migration-pr5c to feat/kilo-chat-migration-pr1 April 30, 2026 13:35
…to feat/kilo-chat-migration-pr5d

# Conflicts:
#	apps/mobile/src/components/kilo-chat/conversation-screen.tsx
#	apps/mobile/src/components/kiloclaw/chat.tsx
#	apps/mobile/src/lib/notifications.ts
#	packages/kilo-chat/src/utils.ts
#	packages/notifications/src/badge-buckets.ts
#	services/kilo-chat/wrangler.jsonc
@iscekic iscekic merged commit 5dd0005 into feat/kilo-chat-migration-pr1 Apr 30, 2026
1 check passed
@iscekic iscekic deleted the feat/kilo-chat-migration-pr5d branch April 30, 2026 13:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant