Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
75 commits
Select commit Hold shift + click to select a range
5cdb59a
removed import errors for types
masonomara Sep 4, 2025
d99584b
Fixed imports
masonomara Sep 4, 2025
9c34eda
setting up new chart
masonomara Sep 4, 2025
321a428
reset home
masonomara Sep 4, 2025
5fa6760
removed directions
masonomara Sep 4, 2025
f091da1
made it look pretty
masonomara Sep 4, 2025
84362e8
styled the context toggle
masonomara Sep 4, 2025
bc5410c
styling
masonomara Sep 4, 2025
1227d90
got started ons tyling and tides for business
masonomara Sep 4, 2025
6adce09
feat(charts): implement new energy chart with time context controls
masonomara Sep 4, 2025
15e45c6
spec file writing
masonomara Sep 5, 2025
526076e
Removed Server context
masonomara Sep 5, 2025
1649233
removed server context
masonomara Sep 5, 2025
59b05b5
refactor(mobile): extract Chat screen and clean up Home component
masonomara Sep 5, 2025
d039ff9
added back ServerEnvironment
masonomara Sep 5, 2025
6b224ae
ui rpesenter view working well
masonomara Sep 5, 2025
5c94f4c
got soem items working on @Chat
masonomara Sep 5, 2025
7a46b67
organized the @Home component
masonomara Sep 6, 2025
7b0eb57
foxed home display
masonomara Sep 6, 2025
b91150f
splitting up timecontext responsibilities
masonomara Sep 6, 2025
a8e28f6
deleted contextToggle
masonomara Sep 6, 2025
694cbe6
removed unused exports from timeContext
masonomara Sep 6, 2025
023f4ff
depreaciated Old TimeContext
masonomara Sep 6, 2025
687db37
created TimeContext
masonomara Sep 6, 2025
e219988
localization setup
masonomara Sep 6, 2025
42c8dc6
feat(mobile): implement ChartDisplayContext for centralized chart par…
masonomara Sep 6, 2025
6c525a8
cleaned up navigator options
masonomara Sep 6, 2025
e297f41
refactor(mobile): eliminate context race conditions and consolidate r…
masonomara Sep 6, 2025
4e6cf44
completely removed depreciated timeContext
masonomara Sep 6, 2025
bcaec1b
refactor(mobile): finalize component extraction and cleanup analysis …
masonomara Sep 6, 2025
fe7dd4d
Cleaned up notes
masonomara Sep 7, 2025
6675a9d
created some spec docs
masonomara Sep 7, 2025
88e0f8c
debugging go
masonomara Sep 7, 2025
26cb2e1
setup dev environment
masonomara Sep 7, 2025
1394056
punt the energy chart for a moment and lets focus on the chat input
masonomara Sep 7, 2025
219c056
chat focus
masonomara Sep 7, 2025
83d591e
add depreciated chatcontext
masonomara Sep 7, 2025
a00631a
added new chat provider
masonomara Sep 7, 2025
5d458b0
added toolbar slider
masonomara Sep 7, 2025
621fde0
fresh chat component
masonomara Sep 7, 2025
865efe7
overloaded chat compoennts
masonomara Sep 7, 2025
4e77567
set up wiring between chat
masonomara Sep 7, 2025
df8bc44
handling depreciated stuff
masonomara Sep 8, 2025
fd3920f
updated tool config
masonomara Sep 8, 2025
00d3193
changed name of demo data
masonomara Sep 8, 2025
3519e2f
changed demo data namne
masonomara Sep 8, 2025
790490d
got rid of unjust flow
masonomara Sep 8, 2025
cf6a463
removed and moved old files relate dto chat
masonomara Sep 8, 2025
0f0e7e0
removed depreciated chat
masonomara Sep 8, 2025
04829fb
removed old items
masonomara Sep 8, 2025
0ac44a1
refactor(mobile): reduce ChatToolbar complexity by 44%
masonomara Sep 8, 2025
8a8a501
refactor(mobile): reduce ChatContext complexity by 36%
masonomara Sep 8, 2025
e0dd19e
cleaning up
masonomara Sep 8, 2025
f19e89d
removed unused component
masonomara Sep 8, 2025
479e99a
getting rid of silly stuff
masonomara Sep 8, 2025
d7c6e31
udpated claude
masonomara Sep 8, 2025
a9cec78
got rid of unused agentService detials
masonomara Sep 8, 2025
105bcec
formatted all services
masonomara Sep 8, 2025
0d298c7
rearranged docs
masonomara Sep 8, 2025
3669700
fixed up docs
masonomara Sep 8, 2025
3b6ef45
cleaned up unnecesary items
masonomara Sep 8, 2025
3d6fcd1
got rid of unused compoennt
masonomara Sep 8, 2025
5d9df60
server environment removal
masonomara Sep 8, 2025
8027db2
removed variable server environment
masonomara Sep 8, 2025
c37e6da
removing server environment
masonomara Sep 8, 2025
39b4ea7
got rid of bad doc
masonomara Sep 8, 2025
dcc5c46
refactor(mobile): restructure chat context architecture with modular …
masonomara Sep 8, 2025
4fe61be
idk like dont shoot the messengertype stuff
masonomara Sep 8, 2025
f8ab8f1
cleane dup chat cotnesxt
masonomara Sep 8, 2025
6bcb504
Added cheap logging messages
masonomara Sep 9, 2025
7e275c5
cleanign up tide cotnext
masonomara Sep 9, 2025
c8c44b6
removed heirarchal flow from frontend
masonomara Sep 9, 2025
5e0f375
All flow_type references have been cleanly removed from the storage l…
masonomara Sep 9, 2025
0173778
refactor: complete removal of hierarchical tide architecture and flow…
masonomara Sep 9, 2025
ebdf660
added time context to settings
masonomara Sep 9, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
617 changes: 617 additions & 0 deletions AGENT_SERVER_INTEGRATION_GUIDE.md

