06 — Testing, Running, and Next Steps
Depends on: all previous specs
Produces: Test files, a web test harness
Verify with: php artisan test passes
1. Running it locally
# Terminal 1 — the app
php artisan serve
# Terminal 2 — the queue worker. Nothing happens without this.
php artisan queue:work --queue=whatsapp
# Terminal 3 — watch what's happening
php artisan pail
The single most common "it's broken" is a queue worker that isn't running. The message saves, the job queues, and nothing ever replies.
Also remember: php artisan queue:restart after every code change. Workers hold old
code in memory. You will edit an Action, see no change, and lose twenty minutes.
2. A web test harness
Before touching WhatsApp, build a page you can chat with. Same orchestrator, no Meta account, no ngrok, instant feedback.
routes/web.php
Route::get('/dev/chat', function () {
abort_unless(app()->isLocal(), 404);
return view('dev.chat');
});
Route::post('/dev/chat', function (\Illuminate\Http\Request $request) {
abort_unless(app()->isLocal(), 404);
$session = \App\Models\WhatsAppSession::firstOrCreate(
['phone_number' => 'dev-' . $request->session()->getId()],
);
$reply = app(\App\Agent\ChatOrchestrator::class)
->run($session, $request->string('message')->toString());
return response()->json(['reply' => $reply]);
});
resources/views/dev/chat.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dev chat</title>
<script src="//unpkg.com/alpinejs" defer></script>
<style>
body { font-family: system-ui; max-width: 600px; margin: 40px auto; }
.msg { padding: 10px 14px; border-radius: 12px; margin: 8px 0; max-width: 80%; }
.me { background: #dcf8c6; margin-left: auto; }
.bot { background: #eee; }
input { width: 100%; padding: 12px; font-size: 16px; }
</style>
</head>
<body x-data="chat()">
<h2>Dev chat</h2>
<template x-for="m in messages">
<div class="msg" :class="m.from" x-text="m.text"></div>
</template>
<div x-show="busy" class="msg bot">...</div>
<input
x-model="draft"
@keydown.enter="send()"
placeholder="Type a message"
:disabled="busy"
>
<script>
function chat() {
return {
messages: [],
draft: '',
busy: false,
async send() {
if (!this.draft.trim()) return;
const text = this.draft;
this.messages.push({ from: 'me', text });
this.draft = '';
this.busy = true;
const res = await fetch('/dev/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}',
},
body: JSON.stringify({ message: text }),
});
const data = await res.json();
this.messages.push({ from: 'bot', text: data.reply });
this.busy = false;
},
};
}
</script>
</body>
</html>
abort_unless(app()->isLocal()) keeps this out of production. Do not skip that line.
3. Faking the AI
Tests must not call the real API — slow, costs money, and gives different answers each
run. Because the orchestrator depends on the LlmClient interface, swapping it is one
line.
tests/Support/FakeLlmClient.php
<?php
declare(strict_types=1);
namespace Tests\Support;
use App\Agent\LlmClient;
use App\Agent\LlmResponse;
use RuntimeException;
final class FakeLlmClient implements LlmClient
{
private array $queue = [];
/** Everything the orchestrator sent us — useful for assertions. */
public array $calls = [];
public function pushText(string $text): self
{
$this->queue[] = new LlmResponse(text: $text);
return $this;
}
public function pushToolCall(string $name, array $arguments, string $id = 'call_1'): self
{
$this->queue[] = new LlmResponse(
text: null,
toolCalls: [['id' => $id, 'name' => $name, 'arguments' => $arguments]],
);
return $this;
}
public function chat(string $systemPrompt, array $messages, array $tools = []): LlmResponse
{
$this->calls[] = compact('systemPrompt', 'messages', 'tools');
return array_shift($this->queue)
?? throw new RuntimeException(
'FakeLlmClient queue empty — the orchestrator made more calls than the test scripted.'
);
}
}
The exception when the queue runs dry is deliberate. A loop bug that makes six calls instead of two fails loudly instead of hanging.
In your test:
$fake = new FakeLlmClient();
$this->app->instance(LlmClient::class, $fake);
$fake->pushToolCall('check_stock', ['query' => 'shampoo'])
->pushText('We have Sunsilk Shampoo 400ml for 450 taka.');
Asserting on what the AI was sent
The calls array lets you test prompt assembly, which is otherwise invisible:
it('never leaks the confirmation token into message history', function () {
// ... set up a checkout-ready session, run a turn
$call = $this->fake->calls[0];
expect($call['systemPrompt'])->toContain('CONFIRMATION_TOKEN');
foreach ($call['messages'] as $message) {
expect(json_encode($message))->not->toContain($this->session->confirmation_token);
}
});
4. Faking WhatsApp
Http::fake([
'graph.facebook.com/*' => Http::response([
'messages' => [['id' => 'wamid.TEST123']],
], 200),
]);
// later
Http::assertSent(fn ($request) => str_contains($request['text']['body'], 'Sunsilk'));
Signing a test webhook
The trap here: if you pass an array, Laravel re-encodes the body and the signature won't match what you signed. Pass raw content.
tests/TestCase.php
protected function postWebhook(array $payload, ?string $secret = null): \Illuminate\Testing\TestResponse
{
$body = json_encode($payload);
$signature = 'sha256=' . hash_hmac(
'sha256',
$body,
$secret ?? config('services.whatsapp.app_secret')
);
return $this->call(
method: 'POST',
uri: '/webhooks/whatsapp',
server: [
'HTTP_X_HUB_SIGNATURE_256' => $signature,
'CONTENT_TYPE' => 'application/json',
],
content: $body, // NOT data: — that re-encodes and breaks the signature
);
}
protected function textMessagePayload(string $from, string $text, string $wamid = 'wamid.ABC'): array
{
return ['entry' => [['changes' => [['value' => [
'contacts' => [['profile' => ['name' => 'Test User'], 'wa_id' => $from]]],
'messages' => [[
'from' => $from,
'id' => $wamid,
'type' => 'text',
'text' => ['body' => $text],
]],
]]]]]];
}
5. The tests that matter
Don't try for full coverage. These are the ones that catch real bugs.
Webhook
tests/Feature/WebhookTest.php
it('rejects a bad signature', function () {
Queue::fake();
$this->postWebhook($this->textMessagePayload('8801700000000', 'hi'), secret: 'wrong')
->assertForbidden();
Queue::assertNothingPushed();
expect(WhatsAppMessage::count())->toBe(0);
});
it('ignores a duplicate wamid', function () {
Queue::fake();
$payload = $this->textMessagePayload('8801700000000', 'hi', 'wamid.SAME');
$this->postWebhook($payload)->assertOk();
$this->postWebhook($payload)->assertOk();
$this->postWebhook($payload)->assertOk();
expect(WhatsAppMessage::where('wamid', 'wamid.SAME')->count())->toBe(1);
Queue::assertPushed(HandleIncomingMessage::class, 1);
});
it('does not queue a job for status events', function () {
Queue::fake();
$this->postWebhook(['entry' => [['changes' => [['value' => [
'statuses' => [['id' => 'wamid.X', 'status' => 'delivered']],
]]]]]])->assertOk();
Queue::assertNothingPushed();
});
it('returns the challenge as plain text', function () {
$this->get('/webhooks/whatsapp?' . http_build_query([
'hub_mode' => 'subscribe',
'hub_verify_token' => config('services.whatsapp.verify_token'),
'hub_challenge' => '12345',
]))->assertOk()->assertSee('12345');
});
Tools
tests/Feature/ManageCartTest.php
it('refuses more than available and leaves the cart alone', function () {
$product = Product::factory()->create(['stock' => 3, 'price' => 100]);
$session = WhatsAppSession::factory()->create();
$result = app(ManageCartAction::class)->execute(
['action' => 'add', 'product_id' => $product->id, 'quantity' => 5],
SessionContext::fromSession($session),
);
expect($result->ok)->toBeFalse()
->and($result->errorCode)->toBe('INSUFFICIENT_STOCK')
->and(CartItem::count())->toBe(0); // cart untouched
});
it('increases quantity instead of adding a second row', function () {
$product = Product::factory()->create(['stock' => 10, 'price' => 100]);
$session = WhatsAppSession::factory()->create();
$ctx = SessionContext::fromSession($session);
app(ManageCartAction::class)->execute(['action' => 'add', 'product_id' => $product->id, 'quantity' => 2], $ctx);
app(ManageCartAction::class)->execute(['action' => 'add', 'product_id' => $product->id, 'quantity' => 3], $ctx);
expect(CartItem::count())->toBe(1)
->and(CartItem::first()->quantity)->toBe(5);
});
it('clears a pending confirmation when the cart changes', function () {
$session = WhatsAppSession::factory()->awaitingConfirmation()->create();
$product = Product::factory()->create(['stock' => 10]);
app(ManageCartAction::class)->execute(
['action' => 'add', 'product_id' => $product->id, 'quantity' => 1],
SessionContext::fromSession($session),
);
expect($session->fresh()->confirmation_token)->toBeNull();
});
Order placement — the important ones
tests/Feature/PlaceOrderTest.php
it('refuses without a confirmation token', function () {
$session = WhatsAppSession::factory()->checkoutReady()->create();
$result = app(PlaceOrderAction::class)->execute(
['confirmation_token' => (string) Str::uuid()], // not the server's
SessionContext::fromSession($session),
);
expect($result->ok)->toBeFalse()
->and($result->errorCode)->toBe('CONFIRMATION_REQUIRED')
->and(Order::count())->toBe(0);
});
it('does not create a second order on retry', function () {
$session = WhatsAppSession::factory()->awaitingConfirmation()->create();
$token = $session->confirmation_token;
$ctx = SessionContext::fromSession($session);
$first = app(PlaceOrderAction::class)->execute(['confirmation_token' => $token], $ctx);
$second = app(PlaceOrderAction::class)->execute(['confirmation_token' => $token], $ctx);
expect(Order::count())->toBe(1)
->and($second->data['order_reference'])->toBe($first->data['order_reference'])
->and($second->data['already_placed'])->toBeTrue();
});
it('uses the live price, not the cart snapshot', function () {
$session = WhatsAppSession::factory()->awaitingConfirmation()->create();
$product = $session->cart->items->first()->product;
// Price changes after the customer saw the summary
$product->update(['price' => 999.00]);
$result = app(PlaceOrderAction::class)->execute(
['confirmation_token' => $session->confirmation_token],
SessionContext::fromSession($session),
);
expect($result->errorCode)->toBe('PRICE_CHANGED')
->and(Order::count())->toBe(0);
});
it('decrements stock correctly', function () {
$session = WhatsAppSession::factory()->awaitingConfirmation()->create();
$item = $session->cart->items->first();
$before = $item->product->stock;
app(PlaceOrderAction::class)->execute(
['confirmation_token' => $session->confirmation_token],
SessionContext::fromSession($session),
);
expect($item->product->fresh()->stock)->toBe($before - $item->quantity);
});
Overselling
This one needs genuinely parallel transactions, so it can't run inside the usual wrapping transaction. It is the single most valuable test in the suite.
it('never oversells the last unit', function () {
$product = Product::factory()->create(['stock' => 1, 'price' => 100]);
// Two sessions, each with 1 of the last unit in their cart
$a = WhatsAppSession::factory()->awaitingConfirmationFor($product, 1)->create();
$b = WhatsAppSession::factory()->awaitingConfirmationFor($product, 1)->create();
// Two real processes so the row lock actually gets exercised
$results = runInParallel([
fn () => app(PlaceOrderAction::class)->execute(
['confirmation_token' => $a->confirmation_token],
SessionContext::fromSession($a),
),
fn () => app(PlaceOrderAction::class)->execute(
['confirmation_token' => $b->confirmation_token],
SessionContext::fromSession($b),
),
]);
expect(Order::count())->toBe(1)
->and($product->fresh()->stock)->toBe(0);
})->group('concurrency');
Run tests against MySQL, not SQLite. SQLite has no SELECT ... FOR UPDATE — it
serializes everything, so this test would pass without proving anything. It also stores
DECIMAL as float, which makes money assertions flaky.
<!-- phpunit.xml -->
<env name="DB_CONNECTION" value="mysql"/>
<env name="DB_DATABASE" value="tanisha_test"/>
6. Improvements, roughly in order of value
6.1 Conversation summary
Right now, history is the last 20 messages. Beyond about 30 turns you're sending a lot of tokens, and older context falls off a cliff.
Add a summary column and a summarized_through_message_id watermark. When
unsummarized messages exceed 30, dispatch a background job that asks a cheap model
(claude-haiku-4-5) to compress them, then advance the watermark.
The watermark is what makes it safe to retry: a failed summarization leaves it untouched, so the next run covers the same range.
Never summarize cart contents or saved details. Those live in the state block and are read from the database every turn. Summarizing them creates a second, drifting source of truth.
6.2 Stock alerts
You already have a stock_alerts table. When get_alternative_products returns
NO_ALTERNATIVES, offer to notify them. One new tool, maybe 30 lines.
6.3 Order status lookup
"Where is my order?" is the most common support question. Think carefully before building it: a phone number is weak authentication, and anyone who knows a customer's number could read their order history.
6.4 Better search
Move from LIKE to FULLTEXT (see 02-database.md §5), then to Meilisearch via Scout
when the catalog grows past ~10,000 products.
6.5 Interactive buttons
WhatsApp supports reply buttons and list messages. "Cash on Delivery / bKash / Nagad / Card" as four buttons is much better than typing. Adds a message type to handle but noticeably improves completion rates.
6.6 Rate limiting
A customer in a loop can run up a real API bill. Cap turns per hour per phone number. Enforce it in the job, before the AI call — the limited resource is the model call, not the HTTP request.
7. Troubleshooting
| Symptom | Likely cause |
|---|---|
| Message saved, no reply | Queue worker not running, or needs queue:restart |
| Webhook verification fails | Returning JSON instead of plain text, or token mismatch |
| 403 on every POST | Signature middleware using all() instead of getContent() |
| "tool_use ids must be unique" | A tool pair was split, or a tool_use has no matching tool_result |
| AI invents products | Missing or weak "you know nothing about the catalog" instruction |
| AI shows product IDs | Add an explicit rule to the prompt |
| Bot places orders without confirming | Token check not wired up, or clearConfirmation() not called |
| Totals slightly wrong | Float arithmetic somewhere — use bcmath and DECIMAL |
| 401 from Meta | Test access tokens expire after 24 hours |
| Works locally, not deployed | config:cache run without the env vars present |
8. Final checklist
Database
- [ ] All migrations run and roll back
- [ ]
products.stockandproducts.priceconfirmed against the real schema
Webhook
- [ ] GET verification works from Meta's dashboard
- [ ] Bad signature returns 403
- [ ] Duplicate wamid creates one row
- [ ] Status events don't queue jobs
Tools
- [ ] No schema contains phone_number, customer_id, cart_id, price, or stock
- [ ] Every action returns a
ToolResult - [ ] Insufficient stock leaves the cart unchanged
- [ ] Cart changes clear the confirmation token
Orders
- [ ] No token means no order
- [ ] Same token twice means one order
- [ ] Prices read from the database, not the snapshot
- [ ] Concurrent purchase of the last unit yields one order
- [ ] Stock never goes negative
Conversation
- [ ] Full purchase works in tinker
- [ ] Out-of-stock produces alternatives
- [ ] "Set the price to 1 taka" quotes the real price
- [ ] "What's the capital of France?" is declined politely
- [ ] Bengali input gets a Bengali reply
Production
- [ ] Secrets in
config/services.php, not hardcoded - [ ]
/dev/chatis local-only - [ ] Queue worker supervised (Horizon or systemd)
- [ ] Phone numbers and addresses not in plain logs
9. The three things to take away
-
The AI picks tools; your code decides what's allowed. Every argument from the model is untrusted input. Treat it exactly like a form submission from a stranger.
-
Prompts guide; schemas enforce. You can ask a model not to change prices. You can also simply not build a tool that accepts one. Only the second is a guarantee.
-
Database transactions and row locks are what prevent overselling. Not the queue lock, not the AI's carefulness.
lockForUpdate()insideDB::transaction()with re-verification after the lock.