Large diffs are not rendered by default.

252 changes: 252 additions & 0 deletions CHAT_CONTEXT_REFACTOR.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
# Chat Context Refactor

**Files to focus on:**
- `apps/mobile/src/context/ChatContext.tsx`
- `apps/mobile/src/components/chat/ChatInput.tsx` - for the secnding messages to agent endpoint functionality

## Summary

`apps/mobile/src/context/ChatContext.tsx` needs a refactor

## Situation Analysis

## Current ChatContext.tsx notes

_at commit `fe7dd4d76d8695490b61a4c4c473dc9c90640e8e`_
_focus file: `apps/mobile/src/context/ChatContext.tsx`_

- I like the `agentStatus` (line 36) for error handling, but it might be redundant with `mcpConnectionStatus` (line 32), `agentConnectionStatus` (line 33) and isLoading (line 25)
- Regarding `messages` (line 24) are we just holding all the messages that are shown on the screen? Should we think of Tides as a context window/conversationr rather than a daily flow?
- Maybe the Chat Context responsibiilities should be split apart from the Tides Context responsibiities?

### Example New Context Format

```
TimeContext (device time/location - stable)
├── TideContext (NEW - tide data & conversation persistence)
├── ChatContext (NEW - pure UI communication layer)
```

TIME CONTEXT (`apps/mobile/src/context/TimeContext.tsx`) - Time & Location from user device. Context compoennt is currently stable. _If Tides is a conversation, TIME CONTEXT is the outside world_

TIDE CONTEXT - Current Tide Messages from the User, the CLoudflare Worker, and from the System (Mobile Client). These messages should be held in sessions torage or soemthign similar. Maybe add a functionality to clear the curretn tide and create a new daily tide by clicking a "New Tide" button that can go ont eh top right of `Home.tsx`. _If Tides is a conversation, TIDE CONTEXT is the room that the conversation takes place in_

CHAT CONTEXT - The context could be responsible for "Is TimeContext loaded/ready?" and then "Is TideContext loaded/ready?" and then "are we connected to the worker/server?". And then ChatCOntext is ultimately responsible for sharing relevant/useful inforamtion to the Tides Server/Agent Entrypoint.

## Ultimate Goals

The Component responsible for the Agent/Worker Entrypoint connection (lets use `apps/mobile/src/components/chat/ChatInput.tsx` as an example for now) should only import functions and parameters from the CHAT CONTEXT

- All relevant info from TIME CONTEXT and TIDE CONTEXT are held and handled by CHAT CONTEXT which feeds right into ChatInput
- The info from TIDE CONTEXT and TIDE CONTEXT needs to be held by the ChatInput because the ChatInput will be passing all info the the "Tides" k2 Storage in Cloudflare int eh 006 ENV as well as Messages to teh Agen/Worker entrypoint.

**It's easier to scale down what we are passing to the agent entrypoint rather than scale up**

## Service Layer Analysis

### agentService.ts - AI Communication Layer

**Primary Responsibilities:**

- AI conversation endpoint integration (`/ai/conversation`)
- Tool intent classification and routing
- Session and conversation ID management (lines 54-56)
- Enhanced conversation context with message history (lines 340-346)
- Fallback mechanisms for AI service unavailability (lines 380-392)
- User ID extraction from API keys for hybrid auth

**Key Methods:**

- `sendMessage()` - Main AI conversation interface
- `sendConversationMessage()` - Enhanced AI endpoint with context
- `classifyToolIntent()` - Natural language to tool routing
- `executeMCPTool()` - Direct MCP tool execution bridge

### mcpService.ts - MCP Protocol Layer

**Primary Responsibilities:**

- JSON-RPC 2.0 MCP protocol implementation
- Direct tide tool execution (tide_create, tide_list, etc.)
- Hierarchical flow management via `startSmartFlow()` (lines 305-325)
- Context-aware operations with automatic daily tide creation
- Connection health monitoring and retry logic

**Key Methods:**

- `tool()` - Generic MCP tool caller
- `startSmartFlow()` - Always uses hierarchical flow system (ADR-003 compliant)
- `getOrCreateTide()` - Automatic context management
- `switchContext()` - Navigate between daily/weekly/monthly views

## Addiitonal Notes

- **Message Persistence**: Conversation history maintained per tide context

**Implementation Implications:**

- Messages scoped to current Daily Tide, not global chat
- Context switching preserves conversation history per daily tide
- A User can now have multiple dialy tides
- "New Tide" functionality creates the new daily tide/fresh converation
- The CHatMessages will only shwo messages from teh current Tide in the Tide Context
- Existing daily flow patterns continue working unchanged

## Gameplan

**TideContext (NEW):**

- Current tide context management (daily/weekly/monthly) baked in but not focus
- Conversation message persistence per tide
- "New Tide" creation for fresh conversation contexts
- Session storage for tide-scoped conversations

**ChatContext (NEW - Clean Implementation):**

- Pure UI state management (single consolidated connection state)
- Agent communication orchestration (agentService integration)
- Tool execution coordination (mcpService bridge)
- Clean interface for ChatInput component

**ChatInput Integration Pattern:**

```typescript
// Single import pattern (Option 1)
const { sendMessage, isLoading, isConnected } = useChat();
// ChatContext orchestrates TideContext + TimeContext internally
```

---

# ADDENDUM: Post-Implementation Analysis & Next Steps

**Status:** ✅ **Integration Complete - Working Successfully**
**Date:** 2025-09-08
**Agent Communication:** Fully functional end-to-end

## ✅ Successfully Implemented

### Bridge Layer Pattern Working
- **useChatMessaging.ts** - Bridge layer successfully coordinates all contexts
- **ChatInput.tsx** - Self-contained component with full send functionality
- **Agent endpoint** - Receiving proper data structure:
```json
{
"user_id": "...",
"tide_id": "tide_1757313819957_unpv4v4t959",
"message": "user input",
"context": {
"tide_tool": "selectedTool", // optional
"tide": { /* full tide object */ },
"tideContext": "daily",
"timeContext": { "timestamp": "...", "timezone": "..." },
"conversationHistory": [/* recent messages */],
"toolSuggestions": ["createTide", "getTideList"]
}
}
```

### K2 Storage Structure Confirmed
**Tide Object in K2:**
```json
{
"id": "tide_1757313819957_unpv4v4t959",
"name": "Daily Focus - Sep 8, 2025",
"description": "Automatically created daily tide for 2025-09-08",
"created_at": "2025-09-08T06:43:39.957Z",
"status": "active",
"flow_sessions": [],
"energy_updates": [],
"task_links": []
}
```

**Messages Storage:**
- Currently in AsyncStorage: `tide_messages_tide_1757313819957_unpv4v4t959`
- 4 messages successfully persisted locally
- Agent responses with suggested tools working

## 🎯 Next Priority: Agent Response Processing

### Current Gap Analysis
**✅ What's Working:**
- Agent receives full rich context
- Agent responds with content and suggested tools
- Messages stored locally per tide
- Tide metadata persists in K2

**❌ Missing Functionality:**
- Agent responses not updating K2 tide object
- Tool calls/suggestions not persisting to `flow_sessions`
- Energy insights not saved to `energy_updates`
- Task management not reflected in `task_links`
- Rich agent interactions not updating tide state

### Proposed Agent Response Handlers

**1. Tool Execution Handler**
```typescript
// When agent suggests tools, execute via MCP and update tide
if (response.suggestedTools) {
await mcpService.updateFlowSession(tideId, {
tools_suggested: response.suggestedTools,
conversation_context: message
});
}
```

**2. Energy Analysis Handler**
```typescript
// When agent analyzes user energy/mood
if (response.energyInsight) {
await mcpService.addEnergyToTide(tideId, response.energyInsight.level, {
agent_analysis: response.energyInsight.analysis,
timestamp: new Date().toISOString()
});
}
```

**3. Task Link Handler**
```typescript
// When agent helps with task management
if (response.taskRecommendations) {
for (const task of response.taskRecommendations) {
await mcpService.linkTaskToTide(tideId, task.url, task.title, 'agent_suggested');
}
}
```

## 🚀 Immediate Next Steps

### Phase 1: Message Display (Priority 1)
- Display agent responses with proper formatting

### Phase 2: Agent Response Processing (Priority 2)
- Add response parsing logic to extract structured data
- Implement K2 tide object updates via MCP service calls
- Sync agent insights back to tide state (flow_sessions, energy_updates, task_links)

### Phase 3: Enhanced UI Integration
- Display suggested tools as actionable buttons
- Show energy insights in UI
- Integrate task links with tide workflow

## 🏗️ Technical Implementation Notes

**Message Flow Architecture:**
```
User Input → ChatInput → Bridge Layer → Agent Service → Agent Response
↓ ↓
AsyncStorage (messages) ← TideContext ← Response Handler → K2 Storage (tide updates)
```

**Key Integration Points:**
- Bridge layer handles all context aggregation
- Agent service manages AI communication
- Response handlers update K2 storage via MCP service
- TideContext maintains local message persistence
- ChatContext manages pure UI state

---

**Status:** Ready to implement message display and agent response processing
Loading